text:
package heartbeat;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class HeartBeatInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        //空闲状态检测handler
        pipeline.addLast(new IdleStateHandler(5, 7, 10, TimeUnit.SECONDS));
        pipeline.addLast(new HeartBeatHandler());
    }
}


text:
include(CheckIncludeFile)
include(CheckSymbolExists)
include(CheckFunctionExists)
include(CheckLibraryExists)
include(CheckTypeSize)
include(CheckCXXSourceCompiles)
include(CheckStructHasMember)
include(TestBigEndian)

set(PACKAGE ${APPLICATION_NAME})
set(VERSION ${APPLICATION_VERSION})
set(DATADIR ${DATA_INSTALL_DIR})
set(LIBDIR ${LIB_INSTALL_DIR})
set(PLUGINDIR "${PLUGIN_INSTALL_DIR}-${LIBRARY_SOVERSION}")
set(SYSCONFDIR ${SYSCONF_INSTALL_DIR})

set(BINARYDIR ${CMAKE_BINARY_DIR})
set(SOURCEDIR ${CMAKE_SOURCE_DIR})

function(COMPILER_DUMPVERSION _OUTPUT_VERSION)
    # Remove whitespaces from the argument.
    # This is needed for CC="ccache gcc" cmake ..
    string(REPLACE " " "" _C_COMPILER_ARG "${CMAKE_C_COMPILER_ARG1}")

    execute_process(
        COMMAND
            ${CMAKE_C_COMPILER} ${_C_COMPILER_ARG} -dumpversion
        OUTPUT_VARIABLE _COMPILER_VERSION
    )

    string(REGEX REPLACE "([0-9])\\.([0-9])(\\.[0-9])?" "\\1\\2"
        _COMPILER_VERSION ${_COMPILER_VERSION})

    set(${_OUTPUT_VERSION} ${_COMPILER_VERSION} PARENT_SCOPE)
endfunction()

if(CMAKE_COMPILER_IS_GNUCC AND NOT MINGW)
    compiler_dumpversion(GNUCC_VERSION)
    if (NOT GNUCC_VERSION EQUAL 34)
        check_c_compiler_flag("-fvisibility=hidden" WITH_VISIBILITY_HIDDEN)
    endif (NOT GNUCC_VERSION EQUAL 34)
endif(CMAKE_COMPILER_IS_GNUCC AND NOT MINGW)

# DEFINITIONS
if (SOLARIS)
    add_definitions(-D__EXTENSIONS__)
endif (SOLARIS)

# HEADER FILES
check_include_file(assert.h HAVE_ASSERT_H)
check_include_file(inttypes.h HAVE_INTTYPES_H)
check_include_file(io.h HAVE_IO_H)
check_include_file(malloc.h HAVE_MALLOC_H)
check_include_file(memory.h HAVE_MEMORY_H)
check_include_file(setjmp.h HAVE_SETJMP_H)
check_include_file(signal.h HAVE_SIGNAL_H)
check_include_file(stdarg.h HAVE_STDARG_H)
check_include_file(stddef.h HAVE_STDDEF_H)
check_include_file(stdint.h HAVE_STDINT_H)
check_include_file(stdio.h HAVE_STDIO_H)
check_include_file(stdlib.h HAVE_STDLIB_H)
check_include_file(string.h HAVE_STRING_H)
check_include_file(strings.h HAVE_STRINGS_H)
check_include_file(sys/stat.h HAVE_SYS_STAT_H)
check_include_file(sys/types.h HAVE_SYS_TYPES_H)
check_include_file(time.h HAVE_TIME_H)
check_include_file(unistd.h HAVE_UNISTD_H)

if (HAVE_TIME_H)
    check_struct_has_member("struct timespec" tv_sec "time.h" HAVE_STRUCT_TIMESPEC)
endif (HAVE_TIME_H)

# FUNCTIONS
check_function_exists(calloc HAVE_CALLOC)
check_function_exists(exit HAVE_EXIT)
check_function_exists(fprintf HAVE_FPRINTF)
check_function_exists(free HAVE_FREE)
check_function_exists(longjmp HAVE_LONGJMP)
check_function_exists(siglongjmp HAVE_SIGLONGJMP)
check_function_exists(malloc HAVE_MALLOC)
check_function_exists(memcpy HAVE_MEMCPY)
check_function_exists(memset HAVE_MEMSET)
check_function_exists(printf HAVE_PRINTF)
check_function_exists(setjmp HAVE_SETJMP)
check_function_exists(signal HAVE_SIGNAL)
check_function_exists(strsignal HAVE_STRSIGNAL)
check_function_exists(sprintf HAVE_SNPRINTF)
check_function_exists(strcmp HAVE_STRCMP)
check_function_exists(vsnprintf HAVE_VSNPRINTF)
check_function_exists(clock_gettime HAVE_CLOCK_GETTIME)

if (WIN32)
    check_function_exists(_vsnprintf_s HAVE__VSNPRINTF_S)
    check_function_exists(_vsnprintf HAVE__VSNPRINTF)
    check_function_exists(_snprintf HAVE__SNPRINTF)
    check_function_exists(_snprintf_s HAVE__SNPRINTF_S)
endif (WIN32)

find_library(RT_LIBRARY rt)
if (RT_LIBRARY)
    set(CMAKE_REQUIRED_LIBRARIES ${RT_LIBRARY})
endif (RT_LIBRARY)

set(CMOCKA_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES} CACHE INTERNAL "cmocka required system libraries")

# OPTIONS
check_c_source_compiles("
__thread int tls;

int main(void) {
    return 0;
}" HAVE_GCC_THREAD_LOCAL_STORAGE)

if (WIN32)
check_c_source_compiles("
__declspec(thread) int tls;

int main(void) {
    return 0;
}" HAVE_MSVC_THREAD_LOCAL_STORAGE)
endif(WIN32)

if (HAVE_TIME_H AND HAVE_STRUCT_TIMESPEC AND HAVE_CLOCK_GETTIME)
    set(CMAKE_REQUIRED_LIBRARIES ${RT_LIBRARY})

    message(STATUS "CMAKE_REQUIRED_INCLUDES=${CMAKE_REQUIRED_INCLUDES} CMAKE_REQUIRED_LIBRARIES=${CMAKE_REQUIRED_LIBRARIES}")
    check_c_source_compiles("
#include <time.h>

int main(void) {
    struct timespec ts;

    clock_gettime(CLOCK_REALTIME, &ts);

    return 0;
}" HAVE_CLOCK_GETTIME_REALTIME)
    set(CMAKE_REQUIRED_INCLUDES)
endif ()

# ENDIAN
if (NOT WIN32)
    set(WORDS_SIZEOF_VOID_P ${CMAKE_SIZEOF_VOID_P})
    test_big_endian(WORDS_BIGENDIAN)
endif (NOT WIN32)

redpajama_set_name: RedPajamaGithub


text:
package org.apache.metamodel.util;

import java.io.Serializable;
import java.util.Arrays;

import org.apache.metamodel.DataContext;
import org.apache.metamodel.schema.Column;
import org.apache.metamodel.schema.ColumnType;
import org.apache.metamodel.schema.MutableColumn;
import org.apache.metamodel.schema.MutableTable;
import org.apache.metamodel.schema.Table;
import org.apache.metamodel.schema.TableType;

/**
 * Represents a table definition to be used in scenarios where a
 * {@link DataContext} is unable to detect/discover the table structure and
 * needs some basic input around expected table structures.
 */
public class SimpleTableDef implements Serializable, HasName {

    private static final long serialVersionUID = 1L;

    private final String _name;
    private final String[] _columnNames;
    private final ColumnType[] _columnTypes;

    /**
     * Constructs a {@link SimpleTableDef} using a {@link Table} as a prototype.
     *
     * @param table
     */
    public SimpleTableDef(Table table) {
        _name = table.getName();
        _columnNames = new String[table.getColumnCount()];
        _columnTypes = new ColumnType[table.getColumnCount()];
        for (int i = 0; i < table.getColumnCount(); i++) {
            Column column = table.getColumn(i);
            _columnNames[i] = column.getName();
            _columnTypes[i] = column.getType();
        }
    }

    /**
     * Constructs a {@link SimpleTableDef}.
     *
     * @param name
     *            the name of the table
     * @param columnNames
     *            the names of the columns to include in the table
     */
    public SimpleTableDef(String name, String[] columnNames) {
        this(name, columnNames, null);
    }

    /**
     * Constructs a {@link SimpleTableDef}.
     *
     * @param name
     *            the name of table
     * @param columnNames
     *            the names of the columns to include in the table
     * @param columnTypes
     *            the column types of the columns specified.
     */
    public SimpleTableDef(String name, String[] columnNames, ColumnType[] columnTypes) {
        if(name == null){
            throw new NullPointerException("Table name cannot be null");
        }
        _name = name;
        _columnNames = columnNames;
        if (columnTypes == null) {
            columnTypes = new ColumnType[columnNames.length];
            for (int i = 0; i < columnTypes.length; i++) {
                columnTypes[i] = ColumnType.VARCHAR;
            }
        } else {
            if (columnNames.length != columnTypes.length) {
                throw new IllegalArgumentException(
                        "Property names and column types cannot have different lengths (found " + columnNames.length
                                + " and " + columnTypes.length + ")");
            }
        }
        _columnTypes = columnTypes;
    }

    /**
     * Gets the name of the table
     *
     * @return the name of the table
     */
    public String getName() {
        return _name;
    }

    /**
     * Gets the names of the columns in the table
     *
     * @return the names of the columns in the table
     */
    public String[] getColumnNames() {
        return _columnNames;
    }

    /**
     * Gets the types of the columns in the table
     *
     * @return the types of the columns in the table
     */
    public ColumnType[] getColumnTypes() {
        return _columnTypes;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((_name == null) ? 0 : _name.hashCode());
        result = prime * result + Arrays.hashCode(_columnTypes);
        result = prime * result + Arrays.hashCode(_columnNames);
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        SimpleTableDef other = (SimpleTableDef) obj;
        if (_name == null) {
            if (other._name != null)
                return false;
        } else if (!_name.equals(other._name))
            return false;
        if (!Arrays.equals(_columnTypes, other._columnTypes))
            return false;
        if (!Arrays.equals(_columnNames, other._columnNames))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "SimpleTableDef[name=" + _name + ",columnNames=" + Arrays.toString(_columnNames) + ",columnTypes="
                + Arrays.toString(_columnTypes) + "]";
    }

    /**
     * Creates a {@link MutableTable} based on this {@link SimpleTableDef}. Note
     * that the created table will not have any schema set.
     *
     * @return a table representation of this table definition.
     */
    public MutableTable toTable() {
        String name = getName();
        String[] columnNames = getColumnNames();
        ColumnType[] columnTypes = getColumnTypes();

        MutableTable table = new MutableTable(name, TableType.TABLE);

        for (int i = 0; i < columnNames.length; i++) {
            table.addColumn(new MutableColumn(columnNames[i], columnTypes[i], table, i, true));
        }
        return table;
    }

    /**
     * Gets the index of a column name, or -1 if the column name does not exist
     *
     * @param columnName
     * @return
     */
    public int indexOf(String columnName) {
        if (columnName == null) {
            throw new IllegalArgumentException("Column name cannot be null");
        }
        for (int i = 0; i < _columnNames.length; i++) {
            if (columnName.equals(_columnNames[i])) {
                return i;
            }
        }
        return -1;
    }
}


text:
package org.thingsboard.server.common.data.event;

import lombok.Getter;

public enum EventType {
    ERROR("error_event", "ERROR"),
    LC_EVENT("lc_event", "LC_EVENT"),
    STATS("stats_event", "STATS"),
    DEBUG_RULE_NODE("rule_node_debug_event", "DEBUG_RULE_NODE", true),
    DEBUG_RULE_CHAIN("rule_chain_debug_event", "DEBUG_RULE_CHAIN", true);

    @Getter
    private final String table;
    @Getter
    private final String oldName;
    @Getter
    private final boolean debug;

    EventType(String table, String oldName) {
        this(table, oldName, false);
    }

    EventType(String table, String oldName, boolean debug) {
        this.table = table;
        this.oldName = oldName;
        this.debug = debug;
    }

}


text:
{-# LANGUAGE NoImplicitPrelude #-}

module FiveFundamentalMonads where

import Data.Monoid

-- | Implement the five basic Monads (Id, Maybe, Reader, State, Writer) (4 kyu)
-- | Link: https://biturl.io/5Monads

import Prelude
       hiding (Identity, Maybe(..), Monad, Reader, State, Writer)

-- | My original solution
class Monad m where
  return :: a -> m a
  (>>=) :: m a -> (a -> m b) -> m b

newtype Identity a =
  Identity a

data Maybe a
  = Nothing
  | Just a
  deriving (Show, Eq)

newtype State s a = State
  { runState :: s -> (a, s)
  }

newtype Reader s a = Reader
  { runReader :: s -> a
  }

newtype Writer w a = Writer
  { runWriter :: (w, a)
  }

instance Monad Identity where
  return = Identity
  (Identity v) >>= f = f v

instance Monad Maybe where
  return = Just
  Nothing >>= _ = Nothing
  (Just v) >>= f = f v

instance Monad (State s) where
  return = State . (\x s -> (x, s))
  (State g) >>= f =
    State $ \s ->
      let (v, s') = g s
      in (runState $ f v) s'

instance Monad (Reader s) where
  return = Reader . const
  (Reader g) >>= f =
    Reader $ \s ->
      let r = f (g s)
      in runReader r s

instance Monoid w => Monad (Writer w) where
  return x = Writer (mempty, x)
  (Writer (s, v)) >>= f =
    Writer $
    let (s', v') = runWriter $ f v
    in (s <> s', v')


text:
require "eventmachine"
require "mq"
require "time"
require "socket"

module PipelineToolkit
  ##
  # The message subscriber is used to subscribe to a AMQP server queue
  # and handle a single message at a time.
  #
  class MessageSubscriber

    include Amqp::Reader

    attr_reader :start_time
    attr_reader :mps
    attr_reader :options
    attr_reader :total_messages
    attr_reader :average_mps
    attr_accessor :structure

    PIPE_PATH = "/tmp"

    ##
    # Initializes a new instance
    #
    # @param options<Hash> An options hash, see command line interface.
    #
    def initialize(options = {})
      @options = options
      options[:ack] = !options[:no_acks]

      DefaultLogger.init_logger(options) if options[:log_conf]

      DefaultLogger.info "================================================================"
      DefaultLogger.info "Booting #{self.class.name}  (#{options[:env]})"
      DefaultLogger.info "Exchange: #{options[:exchange]} (#{options[:type]} passive:#{options[:passive]} durable:#{options[:durable]})"
      DefaultLogger.info "Queue: #{options[:queue]} (ack:#{options[:ack]})"
      DefaultLogger.info "amqp://#{options[:user]}:#{options[:pass]}@#{options[:host]}:#{options[:port]}#{options[:vhost]}"
      DefaultLogger.info "Monitoring: http://localhost:#{options[:http_port]}/ (#{options[:content_type]})"
      DefaultLogger.info ""

      @structure = [description]
      write_pid(options[:pid_path]) if options[:pid_path]

      @total_messages = 0

      reset_message_statistics
    end

    ##
    # Starts the subscriber reactor loop
    #
    def start

      DefaultLogger.debug("MessageSubscriber#start")
      begin
        create_sys_pipe

        Signal.trap('INT')  { self.stop }
        Signal.trap('TERM') { self.stop }
        Signal.trap('PIPE') { self.stop }

        EM.run do
          @start_time = Time.now

          initialize_reader
          queue_subscribe

          conn = EM.watch(@sys_pipe, Handlers::MessageHandler, self, options)
          # must call this to setup callback to notify_readable
          conn.notify_readable = true

          if monitoring_enabled?
            EM.start_server('0.0.0.0', options[:http_port], Monitoring::MonitorServer, self, options)
            EM.add_periodic_timer(5) { calculate_message_statistics }
          end
        end
      rescue Exception => e
        DefaultLogger.error "#{e.class.name}: #{e.message}\n" << e.backtrace.join("\n")
        raise e
      ensure
        cleanup
      end
    end

    ##
    # Stops the command. This stops the event loop, giving it enough time to clear its buffers
    #
    def stop
      DefaultLogger.info("Shutting down #{self.class.name}")
      DefaultLogger.info "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
      stop_connection { EM.stop }
    end

    ##
    # Cleans up any used resource, such as pipes and files.
    #
    def cleanup
      destroy_sys_pipe
    end

    def write_pid(path)
      DefaultLogger.info "Pid file written to #{options[:pid_path]}" if options[:pid_path]
      `echo #{Process.pid} > #{path}`
    end

    def monitoring_enabled?
      !options[:http_port].nil?
    end

    ##
    # Callback for the Handlers::MessageHandler when it receives a message
    #
    # @param message<Hash> The decoded message
    #
    def process(message)
      case message[:msg_type]
        when "ack"
          DefaultLogger.debug("Acknowledging message #{message[:ack_id]}")
          perform_acknowledgement(message[:ack_id])
        when "pipe_desc"
          @structure << message[:description].to_s
        else
          raise "Unknown control message received: #{message.inspect}"
      end
    end

    ##
    # Support templating of member data.
    #
    def get_binding
      binding
    end

    # :nodoc:
    def process_id
      Process.pid.to_s
    end

    ##
    # The uptime of the subscriber in mins
    #
    def uptime
      (Time.now - self.start_time).to_i
    end

    ##
    # The hostname of the server the subscriber is running on
    #
    def hostname
      Socket.gethostname
    end

    def description
      "queue:#{options[:queue]}"
    end

    protected

    ##
    # Process the message received from AMQP server
    #
    # @param header<MQ::Header> The header of the message
    # @param body Description
    #
    def process_queue_message(header, body)
      DefaultLogger.debug("MessageSubscriber#process_queue_message(header, body)")
      body = MessageCoder.decode(body)
      DefaultLogger.debug("---------------  #{body.inspect}")
      unless body.is_a?(Hash)
        message = { :msg_type => 'standard', :raw => body }
      else
        message = { :msg_type => 'standard' }.merge(body)
      end
      store_acknowledgement(message, header) if options[:ack]
      write(message)
    rescue MessagePack::UnpackError => e
      DefaultLogger.error("msg_subscribe couldn't unpack: #{body.inspect}")
      header.ack
    end

    private

      ##
      # Reset the instance variables used to store message statistics
      #
      def reset_message_statistics
        @count = 0
        @prev_time = Time.now
      end

      ##
      # Calculate the statistics on message handling
      #
      def calculate_message_statistics
        @time_delta = Time.now - @prev_time
        @mps  = @count  / @time_delta
        @average_mps = @total_messages / uptime
        reset_message_statistics
      end

      ##
      # Create the acknowledgement named pipe
      #
      def create_sys_pipe
        name = File.join(PIPE_PATH, "sys_pipe_#{generate_guid}")
        `mkfifo #{name}`
        @sys_pipe = File.new(name, "r+")
        message = { :msg_type => "system",
                    :sys_pipe => name,
                    :ack => options[:ack] }
        write_to_pipe(message)
      end

      ##
      # Destroy the acknowledgement named pipe
      #
      def destroy_sys_pipe
        `rm #{@sys_pipe.path}`
      end

      ##
      # Generates a unique guid to use as part of the acknowledgement named pipe name.
      # Stolen from EM.
      #
      def generate_guid
        # Cache uuidgen seed for better performance
        if @ix and @ix >= 10_000
          @ix = nil
          @seed = nil
        end

        # NB. This will only work on *nix platforms
        @seed ||= `uuidgen`.chomp.gsub(/-/,"")
        @ix ||= 0

        "#{@seed}#{@ix += 1}"
      end

      ##
      # Write the message to STDOUT
      #
      # @param message<Hash> The message to write
      #
      def write(message)
        DefaultLogger.debug("MessageSubscriber#write(#{message.inspect})")
        @count += 1
        @total_messages += 1
        write_to_pipe(message)
      end

      def write_to_pipe(message, pipe=$stdout)
        pipe.syswrite(MessageCoder.encode(message) << "\n")
      end

  end

end


text:
module.exports = {
  normalizeEntityName() {},
  afterInstall() {
    return this.addBowerPackageToProject('rangeslider.js');
  }
}


text:
<?php

namespace Symfony\Component\Cache\Tests\Simple;

use Symfony\Component\Cache\Simple\DoctrineCache;
use Symfony\Component\Cache\Tests\Fixtures\ArrayCache;

/**
 * @group time-sensitive
 * @group legacy
 */
class DoctrineCacheTest extends CacheTestCase
{
    protected $skippedTests = [
        'testObjectDoesNotChangeInCache' => 'ArrayCache does not use serialize/unserialize',
        'testNotUnserializable' => 'ArrayCache does not use serialize/unserialize',
    ];

    public function createSimpleCache($defaultLifetime = 0)
    {
        return new DoctrineCache(new ArrayCache($defaultLifetime), '', $defaultLifetime);
    }
}


text:
'''
This is a extended unittest module for Kivy, to make unittest based on
graphics with OpenGL context.

The idea is to let user render a Widget tree, and after 1, 2 or x frame, a
screenshot will be done, and be compared to the original one.
If no screenshot exist for the current test, the very first one will be used.

The screenshots lives in kivy/tests/results, in PNG format, 320x240.
'''

__all__ = ('GraphicUnitTest', )

import unittest
import logging
import os
from kivy.graphics.cgl import cgl_get_backend_name
log = logging.getLogger('unittest')

_base = object
if 'mock' != cgl_get_backend_name():
    _base = unittest.TestCase

class GraphicUnitTest(_base):

    def render(self, root, framecount=1):
        '''Call rendering process using the `root` widget.
        The screenshot will be done in `framecount` frames.
        '''
        from kivy.base import runTouchApp
        self.framecount = framecount
        runTouchApp(root)

        # reset for the next test, but nobody will know if it will be used :/
        if self.test_counter != 0:
            self.tearDown(fake=True)
            self.setUp()

    def run(self, name):
        '''Extend the run of unittest, to check if results directory have been
        found. If no results directory exists, the test will be ignored.
        '''
        from os.path import join, dirname, exists
        results_dir = join(dirname(__file__), 'results')
        if not exists(results_dir):
            log.warning('No result directory found, cancel test.')
            os.mkdir(results_dir)
        self.test_counter = 0
        self.results_dir = results_dir
        self.test_failed = False
        return super(GraphicUnitTest, self).run(name)

    def setUp(self):
        '''Prepare the graphic test, with:
            - Window size fixed to 320x240
            - Default kivy configuration
            - Without any kivy input
        '''

        # use default kivy configuration (don't load user file.)
        from os import environ
        environ['KIVY_USE_DEFAULTCONFIG'] = '1'

        # force window size + remove all inputs
        from kivy.config import Config
        Config.set('graphics', 'width', '320')
        Config.set('graphics', 'height', '240')
        for items in Config.items('input'):
            Config.remove_option('input', items[0])

        # bind ourself for the later screenshot
        from kivy.core.window import Window
        Window.bind(on_flip=self.on_window_flip)

        # ensure our window is correctly created
        Window.create_window()
        Window.canvas.clear()

    def on_window_flip(self, window):
        '''Internal method to be called when the window have just displayed an
        image.
        When an image is showed, we decrement our framecount. If framecount is
        come to 0, we are taking the screenshot.

        The screenshot is done in a temporary place, and is compared to the
        original one -> test ok/ko.
        If no screenshot is available in the results directory, a new one will
        be created.
        '''
        from kivy.base import EventLoop
        from tempfile import mkstemp
        from os.path import join, exists
        from os import unlink, close
        from shutil import move, copy

        # don't save screenshot until we have enough frames.
        # log.debug('framecount %d' % self.framecount)
        self.framecount -= 1
        if self.framecount > 0:
            return

        # don't create screenshots if a specific var is in env
        ignore = ['TRAVIS_OS_NAME', 'APPVEYOR_BUILD_FOLDER']
        from os import environ
        if any(i in environ for i in ignore):
            EventLoop.stop()
            return

        reffn = None
        match = False
        try:
            # just get a temporary name
            fd, tmpfn = mkstemp(suffix='.png', prefix='kivyunit-')
            close(fd)
            unlink(tmpfn)

            # get a filename for the current unit test
            self.test_counter += 1
            test_uid = '%s-%d.png' % (
                '_'.join(self.id().split('.')[-2:]),
                self.test_counter)

            # capture the screen
            log.info('Capturing screenshot for %s' % test_uid)
            tmpfn = window.screenshot(tmpfn)
            log.info('Capture saved at %s' % tmpfn)

            # search the file to compare to
            reffn = join(self.results_dir, test_uid)
            log.info('Compare with %s' % reffn)

            # get sourcecode
            import inspect
            frame = inspect.getouterframes(inspect.currentframe())[6]
            sourcecodetab, line = inspect.getsourcelines(frame[0])
            line = frame[2] - line
            currentline = sourcecodetab[line]
            sourcecodetab[line] = '%s' % (
                currentline)
            sourcecode = ''.join(sourcecodetab)
            sourcecodetab[line] = '>>>>>>>>\n%s<<<<<<<<\n' % currentline
            sourcecodeask = ''.join(sourcecodetab)

            if not exists(reffn):
                log.info('No image reference, move %s as ref ?' % test_uid)
                if self.interactive_ask_ref(sourcecodeask, tmpfn, self.id()):
                    move(tmpfn, reffn)
                    tmpfn = reffn
                    log.info('Image used as reference')
                    match = True
                else:
                    log.info('Image discarded')
            else:
                from kivy.core.image import Image as CoreImage
                s1 = CoreImage(tmpfn, keep_data=True)
                sd1 = s1.image._data[0].data
                s2 = CoreImage(reffn, keep_data=True)
                sd2 = s2.image._data[0].data
                if sd1 != sd2:
                    log.critical(
                        '%s at render() #%d, images are different.' % (
                            self.id(), self.test_counter))
                    if self.interactive_ask_diff(sourcecodeask,
                                                 tmpfn, reffn, self.id()):
                        log.critical('user ask to use it as ref.')
                        move(tmpfn, reffn)
                        tmpfn = reffn
                        match = True
                    else:
                        self.test_failed = True
                else:
                    match = True

            # generate html
            from os.path import join, dirname, exists, basename
            from os import mkdir
            build_dir = join(dirname(__file__), 'build')
            if not exists(build_dir):
                mkdir(build_dir)
            copy(reffn, join(build_dir, 'ref_%s' % basename(reffn)))
            if tmpfn != reffn:
                copy(tmpfn, join(build_dir, 'test_%s' % basename(reffn)))
            with open(join(build_dir, 'index.html'), 'at') as fd:
                color = '#ffdddd' if not match else '#ffffff'
                fd.write('
' % color)
                fd.write('
%s #%d
' % (self.id(), self.test_counter))
                fd.write('

Reference	'
                         'Test	'
                         'Comment	')
                fd.write('
	' %
                         basename(reffn))
                if tmpfn != reffn:
                    fd.write('	' %
                             basename(reffn))
                else:
                    fd.write('First time, no comparison.	')
                fd.write('
%s
	' % sourcecode)
                fd.write('

')
        finally:
            try:
                if reffn != tmpfn:
                    unlink(tmpfn)
            except:
                pass
            EventLoop.stop()

    def tearDown(self, fake=False):
        '''When the test is finished, stop the application, and unbind our
        current flip callback.
        '''
        from kivy.base import stopTouchApp
        from kivy.core.window import Window
        Window.unbind(on_flip=self.on_window_flip)
        stopTouchApp()

        if not fake and self.test_failed:
            self.assertTrue(False)
        super(GraphicUnitTest, self).tearDown()

    def interactive_ask_ref(self, code, imagefn, testid):
        from os import environ
        if 'UNITTEST_INTERACTIVE' not in environ:
            return True

        from tkinter import Tk, Label, LEFT, RIGHT, BOTTOM, Button
        from PIL import Image, ImageTk

        self.retval = False

        root = Tk()

        def do_close():
            root.destroy()

        def do_yes():
            self.retval = True
            do_close()

        image = Image.open(imagefn)
        photo = ImageTk.PhotoImage(image)
        Label(root, text='The test %s\nhave no reference.' % testid).pack()
        Label(root, text='Use this image as a reference ?').pack()
        Label(root, text=code, justify=LEFT).pack(side=RIGHT)
        Label(root, image=photo).pack(side=LEFT)
        Button(root, text='Use as reference', command=do_yes).pack(side=BOTTOM)
        Button(root, text='Discard', command=do_close).pack(side=BOTTOM)
        root.mainloop()

        return self.retval

    def interactive_ask_diff(self, code, tmpfn, reffn, testid):
        from os import environ
        if 'UNITTEST_INTERACTIVE' not in environ:
            return False

        from tkinter import Tk, Label, LEFT, RIGHT, BOTTOM, Button
        from PIL import Image, ImageTk

        self.retval = False

        root = Tk()

        def do_close():
            root.destroy()

        def do_yes():
            self.retval = True
            do_close()

        phototmp = ImageTk.PhotoImage(Image.open(tmpfn))
        photoref = ImageTk.PhotoImage(Image.open(reffn))
        Label(root, text='The test %s\nhave generated an different'
              'image as the reference one..' % testid).pack()
        Label(root, text='Which one is good ?').pack()
        Label(root, text=code, justify=LEFT).pack(side=RIGHT)
        Label(root, image=phototmp).pack(side=RIGHT)
        Label(root, image=photoref).pack(side=LEFT)
        Button(root, text='Use the new image -->',
               command=do_yes).pack(side=BOTTOM)
        Button(root, text='<-- Use the reference',
               command=do_close).pack(side=BOTTOM)
        root.mainloop()

        return self.retval


text:
.eternity-form h3, .eternity-form h4 {
  font-family: 'Roboto', 'PT Sans', sans-serif;
  font-weight: 300;
}

.eternity-form .login-form-section {
  width: 100%;
  max-width: 360px;
  margin: 0 auto;
}

.eternity-form .login-content, .eternity-form .reg-content {
  background-color: white;
  box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);
}

.eternity-form .section-title {
  padding: 10px 20px;
  background-color: white;
}

.eternity-form .section-title h3 {
  color: #3498db;
}

.eternity-form .textbox-wrap {
  padding: 20px 20px 20px 15px;
  border-left: 5px solid transparent;
  transition: border-left-color 0.5s, box-shadow 0.5s, background-color 0.5s;
}

.eternity-form .textbox-wrap .input-group {
  border: 1px solid #e0e0e0;
  background-color: #ffffff;
}

.eternity-form .textbox-wrap .input-group .input-group-addon, .eternity-form .textbox-wrap .input-group input, .eternity-form .textbox-wrap .input-group .form-control {
  background-color: transparent;
  border: none;
}

.eternity-form .textbox-wrap .input-group input, .eternity-form .textbox-wrap .input-group .form-control, .eternity-form .textbox-wrap .input-group input:focus, .eternity-form .textbox-wrap .input-group .form-control:focus {
  box-shadow: none;
  outline: none;
}

.eternity-form .textbox-wrap .input-group [class^="icon-"], .eternity-form .textbox-wrap .input-group [class*=" icon-"], .eternity-form .textbox-wrap .input-group i {
  color: #cccccc;
}

.eternity-form .textbox-wrap.focused {
  border-left-color: #3498db;
  background-color: #f0f0f0;
  box-shadow: inset 0 0 3px rgba(0, 0, 0, .1);
}

.eternity-form .green-btn, .eternity-form .green-btn:hover, .eternity-form .blue-btn {
  background-color: #2ecc71;
  border: none;
}

.eternity-form .blue-btn, .eternity-form .blue-btn:hover {
  background-color: #2980b9;
}

.eternity-form .login-form-action {
  padding: 15px 20px 30px 20px;
}

.eternity-form input[type="checkbox"] {
  width: 30px;
}

.eternity-form .blue {
  color: #3498db;
}

.eternity-form .green {
  color: #2ecc71;
}

.eternity-form .login-form-links {
  padding: 20px;
  margin-top: 5px;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.4);
  background-color: white;
}

.eternity-form .login-form-links a.blue:hover, .eternity-form .login-form-links a a.blue:focus {
  color: #3498db;
  text-decoration: underline;
}

.eternity-form .login-form-links a.green:hover, .eternity-form .login-form-links a a.green:focus {
  color: #2ecc71;
  text-decoration: underline;
}

.eternity-form .forget-form-action {
  padding: 20px;
}

.eternity-form .registration-form-section {
  max-width: 620px;
  margin: 0 auto;
  width: 100%;
}

.eternity-form .form-control:-moz-placeholder {
  font-weight: 300;
}

.eternity-form .form-control::-moz-placeholder {
  font-weight: 300;
}

.eternity-form .form-control:-ms-input-placeholder {
  font-weight: 300;
}

.eternity-form .form-control::-webkit-input-placeholder {
  font-weight: 300;
}

/*#region ScrollBar Styles */

/*::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

::-webkit-scrollbar-track {
  background-color: rgba(113, 112, 107, 0.2);
}

::-webkit-scrollbar-thumb:vertical {
  background-color: rgba(0, 0, 0, 0.2);
}

::-webkit-scrollbar-thumb:vertical:hover, ::-webkit-scrollbar-thumb:horizontal:hover {
  background: white;
}

::-webkit-scrollbar-thumb:horizontal {
  background-color: rgba(0, 0, 0, 0.2);
}*/


text:
package app.components.semanticui

import japgolly.scalajs.react
import japgolly.scalajs.react.Children
import japgolly.scalajs.react.vdom.VdomNode

import scala.scalajs.js

object Segment {
  val component = react.JsComponent[js.Object, Children.Varargs, Null](SemanticUiComponents.Segment)

  def apply(stacked: js.UndefOr[Boolean] = js.undefined,
            style: js.UndefOr[js.Object] = js.undefined,
           )(children: VdomNode*) = {
    val props = js.Dynamic.literal(
      stacked = stacked,
      style = style
    )
    component(props)(children:_*)
  }
}


text:
/*! head.core - v1.0.2 */
/*
 * HeadJS     The only script in your <HEAD>
 * Author     Tero Piirainen  (tipiirai)
 * Maintainer Robert Hoffmann (itechnology)
 * License    MIT / http://bit.ly/mit-license
 * WebSite    http://headjs.com
 */
(function(win, undefined) {
    "use strict";

    // gt, gte, lt, lte, eq breakpoints would have been more simple to write as ['gt','gte','lt','lte','eq']
    // but then we would have had to loop over the collection on each resize() event,
    // a simple object with a direct access to true/false is therefore much more efficient
    var doc   = win.document,
        nav   = win.navigator,
        loc   = win.location,
        html  = doc.documentElement,
        klass = [],
        conf  = {
            screens   : [240, 320, 480, 640, 768, 800, 1024, 1280, 1440, 1680, 1920],
            screensCss: { "gt": true, "gte": false, "lt": true, "lte": false, "eq": false },
            browsers  : [
                            { ie: { min: 6, max: 11 } }
                           //,{ chrome : { min: 8, max: 33 } }
                           //,{ ff     : { min: 3, max: 26 } }
                           //,{ ios    : { min: 3, max:  7 } }
                           //,{ android: { min: 2, max:  4 } }
                           //,{ webkit : { min: 9, max: 12 } }
                           //,{ opera  : { min: 9, max: 12 } }
            ],
            browserCss: { "gt": true, "gte": false, "lt": true, "lte": false, "eq": true },
            html5     : true,
            page      : "-page",
            section   : "-section",
            head      : "head"
        };

    if (win.head_conf) {
        for (var item in win.head_conf) {
            if (win.head_conf[item] !== undefined) {
                conf[item] = win.head_conf[item];
            }
        }
    }

    function pushClass(name) {
        klass[klass.length] = name;
    }

    function removeClass(name) {
        // need to test for both space and no space
        // https://github.com/headjs/headjs/issues/270
        // https://github.com/headjs/headjs/issues/226
        var re = new RegExp(" ?\\b" + name + "\\b");
        html.className = html.className.replace(re, "");
    }

    function each(arr, fn) {
        for (var i = 0, l = arr.length; i < l; i++) {
            fn.call(arr, arr[i], i);
        }
    }

    // API
    var api = win[conf.head] = function() {
        api.ready.apply(null, arguments);
    };

    api.feature = function(key, enabled, queue) {

        // internal: apply all classes
        if (!key) {
            html.className += " " + klass.join(" ");
            klass = [];

            return api;
        }

        if (Object.prototype.toString.call(enabled) === "[object Function]") {
            enabled = enabled.call();
        }

        pushClass((enabled ? "" : "no-") + key);
        api[key] = !!enabled;

        // apply class to HTML element
        if (!queue) {
            removeClass("no-" + key);
            removeClass(key);
            api.feature();
        }

        return api;
    };

    // no queue here, so we can remove any eventual pre-existing no-js class
    api.feature("js", true);

    // browser type & version
    var ua     = nav.userAgent.toLowerCase(),
        mobile = /mobile|android|kindle|silk|midp|phone|(windows .+arm|touch)/.test(ua);

    // useful for enabling/disabling feature (we can consider a desktop navigator to have more cpu/gpu power)
    api.feature("mobile" , mobile , true);
    api.feature("desktop", !mobile, true);

    // http://www.zytrax.com/tech/web/browser_ids.htm
    // http://www.zytrax.com/tech/web/mobile_ids.html
    ua = /(chrome|firefox)[ \/]([\w.]+)/.exec(ua) || // Chrome & Firefox
        /(iphone|ipad|ipod)(?:.*version)?[ \/]([\w.]+)/.exec(ua) || // Mobile IOS
        /(android)(?:.*version)?[ \/]([\w.]+)/.exec(ua) || // Mobile Webkit
        /(webkit|opera)(?:.*version)?[ \/]([\w.]+)/.exec(ua) || // Safari & Opera
        /(msie) ([\w.]+)/.exec(ua) ||
        /(trident).+rv:(\w.)+/.exec(ua) || [];

    var browser = ua[1],
        version = parseFloat(ua[2]);

    switch (browser) {
    case "msie":
    case "trident":
        browser = "ie";
        version = doc.documentMode || version;
        break;

    case "firefox":
        browser = "ff";
        break;

    case "ipod":
    case "ipad":
    case "iphone":
        browser = "ios";
        break;

    case "webkit":
        browser = "safari";
        break;
    }

    // Browser vendor and version
    api.browser = {
        name: browser,
        version: version
    };
    api.browser[browser] = true;

    for (var i = 0, l = conf.browsers.length; i < l; i++) {
        for (var key in conf.browsers[i]) {
            if (browser === key) {
                pushClass(key);

                var min = conf.browsers[i][key].min;
                var max = conf.browsers[i][key].max;

                for (var v = min; v <= max; v++) {
                    if (version > v) {
                        if (conf.browserCss.gt) {
                            pushClass("gt-" + key + v);
                        }

                        if (conf.browserCss.gte) {
                            pushClass("gte-" + key + v);
                        }
                    } else if (version < v) {
                        if (conf.browserCss.lt) {
                            pushClass("lt-" + key + v);
                        }

                        if (conf.browserCss.lte) {
                            pushClass("lte-" + key + v);
                        }
                    } else if (version === v) {
                        if (conf.browserCss.lte) {
                            pushClass("lte-" + key + v);
                        }

                        if (conf.browserCss.eq) {
                            pushClass("eq-" + key + v);
                        }

                        if (conf.browserCss.gte) {
                            pushClass("gte-" + key + v);
                        }
                    }
                }
            } else {
                pushClass("no-" + key);
            }
        }
    }

    pushClass(browser);
    pushClass(browser + parseInt(version, 10));

    // IE lt9 specific
    if (conf.html5 && browser === "ie" && version < 9) {
        // HTML5 support : you still need to add html5 css initialization styles to your site
        // See: assets/html5.css
        each("abbr|article|aside|audio|canvas|details|figcaption|figure|footer|header|hgroup|main|mark|meter|nav|output|progress|section|summary|time|video".split("|"), function(el) {
            doc.createElement(el);
        });
    }

    // CSS "router"
    each(loc.pathname.split("/"), function(el, i) {
        if (this.length > 2 && this[i + 1] !== undefined) {
            if (i) {
                pushClass(this.slice(i, i + 1).join("-").toLowerCase() + conf.section);
            }
        } else {
            // pageId
            var id = el || "index", index = id.indexOf(".");
            if (index > 0) {
                id = id.substring(0, index);
            }

            html.id = id.toLowerCase() + conf.page;

            // on root?
            if (!i) {
                pushClass("root" + conf.section);
            }
        }
    });

    // basic screen info
    api.screen = {
        height: win.screen.height,
        width : win.screen.width
    };

    // viewport resolutions: w-100, lt-480, lt-1024 ...
    function screenSize() {
        // remove earlier sizes
        html.className = html.className.replace(/ (w-|eq-|gt-|gte-|lt-|lte-|portrait|no-portrait|landscape|no-landscape)\d+/g, "");

        // Viewport width
        var iw = win.innerWidth || html.clientWidth,
            ow = win.outerWidth || win.screen.width;

        api.screen.innerWidth = iw;
        api.screen.outerWidth = ow;

        // for debugging purposes, not really useful for anything else
        pushClass("w-" + iw);

        each(conf.screens, function(width) {
            if (iw > width) {
                if (conf.screensCss.gt) {
                    pushClass("gt-" + width);
                }

                if (conf.screensCss.gte) {
                    pushClass("gte-" + width);
                }
            } else if (iw < width) {
                if (conf.screensCss.lt) {
                    pushClass("lt-" + width);
                }

                if (conf.screensCss.lte) {
                    pushClass("lte-" + width);
                }
            } else if (iw === width) {
                if (conf.screensCss.lte) {
                    pushClass("lte-" + width);
                }

                if (conf.screensCss.eq) {
                    pushClass("e-q" + width);
                }

                if (conf.screensCss.gte) {
                    pushClass("gte-" + width);
                }
            }
        });

        // Viewport height
        var ih = win.innerHeight || html.clientHeight,
            oh = win.outerHeight || win.screen.height;

        api.screen.innerHeight = ih;
        api.screen.outerHeight = oh;

        // no need for onChange event to detect this
        api.feature("portrait" , (ih > iw));
        api.feature("landscape", (ih < iw));
    }

    screenSize();

    // Throttle navigators from triggering too many resize events
    var resizeId = 0;

    function onResize() {
        win.clearTimeout(resizeId);
        resizeId = win.setTimeout(screenSize, 50);
    }

    // Manually attach, as to not overwrite existing handler
    if (win.addEventListener) {
        win.addEventListener("resize", onResize, false);

    } else {
        // IE8 and less
        win.attachEvent("onresize", onResize);
    }
}(window));


text:
package cn.itcast_13;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class UploadServer {
	public static void main(String[] args) throws IOException {
		// 创建服务器Socket对象
		ServerSocket ss = new ServerSocket(19191);

		// 监听客户端连接
		Socket s = ss.accept();

		// 封装通道内流
		BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
		// 封装图片文件
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream("mn.jpg"));

		byte[] bys = new byte[1024];
		int len = 0;
		while ((len = bis.read(bys)) != -1) {
			bos.write(bys, 0, len);
			bos.flush();
		}

		// 给一个反馈
		OutputStream os = s.getOutputStream();
		os.write("图片上传成功".getBytes());

		bos.close();
		s.close();
	}
}


text:
set(target_libraries
  VTK_LIBRARIES
  CTKWidgets
  CTKVisualizationVTKCore
  )


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

from wagtail.wagtailcore.compat import AUTH_USER_MODEL, AUTH_USER_MODEL_NAME

class Migration(SchemaMigration):

    depends_on = (
        ("wagtailcore", "0002_initial_data"),
    )

    def forwards(self, orm):
        # Adding model 'Document'
        db.create_table(u'wagtaildocs_document', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('title', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('file', self.gf('django.db.models.fields.files.FileField')(max_length=100)),
            ('created_at', self.gf('django.db.models.fields.DateTimeField')
             (auto_now_add=True, blank=True)),
            ('uploaded_by_user', self.gf('django.db.models.fields.related.ForeignKey')
             (to=orm[AUTH_USER_MODEL], null=True, blank=True)),
        ))
        db.send_create_signal(u'wagtaildocs', ['Document'])

    def backwards(self, orm):
        # Deleting model 'Document'
        db.delete_table(u'wagtaildocs_document')

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        AUTH_USER_MODEL: {
            'Meta': {'object_name': AUTH_USER_MODEL_NAME},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'wagtaildocs.document': {
            'Meta': {'object_name': 'Document'},
            'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'uploaded_by_user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['%s']" % AUTH_USER_MODEL, 'null': 'True', 'blank': 'True'})
        }
    }

    complete_apps = ['wagtaildocs']


text:
- Replace the existing `Cordova` project in Eclipse with the Mobile SDK 3.3 `Cordova` project.
- Replace the existing `SalesforceSDK` project in Eclipse with the new `SalesforceSDK` project.
- If your app uses `SmartStore`, replace the existing `SmartStore` project in Eclipse with the new `SmartStore` project.
- If your app uses `SmartSync`, replace the existing `SmartSync` project in Eclipse with the new `SmartSync` project.
- Right click your project and select `Properties`.
- Click the `Android` tab and navigate to the library project section at the bottom.
- Replace the existing `SalesforceSDK` entry with the new `SalesforceSDK` project in your workspace.
- If your app uses `SmartStore`, repeat the previous step for the `SmartStore` project.
- If your app uses `SmartSync`, repeat the previous step for the `SmartSync` project.

## Upgrade steps from v. 3.2.x to v. 3.3 for hybrid apps

- Existing hybrid apps should continue to work with Mobile SDK 3.3.

See the [Mobile SDK Development Guide](https://github.com/forcedotcom/SalesforceMobileSDK-Shared/blob/master/doc/mobile_sdk.pdf?raw=true) for more information about developing hybrid apps with the 3.3 SDK and Cordova 3.6.4.


text:
<?php
/**
 * Database migration class
 *
 * @author David Vandemaele <david@tigron.be>
 */

class Migration_20180404_135343_Invoice_reminder_email extends \Skeleton\Database\Migration {

	/**
	 * Migrate up
	 *
	 * @access public
	 */
	public function up() {
		$setting = new Setting();
		$setting->name = 'invoice_reminder_email_window';
		$setting->value = 7;
		$setting->save();
	}

	/**
	 * Migrate down
	 *
	 * @access public
	 */
	public function down() {

	}
}


text:
package ru.job4j.bank;

public class User implements Comparable<User> {

    private String name;
    private String passport;

    public User(String name, String passport) {
        this.name = name;
        this.passport = passport;
    }

    public String getName() {
        return this.name;
    }

    public String getPassport() {
        return this.passport;
    }

    @Override
    public String toString() {
        return "User{" + "name: " + name + ", passport: " + passport + "}";
    }

    @Override
    public int hashCode() {
        return this.passport.hashCode();
    }

    @Override
    public boolean equals(java.lang.Object obj) {
        if (obj == this)
            return true;
        if (!(obj instanceof User))
            return false;
        User user = (User) obj;
        return (user.getName().equals(this.getName()))
                && (user.getPassport().equals(this.getPassport()));
    }

    @Override
    public int compareTo(User o) {
        return 0;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Alipay.Validators
{
    /// <summary>
    /// 表示必需参数的自定义属性。
    /// </summary>
    public class RequiredAttribute : System.Attribute
    {
        /// <summary>
        /// 初始化 Pay.RequiredAttribute 类的新实例。
        /// </summary>
        /// <param name="key">待检测参数的名称。</param>
        /// <exception cref="System.ArgumentNullException"></exception>
        public RequiredAttribute(string key)
        {
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key");

            this.Key = key;
        }

        /// <summary>
        /// 获取或设置待检测参数的名称。
        /// </summary>
        public string Key { get; set; }
    }
}


text:
namespace {

const char kGinJavaBridgeMessageFilterKey[] = "GinJavaBridgeMessageFilter";

}  // namespace

namespace content {

GinJavaBridgeMessageFilter::GinJavaBridgeMessageFilter(
    base::PassKey<GinJavaBridgeMessageFilter> pass_key,
    AgentSchedulingGroupHost& agent_scheduling_group)
    : BrowserMessageFilter(GinJavaBridgeMsgStart),
      agent_scheduling_group_(agent_scheduling_group),
      current_routing_id_(MSG_ROUTING_NONE) {}

GinJavaBridgeMessageFilter::~GinJavaBridgeMessageFilter() {
}

void GinJavaBridgeMessageFilter::OnDestruct() const {
  if (BrowserThread::CurrentlyOn(BrowserThread::UI)) {
    delete this;
  } else {
    GetUIThreadTaskRunner({})->DeleteSoon(FROM_HERE, this);
  }
}

bool GinJavaBridgeMessageFilter::OnMessageReceived(
    const IPC::Message& message) {
  DCHECK(JavaBridgeThread::CurrentlyOn());
  base::AutoReset<int32_t> routing_id(&current_routing_id_,
                                      message.routing_id());
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(GinJavaBridgeMessageFilter, message)
    IPC_MESSAGE_HANDLER(GinJavaBridgeHostMsg_GetMethods, OnGetMethods)
    IPC_MESSAGE_HANDLER(GinJavaBridgeHostMsg_HasMethod, OnHasMethod)
    IPC_MESSAGE_HANDLER(GinJavaBridgeHostMsg_InvokeMethod, OnInvokeMethod)
    IPC_MESSAGE_HANDLER(GinJavaBridgeHostMsg_ObjectWrapperDeleted,
                        OnObjectWrapperDeleted)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

scoped_refptr<base::SequencedTaskRunner>
GinJavaBridgeMessageFilter::OverrideTaskRunnerForMessage(
    const IPC::Message& message) {
  // As the filter is only invoked for the messages of the particular class,
  // we can return the task runner unconditionally.
  return JavaBridgeThread::GetTaskRunner();
}

void GinJavaBridgeMessageFilter::AddRoutingIdForHost(
      GinJavaBridgeDispatcherHost* host,
      RenderFrameHost* render_frame_host) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  base::AutoLock locker(hosts_lock_);
  hosts_[render_frame_host->GetRoutingID()] = host;
}

void GinJavaBridgeMessageFilter::RemoveHost(GinJavaBridgeDispatcherHost* host) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  base::AutoLock locker(hosts_lock_);
  auto iter = hosts_.begin();
  while (iter != hosts_.end()) {
    if (iter->second == host)
      hosts_.erase(iter++);
    else
      ++iter;
  }
}

void GinJavaBridgeMessageFilter::RenderProcessExited(
    RenderProcessHost* rph,
    const ChildProcessTerminationInfo& info) {
#if DCHECK_IS_ON()
  {
    scoped_refptr<GinJavaBridgeMessageFilter> filter =
        base::UserDataAdapter<GinJavaBridgeMessageFilter>::Get(
            &agent_scheduling_group_, kGinJavaBridgeMessageFilterKey);
    DCHECK_EQ(this, filter.get());
  }
#endif
  // Since the message filter is tied to the `agent_scheduling_group_`,
  // introducing the concept of an AgentSchedulingGroupHostObserver was under
  // consideration, but we did not go with this because:
  //   - For now, this would be the only user of it
  //   - We'd still be interested in responding to RenderProcessExited in the
  //     same way, so the new observer's event would end up just duplicating
  //     this observer method, which seemed unnecessary.
  // We may introduce this interface later once crbug.com/1141459 is fixed.
  rph->RemoveObserver(this);
  // While we're observing the `RenderProcessHost`, the message filter is 1:1
  // with `agent_scheduling_group_`, so at this point we must remove ourselves
  // from the user data, thus destroying `this`. If later the render process is
  // restarted and new frames are created, a new `GinJavaBridgeMessageFilter`
  // will be created and installed on the IPC channel associated with
  // `agent_scheduling_group_`.
  agent_scheduling_group_.RemoveUserData(kGinJavaBridgeMessageFilterKey);

  // DO NOT use `this` from here on, as the object has been destroyed.
}

// static
scoped_refptr<GinJavaBridgeMessageFilter> GinJavaBridgeMessageFilter::FromHost(
    AgentSchedulingGroupHost& agent_scheduling_group,
    bool create_if_not_exists) {
  scoped_refptr<GinJavaBridgeMessageFilter> filter =
      base::UserDataAdapter<GinJavaBridgeMessageFilter>::Get(
          &agent_scheduling_group, kGinJavaBridgeMessageFilterKey);
  if (!filter && create_if_not_exists) {
    filter = base::MakeRefCounted<GinJavaBridgeMessageFilter>(
        base::PassKey<GinJavaBridgeMessageFilter>(), agent_scheduling_group);
    agent_scheduling_group.AddFilter(filter.get());
    agent_scheduling_group.GetProcess()->AddObserver(filter.get());

    agent_scheduling_group.SetUserData(
        kGinJavaBridgeMessageFilterKey,
        std::make_unique<base::UserDataAdapter<GinJavaBridgeMessageFilter>>(
            filter.get()));
  }
  return filter;
}

scoped_refptr<GinJavaBridgeDispatcherHost>
GinJavaBridgeMessageFilter::FindHost() {
  base::AutoLock locker(hosts_lock_);
  auto iter = hosts_.find(current_routing_id_);
  if (iter != hosts_.end())
    return iter->second;
  // Not being able to find a host is OK -- we can receive messages from
  // RenderFrames for which the corresponding host part has already been
  // destroyed. That means, any references to Java objects that the host was
  // holding were already released (with the death of WebContents), so we
  // can just ignore such messages.
  // RenderProcessHostImpl does the same -- if it can't find a listener
  // for the message's routing id, it just drops the message silently.
  // The only action RenderProcessHostImpl does is sending a reply to incoming
  // synchronous messages, but as we handle all our messages using
  // IPC_MESSAGE_HANDLER, the reply will be sent automatically.
  return nullptr;
}

void GinJavaBridgeMessageFilter::OnGetMethods(
    GinJavaBoundObject::ObjectID object_id,
    std::set<std::string>* returned_method_names) {
  DCHECK(JavaBridgeThread::CurrentlyOn());
  scoped_refptr<GinJavaBridgeDispatcherHost> host = FindHost();
  if (host) {
    host->OnGetMethods(object_id, returned_method_names);
  } else {
    *returned_method_names = std::set<std::string>();
  }
}

void GinJavaBridgeMessageFilter::OnHasMethod(
    GinJavaBoundObject::ObjectID object_id,
    const std::string& method_name,
    bool* result) {
  DCHECK(JavaBridgeThread::CurrentlyOn());
  scoped_refptr<GinJavaBridgeDispatcherHost> host = FindHost();
  if (host) {
    host->OnHasMethod(object_id, method_name, result);
  } else {
    *result = false;
  }
}

void GinJavaBridgeMessageFilter::OnInvokeMethod(
    GinJavaBoundObject::ObjectID object_id,
    const std::string& method_name,
    const base::ListValue& arguments,
    base::ListValue* wrapped_result,
    content::GinJavaBridgeError* error_code) {
  DCHECK(JavaBridgeThread::CurrentlyOn());
  scoped_refptr<GinJavaBridgeDispatcherHost> host = FindHost();
  if (host) {
    host->OnInvokeMethod(current_routing_id_, object_id, method_name, arguments,
                         wrapped_result, error_code);
  } else {
    wrapped_result->GetList().Append(base::Value());
    *error_code = kGinJavaBridgeRenderFrameDeleted;
  }
}

void GinJavaBridgeMessageFilter::OnObjectWrapperDeleted(
    GinJavaBoundObject::ObjectID object_id) {
  DCHECK(JavaBridgeThread::CurrentlyOn());
  scoped_refptr<GinJavaBridgeDispatcherHost> host = FindHost();
  if (host)
    host->OnObjectWrapperDeleted(current_routing_id_, object_id);
}

}  // namespace content


text:
Date: Thu, 21 Nov 1996 22:10:47 GMT
Server: Apache/1.1.1
Content-type: text/html
Content-length: 4402
Last-modified: Fri, 11 Nov 1994 13:02:28 GMT

<TITLE> Kathryn Stockton's Home Page </TITLE>

 Kathryn Stockton

<!WA0>

<!WA1>

Contact Information

<address> Kathryn Stockton </address>
<address> e-mail (Atlanta, Georgia): kathryn@cc.gatech.edu </address>
<address> e-mail (Portland, Oregon): kathryn@metheus.com </address>

<!WA2>

Kathryn Stockton was a Master's student in the
<!WA3>
College of Computing  at
<!WA4> Georgia Tech
and graduated September 1994.
She was working at the
<!WA5>
Graphics, Visualization and Usability Center (GVU), in the
<!WA6>
Multimedia Computing Group .

Ms. Stockton's main areas of research interest include Software Engineering
and User Interface Design.  She was working on
<!WA7>
Mercator, which is a project that provides access to
graphical interfaces for people who are blind.

Ms. Stockton is currently working at Metheus (link soon available),
located in Beaverton, Oregon.
Click for a copy of her <!WA8>resume.

<!WA9>

Software Engineering Links

<!WA10>
<!WA11>
Software ReEngineering
<!WA12>

<!WA13>
<!WA14>
A Software Engineering Virtual Library

<!WA15>
<!WA16>
SEI
<!WA17>

<!WA18>

User Interface Design Links

<!WA19>
<!WA20>
The HCI Bibliography Project

<!WA21>

Personal

<!WA22>
I moved to
<!WA23>
Portland, Oregon

 in September 1994!

<!WA24>
My cat
<!WA25>
Tasha
<!WA26>
.

<!WA27>

Interesting Places

<!WA28>
The Weather:

<!WA29>
Atlanta
<!WA30>
 vs.
<!WA31>
Portland

<!WA32>
<!WA33>
Stock Quotes
<!WA34>

<!WA35>
<!WA36>
Electronic Newsstand

<!WA37>
<!WA38>
Wired Magazine
<!WA39>

<!WA40>
<!WA41>
 Women in Computer Science
<!WA42>

<!WA43>
And of course the people in the Multimedia lab:

<!WA44>
Stacy
<!WA45>,

<!WA46>
Ian
<!WA47>,

<!WA48>
Keith
<!WA49>,

<!WA50>
Lisa
<!WA51>,

and
<!WA52>
Beth
<!WA53>

<!WA54>


text:
package org.kuali.rice.krad.bo;

import org.kuali.rice.core.api.mo.common.GloballyUnique;
import org.kuali.rice.core.api.mo.common.Versioned;

import java.util.Collection;
import java.util.List;
import java.util.UUID;

/**
 * Declares a common interface for all {@link BusinessObject} classes which can have their
 * state persisted.  A business object which is persistable defines some additional methods
 * which allow for various operations to be executed that relate to the persistent nature of
 * the business object.  A persistable business object also has some additional data
 * attributes which include the version number, the object id, and the extension.
 *
 *
The version number indicates the version of the business object when it was retrieved
 * from persistent storage.  This allows for services to check this version number
 * during persistence operations to prevent silent overwrites of business object state.
 * These kinds of scenarios might arise as a result of concurrent modification to the business
 * object in the persistent store (i.e. two web application users updating the same record
 * in a database).  The kind of check which would be performed using the version number is commonly
 * referred to as "optimistic locking".
 *
 *
The object id represents a globally unique identifier for the business object.  In practice,
 * this can be used by other portions of the system to link to persistable business objects which
 * might be stored in different locations or even different persistent data stores.  In general, it
 * is not the responsibility of the client who implements a persistable business object to handle
 * generating this value.  The framework will handle this automatically at the point in time when
 * the business object is persisted.  If the client does need to do this themselves, however, care
 * should be taken that an appropriate globally unique value generator algorithm is used
 * (such as the one provided by {@link UUID}).
 *
 *
The extension object is primarily provided for the purposes of allowing implementer
 * customization of the business object without requiring the original business object to be
 * modified.  The additional {@link PersistableBusinessObjectExtension} which is linked with the
 * parent business object can contain additional data attributes and methods.  The framework will
 * automatically request that this extension object be persisted when the parent business object
 * is persisted.  This is generally the most useful in cases where an application is defining
 * business objects that will be used in redistributable software packages (such as the
 * actual Kuali Foundation projects themselves).  If using the framework for the purposes
 * of implementing an internal application, the use of a business object extensions
 * is likely unnecessary.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public interface PersistableBusinessObject extends BusinessObject, Versioned, GloballyUnique {

    /**
     * Sets the business object's version number.  It is rarely advisable
     * for client code to manually set this value as the framework should
     * generally handle the management of version numbers internally.
     *
     * @param versionNumber the version number to set on this business object
     */
    public void setVersionNumber(Long versionNumber);

    /**
     * Sets the unique identifier for the object
     *
     * @param objectId
     */
    public void setObjectId(String objectId);

    public PersistableBusinessObjectExtension getExtension();

    public void setExtension(PersistableBusinessObjectExtension extension);

    /**
     * @see BusinessObject#refresh()
     */
    public abstract void refreshNonUpdateableReferences();

    /**
     * This method is used to refresh a reference object that hangs off of a document. For example, if the attribute's keys were
     * updated for a reference object, but the reference object wasn't, this method would go out and retrieve the reference object.
     *
     * @param referenceObjectName
     */
    public abstract void refreshReferenceObject(String referenceObjectName);

    /**
     * If this method is not implemented appropriately for PersistableBusinessObject with collections, then PersistableBusinessObject with collections will not persist deletions correctly.
     * Elements that have been deleted will reappear in the DB after retrieval.
     *
     * @return List of collections which need to be monitored for changes by OJB
     */
    public List<Collection<PersistableBusinessObject>> buildListOfDeletionAwareLists();

    /**
     * Returns the boolean indicating whether this record is a new record of a maintenance document collection.
     * Used to determine whether the record can be deleted on the document.
     */
    public boolean isNewCollectionRecord();

    /**
     * Sets the boolean indicating this record is a new record of a maintenance document collection.
     * Used to determine whether the record can be deleted on the document.
     */
    public void setNewCollectionRecord(boolean isNewCollectionRecord);

    /**
     * Hook to link in any editable user fields.
     */
    public void linkEditableUserFields();

}


text:
emChunk - NP Chunker

About the tool

What is it good for? What does it do?

emChunk produces two types of output: i) it identifies maximal NPs in the text and ii) it identifies all kinds of phrases in the text.

What is the input?

Texts that had previously been processed in the toolchain, i.e.: i) they had been segmented into words and sentences
                ii) words are assigned their full morphological analyses. These pieces of information are neccesary for the NP Chunker module to be effective.

What is the output?

The module assigns a tag to every token in a text that had been segmented into words and sentences. Depending on the two modes of analysis two kinds of tags are possible.

In the first case the tag indicates  i) whether the word is part of a maximal noun phrase (NP), and if yes,  ii) whether the NP has a single or more components. If the latter, it also indicates iii) whether the given word is an initial, medial or final component of the NP.
                In the second case the tag indicates i) whether the given word is part of any phrase, if yes ii) what kind of phrase it is part of, iii) whether the phrase has a single or more components, and if the latter, iv) whether the word is an initial, medial or final component of the NP.
                The output keeps  the analyses of the previous processing levels, and adds the tags of the chunker module.

An example:

In the first mode we are looking for  maximal NPs in the text, i.e. NPs that are not part of any higher level NPs.

In the example sentences we can find two maximal NPs and two units represented with O -- these latter ones are not NPs. 'B' stands for tokens at the beginning of phrases (initial elements), 'I'  for medial / internal elements, and 'E' for final elements.

A szállásunk egy Balaton melletti kis üdülőfaluban, Zamárdiban volt.

                        A
                        B-NP

                        szállásunk
                        E-NP

                        egy
                        B-NP

                        Balaton
                        I-NP

                        melletti
                        I-NP

                        kis
                        I-NP

                        üdülőfaluban
                        I-NP

                        ,
                        I-NP

                        Zamárdiban
                        E-NP

                        volt
                        O

                        .
                        O

In the second way of operation we are identifying every kind of phrase in the sentence..

In the sentence above we can find an NP with two components, an NP with a single component, and an ADVP (adverbial phrase) with two components:

Az osztály már csütörtökön fel volt villanyozva.

                        Az
                        B-NP

                        osztály
                        E-NP

                        már
                        1-ADVP

                        csütörtökön
                        1-NP

                        teljesen
                        1-ADVP

                        fel
                        O

                        volt
                        O

                        villanyozva
                        O

                        .
                        O

For developers

                        Source
                        https://github.com/ppke-nlpg/HunTag3

                        Source code
                        Python 3

                        Input format
                        Plain text file in UTF-8  character encoding, one row - one word format, sentence boundaries marked by an empty line, first column containing the word, with each annotation tag following it in columns separated by tabs.

                        Output formátum
                        Plain text file in UTF-8  character encoding, one row - one word format, sentence boundaries marked by an empty line, first column containing the word, with each annotation tag following it in columns separated by tabs; the last columns containing the Chunker tags.

                        Execution
                        See the README file: https://github.com/ppke-nlpg/HunTag3

                        Licence
                        GNU Lesser General Public License v3.0


text:
/*
 * Created on Aug 19, 2004
 *
 *
 */
package applications;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import java.io.*;
import java.util.*;
import java.nio.channels.*;

import data.LinguisticDataAbstract;

import morph.Decomposition;
import morph.MorphInuk;

/**
 * @author Marta
 *
 */
public class DecomposeHansardTest extends TestCase {

	String fileGoldStandard = "ressources/goldstandardHansard.txt";
	String fileTargetSuccessfulAnalysis = "ressources/target_successful_analysis_";
	String fileSuccessfulAnalysis = "outputFiles/successful_analysis_";
	String fileFailedAnalysis = "outputFiles/failed_analysis_";
	String filePrevSuccessNowFailedAnalysis = "outputFiles/previous_success_now_failed_analysis_";
	String fileFullSuccessfulAnalysis = "outputFiles/full_successful_analysis_";

	BufferedReader readerGoldStandard;
	BufferedReader readerTargetSuccessfulAnalysis;

	BufferedWriter writerSuccessfulAnalysis;
	BufferedWriter writerFullSuccessfulAnalysis;
	BufferedWriter writerFailedAnalysis;
	BufferedWriter writerPrevSuccessNowFailedAnalysis;

	Hashtable hashTargetSuccessfulAnalysis = null;

	Hashtable errorMessages = new Hashtable();

	Vector newSuccessfullyAnalyzedWords = new Vector();

	int nbWordsToBeAnalyzed = 0;
	int nbSuccessfulAnalyses = 0;
	int nbNewSuccessfulAnalyses = 0;
	int nbPrevSuccessNowFailedAnalyses = 0;
	int nbFailedAnalyses = 0;
	int nbTargetSuccessfulAnalyses = -1;

	static final int decompositionNotFoundInGoldStandard = 1;
	static final int hasFailedButPreviouslySucceded = 2;
	static final int hasFailed = 3;
	static final int hasMoreSuccessfulAnalyses = 4;

	/*
	 * @see TestCase#setUp()
	 */
	protected void setUp() throws Exception {
		super.setUp();
		fileTargetSuccessfulAnalysis += this.getClass().getSimpleName() + ".txt";
		fileSuccessfulAnalysis += this.getClass().getSimpleName() + ".txt";
		fileFailedAnalysis += this.getClass().getSimpleName() + ".txt";
		filePrevSuccessNowFailedAnalysis += this.getClass().getSimpleName() + ".txt";
		fileFullSuccessfulAnalysis += this.getClass().getSimpleName() + ".txt";
	}

	/*
	 * This method reads goldstandard.txt line by line, sends the word to be analyzed to
	 *  decomposeWord. The word was analyzed if decomposeWord returns a non-empty array.
	 * In that case it should compare each array element to the decomposition in the gold standard.
	 * If it's the same, it's written in the succesful_analysis file. If not, we consider it as a failure,
	 * the word and its decompositions are put in a failed_analysis file.
	 *
	 *
	 * If the array is empty, the analysis failed. In that case it should be checked if
	 * it was previously successful by checking the appropriate hashtable. If yes, it should be
	 * written in a prev_succes_now_failed_analysis file.  If not, it's written in a failed_analysis file.
	 *
	 */

	public void testDecomposer() throws Exception {
//		Debogage.init();
		LinguisticDataAbstract.init("csv");
		openFilesForReadingAndWriting ();
		StringTokenizer st;

		System.out.println("Analyzing the words. Please wait ...");

		Calendar startCalendar = Calendar.getInstance();

		while ((st=readLine(readerGoldStandard)) != null) {
		    boolean noProcessing = false;
		    String wordId = st.nextToken();
			String wordToBeAnalyzed = st.nextToken();
			String goldStandardDecomposition = st.nextToken();
			System.out.print("> :"+wordToBeAnalyzed+":");
			Decomposition [] decs = null;
			/*
			 * *x: x is a proper name of some sort
			 * ?x: x's real decomposition is unknown
			 * #x: x is known to contain an error, typo or orthographic
			 *
			 * Those x words are not analyzed in this test.
			 *
			 * @x: x is not to be considered only in the test destined to users
			 */
			if (!wordId.startsWith("*") && !wordId.startsWith("?") && !wordId.startsWith("#")) {
                try {
                    decs = MorphInuk.decomposeWord(wordToBeAnalyzed);
                } catch (OutOfMemoryError e) {
                    decs = new Decomposition[]{};
                    System.out.print(" Out of memory error");
                }
                nbWordsToBeAnalyzed++;
                System.out.println(" []");
            } else {
			    noProcessing = true;
				System.out.println(" [x]");
			}

			if (noProcessing) {

			}
			//No decompositions: the analyzer fails to decompose the word
        	else if (decs.length == 0) {
        	    // Either the word was previously analyzed with success and now failed,
        	    // or it was not analyzed with success.
        		if (hashTargetSuccessfulAnalysis != null && hashTargetSuccessfulAnalysis.containsKey(wordId)){
            		//if it was previously successful and now it failed write the word in the appropriate file
            		//the test is red
        			writerPrevSuccessNowFailedAnalysis.write(wordId);
        			writerPrevSuccessNowFailedAnalysis.newLine();
        			writerFailedAnalysis.write("!!!" + wordId + " " + wordToBeAnalyzed + "------------------------");
        			writerFailedAnalysis.newLine();
        			writerFailedAnalysis.write(">>>" + goldStandardDecomposition);
        			writerFailedAnalysis.newLine();
        			writerFailedAnalysis.newLine();
        			writeErrorMessage(hasFailedButPreviouslySucceded);
        			nbPrevSuccessNowFailedAnalyses++;
        		} else {
        		//if it failed as before write it in the appropriate file
        			writerFailedAnalysis.write(wordId + " "+ wordToBeAnalyzed + "------------------------");
        			writerFailedAnalysis.newLine();
        			writerFailedAnalysis.write(">>>" + goldStandardDecomposition);
        			writerFailedAnalysis.newLine();
        			writerFailedAnalysis.newLine();
//        			writeErrorMessage(hasFailed);
        		}
    			nbFailedAnalyses++;
        	} else {
        		//the analyzer returned a decomposition (or decompositions)
        		//now we test to see if one of them matches the one in goldstandard.txt
        		int i;
        		for (i = 0; i < decs.length; i++) {
//        			if (decs[i].toStrSimple().equals(goldStandardDecomposition)){
            	    if (decs[i].toStr2().equals(goldStandardDecomposition)){
        			    // Successful analysis
        				writerSuccessfulAnalysis.write(wordId + " " + wordToBeAnalyzed + " " + goldStandardDecomposition + " " + (i+1));
        				writerSuccessfulAnalysis.newLine();
        				if (hashTargetSuccessfulAnalysis != null &&
        				        !hashTargetSuccessfulAnalysis.containsKey(wordId)) {
        				    // New successful analysis
        				    writeErrorMessage(hasMoreSuccessfulAnalyses);
        				    newSuccessfullyAnalyzedWords.add(wordId);
        				    nbNewSuccessfulAnalyses++;
        				}
        				nbSuccessfulAnalyses++;
        				// Write the full decomposition in file 'full_successful_analysis_Decomposer...Test.txt'
        				writerFullSuccessfulAnalysis.write(wordId+" "+wordToBeAnalyzed+" "+decs[i].toStr2());
        				writerFullSuccessfulAnalysis.newLine();
        				writerFullSuccessfulAnalysis.flush();
                		break; //this is to avoid repetitions, as we can have same decompositions for one word. toStr method avoids this, but here we're using toString
        			}
        		}

        		//if the counter for the for loop reaches decs.length, that means that neither of the decompositions was equal to the gold standard one
        		if (i == decs.length){
        		    // Failure
            		//if it was previously successful and now it failed write the word in the appropriate file
            		//the test is red
            		if (hashTargetSuccessfulAnalysis != null && hashTargetSuccessfulAnalysis.containsKey(wordId)){
            			writerPrevSuccessNowFailedAnalysis.write(wordId);
            			writerPrevSuccessNowFailedAnalysis.newLine();
            			writerFailedAnalysis.write("!!!" + wordId + " " + wordToBeAnalyzed + "------------------------");
            			writerFailedAnalysis.newLine();
            			writerFailedAnalysis.write(">>>" + goldStandardDecomposition);
            			writerFailedAnalysis.newLine();
            			for (i = 0; i < decs.length; i++) {
//            				writerFailedAnalysis.write(decs[i].toStr2());
            				writerFailedAnalysis.newLine();
            			}
            			writerFailedAnalysis.newLine();
            			writeErrorMessage(hasFailedButPreviouslySucceded);
            			nbPrevSuccessNowFailedAnalyses++;
            		} else {
            		//write it in the appropriate file
            			writerFailedAnalysis.write(wordId + " " + wordToBeAnalyzed + "------------------------");
            			writerFailedAnalysis.newLine();
            			writerFailedAnalysis.write(">>>" + goldStandardDecomposition);
            			writerFailedAnalysis.newLine();
            			for (i = 0; i < decs.length; i++) {
//            				writerFailedAnalysis.write(decs[i].toStr2());
            				writerFailedAnalysis.newLine();
            			}
            			writerFailedAnalysis.newLine();
//            			writeErrorMessage(hasFailed);
            		}
        			nbFailedAnalyses++;
    			}
        	}
		}

		Calendar endCalendar = Calendar.getInstance();

		long time = endCalendar.getTimeInMillis() - startCalendar.getTimeInMillis();

		float percentageSuccessfulAnalyses = (float)nbSuccessfulAnalyses / (float)nbWordsToBeAnalyzed;
		writerSuccessfulAnalysis.write("--- ");
		writerSuccessfulAnalysis.write(new Integer(nbSuccessfulAnalyses).toString());
		writerSuccessfulAnalysis.write(" /");
		writerSuccessfulAnalysis.write(new Integer(nbWordsToBeAnalyzed).toString());
		writerSuccessfulAnalysis.write(" ");
		writerSuccessfulAnalysis.write(Float.toString(percentageSuccessfulAnalyses));
		writerSuccessfulAnalysis.newLine();
		closeFiles();
		System.out.println("Done.\n");
		System.out.println("Nb. of successful analyses: "+nbSuccessfulAnalyses+" /"+nbWordsToBeAnalyzed+" ("+ nbTargetSuccessfulAnalyses + ")");
		System.out.println("Success rate: " + Float.toString(percentageSuccessfulAnalyses));
		System.out.println();
		System.out.println("Nb. of successful analyses: "+nbSuccessfulAnalyses);
		System.out.println("Nb. of new successful analyses: "+nbNewSuccessfulAnalyses);
		System.out.println("Nb. of failed analyses: "+nbFailedAnalyses);
		System.out.println("Nb. of previous successful now failed analyses: "+nbPrevSuccessNowFailedAnalyses);
        if (newSuccessfullyAnalyzedWords.size() != 0) {
            StringBuffer words = new StringBuffer();
            words.append("\nNew successfully analyzed words: ");
            for (int m = 0; m < newSuccessfullyAnalyzedWords.size(); m++)
                words.append((String) newSuccessfullyAnalyzedWords.elementAt(m)
                        + " ");
            words.append("\n");
            System.out.println(words);
        }

		System.out.println("");
		System.out.println("Time in milliseconds: "+time);

		String errorMessagesForPrint =  printErrorMessages(errorMessages);
		//The test is red if at least one error message is produced
		assertTrue("\nThe following error messages were produced by this analysis: \n" + errorMessagesForPrint, errorMessages.isEmpty());
	}

	protected void writeErrorMessage(int key) {
        if (!errorMessages.containsKey(new Integer(key))) {
            switch (key) {
            case decompositionNotFoundInGoldStandard:
                errorMessages
                        .put(
                                new Integer(key),
                                "--- Check the file "
                                        + fileFailedAnalysis
                                        + " for the words that were decomposed but whose decomposition is different from the gold standard one.\n");
                break;
            case hasFailedButPreviouslySucceded:
                errorMessages
                        .put(
                                new Integer(key),
                                "--- Check the file "
                                        + filePrevSuccessNowFailedAnalysis
                                        + " for a list of words whose analysis previously succeeded but now fails.\n"
                                        + "The same words can be found in the file "
                                        + fileFailedAnalysis
                                        + " marked with !!!.\n");
                break;
            case hasFailed:
                errorMessages
                        .put(
                                new Integer(key),
                                "--- Check the file "
                                        + fileFailedAnalysis
                                        + " for a list of words whose analysis failed. The gold standard decomposition is marked with >>>.\n");
                break;
            case hasMoreSuccessfulAnalyses:
                errorMessages.put(new Integer(key),
                        "--- More successful analyses.  Copy the file "
                                + fileSuccessfulAnalysis + " to the file "
                                + fileTargetSuccessfulAnalysis + ".\n");
                break;
            }
        }
    }

	protected String printErrorMessages (Hashtable hashOfErrorMessages) {
		String errorMessagesForPrint = "";
		if (!hashOfErrorMessages.isEmpty()) {
			Object[] arrayOfErrorMessages = hashOfErrorMessages.values().toArray();
			for (int i = 0; i < hashOfErrorMessages.size(); i++){
				System.out.println((String)arrayOfErrorMessages[i]);
				errorMessagesForPrint = errorMessagesForPrint.concat((String)arrayOfErrorMessages[i]);
			}
		}
		return errorMessagesForPrint;
	}

	protected void openFilesForReadingAndWriting () throws Exception {
		try {
			readerGoldStandard = new BufferedReader(new FileReader(fileGoldStandard));
		} catch (FileNotFoundException e) {
			System.out.println("The file goldstandard.txt is not found in the *ressources* folder. Move it there and try again.");
			System.exit(1);
		}
		try {
			readerTargetSuccessfulAnalysis = new BufferedReader(new FileReader(fileTargetSuccessfulAnalysis));
			createHashTargetSuccessfulAnalysis ();
			readerTargetSuccessfulAnalysis.close();
		} catch (Exception e) {
			readerTargetSuccessfulAnalysis = null;
			System.out.println("Only for the first run the file " + fileTargetSuccessfulAnalysis + " cannot be found. If this is not the first run, something is wrong.");
		}

		writerSuccessfulAnalysis = new BufferedWriter(new FileWriter(fileSuccessfulAnalysis));
		writerFullSuccessfulAnalysis = new BufferedWriter(new FileWriter(fileFullSuccessfulAnalysis));
		writerFailedAnalysis = new BufferedWriter(new FileWriter(fileFailedAnalysis));
		writerPrevSuccessNowFailedAnalysis = new BufferedWriter(new FileWriter(filePrevSuccessNowFailedAnalysis));
	}

	protected void closeFiles () throws IOException {
		readerGoldStandard.close();

		writerSuccessfulAnalysis.close();
		writerFullSuccessfulAnalysis.close();
		writerFailedAnalysis.close();
		writerPrevSuccessNowFailedAnalysis.close();

		//copyFile(new File(fileSuccessfulAnalysis), new File(filePreviousSuccessfulAnalysis));
		//(new File(fileSuccessfulAnalysis)).delete();
	}

	protected StringTokenizer readLine(BufferedReader bufReader) throws IOException {
		String line = bufReader.readLine();
		StringTokenizer st;
		if (line != null) {
			st = new StringTokenizer (line);
		} else {
			return null;
		}
		return st;
	}

	protected void createHashTargetSuccessfulAnalysis () throws IOException {
		hashTargetSuccessfulAnalysis = new Hashtable();
		StringTokenizer st;
		while ((st=readLine(readerTargetSuccessfulAnalysis)) != null) {
		    String wordId = st.nextToken();
		    if (hashTargetSuccessfulAnalysis.containsKey(wordId))
		        System.out.println("***************"+wordId+"****************");
		    if (wordId.equals("---")) {
//		        nbTargetSuccessfulAnalyses = new Integer(st.nextToken()).intValue();
		        nbTargetSuccessfulAnalyses = hashTargetSuccessfulAnalysis.size();
		    } else {
		        String x[] = new String[]{st.nextToken(),st.nextToken()};
		        hashTargetSuccessfulAnalysis.put(wordId,x);
		    }
		}
	}

	protected void copyFile(File in, File out) throws IOException {
	     FileChannel sourceChannel = new FileInputStream(in).getChannel();
	     FileChannel destinationChannel = new FileOutputStream(out).getChannel();
	     sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
	     sourceChannel.close();
	     destinationChannel.close();
	}

	public static Test suite() {

		/* Junit uses reflexion to add automatically all the methods of TestFoo

		whose name begins by "test"

		*/

		return new TestSuite(DecomposeHansardTest.class);

    }

	public static void main(String [] args) {
		junit.textui.TestRunner.run(suite());	}

}