text:
// -------------------------------------------------------------------------------------------------
// <copyright file="Validate.cs" author="Christopher Sellers">
//   Copyright (C) 2017. All rights reserved.
//   https://github.com/cjdsellers/FuzzyLogic
//   the use of this source code is governed by the Apache 2.0 license
//   as found in the LICENSE.txt file.
// </copyright>
// -------------------------------------------------------------------------------------------------

namespace FuzzyLogic.Utility
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using FuzzyLogic.Annotations;
    using FuzzyLogic.Fuzzification;

    /// <summary>
    /// The immutable static <see cref="Validate"/> class.
    /// </summary>
    [Immutable]
    internal static class Validate
    {
        /// <summary>
        /// Validates that the given argument is not null.
        /// </summary>
        /// <param name="argument">
        /// The argument.
        /// </param>
        /// <param name="paramName">
        /// The parameter name.
        /// </param>
        /// <typeparam name="T">
        /// The argument type.
        /// </typeparam>
        /// <exception cref="ArgumentNullException">
        /// Throws if the argument is null.
        /// </exception>
        [DebuggerStepThrough]
        internal static void NotNull<T>(T argument, string paramName)
        {
            if (argument == null)
            {
                throw new ArgumentNullException(paramName);
            }
        }

        /// <summary>
        /// Validates that the given string is not null.
        /// </summary>
        /// <param name="argument">
        /// The argument.
        /// </param>
        /// <param name="paramName">
        /// The param name.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Throws if the string is null or white space.
        /// </exception>
        [DebuggerStepThrough]
        internal static void NotNull(string argument, string paramName)
        {
            if (string.IsNullOrWhiteSpace(argument))
            {
                throw new ArgumentNullException(paramName);
            }
        }

        /// <summary>
        /// Validates that the given collection is not null or empty.
        /// </summary>
        /// <param name="collection">
        /// The collection.
        /// </param>
        /// <param name="paramName">
        /// The param name.
        /// </param>
        /// <typeparam name="T">
        /// The type.
        /// </typeparam>
        /// <exception cref="ArgumentNullException">
        /// Throws if the collection is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// Throws if the collection is empty.
        /// </exception>
        [DebuggerStepThrough]
        internal static void CollectionNotNullOrEmpty<T>(ICollection<T> collection, string paramName)
        {
            if (collection == null)
            {
                throw new ArgumentNullException(
                    paramName, $"The {paramName} collection is null.");
            }

            if (collection.Count == 0)
            {
                throw new ArgumentException(
                    $"The {paramName} collection is empty.", paramName);
            }
        }

        /// <summary>
        /// Validates that the collection is not null, or empty (count zero).
        /// </summary>
        /// <param name="collection">
        /// The collection.
        /// </param>
        /// <param name="paramName">
        /// The parameter name.
        /// </param>
        /// <typeparam name="T">
        /// The type of collection.
        /// </typeparam>
        /// <exception cref="ArgumentNullException">
        /// Throws if the collection is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// Throws if the collection is empty.
        /// </exception>
        [DebuggerStepThrough]
        internal static void CollectionEmpty<T>(ICollection<T> collection, string paramName)
        {
            if (collection == null)
            {
                throw new ArgumentNullException(
                    paramName, $"The {paramName} collection is null.");
            }

            if (collection.Count != 0)
            {
                throw new ArgumentException(
                    $"The {paramName} collection is not empty.", paramName);
            }
        }

        /// <summary>
        /// Validates that the collection contains the element.
        /// </summary>
        /// <param name="element">
        /// The element.
        /// </param>
        /// <param name="paramName">
        /// The parameter name.
        /// </param>
        /// <param name="collection">
        /// The collection.
        /// </param>
        /// <typeparam name="T">
        /// The type of collection.
        /// </typeparam>
        /// <exception cref="ArgumentException">
        /// Throws if the collection does not contain the element.
        /// </exception>
        [DebuggerStepThrough]
        internal static void CollectionContains<T>(T element, string paramName, ICollection<T> collection)
        {
            if (!collection.Contains(element))
            {
                throw new ArgumentException(
                    $"The collection does not contain the {paramName} element.", paramName);
            }
        }

        /// <summary>
        /// Validates that the collection does not contain the element.
        /// </summary>
        /// <param name="element">
        /// The element.
        /// </param>
        /// <param name="paramName">
        /// The parameter name.
        /// </param>
        /// <param name="collection">
        /// The collection.
        /// </param>
        /// <typeparam name="T">
        /// The type of collection.
        /// </typeparam>
        /// <exception cref="ArgumentException">
        /// Throws if the collection contains the element.
        /// </exception>
        [DebuggerStepThrough]
        internal static void CollectionDoesNotContain<T>(T element, string paramName, ICollection<T> collection)
        {
            if (collection.Contains(element))
            {
                throw new ArgumentException(
                    $"The collection already contains the {paramName} element.", paramName);
            }
        }

        /// <summary>
        /// Validates that the dictionary contains the key.
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <param name="paramName">
        /// The parameter name.
        /// </param>
        /// <param name="collection">
        /// The collection.
        /// </param>
        /// <typeparam name="T1">
        /// The type of the keys.
        /// </typeparam>
        /// <typeparam name="T2">
        /// The type of the values
        /// </typeparam>
        /// <exception cref="ArgumentException">
        /// Throws if the dictionary does not contain the key.
        /// </exception>
        [DebuggerStepThrough]
        internal static void DictionaryContainsKey<T1, T2>(T1 key, string paramName, IDictionary<T1, T2> collection)
        {
            if (!collection.ContainsKey(key))
            {
                throw new ArgumentException(
                    $"The collection does not contain the {paramName} element.", paramName);
            }
        }

        /// <summary>
        /// Validates that the dictionary does not contain the key.
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <param name="paramName">
        /// The parameter name.
        /// </param>
        /// <param name="collection">
        /// The collection.
        /// </param>
        /// <typeparam name="T1">
        /// The type of the keys.
        /// </typeparam>
        /// <typeparam name="T2">
        /// The type of the values.
        /// </typeparam>
        /// <exception cref="ArgumentException">
        /// Throws if the dictionary does not contain the key.
        /// </exception>
        [DebuggerStepThrough]
        internal static void DictionaryDoesNotContainKey<T1, T2>(T1 key, string paramName, IDictionary<T1, T2> collection)
        {
            if (collection.ContainsKey(key))
            {
                throw new ArgumentException(
                    $"The collection already contains the {paramName} element.", paramName);
            }
        }

        /// <summary>
        /// Validates the minimum vs maximum arguments.
        /// </summary>
        /// <param name="min">
        /// The min value.
        /// </param>
        /// <param name="max">
        /// The max value.
        /// </param>
        /// <exception cref="ArgumentException">
        /// Throws if min is greater than max.
        /// </exception>
        [DebuggerStepThrough]
        internal static void MinMax(double min, double max)
        {
            if (min > max)
            {
                throw new ArgumentException(
                    "Minimum value cannot be greater than Maximum value.");
            }
        }

        /// <summary>
        /// Validates the the given <see cref="double"/> is not out of the specified range.
        /// </summary>
        /// <param name="value">
        /// The value.
        /// </param>
        /// <param name="paramName">
        /// The param name.
        /// </param>
        /// <param name="lowerBound">
        /// The lower bound of the range.
        /// </param>
        /// <param name="upperBound">
        /// The upper bound of the range.
        /// </param>
        /// <param name="endPoints">
        /// The end point literal.
        /// </param>
        [DebuggerStepThrough]
        internal static void NotOutOfRange(
            double value,
            string paramName,
            double lowerBound = double.MinValue,
            double upperBound = double.MaxValue,
            RangeEndPoints endPoints = RangeEndPoints.Inclusive)
        {
            NotInvalidNumber(value, paramName);

            switch (endPoints)
            {
                case RangeEndPoints.Inclusive:
                    if (value < lowerBound || value > upperBound)
                    {
                        throw new ArgumentOutOfRangeException(
                            paramName, $"The {paramName} is not within the specified range [{lowerBound}, {upperBound}]. Value = {value}.");
                    }
                    break;

                case RangeEndPoints.LowerExclusive:
                    if (value <= lowerBound || value > upperBound)
                    {
                        throw new ArgumentOutOfRangeException(
                            paramName, $"The {paramName} is not within the specified range ({lowerBound}, {upperBound}]. Value = {value}.");
                    }
                    break;

                case RangeEndPoints.UpperExclusive:
                    if (value < lowerBound || value >= upperBound)
                    {
                        throw new ArgumentOutOfRangeException(
                            paramName, $"The {paramName} is not within the specified range [{lowerBound}, {upperBound}). Value = {value}.");
                    }
                    break;

                case RangeEndPoints.Exclusive:
                    if (value <= lowerBound || value >= upperBound)
                    {
                        throw new ArgumentOutOfRangeException(
                            paramName, $"The {paramName} is not within the specified range ({lowerBound}, {upperBound}). Value = {value}.");
                    }
                    break;
            }
        }

        /// <summary>
        /// Validates the <see cref="FuzzyPoint"/> array.
        /// </summary>
        /// <param name="points">
        /// The points array.
        /// </param>
        /// <param name="paramName">
        /// The parameter name.
        /// </param>
        /// <exception cref="ArgumentException">
        /// Throws if points are out of sequence.
        /// </exception>
        [DebuggerStepThrough]
        internal static void FuzzyPointArray(FuzzyPoint[] points, string paramName)
        {
            CollectionNotNullOrEmpty(points, nameof(points));

            for (var i = 0; i < points.Length; i++)
            {
                if (i == 0)
                {
                    continue;
                }

                if (points[i - 1].X > points[i].X)
                {
                    throw new ArgumentException(
                        "Points array out of sequence (must be in ascending order on X axis).", paramName);
                }
            }
        }

        /// <summary>
        /// Validates the collection of <see cref="FuzzySet"/>.
        /// </summary>
        /// <param name="inputSets">
        /// The input sets.
        /// </param>
        /// <param name="lowerBound">
        /// The lower bound.
        /// </param>
        /// <param name="upperBound">
        /// The upper bound.
        /// </param>
        /// <exception cref="ArgumentException">
        /// Throws if elements of a set are out of bounds.
        /// </exception>
        [DebuggerStepThrough]
        internal static void FuzzySetCollection(
            ICollection<FuzzySet> inputSets,
            double lowerBound,
            double upperBound)
        {
            CollectionNotNullOrEmpty(inputSets, nameof(inputSets));
            NotOutOfRange(lowerBound, nameof(lowerBound));
            NotOutOfRange(upperBound, nameof(upperBound));
            MinMax(lowerBound, upperBound);

            foreach (var set in inputSets)
            {
                NotOutOfRange(set.LowerBound, nameof(set.LowerBound), lowerBound, upperBound);
                NotOutOfRange(set.UpperBound, nameof(set.UpperBound), lowerBound, upperBound);
            }
        }

        /// <summary>
        /// Validates the given number.
        /// </summary>
        /// <param name="value">
        /// The value.
        /// </param>
        /// <param name="paramName">
        /// The parameter name.
        /// </param>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Throws if the input value is invalid.
        /// </exception>
        [DebuggerStepThrough]
        private static void NotInvalidNumber(double value, string paramName)
        {
            if (double.IsNaN(value)
             || double.IsNegativeInfinity(value)
             || double.IsPositiveInfinity(value))
            {
                throw new ArgumentOutOfRangeException(
                    paramName, $"The {paramName} is an invalid number.");
            }
        }
    }
}


text:
print """
/Sketches/filereading/Chassis:

 This file has been retired.
 It is retired because it is now part of the main code base.
 If you want to use this, you should be using Kamaelia.Chassis.Carousel

 This file now deliberately exits to encourage you to fix your code :-)
"""

import sys
sys.exit(0)
#

import Axon
from Axon.Component import component
from Axon.Ipc import producerFinished, shutdownMicroprocess, newComponent

class Carousel(component):
    """Encapsulates a changing carousel of components. The current component is wired
       such that it's inbox and outbox are exported  as "inbox" and "outbox".
       When the component emits producerFinished on its 'signal' output, a 'next' message is
       sent from 'requestNext'.

       Whenever arguments are received on 'next' eg. (but not necessarily) in response to
       a 'next' request, the components are destroyed and replaced with new ones, created
       with the arguments specified.

       After initialisation, Carousel will wait for the first  set of instructions, unless you
       set the make1stRequest argument, in which case it will issue a 'next' request immediately

       A factory method that takes a single argument should be supplied to create the components
       for the carousel.
       If you want to support more complex argument forms, you'll need to put a wrapper in.
    """

    Inboxes = { "inbox" : "child's inbox",
                "next" : "single argument for factory method new child component",
                "control" : "",
                "_control" : "for child to signal 'producerFinished' or 'shutdownMicroprocess' to Carousel"
              }
    Outboxes = { "outbox" : "child's outbox",
                 "signal" : "",
                 "_signal" : "for signalling 'shutdownMicroprocess' to child",
                 "requestNext" : "for requesting new child component"
               }

    def __init__(self, componentFactory, make1stRequest=False):
        super(Carousel, self).__init__()

        self.factory = componentFactory
        self.childDone = False

        self.make1stRequest = make1stRequest

    def main(self):
        if self.make1stRequest:
            self.requestNext()

        while not self.shutdown():
            self.handleFinishedChild()

            yield 1  # gap important - to allow shutdown messages to propogate to the child

            yield self.handleNewChild()

        self.unplugChildren()
#        print"Carousel done"

    def requestNext(self):
#        print "REQUESTING NEXT"
        self.send( "NEXT", "requestNext" )

    def handleFinishedChild(self):
        if self.dataReady("_control"):
            msg = self.recv("_control")

            if isinstance(msg, producerFinished) or isinstance(msg, shutdownMicroprocess):
                if not self.childDone:
                    self.childDone = True
                    self.requestNext()
                self.unplugChildren()

    def handleNewChild(self):
        if self.dataReady("next"):
            arg = self.recv("next")

            # purge old child and any control messages that may have come from the old child
            while self.dataReady("_control"):
                self.recv("_control")

            self.unplugChildren()

            # create new child
            newChild = self.factory(arg)
            self.addChildren( newChild )

            # set flag for handleFinishedChild's sake
            self.childDone = False

            # wire it in
            self.link( (self,     "inbox"),   (newChild, "inbox"),  passthrough=1 )
            self.link( (self,     "_signal"), (newChild, "control")  )

            self.link( (newChild, "outbox"),  (self,     "outbox"), passthrough=2 )
            self.link( (newChild, "signal"),  (self,     "_control") )

            # return it to be yielded
            return newComponent(*(self.children))
        return 1

    def unplugChildren(self):
        for child in self.childComponents():
            self.send( shutdownMicroprocess(self), "_signal" )
            self.postoffice.deregisterlinkage(thecomponent=child)
            self.removeChild(child)

    def shutdown(self):
        if self.dataReady("control"):
            msg = self.recv("control")
            if isinstance(msg, shutdownMicroprocess) or isinstance(msg, producerFinished):
                self.send( msg, "signal")
                return True
        return False

if __name__ == "__main__":
    pass

redpajama_set_name: RedPajamaGithub


text:
module NestedForm
  module BuilderMixin
    # Adds a link to insert a new associated records. The first argument is the name of the link, the second is the name of the association.
    #
    #   f.link_to_add("Add Task", :tasks)
    #
    # You can pass HTML options in a hash at the end and a block for the content.
    #
    #   <%= f.link_to_add(:tasks, :class => "add_task", :href => new_task_path) do %>
    #     Add Task
    #   <% end %>
    #
    # You can also pass <tt>model_object</tt> option with an object for use in
    # the blueprint, e.g.:
    #
    #   <%= f.link_to_add(:tasks, :model_object => Task.new(:name => 'Task')) %>
    #
    # See the README for more details on where to call this method.
    def link_to_add(*args, &block)
      options = args.extract_options!.symbolize_keys
      association = args.pop

      unless (reflection = object.class.reflect_on_association(association))
        raise ArgumentError, "Failed to find #{object.class.name} association by name \"#{association}\""
      end
      model_object = options.delete(:model_object) || reflection.klass.new

      options[:class] = [options[:class], "add_nested_fields"].compact.join(" ")
      options["data-association"] = association
      options["data-blueprint-id"] = fields_blueprint_id = fields_blueprint_id_for(association)
      options["data-node"] = options.delete(:node)
      options["data-position"] = options.delete(:position)
      args << (options.delete(:href) || "javascript:void(0)")
      args << options

      @fields ||= {}
      @template.after_nested_form(fields_blueprint_id) do
        blueprint = {:id => fields_blueprint_id, :style => 'display: none'}
        block, options = @fields[fields_blueprint_id].values_at(:block, :options)
        options[:child_index] = "new_#{association}"
        blueprint[:"data-blueprint"] = fields_for(association, model_object, options, &block).to_str
        @template.content_tag(:div, nil, blueprint)
      end
      @template.link_to(*args, &block)
    end

    # Adds a link to remove the associated record. The first argment is the name of the link.
    #
    #   f.link_to_remove("Remove Task")
    #
    # You can pass HTML options in a hash at the end and a block for the content.
    #
    #   <%= f.link_to_remove(:class => "remove_task", :href => "#") do %>
    #     Remove Task
    #   <% end %>
    #
    # See the README for more details on where to call this method.
    def link_to_remove(*args, &block)
      options = args.extract_options!.symbolize_keys
      options[:class] = [options[:class], "remove_nested_fields"].compact.join(" ")

      # Extracting "milestones" from "...[milestones_attributes][...]"
      md = object_name.to_s.match /(\w+)_attributes\]\[[\w\d]+\]$/
      association = md && md[1]
      options["data-association"] = association

      args << (options.delete(:href) || "javascript:void(0)")
      args << options
      hidden_field(:_destroy) << @template.link_to(*args, &block)
    end

    def fields_for_with_nested_attributes(association_name, *args)
      # TODO Test this better
      block = args.pop || Proc.new { |fields| @template.render(:partial => "#{association_name.to_s.singularize}_fields", :locals => {:f => fields}) }

      options = if args[0].kind_of? Array # Rails 3.0.x
        args[0].dup.extract_options!
      else
        args.dup.extract_options!
      end

      @fields ||= {}
      @fields[fields_blueprint_id_for(association_name)] = { :block => block, :options => options }
      super(association_name, *(args << block))
    end

    def fields_for_nested_model(name, object, options, block)
      classes = 'fields'
      classes << ' marked_for_destruction' if object.respond_to?(:marked_for_destruction?) && object.marked_for_destruction?

      if options.fetch(:wrapper, true)
        @template.content_tag(:div, super, :class => classes)
      else
        super
      end
    end

    private

    def fields_blueprint_id_for(association)
      assocs = object_name.to_s.scan(/(\w+)_attributes/).map(&:first)
      assocs << association
      assocs.join('_') + '_fields_blueprint'
    end
  end
end


text:
class index_file_finder {
	public:
		// Constructor.
		index_file_finder();

		// Destructor.
		virtual ~index_file_finder();

		// Reset.
		void reset();

		// Add index file.
		bool add(const char* name, size_t len);

		// Search index file.
		bool search(char* dir, size_t& dirlen, struct stat* buf) const;

	protected:
		buffer _M_buf;

		struct index_file {
			size_t offset;
			size_t len;
		};

		index_file _M_index_files[MAX_INDEX_FILES];
		size_t _M_used;
};

inline index_file_finder::index_file_finder()
{
	_M_used = 0;
}

inline index_file_finder::~index_file_finder()
{
}

inline void index_file_finder::reset()
{
	_M_buf.reset();
	_M_used = 0;
}

#endif // INDEX_FILE_FINDER_H


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Calandrinia cephalophora I.M.Johnst.

### Remarks
null


text:
//
//  HookNode.h
//  ubserver
//
//  Created by MikeRiy on 16/12/28.
//  Copyright © 2016年 MikeRiy. All rights reserved.
//

#ifndef HookNode_h
#define HookNode_h

#include <stdio.h>
#include "global.h"
#include "NetContext.h"

class HookNode
{
private:
    //服务器编号
    int32 m_hook_id;
    //服务器类型
    int8 m_ser_type;
    //--
    NetContext* m_context;
public:
    HookNode();

    virtual~ HookNode();

    void Register(int32 idx, NetContext* context, int8 type = 0);

    bool isRegister();

    void UnRegister();

    NetContext* getContext()const;

    int32 getSerType()const;

    int8 getSerID()const;
};

#endif /* HookNode_h */


text:
using Microsoft.VisualStudio.TestTools.UITesting.HtmlControls;

namespace Highway.Insurance.UI.Web.Controls.HtmlControls
{
    public class EnhancedHtmlDiv : EnhancedHtmlControl<HtmlDiv>
    {
        public EnhancedHtmlDiv() : base() { }
        public EnhancedHtmlDiv(string searchParameters) : base(searchParameters) { }
        public EnhancedHtmlDiv(WebPage page, string selector) : base(page, selector) { }
        public EnhancedHtmlDiv(HtmlDiv control) : base(control) { }
    }
}


text:
This library is still in development; it is not ready for production use.

Deamortized Hash Tables
======================

Hash tables are usually very fast, but have some very slow operations
when rehashing is required or there are too many hash collisions.
This project provides a deamortized hash table that reduces the
worst-case insert time.  This reduction has a cost: the average insert
time increases.  For some applications, this may be a good tradeoff.


text:
class BaseError(Exception):
    def __init__(self, code=None, message=None, *args, **kwargs):
        super(BaseError, self).__init__(message)


text:
from pymel.util.testing import TestCaseExtended, setupUnittestModule, TestCase
from pymel.util import utilitytypes

aDict = {'A':1, 'a':2}
bDict = {'B':3, 'b':4}

class BasicSingleton(object):
    __metaclass__ = utilitytypes.Singleton

class DictSingleton(dict) :
    __metaclass__ = utilitytypes.Singleton

class TestBasicSingleton(TestCaseExtended):
    # Override this attribute in derived classes!
    # Also, should use self.testClass (as
    # opposed to just 'testClass') in derived classes,
    # in case other classes derive from them...
    testClass = BasicSingleton

    def setUp(self):
        self.testClass = self.__class__.testClass

    def testSameInstance(self):
        self.assertTrue(self.testClass() is self.testClass())

class __AbstractTestDict(TestBasicSingleton):

    def testCanInitialize(self):
        self.testClass(aDict)
        self.assertEqual(aDict, dict(self.testClass()))

    def testReferencesEqual(self):
        oldRef = self.testClass(aDict)
        newRef = self.testClass()
        self.assertTrue( oldRef == newRef)

class TestDictSingleton(__AbstractTestDict):
    testClass = DictSingleton
    def setUp(self):
        super(TestDictSingleton, self).setUp()
        self.testClass().clear()

    def testInitializeResets(self):
        self.testClass(aDict)
        self.assertTrue(len(self.testClass())>0)
        self.testClass({})
        self.assertTrue(len(self.testClass())==0)

    def testSameInstanceAfterReinitializing(self):
        oldInst = self.testClass({'A':1})
        self.assertTrue(self.testClass({}) is oldInst)

    def testCanUpdate(self):
        self.testClass()['z'] = 3
        self.assertEqual(self.testClass()['z'], 3)
        self.testClass()['z'] = 12
        self.assertEqual(self.testClass()['z'], 12)

    def testNoClearOnUpdate(self):
        self.testClass()['a'] = "foobar"
        self.assertEqual(self.testClass()['a'], "foobar")
        self.testClass()['fuzzy'] = "bear"
        self.assertEqual(self.testClass()['a'], "foobar")

class TestFrozenDict(__AbstractTestDict):
    # In the case of static classes, need to create a new class
    # on each setup...

    def setUp(self):
        self._makeNewFrozenDictClass()

    def _makeNewFrozenDictClass(self, initialValue=None):
        class FrozenDict(dict):
            __metaclass__ = utilitytypes.metaStatic
        self.testClass = FrozenDict

    def _doInit(self, initialValue=None):
        if initialValue:
            return self.testClass(initialValue)
        else:
            return self.testClass()

    def _doAssignation(self, key, value):
        self.testClass()[key] = value

    def testNoReinitialization(self):
        self._doInit(aDict)
        self.assertRaises(TypeError, self._doInit, aDict)

    def testNoErrorIfNoArgs(self):
        self._doInit(aDict)
        self.assertNoError(self._doInit)
        self.assertNoError(self._doInit)

    def testNoAssignation(self):
        self.assertRaises(TypeError, self._doAssignation, 'A', 3)

    def testHidden(self):
        shouldBeHidden = ('clear', 'update', 'pop', 'popitem', '__setitem__', '__delitem__', 'append', 'extend' )
        for hidden in shouldBeHidden:
            self.assertFalse(hasattr(self.testClass(), hidden))

class TestEquivalencePairs(TestCaseExtended):
    def testInitPairs(self):
        ep = utilitytypes.EquivalencePairs( ((1,'foo'), (2,'bar')) )
        self.assertEqual(ep[1], 'foo')
        self.assertEqual(ep[2], 'bar')
        self.assertEqual(ep['foo'], 1)
        self.assertEqual(ep['bar'], 2)

    def testInitDict(self):
        ep = utilitytypes.EquivalencePairs( {1:'foo', 2:'bar'} )
        self.assertEqual(ep[1], 'foo')
        self.assertEqual(ep[2], 'bar')
        self.assertEqual(ep['foo'], 1)
        self.assertEqual(ep['bar'], 2)

    def testInitEquivPairs(self):
        otherEp = utilitytypes.EquivalencePairs( {1:'foo', 2:'bar'} )
        ep = utilitytypes.EquivalencePairs(otherEp)
        self.assertEqual(ep[1], 'foo')
        self.assertEqual(ep[2], 'bar')
        self.assertEqual(ep['foo'], 1)
        self.assertEqual(ep['bar'], 2)

    def testOverwritePairs(self):
        ep = utilitytypes.EquivalencePairs({1:'a', 2:'b'})
        self.assertEqual(ep[1], 'a')
        self.assertEqual(ep[2], 'b')
        self.assertEqual(ep['a'], 1)
        self.assertEqual(ep['b'], 2)
        ep[1] = 2
        self.assertRaises(KeyError, self._getIndex, ep, 'a')
        self.assertRaises(KeyError, self._getIndex, ep, 'b')
        self.assertEqual(ep[1], 2)
        self.assertEqual(ep[2], 1)

    def _getIndex(self, indexableObj, index):
        return indexableObj[index]

class TestProxyClass(TestCase):
    class MyClass(object):
        "MyClass's doc string!"
        data = 3.14

        def __init__(self, id):
            self.id = id

        @classmethod
        def clsMeth(cls):
            return cls

        @staticmethod
        def statMeth():
            return 'static'

        def instMeth(self):
            return (self, self.id)

    def test_wrapData(self):
        Wrapped = utilitytypes.proxyClass(self.MyClass, 'Wrapped',
                                          dataAttrName='_data', makeDefaultInit=True)
        self.assertEqual(Wrapped.data, self.MyClass.data)
        self.assertEqual(Wrapped('foo').data, self.MyClass('foo').data)

    def test_classMethod(self):
        Wrapped = utilitytypes.proxyClass(self.MyClass, 'Wrapped',
                                          dataAttrName='_data', makeDefaultInit=True)
        self.assertEqual(Wrapped.clsMeth(), self.MyClass.clsMeth())

    def test_staticMethod(self):
        Wrapped = utilitytypes.proxyClass(self.MyClass, 'Wrapped',
                                          dataAttrName='_data', makeDefaultInit=True)
        self.assertEqual(Wrapped.statMeth(), self.MyClass.statMeth())

    def test_instMethod(self):
        Wrapped = utilitytypes.proxyClass(self.MyClass, 'Wrapped',
                                          dataAttrName='_data', makeDefaultInit=True)
        wrappedResult = Wrapped('bar').instMeth()
        myClassResult = self.MyClass('bar').instMeth()
        self.assertEqual(wrappedResult[0].__class__, myClassResult[0].__class__)
        self.assertEqual(wrappedResult[1], myClassResult[1])

    def test_docString(self):
        Wrapped = utilitytypes.proxyClass(self.MyClass, 'Wrapped',
                                          dataAttrName='_data', makeDefaultInit=True)
        self.assertEqual(Wrapped.__doc__, self.MyClass.__doc__)

    def test_immutable(self):

        Wrapped = utilitytypes.proxyClass(''.__class__, 'Wrapped',
                                          dataAttrName='_data', makeDefaultInit=True)
        self.assertEqual(Wrapped('Fun times were had by all')[3:7],
                         'Fun times were had by all'[3:7])

    def test_unboundMethod(self):
        """
        We should be able to do MyProxyClass.wrappedMethod(myProxyClassInst)
        """
        Wrapped = utilitytypes.proxyClass(self.MyClass, 'Wrapped',
                                          dataAttrName='_data', makeDefaultInit=True)
        wrapInst = Wrapped('bar')
        wrappedResult = Wrapped.instMeth(wrapInst)
        myClassResult = self.MyClass('bar').instMeth()
        self.assertEqual(wrappedResult[0].__class__, myClassResult[0].__class__)
        self.assertEqual(wrappedResult[1], myClassResult[1])

    def test_unboundMethodDescriptor(self):
        """
        Some built-in types have fun things called method descriptors...
        ...they're like methods, but not!
        """
        Wrapped = utilitytypes.proxyClass(''.__class__, 'Wrapped',
                                          dataAttrName='_data', makeDefaultInit=True)
        theString = 'Fun times were had by all!'
        wrapInst = Wrapped(theString)
        self.assertEqual(Wrapped.__len__(wrapInst), len(theString))

setupUnittestModule(__name__)


text:
//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2014 Michael Fink
//
/// \file CdsdkViewfinderImpl.hpp CDSDK - Viewfinder impl
//
#pragma once

// includes
#include "Viewfinder.hpp"
#include "CdsdkCommon.hpp"
#include <ulib/thread/LightweightMutex.hpp>

namespace CDSDK
{

class SourceDeviceImpl;

/// viewfinder impl for CDSDK
class ViewfinderImpl : public Viewfinder
{
public:
   /// ctor
   ViewfinderImpl(std::shared_ptr<SourceDeviceImpl> spSourceDevice)
      :m_spSourceDevice(spSourceDevice),
       m_dwLastViewfinderCallbackTick(0)
   {
      // note: check if camera supports viewfinder before calling CDStartViewfinder()
      // Not all camera models support the Viewfinder function. Cameras that support Viewfinder
      // are those cameras for which the cdRELEASE_CONTROL_CAP_VIEWFINDER bit is set. Obtain the
      // value by executing CDGetDevicePropertyData using cdDEVICE_PROP_RELEASE_CONTROL_CAP.

      cdUInt32 format = 0; // 0 = JPEG, 1 = Bitmap
      StartViewfinder(format);
   }

   /// dtor
   virtual ~ViewfinderImpl()
   {
      try
      {
         SetAvailImageHandler(Viewfinder::T_fnOnAvailViewfinderImage());

         Close();
      }
      catch (...)
      {
      }
   }

   virtual bool GetCapability(T_enViewfinderCapability enViewfinderCapability) const override
   {
      switch (enViewfinderCapability)
      {
      case Viewfinder::capOutputTypeVideoOut:
         return true; // supported using CDSelectViewFinderCameraOutput

      case Viewfinder::capGetHistogram:
         return false;

      default:
         ATLASSERT(false);
         break;
      }

      return false;
   }

   virtual void SetOutputType(Viewfinder::T_enOutputType enOutputType) override
   {
      // note that T_enOutputType values exactly correspond to cdRelViewfinderOutput
      cdRelViewfinderOutput output = static_cast<cdRelViewfinderOutput>(enOutputType);

      cdError err = CDSelectViewFinderCameraOutput(GetSource(), output);
      LOG_TRACE(_T("CDSelectViewFinderCameraOutput(%08x) returned %08x\n"), GetSource(), err);
      CheckError(_T("CDSelectViewFinderCameraOutput"), err, __FILE__, __LINE__);
   }

   virtual void SetAvailImageHandler(Viewfinder::T_fnOnAvailViewfinderImage fnOnAvailViewfinderImage) override
   {
      LightweightMutex::LockType lock(m_mtxFnOnAvailViewfinderImage);

      m_fnOnAvailViewfinderImage = fnOnAvailViewfinderImage;
   }

   virtual void GetHistogram(T_enHistogramType, std::vector<unsigned int>&) override
   {
      // histogram not supported by CDSDK
      throw CameraException(_T("CDSDK::Viewfinder::GetHistogram"),
         _T("Not supported"), cdERROR_CDSDK_COMPONENTID | cdNOT_SUPPORTED, __FILE__, __LINE__);
   }

   virtual void Close() override
   {
      // may return cdINVALID_HANDLE, cdINVALID_FN_CALL
      cdError err = CDTermViewfinder(GetSource());
      LOG_TRACE(_T("CDTermViewfinder(%08x) returned %08x\n"), GetSource(), err);
      CheckError(_T("CDTermViewfinder"), err, __FILE__, __LINE__);
   }

private:
   /// starts viewfinder
   void StartViewfinder(cdUInt32 format)
   {
      // check: pointers (e.g. this) must fit into cdContext; may not work on 64-bit
      static_assert(sizeof(cdContext) == sizeof(void*), "pointers must fit into cdContext");

#pragma warning(push)
#pragma warning(disable: 4311) // 'reinterpret_cast' : pointer truncation from 'P' to 'T'
      cdContext context = reinterpret_cast<cdContext>(this);
#pragma warning(pop)

      // may return cdINVALID_HANDLE, cdNOT_SUPPORTED
      cdError err = CDStartViewfinder(GetSource(),
         format,
         &ViewfinderImpl::ViewfinderCallback,
         context);

      LOG_TRACE(_T("CDStartViewfinder(source = %08x, %u (%s), &CallbackFunc, context=%08x) returned %08x\n"),
         GetSource(),
         format,
         format == 0 ? _T("JPEG") :
         format == 1 ? _T("BMP") : _T("???"),
         this, err);
      CheckError(_T("CDStartViewfinder"), err, __FILE__, __LINE__);
   }

   /// callback function called when new viewfinder image is available
   static cdUInt32 __stdcall ViewfinderCallback(
      cdVoid* pBuf,        // Pointer to the buffer that contains one frame of Viewfinder data.
      cdUInt32 Size,       // Buffer size indicated by pBuf
      cdUInt32 Format,     // Viewfinder data format
      cdContext Context)   // Context
   {
#pragma warning(push)
#pragma warning(disable: 4312) // 'reinterpret_cast' : conversion from 'T' to 'P' of greater size
      ViewfinderImpl* pThis = reinterpret_cast<ViewfinderImpl*>(Context);
      ATLASSERT(pThis != nullptr);
#pragma warning(pop)

#ifdef _DEBUG
      DWORD dwCurrentTick = GetTickCount();

      LOG_TRACE(_T("\nViewfinderCallback(p = %p, size = %u, format = %u (%s), context) called with new viewfinder data;")
         _T("last callback was %u ms ago.\n"),
         pBuf, Size, Format,
         Format == 0 ? _T("JPEG") : Format == 1 ? _T("BMP") : _T("???"),
         pThis->m_dwLastViewfinderCallbackTick == 0 ? 0 : dwCurrentTick - pThis->m_dwLastViewfinderCallbackTick);
      pThis->m_dwLastViewfinderCallbackTick = dwCurrentTick;
#endif

      const BYTE* pbData = static_cast<BYTE*>(pBuf);

      std::vector<BYTE> vecData(pbData, pbData+Size);
      pThis->OnViewfinderImage(vecData, Format == 0);

      return 0;
   }

   /// called when new viewfinder image is available
   void OnViewfinderImage(const std::vector<BYTE>& vecData, bool /*bFormatIsJpeg*/)
   {
      LightweightMutex::LockType lock(m_mtxFnOnAvailViewfinderImage);

      if (m_fnOnAvailViewfinderImage)
         m_fnOnAvailViewfinderImage(vecData);
   }

   /// returns source
   cdHSource GetSource() const;

private:
   /// source device
   std::shared_ptr<SourceDeviceImpl> m_spSourceDevice;

   /// last tick where viewfinder image was retrieved
   DWORD m_dwLastViewfinderCallbackTick;

   /// mutex to protect m_fnOnAvailViewfinderImage
   LightweightMutex m_mtxFnOnAvailViewfinderImage;

   /// viewfinder image handler
   Viewfinder::T_fnOnAvailViewfinderImage m_fnOnAvailViewfinderImage;
};

} // namespace CDSDK


text:
NPPS 2
======

A refactored version of [NPPS](https://github.com/MikuAuahDark/NPPS) suitable for SIF v4.0.3.

###Overview

NPPS (short of **Null-Pointer Private Server**) is a SIF private server engine designed to be
simple, flexible, and fast. Modules and action can be easily modified, so it can be used for other
SIF versions (v3.1.x, v2.0.5, ...)

For security reasons, NPPS is written in PHP 7, which mostly uses null coalescing operator, scalar
type hinting, and return type hinting. With it, calls to `is_*` is nicely decreased while keeping
good security.

###System Requirements

* PHP 7.0 or above (PHP 7.1 also work)

* MBString PHP extension.

* cURL PHP extension (if DLC from prod configuration is enabled).

* SQLite3 PHP module (not PDO SQLite3). SQLite v3.7.0 or later is required if you're using SQLite3 as DB backend.

* MySQL v5.5 (or later) and MySQLi PHP module (necessary if you're using MySQL as DB backend)

* For Windows: Windows 7 SP1 or Windows Server 2008 R2 SP1 with latest updates (because you can't run PHP 7 in the earlier Windows version). Windows 8.1 or Windows Server 2012 is recommended.

* For Ubuntu: Ubuntu 16.04 (with simple `apt-get`), or 14.04 with [Ondřej Surý PPA](https://launchpad.net/~ondrej/+archive/ubuntu/php) to install PHP 7 and it's modules.

* For Mac OS X 10.6 and above: [use this method](http://php-osx.liip.ch/). **64-bit only**.

###Some Notes

* This one is still incomplete.


text:
package com.softwareverde.http.server.endpoint;

import com.softwareverde.http.server.servlet.WebSocketServlet;

public class WebSocketEndpoint {
    protected final WebSocketServlet _servlet;
    protected String _path;
    protected Boolean _shouldUseStrictPath;

    public WebSocketEndpoint(final WebSocketServlet servlet) {
        _servlet = servlet;
    }

    public void setPath(final String path) {
        _path = path;
    }

    public String getPath() {
        return _path;
    }

    public void setStrictPathEnabled(final Boolean strictPathEnabled) {
        _shouldUseStrictPath = strictPathEnabled;
    }

    public Boolean shouldUseStrictPath() {
        return _shouldUseStrictPath;
    }

    public WebSocketServlet getServlet() {
        return _servlet;
    }
}


text:
{% if site.owner.google.ad-client and site.owner.google.ad-slot %}{% include ad-footer.html %}{% endif %}

<button id="toTop" style="display: block;">  </button>

© {{ site.time | date: '%Y' }} . {{ site.owner.name }}. Powered by Jekyll.


text:
/* Includes ------------------------------------------------------------------*/
#include "usb_bsp.h"
#include "port.h"

/** @addtogroup USB_OTG_DRIVER
* @{
*/

/** @defgroup USB_BSP
  * @brief This file is responsible to offer board support package
  * @{
  */

/** @defgroup USB_BSP_Private_Defines
  * @{
  */
/**
  * @}
  */

/** @defgroup USB_BSP_Private_TypesDefinitions
  * @{
  */
/**
  * @}
  */

/** @defgroup USB_BSP_Private_Macros
  * @{
  */
/**
  * @}
  */

/** @defgroup USBH_BSP_Private_Variables
  * @{
  */

/**
  * @}
  */

/** @defgroup USBH_BSP_Private_FunctionPrototypes
  * @{
  */
/**
  * @}
  */

/** @defgroup USB_BSP_Private_Functions
  * @{
  */

/**
* @brief  USB_OTG_BSP_Init
*         Initilizes BSP configurations
* @param  None
* @retval None
*/

void USB_OTG_BSP_Init(USB_OTG_CORE_HANDLE *pdev)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	//USB GPIOA config
	//Vbus set as Input Floating for OTG
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
	GPIO_InitStructure.GPIO_Mode = 	GPIO_Mode_IN_FLOATING;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	//ID set as input pull up for OTG
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 ;
	GPIO_InitStructure.GPIO_Mode = 	GPIO_Mode_IPU;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	// the DP and DM are controlled automatically
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11 | GPIO_Pin_12;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);

	// Enable USB clock (48Mbps)
	RCC_AHBPeriphClockCmd( RCC_AHBPeriph_OTG_FS, ENABLE) ;
}

/**
* @brief  USB_OTG_BSP_EnableInterrupt
*         Enabele USB Global interrupt
* @param  None
* @retval None
*/
void USB_OTG_BSP_EnableInterrupt(USB_OTG_CORE_HANDLE *pdev)
{
  NVIC_InitTypeDef NVIC_InitStructure;
  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
  NVIC_InitStructure.NVIC_IRQChannel = OTG_FS_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);
}

/**
  * @brief  BSP_Drive_VBUS
  *         Drives the Vbus signal through IO
  * @param  speed : Full, Low
  * @param  state : VBUS states
  * @retval None
  */
void USB_OTG_BSP_DriveVBUS(USB_OTG_CORE_HANDLE *pdev,uint8_t state)
//void USB_OTG_BSP_DriveVBUS(uint32_t speed, uint8_t state)
{

}

/**
  * @brief  USB_OTG_BSP_ConfigVBUS
  *         Configures the IO for the Vbus and OverCurrent
  * @param  Speed : Full, Low
  * @retval None
  */
void USB_OTG_BSP_ConfigVBUS(USB_OTG_CORE_HANDLE *pdev)
//void  USB_OTG_BSP_ConfigVBUS(uint32_t speed)
{

}

/**
  * @brief  USB_OTG_BSP_TimeInit
  *         Initialises delay unit Systick timer /Timer2
  * @param  None
  * @retval None
  */
void USB_OTG_BSP_TimeInit ( void )
{

}

/**
  * @brief  USB_OTG_BSP_uDelay
  *         This function provides delay time in micro sec
  * @param  usec : Value of delay required in micro sec
  * @retval None
  */
void USB_OTG_BSP_uDelay (const uint32_t usec)
{

  uint32_t count = 0;
  const uint32_t utime = (120 * usec / 7);
  do
  {
    if ( ++count > utime )
    {
      return ;
    }
  }
  while (1);

}

/**
  * @brief  USB_OTG_BSP_mDelay
  *          This function provides delay time in milli sec
  * @param  msec : Value of delay required in milli sec
  * @retval None
  */
void USB_OTG_BSP_mDelay (const uint32_t msec)
{

    USB_OTG_BSP_uDelay(msec * 1000);

}

/**
  * @brief  USB_OTG_BSP_TimerIRQ
  *         Time base IRQ
  * @param  None
  * @retval None
  */

void USB_OTG_BSP_TimerIRQ (void)
{

}

/**
* @}
*/

/**
* @}
*/

/**
* @}
*/

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
package org.wso2.msf4j.spring;

import org.springframework.context.ConfigurableApplicationContext;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.wso2.msf4j.HttpServerTest;
import org.wso2.msf4j.conf.Constants;
import org.wso2.msf4j.service.SecondService;
import org.wso2.msf4j.spring.service.second.TestMicroServiceWithDynamicPath;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

/**
 * Spring tests.
 */
public class SpringHttpServerTest extends HttpServerTest {

    private static final int port = Constants.PORT;
    private List<ConfigurableApplicationContext> configurableApplicationContexts = new ArrayList<>();

    @BeforeClass
    public void setup() throws Exception {
        baseURI = URI.create(String.format("http://%s:%d", Constants.HOSTNAME, port));
        MSF4JSpringApplication msf4JSpringApplication = new MSF4JSpringApplication(SpringHttpServerTest.class);
        configurableApplicationContexts.add(msf4JSpringApplication.run(true, "--http.port=8090"));
        configurableApplicationContexts.add(MSF4JSpringApplication.run(SecondService.class, "--http.port=8091"));
        msf4JSpringApplication.addService(configurableApplicationContexts.get(1), TestMicroServiceWithDynamicPath.class,
                                          "/DynamicPath");
        msf4JSpringApplication.addService(configurableApplicationContexts.get(1), TestMicroServiceWithDynamicPath.class,
                                          "/DynamicPath2");
    }

    @AfterClass
    public void teardown() throws Exception {
        configurableApplicationContexts.stream().forEach(
                configurableApplicationContext -> configurableApplicationContext.close());
    }
}


text:
<?php
# $Id$
# PHPlot test: Box plot - tuning parameters
require_once 'phplot.php';
# This is a parameterized test. Other scripts can set $tp and then include
# this script. The parameters are shown in the defaults array below:
if (!isset($tp)) $tp = array();
$tp = array_merge(array(
  'subtitle' => 'Baseline',    # Title part 2
  'n_points' => 10,            # Number of data points
  'max_width' => NULL,         # Tune: boxes_max_width
  'min_width' => NULL,         # Tune: boxes_min_width
  'frac_width' => NULL,        # Tune: boxes_frac_width
  't_width' => NULL,           # Tune: boxes_t_width
        ), $tp);
require_once 'phplot.php';
# Extract all test parameters as local variables:
extract($tp);

$title = "Box Plot ($n_points points) Tuning\n$subtitle";

# Make a data array. Actual values does not matter, since
# this is only testing the widths of the boxes and Ts.
$data = array();
for ($i = 1; $i <= $n_points; $i++)
   $data[] = array('', 1, 5 + $i % 2, 10 + $i % 3, 15 + $i % 2, 19);

$p = new PHPlot(800, 600);
$p->SetTitle($title);
$p->SetDataType('text-data');
$p->SetDataValues($data);
$p->SetPlotType('boxes');
$p->SetXTickPos('none');
$p->SetXTickLabelPos('none');
$p->SetDrawYGrid(False);
# Tuning:
if (isset($max_width))  $p->boxes_max_width = $max_width;
if (isset($min_width))  $p->boxes_min_width = $min_width;
if (isset($frac_width)) $p->boxes_frac_width = $frac_width;
if (isset($t_width))    $p->boxes_t_width = $t_width;
$p->DrawGraph();


text:
package org.apache.myfaces.portlet.faces.application;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;
import javax.faces.FacesException;
import javax.faces.FactoryFinder;
import javax.faces.application.StateManager;
import javax.faces.application.ViewHandler;
import javax.faces.application.ViewHandlerWrapper;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.RenderKit;
import javax.faces.render.RenderKitFactory;

import javax.portlet.PortletContext;
import javax.portlet.RenderResponse;
import javax.portlet.faces.Bridge;
import javax.portlet.faces.BridgeUtil;
import javax.portlet.faces.annotation.PortletNamingContainer;
import javax.portlet.faces.component.PortletNamingContainerUIViewRoot;

/**
 * View handler implementation for JSF portlet bridge.
 *
 * The only method we override here is getActionURL().
 *
 * TODO JSF 1.2 note: JSF 1.2 RI implements ViewHandler.renderView() differently in order to handle
 * emitting non-JSF markup that follows the JSF tags after the JSF renders correctly. Unfortunately,
 * the RI handles this by introducing several servlet dependencies. Currently, the bridge handles
 * this by overriding the renderView() and ignoring (not interleafing) the non-JSF markup - see HACK
 * below
 */
public class PortletViewHandlerImpl extends ViewHandlerWrapper
{

  // the ViewHandler to delegate to
  private ViewHandler mDelegate;
  private Bridge.BridgeRenderPolicy mRenderPolicy = null;

  public PortletViewHandlerImpl(ViewHandler handler)
  {
    mDelegate = handler;
  }

  protected ViewHandler getWrapped()
  {
    return mDelegate;
  }

  @Override
  public UIViewRoot createView(FacesContext facesContext, String viewId)
  {
    // Do nothing when not running in portlet request
    if (!BridgeUtil.isPortletRequest())
    {
      return super.createView(facesContext, viewId);
    }

    UIViewRoot viewRoot = super.createView(facesContext, viewId);

    // Use the delegatees UIViewRoot if its not the native Faces one
    // or it already implements the PortletNamingContainer behavior
    if ((viewRoot.getClass() != UIViewRoot.class) ||
        (viewRoot.getClass().getAnnotation(PortletNamingContainer.class) != null))
    {
      return viewRoot;
    }
    else
    {
      return new PortletNamingContainerUIViewRoot(viewRoot);
    }

  }

  @Override
  public void renderView(FacesContext context, UIViewRoot viewToRender) throws IOException,
                                                                       FacesException
  {
    // Do nothing when not running in portlet request
    if (!BridgeUtil.isPortletRequest())
    {
      super.renderView(context, viewToRender);
      return;
    }

    // If first time -- Get the renderPolicy from the context init parameter
    if (mRenderPolicy == null)
    {
      PortletContext pCtx = (PortletContext) context.getExternalContext().getContext();
      String policy = pCtx.getInitParameter(Bridge.RENDER_POLICY);
      if (policy != null)
      {
        mRenderPolicy = Bridge.BridgeRenderPolicy.valueOf(policy);
      }
      else
      {
        mRenderPolicy = Bridge.BridgeRenderPolicy.DEFAULT;
      }
    }

    if (mRenderPolicy == Bridge.BridgeRenderPolicy.ALWAYS_DELEGATE)
    {
      super.renderView(context, viewToRender);
      return;
    }
    else if (mRenderPolicy == Bridge.BridgeRenderPolicy.DEFAULT)
    {
      try
      {
        super.renderView(context, viewToRender);
        return;
      }
      catch (Throwable t)
      {
        // catch all throws and swallow -- falling through to our own
        // render
      }
    }

    // suppress rendering if "rendered" property on the component is
    // false
    if (!viewToRender.isRendered())
    {
      return;
    }

    ExternalContext extContext = context.getExternalContext();
    RenderResponse renderResponse = (RenderResponse) extContext.getResponse();

    try
    {

      // set request attribute indicating we can deal with content
      // that is supposed to be delayed until after JSF tree is ouput.
      extContext.getRequestMap().put(Bridge.RENDER_CONTENT_AFTER_VIEW, Boolean.TRUE);
      // TODO JSF 1.2 - executePageToBuildView() creates
      // ViewHandlerResponseWrapper
      // to handle error page and text that exists after the <f:view> tag
      // among other things which have lots of servlet dependencies -
      // we're skipping this for now for portlet

      // Bridge has had to set this attribute so  Faces RI will skip servlet dependent
      // code when mapping from request paths to viewIds -- however we need to remove it
      // as it screws up the dispatch
      extContext.getRequestMap().remove("javax.servlet.include.servlet_path");
      extContext.dispatch(viewToRender.getViewId());
      /*
       * if (executePageToBuildView(context, viewToRender)) { response.flushBuffer(); return; }
       */
    }
    catch (IOException e)
    {
      throw new FacesException(e);
    }

    // set up the ResponseWriter
    RenderKitFactory renderFactory = (RenderKitFactory) FactoryFinder
                                                                     .getFactory(FactoryFinder.RENDER_KIT_FACTORY);
    RenderKit renderKit = renderFactory.getRenderKit(context, viewToRender.getRenderKitId());

    ResponseWriter oldWriter = context.getResponseWriter();
    StringBuilderWriter strWriter = new StringBuilderWriter(context, 4096);
    ResponseWriter newWriter;
    if (null != oldWriter)
    {
      newWriter = oldWriter.cloneWithWriter(strWriter);
    }
    else
    {
      newWriter = renderKit.createResponseWriter(strWriter, null,
                                                 renderResponse.getCharacterEncoding());
    }
    context.setResponseWriter(newWriter);

    newWriter.startDocument();

    doRenderView(context, viewToRender);

    newWriter.endDocument();

    // replace markers in the body content and write it to response.

    ResponseWriter responseWriter;

    // Dispatch may have output to an OutputStream instead of a Writer
    Writer renderResponseWriter = null;
    try {
      renderResponseWriter = renderResponse.getWriter();
    }
    catch (IllegalStateException ise) {
      // got this exception because we've called getOutputStream() previously
      renderResponseWriter = new BufferedWriter(
                          new OutputStreamWriter(
                               renderResponse.getPortletOutputStream(),
                               renderResponse.getCharacterEncoding()));
    }
    if (null != oldWriter)
    {
      responseWriter = oldWriter.cloneWithWriter(renderResponseWriter);
    }
    else
    {
      responseWriter = newWriter.cloneWithWriter(renderResponseWriter);
    }
    context.setResponseWriter(responseWriter);

    strWriter.write(responseWriter);
    renderResponseWriter.flush();

    if (null != oldWriter)
    {
      context.setResponseWriter(oldWriter);
    }

    Object content = extContext.getRequestMap().get(Bridge.AFTER_VIEW_CONTENT);
    if (content != null)
    {
      if (content instanceof char[])
      {
        renderResponse.getWriter().write(new String((char[]) content));
      }
      else if (content instanceof byte[])
      {
        renderResponse.getWriter().write(new String((byte[]) content));
      }
      else
      {
        throw new IOException("PortletViewHandlerImpl: invalid" + "AFTER_VIEW_CONTENT buffer type");
      }
    }
    renderResponse.flushBuffer();
  }

  /**
   *

   * This is a separate method to account for handling the content after the view tag.
   *

   *
   *

   * Create a new ResponseWriter around this response's Writer. Set it into the FacesContext, saving
   * the old one aside.
   *

   *
   *

   * call encodeBegin(), encodeChildren(), encodeEnd() on the argument UIViewRoot.
   *

   *
   *

   * Restore the old ResponseWriter into the FacesContext.
   *

   *
   *

   * Write out the after view content to the response's writer.
   *

   *
   *

   * Flush the response buffer, and remove the after view content from the request scope.
   *

   *
   * @param context
   *          the FacesContext for the current request
   * @param viewToRender
   *          the view to render
   * @throws IOException
   *           if an error occurs rendering the view to the client
   */
  private void doRenderView(FacesContext context, UIViewRoot viewToRender) throws IOException,
                                                                          FacesException
  {
    viewToRender.encodeAll(context);
  }

  private static final class StringBuilderWriter extends Writer
  {
    private StringBuilder       mBuilder;
    private FacesContext        mContext;

    // TODO: These bridge needs to use it's own constants here. This will
    // confine
    // us to only work with the R.I.
    private static final String SAVESTATE_FIELD_MARKER = "~com.sun.faces.saveStateFieldMarker~";

    public StringBuilderWriter(FacesContext context, int initialCapacity)
    {
      if (initialCapacity < 0)
      {
        throw new IllegalArgumentException();
      }
      mBuilder = new StringBuilder(initialCapacity);
      mContext = context;
    }

    @Override
    public void write(char[] cbuf, int off, int len) throws IOException
    {
      if (off < 0 || off > cbuf.length || len < 0 || off + len > cbuf.length || off + len < 0)
      {
        throw new IndexOutOfBoundsException();
      }
      else if (len == 0)
      {
        return;
      }
      mBuilder.append(cbuf, off, len);
    }

    @Override
    public void flush() throws IOException
    {
    }

    @Override
    public void close() throws IOException
    {
    }

    /**
     * Write a string.
     *
     * @param str
     *          String to be written
     */
    @Override
    public void write(String str)
    {
      mBuilder.append(str);
    }

    @Override
    public void write(String str, int off, int len)
    {
      write(str.substring(off, off + len));
    }

    public StringBuilder getBuffer()
    {
      return mBuilder;
    }

    @Override
    public String toString()
    {
      return mBuilder.toString();
    }

    public void write(Writer writer) throws IOException
    {
      // TODO: Buffer?
      StateManager stateManager = mContext.getApplication().getStateManager();
      Object stateToWrite = stateManager.saveView(mContext);
      int markLen = SAVESTATE_FIELD_MARKER.length();
      int pos = 0;
      int tildeIdx = mBuilder.indexOf(SAVESTATE_FIELD_MARKER);
      while (tildeIdx > 0)
      {
        writer.write(mBuilder.substring(pos, (tildeIdx - pos)));
        stateManager.writeState(mContext, stateToWrite);
        pos += tildeIdx + markLen;
        tildeIdx = mBuilder.indexOf(SAVESTATE_FIELD_MARKER, pos);
      }
      writer.write(mBuilder.substring(pos));
    }
  }

  // END TODO HACK JSF 1.2
}


text:
<?php

namespace Nucleus;

class Client
{

	private $client;

	public function __construct($config)
	{
		 $this->client = NucleusClient::factory($config);
	}

    public function __call($method, $params)
    {

	    if (isset($params[0]))
    	{
	    	$command = $this->client->getCommand($method, $params[0]);
	    }
	    else
	    {
		    $command = $this->client->getCommand($method);
	    }

	    return $this->client->execute($command);
    }
}

// EOF


text:
from docx import *
from docx.shared import Inches
import pprint
import codecs
import sys
import smtplib
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email import encoders
#import CONFIG_test as CONFIG
import CONFIG as CONFIG
from openpyxl import Workbook

doc_level = 0
current = 'pseudo_code'
students = {}
student = {}

def get_grade(s):
	if s >= 70:
		return "First"
	if s >= 67 and s < 70:
		return "High 2:1"
	if s >= 63 and s < 67:
		return "Mid 2:1"
	if s >= 60 and s < 64:
		return "Low 2:1"
	if s >= 57 and s < 60:
		return "High 2:2"
	if s >= 53 and s < 57:
		return "Mid 2:2"
	if s >= 50 and s < 54:
		return "Low 2:2"
	if s >= 47 and s < 50:
		return "High 3rd"
	if s >= 43 and s < 47:
		return "Mid 3rd"
	if s >= 40 and s < 44:
		return "Low 3rd"
	if s >= 35 and s < 40:
		return "Marginal Fail"
	if s < 35:
		return "Fail"

def parse_student (t, post):
	global doc_level, student, current
	if t == '' and not post == '':
		doc_level = 0
		## save previous student into students
		if not student.has_key('student_id'):
			#print "student_id empty"
			#sys.exit(1)
			print
		else:
			students[student['student_id']] = student
			#pprint.pprint(student)
			#print '\n\n\n'
		## parse name and student id
		name_id = post
		name_id = name_id.split('(')
		studnet_name = name_id[0].strip()
		student_id = name_id[1].replace(')', '').strip()
		student = {'parts':{}, 'student_name': studnet_name, 'student_id': student_id}
	if 'part a:' in t.lower():
		score = t.lower().split(':')[1]
		doc_level = 1
		student['parts'][doc_level] = {'score':score, 'pseudo_code':[], 'js_code':[]}
	elif 'part b:' in t.lower():
		score = t.lower().split(':')[1]
		doc_level = 2
		student['parts'][doc_level] = {'score':score, 'pseudo_code':[], 'js_code':[]}
	elif 'part c:' in t.lower():
		score = t.lower().split(':')[1]
		doc_level = 3
		student['parts'][doc_level] = {'score':score, 'pseudo_code':[], 'js_code':[]}
	elif 'overall:' in t.lower():
		score = t.lower().split(':')
		doc_level = 4
		student['parts'][doc_level] = {'score':0, 'pseudo_code':[], 'js_code':[]}
	elif 'pseudo code:' in t.lower():
		current = 'pseudo_code'
	elif 'js code:' in t.lower():
		current = 'js_code'
	elif 'all:' in t.lower() or 'you have therefore' in t.lower():
		return
	else:
		#print t
		if doc_level == 0:
			return
		if t == '':
			return
		student['parts'][doc_level][current].append(t)

def calcualte_score_grade():
	highest = 0
	lowest = 0
	average = 0
	grades = {}
	for student_id in students:
		parts = students[student_id]['parts']
		score_total = 0
		for part_id in parts:
			part_score = parts[part_id]['score']
			part_score = int(part_score)
			score_total = score_total + part_score
		grade = get_grade(score_total)
		students[student_id]['student_score'] = score_total
		students[student_id]['student_grade'] = grade
		## stastic
		if score_total > highest:
			highest = score_total
		if score_total < lowest:
			lowest = score_total
		average = average + score_total
		if not grades.has_key(grade):
			grades[grade] = {}
		grades[grade][student_id] = score_total
	average = average * 1.0 / len(students)
	print "==== student performance stastics ===="
	print "Students counts:", len(students)
	print "Highest:", highest, 'Lowest:', lowest, 'Average:', average
	for grade in grades:
		print "Grade:", grade, 'has student counts:', len(grades[grade])

def parse_docx(doc_name):
	pre = ''
	document = Document(doc_name)
	for post in document.paragraphs:
		t = post.text.strip()  ## curent line text
		parse_student(pre, t)
		pre = t
	students[student['student_id']] = student
	pprint.pprint(students)
	print "Student counts:", len(students)
	calcualte_score_grade()

##########################################################################

def print_student_grade_only(file_name):
	f = codecs.open(file_name, 'w', encoding='utf-8')
	f.write(u'%s\t%s\t%s\t%s\t\n'%('student_id', 'student_name', 'student_score', 'student_grade'))
	for student_id in students:
		student = students[student_id]
		student_name = student['student_name']
		student_score = student['student_score']
		student_grade = student['student_grade']
		f.write(u'%s\t%s\t%s\t%s\t\n'%(student_id, student_name, student_score, student_grade))
	f.close()
	print "== print_student_grade_only: %s =="%(file_name)

def print_student_comments_in_one_file(file_name, title, show_score):
	doc = Document()
	for student_id in students:
		student = students[student_id]
		student_name = student['student_name']
		student_score = student['student_score']
		student_grade = student['student_grade']
		doc.add_heading(title, 0)
		doc.add_heading(u'Student ID: %s, Student Name: %s'%(student_id, student_name), 1)
		doc.add_heading(u'Final Grade: %s'%(student_grade), 1)
		parts = student['parts']
		for part_id in parts:
			part_label = u'Part-%s'%(part_id)
			part_score = parts[part_id]['score']
			if (part_id == 4):
				part_label = 'Overall'
				part_score = student_score
			if show_score == True:
				doc.add_heading(u'%s: %s :'%(part_label, part_score), 2)
			else:
				doc.add_heading(u'%s: '%(part_label), 2)
			doc.add_heading('Pseudo code', 4)
			for c in parts[part_id]['pseudo_code']:
				doc.add_paragraph(c, style='ListBullet2')
			doc.add_heading('JS code', 4)
			for c in parts[part_id]['js_code']:
				doc.add_paragraph(c, style='ListBullet2')
		doc.add_page_break()
	doc.save(file_name)
	print "== print_student_comments_in_one_file: %s =="%(file_name)

def print_student_comments_in_seperate_file(file_name_prefix, title, show_score):
	for student_id in students:
		student = students[student_id]
		student_name = student['student_name']
		student_score = student['student_score']
		student_grade = student['student_grade']
		doc = Document()
		doc.add_heading(title, 0)
		doc.add_heading(u'Student ID: %s, Student Name: %s'%(student_id, student_name), 1)
		doc.add_heading(u'Final Grade: %s'%(student_grade), 1)
		parts = student['parts']
		for part_id in parts:
			part_label = u'Part-%s'%(part_id)
			part_score = parts[part_id]['score']
			if (part_id == 4):
				part_label = 'Overall'
				part_score = student_score
			if show_score == True:
				doc.add_heading(u'%s: %s :'%(part_label, part_score), 2)
			else:
				doc.add_heading(u'%s: '%(part_label), 2)
			doc.add_heading('Pseudo code', 4)
			for c in parts[part_id]['pseudo_code']:
				doc.add_paragraph(c, style='ListBullet2')
			doc.add_heading('JS code', 4)
			for c in parts[part_id]['js_code']:
				doc.add_paragraph(c, style='ListBullet2')
		doc.add_page_break()
		file_name = u'%s%s.docx'%(file_name_prefix, student_id)
		doc.save(file_name)
		print "== print_student_comments_in_seperate_file: %s =="%(file_name)

def print_student_comments_to_email(file_name_prefix, email_title_prefix, is_test, mail_type):
	for student_id in students:
		student = students[student_id]
		student_name = student['student_name']
		student_score = student['student_score']
		student_grade = student['student_grade']
		parts = student['parts']
		parts_html = ''
		for part_id in parts:
			part_label = u'Part-%s'%(part_id)
			if (part_id == 4):
				part_label = 'Overall'
				part_score = student_score
			part_html_pseudo_code = ''
			for c in parts[part_id]['pseudo_code']:
				part_html_pseudo_code = u'%s
%s
'%(part_html_pseudo_code, c)
			part_html_pseudo_code = u'
%s
'%(part_html_pseudo_code)
			part_html_js_code = ''
			for c in parts[part_id]['js_code']:
				part_html_js_code = u'%s
%s
'%(part_html_js_code, c)
			part_html_js_code = u'
%s
'%(part_html_js_code)
			part_html = part_template%(part_label, part_html_pseudo_code, part_html_js_code)
			parts_html = u'%s
%s'%(parts_html, part_html)
		file_name = u'%s%s.docx'%(file_name_prefix, student_id)
		email_body = email_template%(student_name, student_id, student_grade, parts_html)
		email_title = u'Web-Based-Programing In-Class test results: %s'%(student_id)
		#print email_body
		if is_test == True:
			address_to = CONFIG.address_to_test
			send_email(mail_type, email_title, email_body, address_to)
			print "== print_student_comments_to_email: %s =="%(file_name)
			print "only in test"
			return
		else:
			address_to = '%s@ntu.ac.uk'%(student_id)
			send_email(mail_type, email_title, email_body, address_to)
			print "== print_student_comments_to_email: %s =="%(file_name)

part_template = u'''
%s

Pseudo Code:

%s

JS Code:

%s

'''
email_template = u'''
To %s:

Your student_id is %s, and your final grade is %s

Bellow are your comments details:

%s
'''
def send_email(mail_type, email_title, email_body, address_to):
	#mail_type = 'gmail' # or ntu
	is_attachment = False
	if mail_type == 'gmail':
		smtp_server = 'smtp.gmail.com'
		smtp_port = 587
		address_from = CONFIG.gmail_address_from
		username = CONFIG.gmail_username
		password = CONFIG.gmail_password
	if mail_type == 'ntu':
		smtp_server = 'smtphost.ntu.ac.uk'
		smtp_port = 25
		address_from = CONFIG.ntu_address_from
		#username = CONFIG.ntu_username
		#password = CONFIG.ntu_password
	address_cc = CONFIG.address_cc
	msg = MIMEMultipart('alternative')
	msg.set_charset('utf-8')
	msg['FROM'] = address_from
	msg['TO'] = address_to
	msg['CC'] = address_cc
	msg['Subject'] = email_title
	part2 = MIMEText(email_body, 'html', 'utf-8')
	msg.attach(part2)
	if is_attachment == True:
		### this is for attachment, disabled at moment
		#part = MIMEBase('application', "octet-stream")
		#part.set_payload(open('comments/H-N0491912.docx',"rb").read() )
		#encoders.encode_base64(part)
		#part.add_header('Content-Disposition', 'attachment; filename="H-N0491912.docx"')
		#msg.attach(part)
		#print msg
		print 'no attachment now'
	server = smtplib.SMTP(smtp_server, smtp_port)
	server.ehlo()
	server.starttls()
	if mail_type == 'ntu':
		print "NTU do not need to login"
	else:
		server.login(username, password)
	server.sendmail(address_from, address_to, msg.as_string())
	server.quit()

def print_student_comments_to_one_excel(filename, group_name):
	wb = Workbook()
	ws = wb.create_sheet(1)
	ws.title = group_name
	j = 0
	ws.cell(row=j, column=0).value = "student_id"
	ws.cell(row=j, column=1).value = "student_name"
	ws.cell(row=j, column=2).value = "student_grade"
	ws.cell(row=j, column=3).value = "Part-A"
	ws.cell(row=j, column=4).value = "Part-B"
	ws.cell(row=j, column=5).value = "Part-C"
	ws.cell(row=j, column=6).value = "Overall"
	ws.cell(row=j, column=7).value = "Extra"
	j = 1
	for student_id in students:
		#pprint.pprint(students[student_id])
		#return
		student = students[student_id]
		student_name = student['student_name']
		student_score = student['student_score']
		student_grade = student['student_grade']
		parts = student['parts']
		parts_html = {}
		for part_id in parts:
			part_label = u'Part-%s'%(part_id)
			if (part_id == 4):
				part_label = 'Overall'
				part_score = student_score
			part_html_pseudo_code = 'COMMENTS FOR PSEUDO CODE: '
			i = 0
			for c in parts[part_id]['pseudo_code']:
				i = i + 1
				part_html_pseudo_code = u'%s %s) %s'%(part_html_pseudo_code, i, c)
			#part_html_pseudo_code = u'
%s
'%(part_html_pseudo_code)
			part_html_js_code = 'COMMENTS FOR JS CODE: '
			i = 0
			for c in parts[part_id]['js_code']:
				i = i + 1
				part_html_js_code = u'%s %s) %s'%(part_html_js_code, i, c)
			#part_html_js_code = u'
%s
'%(part_html_js_code)
			part_html = u'%s. %s'%(part_html_pseudo_code, part_html_js_code)
			parts_html[part_id] = part_html
		#pprint.pprint(parts_html)
		#print
		extra = u'You are awarded a %s'%(student_grade)
		ws.cell(row=j, column=0).value = student_id
		ws.cell(row=j, column=1).value = student_name
		ws.cell(row=j, column=2).value = student_grade
		ws.cell(row=j, column=3).value = parts_html[1]
		ws.cell(row=j, column=4).value = parts_html[2]
		ws.cell(row=j, column=5).value = parts_html[3]
		ws.cell(row=j, column=6).value = parts_html[4]
		ws.cell(row=j, column=7).value = extra
		j = j + 1
	wb.save(filename)

def main_in_group(doc_name, group_name):
	doc_level = 0
	current = 'pseudo_code'
	student = {}
	parse_docx(doc_name)
	print_student_grade_only('./output_files/'+group_name+'-grade.txt')
	print_student_comments_in_one_file('./output_files/'+group_name+'-comments_in_one_file_with_score.docx', 'Web-Based-Programing In-Class test result', True)
	print_student_comments_in_one_file('./output_files/'+group_name+'-comments_in_one_file.docx', 'Web-Based-Programing In-Class test result', False)
	print_student_comments_in_seperate_file('./comments/'+group_name+'-', 'Web-Based-Programing In-Class test result', False)
	print_student_comments_to_one_excel('./output_files/'+group_name+'.xlsx', group_name)
	### ready to send email
	#send_email_in_test = True   ############### make sure you changed here ##################
	#mail_type = 'ntu' # or ntu ############### make sure you changed here ##################
	#print_student_comments_to_email('./comments/'+group_name+'-', 'Web-Based-Programing In-Class test result', send_email_in_test, mail_type)

if __name__ == "__main__":
	main_in_group('./input_files/Marking-Group-H.docx', 'H') ############### make sure you changed here ##################
	main_in_group('./input_files/Marking-Group-F.docx', 'F') ############### make sure you changed here ##################


text:
from __future__ import unicode_literals

from django.db import models, migrations
import django.utils.timezone
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Post',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('title', models.CharField(max_length=200)),
                ('text', models.TextField()),
                ('created_date', models.DateTimeField(default=django.utils.timezone.now)),
                ('published_date', models.DateTimeField(null=True, blank=True)),
                ('author', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
            ],
        ),
    ]


text:
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <target name="phploc" description="Measure project size using PHPLOC.">
    <exec executable="phploc" failonerror="false">
      <arg value="--log-csv" />
      <arg value="${workspace.build}/logs/phploc.csv" />
      <arg path="${workspace.src}" />
    </exec>
  </target>
</project>


text:
package org.evilkitten.slack.response.rtm.mesage.group;

import lombok.Data;
import org.evilkitten.slack.response.rtm.MessageEvent;

@Data
public class GroupUnarchiveEvent extends MessageEvent {
}


text:
#include <string>
#include "library/messages.h"
#include "frontends/lean/info_manager.h"
#include "util/task_builder.h"

namespace lean {

message::message(parser_exception const & ex) :
        message(ex.get_file_name(), *ex.get_pos(),
                ERROR, ex.get_msg()) {}

std::ostream & operator<<(std::ostream & out, message const & msg) {
    if (msg.get_severity() != INFORMATION) {
        out << msg.get_file_name() << ":" << msg.get_pos().first << ":" << msg.get_pos().second << ": ";
        switch (msg.get_severity()) {
            case INFORMATION: break;
            case WARNING: out << "warning: "; break;
            case ERROR:   out << "error: ";   break;
        }
        if (!msg.get_caption().empty())
            out << msg.get_caption() << ":\n";
    }
    auto const & text = msg.get_text();
    out << text;
    if (!text.size() || text[text.size() - 1] != '\n')
        out << "\n";
    return out;
}

void report_message(message const & msg0) {
    auto & l = logtree();
    auto & loc = logtree().get_location();

    std::shared_ptr<message> msg;
    if (loc.m_file_name.empty()) {
        msg = std::make_shared<message>(msg0);
    } else {
        auto pos_ok = loc.m_range.m_begin <= msg0.get_pos() && msg0.get_pos() <= loc.m_range.m_end;
        msg = std::make_shared<message>(loc.m_file_name, pos_ok ? msg0.get_pos() : loc.m_range.m_begin,
            msg0.get_severity(), msg0.get_caption(), msg0.get_text());
    }
    l.add(msg);
}

task<bool> has_errors(log_tree::node const & n) {
    return n.has_entry(is_error_message);
}

bool is_error_message(log_entry const & e) {
    if (auto msg = dynamic_cast<message const *>(e.get())) {
        return msg->is_error();
    }
    return false;
}

}