text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities

Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations
    ''' <summary>
    ''' Recommends the "Property" keyword in member declaration contexts
    ''' </summary>
    Friend Class ModifierKeywordsRecommender
        Inherits AbstractKeywordRecommender

        Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As IEnumerable(Of RecommendedKeyword)
            If Not context.IsTypeMemberDeclarationKeywordContext AndAlso Not context.IsTypeDeclarationKeywordContext Then
                Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)()
            End If

            Dim modifierFacts = context.ModifierCollectionFacts
            Dim recommendations As New List(Of RecommendedKeyword)
            Dim targetToken = context.TargetToken

            Dim innermostDeclaration = GetInnermostDeclarationContext(targetToken)
            Dim innermostDeclarationKind =
                If(innermostDeclaration IsNot Nothing AndAlso innermostDeclaration.Kind <> SyntaxKind.CompilationUnit,
                   innermostDeclaration.Kind,
                   SyntaxKind.NamespaceBlock)

            If modifierFacts.AccessibilityKeyword.Kind = SyntaxKind.None AndAlso Not context.IsInterfaceMemberDeclarationKeywordContext Then
                If modifierFacts.OverridableSharedOrPartialKeyword.Kind <> SyntaxKind.PartialKeyword Then
                    recommendations.Add(New RecommendedKeyword("Public", VBFeaturesResources.Specifies_that_one_or_more_declared_programming_elements_have_no_access_restrictions))
                End If

                ' Only "Public" is legal for operators
                If modifierFacts.NarrowingOrWideningKeyword.Kind = SyntaxKind.None Then
                    If modifierFacts.OverridableSharedOrPartialKeyword.Kind <> SyntaxKind.PartialKeyword Then
                        recommendations.Add(New RecommendedKeyword("Friend", VBFeaturesResources.Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_the_assembly_that_contains_their_declaration))
                    End If

                    If modifierFacts.DefaultKeyword.Kind = SyntaxKind.None AndAlso innermostDeclarationKind <> SyntaxKind.NamespaceBlock Then
                        recommendations.Add(New RecommendedKeyword("Private", VBFeaturesResources.Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_their_module_class_or_structure))
                    End If
                End If
            End If

            If modifierFacts.CouldApplyToOneOf(PossibleDeclarationTypes.ProtectedMember) Then
                If modifierFacts.AccessibilityKeyword.Kind = SyntaxKind.None Then
                    recommendations.Add(New RecommendedKeyword("Protected", VBFeaturesResources.Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_their_own_class_or_from_a_derived_class))
                    recommendations.Add(New RecommendedKeyword("Protected Friend", VBFeaturesResources.Specifies_that_one_or_more_declared_members_of_a_class_are_accessible_from_anywhere_in_the_same_assembly_their_own_classes_and_derived_classes))
                ElseIf modifierFacts.AccessibilityKeyword.Kind = SyntaxKind.ProtectedKeyword AndAlso Not modifierFacts.HasProtectedAndFriend Then
                    ' We could still have a "Friend" later
                    recommendations.Add(New RecommendedKeyword("Friend", VBFeaturesResources.Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_the_assembly_that_contains_their_declaration))
                ElseIf modifierFacts.AccessibilityKeyword.Kind = SyntaxKind.FriendKeyword AndAlso Not modifierFacts.HasProtectedAndFriend Then
                    ' We could still have a "Protected" later
                    recommendations.Add(New RecommendedKeyword("Protected", VBFeaturesResources.Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_their_own_class_or_from_a_derived_class))
                End If
            End If

            ' Show "Partial" at the module level. Recommending it before "Private"
            ' is fine, because we'll prettylist it.
            If innermostDeclarationKind = SyntaxKind.ClassBlock OrElse
               innermostDeclarationKind = SyntaxKind.ModuleBlock OrElse
               innermostDeclarationKind = SyntaxKind.StructureBlock OrElse
               innermostDeclarationKind = SyntaxKind.NamespaceBlock Then

                If modifierFacts.CouldApplyToOneOf(PossibleDeclarationTypes.Class) AndAlso
                    modifierFacts.OverridableSharedOrPartialKeyword.Kind <> SyntaxKind.PartialKeyword AndAlso
                    modifierFacts.AsyncKeyword.Kind = SyntaxKind.None AndAlso
                    modifierFacts.IteratorKeyword.Kind = SyntaxKind.None Then

                    recommendations.Add(New RecommendedKeyword("Partial", VBFeaturesResources.Indicates_that_a_method_class_or_structure_declaration_is_a_partial_definition_of_the_method_class_or_structure))
                End If
            End If

            If modifierFacts.AsyncKeyword.Kind = SyntaxKind.None AndAlso
               modifierFacts.IteratorKeyword.Kind = SyntaxKind.None Then

                If modifierFacts.MutabilityOrWithEventsKeyword.Kind = SyntaxKind.None Then
                    If modifierFacts.CouldApplyToOneOf(PossibleDeclarationTypes.Field) Then
                        recommendations.Add(New RecommendedKeyword("Const", VBFeaturesResources.Declares_and_defines_one_or_more_constants))
                        recommendations.Add(New RecommendedKeyword("WithEvents", VBFeaturesResources.Specifies_that_one_or_more_declared_member_variables_refer_to_an_instance_of_a_class_that_can_raise_events))
                    End If

                    If modifierFacts.CouldApplyToOneOf(PossibleDeclarationTypes.Property) OrElse modifierFacts.CouldApplyToOneOf(PossibleDeclarationTypes.Field) Then
                        recommendations.Add(New RecommendedKeyword("ReadOnly", VBFeaturesResources.Specifies_that_a_variable_or_property_can_be_read_but_not_written_to))
                    End If

                    If modifierFacts.CouldApplyToOneOf(PossibleDeclarationTypes.Property) Then
                        recommendations.Add(New RecommendedKeyword("WriteOnly", VBFeaturesResources.Specifies_that_a_property_can_be_written_to_but_not_read))
                    End If
                End If

                ' Some modifiers cannot appear at the module level
                If innermostDeclarationKind = SyntaxKind.ClassBlock OrElse
                   innermostDeclarationKind = SyntaxKind.InterfaceBlock OrElse
                   innermostDeclarationKind = SyntaxKind.StructureBlock OrElse
                   innermostDeclarationKind = SyntaxKind.NamespaceBlock Then

                    If modifierFacts.InheritenceKeyword.Kind = SyntaxKind.None AndAlso modifierFacts.CouldApplyToOneOf(PossibleDeclarationTypes.Class) Then
                        recommendations.Add(New RecommendedKeyword("MustInherit", VBFeaturesResources.Specifies_that_a_class_can_be_used_only_as_a_base_class_and_that_you_cannot_create_an_object_directly_from_it))
                        recommendations.Add(New RecommendedKeyword("NotInheritable", VBFeaturesResources.Specifies_that_a_class_cannot_be_used_as_a_base_class))
                    End If

                    If modifierFacts.OverridableSharedOrPartialKeyword.Kind = SyntaxKind.None Then
                        If Not context.IsInterfaceMemberDeclarationKeywordContext AndAlso
                           modifierFacts.OverridesOrShadowsKeyword.Kind <> SyntaxKind.OverridesKeyword Then
                            recommendations.Add(New RecommendedKeyword("Shared", VBFeaturesResources.Specifies_that_one_or_more_declared_programming_elements_are_associated_with_all_instances_of_a_class_or_structure))
                        End If

                        If modifierFacts.CouldApplyToOneOf(PossibleDeclarationTypes.OverridableMethod) Then
                            recommendations.Add(New RecommendedKeyword("MustOverride", VBFeaturesResources.Specifies_that_a_property_or_procedure_is_not_implemented_in_the_class_and_must_be_overridden_in_a_derived_class_before_it_can_be_used))

                            If modifierFacts.OverridesOrShadowsKeyword.Kind <> SyntaxKind.ShadowsKeyword Then
                                recommendations.Add(New RecommendedKeyword("NotOverridable", VBFeaturesResources.Specifies_that_a_property_or_procedure_cannot_be_overridden_in_a_derived_class))
                            End If

                            If modifierFacts.OverridesOrShadowsKeyword.Kind <> SyntaxKind.OverridesKeyword Then
                                recommendations.Add(New RecommendedKeyword("Overridable", VBFeaturesResources.Specifies_that_a_property_or_procedure_can_be_overridden_by_an_identically_named_property_or_procedure_in_a_derived_class))
                            End If
                        End If
                    End If

                    If modifierFacts.OverridesOrShadowsKeyword.Kind = SyntaxKind.None Then
                        If modifierFacts.OverridableSharedOrPartialKeyword.Kind <> SyntaxKind.OverridableKeyword AndAlso
                           modifierFacts.CouldApplyToOneOf(PossibleDeclarationTypes.Method Or PossibleDeclarationTypes.Property) AndAlso
                           Not context.IsInterfaceMemberDeclarationKeywordContext AndAlso
                           modifierFacts.SharedKeyword.Kind = SyntaxKind.None AndAlso
                           modifierFacts.OverridableSharedOrPartialKeyword.Kind <> SyntaxKind.PartialKeyword Then
                            recommendations.Add(New RecommendedKeyword("Overrides", VBFeaturesResources.Specifies_that_a_property_or_procedure_overrides_an_identically_named_property_or_procedure_inherited_from_a_base_class))
                        End If

                        If modifierFacts.OverloadsKeyword.Kind = SyntaxKind.None AndAlso
                           modifierFacts.OverridableSharedOrPartialKeyword.Kind <> SyntaxKind.NotOverridableKeyword AndAlso
                           modifierFacts.CouldApplyToOneOf(PossibleDeclarationTypes.Method Or PossibleDeclarationTypes.Property Or PossibleDeclarationTypes.Operator) Then
                            recommendations.Add(New RecommendedKeyword("Shadows", VBFeaturesResources.Specifies_that_a_declared_programming_element_redeclares_and_hides_an_identically_named_element_in_a_base_class))
                        End If
                    End If

                    If modifierFacts.OverloadsKeyword.Kind = SyntaxKind.None AndAlso
                       modifierFacts.OverridesOrShadowsKeyword.Kind <> SyntaxKind.ShadowsKeyword AndAlso
                       modifierFacts.CouldApplyToOneOf(PossibleDeclarationTypes.Property Or PossibleDeclarationTypes.Method Or PossibleDeclarationTypes.Operator) Then
                        recommendations.Add(New RecommendedKeyword("Overloads", VBFeaturesResources.Specifies_that_a_property_or_procedure_re_declares_one_or_more_existing_properties_or_procedures_with_the_same_name))
                    End If

                    If modifierFacts.DefaultKeyword.Kind = SyntaxKind.None AndAlso
                       modifierFacts.CouldApplyToOneOf(PossibleDeclarationTypes.Property) AndAlso
                       modifierFacts.AccessibilityKeyword.Kind <> SyntaxKind.PrivateKeyword Then
                        recommendations.Add(New RecommendedKeyword("Default", VBFeaturesResources.Identifies_a_property_as_the_default_property_of_its_class_structure_or_interface))
                    End If

                    If modifierFacts.NarrowingOrWideningKeyword.Kind = SyntaxKind.None AndAlso modifierFacts.CouldApplyToOneOf(PossibleDeclarationTypes.Operator) Then
                        recommendations.Add(New RecommendedKeyword("Narrowing", VBFeaturesResources.Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_might_not_be_able_to_hold_some_of_the_possible_values_of_the_original_class_or_structure))
                        recommendations.Add(New RecommendedKeyword("Widening", VBFeaturesResources.Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_can_hold_all_possible_values_of_the_original_class_or_structure))
                    End If
                End If
            End If

            Return recommendations
        End Function
    End Class
End Namespace


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

using TravelService.Model.Base.Common;

namespace TravelService.Model.ServiceModel
{
    public class GetUserInfoResponse
    {
        public UserInfo userInfo { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * The template for displaying the homepage.
 *
 * This page template will display any functions hooked into the `homepage` action.
 * By default this includes a variety of product displays and the page content itself.
 *
 * Template name: Homepage
 *
 * @package neckbeard
 */

get_header(); ?>

<div class="slide slide-front" style="background-image:url(<?php if ( has_post_thumbnail($id)) : ?><?php echo wp_get_attachment_url( get_post_thumbnail_id($id) ); ?><?php else: ?><?php echo get_template_directory_uri(); ?>/images/coffee.jpg<?php endif; ?>);">

Excepteur sint occaecat cupidatat non proident.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus amet mollitia delectus ut, quis laboriosam totam, dolores, magni dicta consectetur incidunt officia pariatur officiis facilis nam, nobis veniam vitae odio.

Sample button

				<?php
				// See hooks.php
				do_action( 'homepage' ); ?>

<?php get_footer(); ?>


text:
/**
 *
 */
package org.pathwayeditor.businessobjects.drawingprimitives.listeners;

/**
 * @author Stuart Moodie
 *
 */
public enum CanvasAttributePropertyChange {
	BOUNDS, FILL_COLOUR, LINE_COLOUR, LINE_STYLE, LINE_WIDTH,
	ANNOTATION_VALUE, NO_FILL, NO_BORDER, NAME, FONT_COLOUR, FONT
}


text:
<sect1 id="zend.version.reading">

    <title>Odczytywanie wersji Zend Framework</title>

    <para>
        Stała klasy Zend_Version::VERSION zawiera łańcuch znaków,
        który określa aktualny numer wersji Zend Framework. Przykładowo może
        to być "0.9.0beta".
    </para>

    <para>
        Statyczna metoda Zend_Version::compareVersion($version)
        jest oparta na funkcji
        <ulink url="http://php.net/version_compare">version_compare()</ulink>.
        Metoda zwraca -1 gdy wersja ze zmiennej $version
        jest starsza niż wersja Zend Framework, 0 jeśli są takie same,
        a +1 gdy wersja ze zmiennej $version jest nowsza niż
        wersja Zend Framework.
    </para>

    <example id="zend.version.reading.example">
        <title>Przykład użycia metody compareVersion()</title>
        <programlisting role="php"><![CDATA[
// zwraca -1, 0 lub 1
$cmp = Zend_Version::compareVersion('1.0.0');
]]>
        </programlisting>
    </example>

</sect1>


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Windows.Media
{
  sealed public partial class VisualBrush : TileBrush, ICyclicBrush
  {
    #region Methods and constructors
    public VisualBrush Clone()
    {
      return default(VisualBrush);
    }

    public VisualBrush CloneCurrentValue()
    {
      return default(VisualBrush);
    }

    protected override System.Windows.Freezable CreateInstanceCore()
    {
      return default(System.Windows.Freezable);
    }

    protected override void GetContentBounds(out System.Windows.Rect contentBounds)
    {
      contentBounds = default(System.Windows.Rect);
    }

    protected override void OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs e)
    {
    }

    void System.Windows.Media.ICyclicBrush.FireOnChanged()
    {
    }

    public VisualBrush()
    {
    }

    public VisualBrush(Visual visual)
    {
    }
    #endregion

    #region Properties and indexers
    public bool AutoLayoutContent
    {
      get
      {
        return default(bool);
      }
      set
      {
      }
    }

    public Visual Visual
    {
      get
      {
        return default(Visual);
      }
      set
      {
      }
    }
    #endregion

    #region Fields
    public readonly static System.Windows.DependencyProperty AutoLayoutContentProperty;
    public readonly static System.Windows.DependencyProperty VisualProperty;
    #endregion
  }
}


text:
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using Microsoft.Xunit.Performance.Api;

public class PerfHarness
{
    public static void Main(string[] args)
    {
        using (XunitPerformanceHarness harness = new XunitPerformanceHarness(args))
        {
            foreach(var testName in GetTestAssemblies())
            {
                harness.RunBenchmarks(GetTestAssembly(testName));
            }
        }
    }

    private static string GetTestAssembly(string testName)
    {
        // Assume test assemblies are colocated/restored next to the PerfHarness.
        return Path.Combine(
            Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), testName);
    }

    private static IEnumerable<string> GetTestAssemblies()
    {
        return Directory.EnumerateFiles(".", "*.Performance.Tests.dll");
    }
}


text:
// distinct_powers.cpp : algorithm to find all integer combinations of a^b for some range [min, max]
//
// Copyright (C) 2017-2022 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#include <iostream>
#include <sstream>
#include <vector>
#include <set>
#include <algorithm>
// integer number system
#include <universal/number/integer/integer.hpp>
#include <universal/number/integer/attributes.hpp>
// posit number system
#define POSIT_ENABLE_LITERALS 1
#include <universal/number/posit/posit.hpp>

namespace sw {
	namespace universal {
/*
 * Consider all integer combinations of a^b for lowerbound <= a <= upperbound, lowerbound <= b <= upperbound
 *
 * Sorted, with any repeats removed, we get some sequence. What is the cardinality of that sequence?
 */
template<unsigned nbits, typename BlockType, IntegerNumberType NumberType>
integer<nbits, BlockType, NumberType> IntegerPowerCombinationsUsingVector(const integer<nbits, BlockType, NumberType>& min, const integer<nbits, BlockType, NumberType>& max) {
	using namespace sw::universal;
	using Integer = integer<nbits, BlockType, NumberType>;

	std::vector<Integer> combinations;
	for (Integer a = min; a <= max; ++a) {
		for (Integer b = min; b <= max; ++b) {
			combinations.push_back(ipow(a, b));
		}
	}
	std::sort(combinations.begin(), combinations.end());
	// remove duplicates
	combinations.erase(unique(combinations.begin(), combinations.end()), combinations.end());
	return Integer(combinations.size());
}

template<unsigned nbits, typename BlockType, IntegerNumberType NumberType>
integer<nbits, BlockType, NumberType> IntegerPowerCombinationsUsingSet(const integer<nbits, BlockType, NumberType>& min, const integer<nbits, BlockType, NumberType>& max) {
	using namespace sw::universal;
	using Integer = integer<nbits, BlockType, NumberType>;

	std::set<Integer> combinations;
	for (Integer a = min; a <= max; ++a) {
		for (Integer b = min; b <= max; ++b) {
			combinations.insert(ipow(a, b));
		}
	}
	return Integer(combinations.size());
}

template<unsigned nbits, unsigned es>
size_t IntegerPowerCombinationsUsingSet(const posit<nbits, es>& min, const posit<nbits, es>& max) {
	using namespace sw::universal;
	using Posit = posit<nbits, es>;

	std::set<Posit> combinations;
	for (Posit a = min; a <= max; a = a + 1) {
		for (Posit b = min; b <= max; b = b + 1) {
			combinations.insert(ipow(a, b));
		}
	}
	return combinations.size();
}

size_t DistinctPowerCombinations(size_t min, size_t max) {
	std::set<double> combinations;
	for (size_t a = min; a <= max; ++a) {
		for (size_t b = min; b <= max; ++b) {
			combinations.insert(ipow(a, b));
		}
	}
	return combinations.size();
}

}}  // namespace sw::universal

int main()
try {
	using namespace sw::universal;

	goto version_double;
	goto version_integer_vector;
	goto version_integer_set;
	goto version_posit_set;

	// use a set of doubles to generate cardinality of unique power values
version_double:
	{
		size_t min = 2, max = 100;
		size_t cardinality = DistinctPowerCombinations(min, max);

		std::cout << "cardinality of integer power combinations in the range "
			<< "[" << min << ',' << max << "] = " << cardinality << '\n';

		return 0;
	}

	// use a vector to store and post-process to remove duplicates
version_integer_vector:
	{
		constexpr size_t nbits = 1024;
		using Integer = integer<nbits>;

		Integer min = 2, max = 100;
	//	Integer cardinality = IntegerPowerCombinationsUsingSet(min, max);
		Integer cardinality = IntegerPowerCombinationsUsingVector(min, max);

		std::cout << "cardinality of integer power combinations in the range "
			<< "[" << min << ',' << max << "] = " << cardinality << '\n';

		return 0;
	}

	// use a set to remove duplicates during insert
version_integer_set:
	{
		constexpr size_t nbits = 1024;
		using Integer = integer<nbits>;

		std::cout << "100^100 = " << ipow(Integer(100), Integer(100)) << '\n';

		Integer min = 2;
		for (Integer max = min + 1; max <= 100; ++max) {
			Integer cardinality = IntegerPowerCombinationsUsingSet(min, max);

			std::cout << "cardinality of integer power combinations in the range "
				 << "[" << min << ',' << max << "] = " << cardinality << '\n';
		}
	}

version_posit_set:
	{
		constexpr size_t nbits = 64;
		constexpr size_t es = 3;
		using Posit = posit<nbits, es>;

		std::cout << "100^100 = " << ipow(Posit(100), Posit(100)) << '\n';

		Posit min = 2;
		for (Posit max = min + 1; max <= 100; ++max) {
			size_t cardinality = IntegerPowerCombinationsUsingSet(min, max);

			std::cout << "cardinality of integer power combinations in the range "
				<< "[" << min << ',' << max << "] = " << cardinality << '\n';
		}
	}

	return EXIT_SUCCESS;
}
catch (char const* msg) {
	std::cerr << "Caught ad-hoc exception: " << msg << std::endl;
	return EXIT_FAILURE;
}
catch (const sw::universal::universal_arithmetic_exception& err) {
	std::cerr << "Caught unexpected universal arithmetic exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (const sw::universal::universal_internal_exception& err) {
	std::cerr << "Caught unexpected universal internal exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (std::runtime_error& err) {
	std::cerr << "Caught unexpected runtime error: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (...) {
	std::cerr << "Caught unknown exception" << std::endl;
	return EXIT_FAILURE;
}

/*
cardinality of integer power combinations in the range [2,3] = 4
cardinality of integer power combinations in the range [2,4] = 8
cardinality of integer power combinations in the range [2,5] = 15
cardinality of integer power combinations in the range [2,6] = 23
cardinality of integer power combinations in the range [2,7] = 34
cardinality of integer power combinations in the range [2,8] = 44
cardinality of integer power combinations in the range [2,9] = 54
cardinality of integer power combinations in the range [2,10] = 69
cardinality of integer power combinations in the range [2,11] = 88
cardinality of integer power combinations in the range [2,12] = 106
cardinality of integer power combinations in the range [2,13] = 129
cardinality of integer power combinations in the range [2,14] = 152
cardinality of integer power combinations in the range [2,15] = 177
cardinality of integer power combinations in the range [2,16] = 195
cardinality of integer power combinations in the range [2,17] = 226
cardinality of integer power combinations in the range [2,18] = 256
cardinality of integer power combinations in the range [2,19] = 291
cardinality of integer power combinations in the range [2,20] = 324
cardinality of integer power combinations in the range [2,21] = 361
cardinality of integer power combinations in the range [2,22] = 399
cardinality of integer power combinations in the range [2,23] = 442
cardinality of integer power combinations in the range [2,24] = 483
cardinality of integer power combinations in the range [2,25] = 519
cardinality of integer power combinations in the range [2,26] = 564
cardinality of integer power combinations in the range [2,27] = 600
cardinality of integer power combinations in the range [2,28] = 648
cardinality of integer power combinations in the range [2,29] = 703
cardinality of integer power combinations in the range [2,30] = 755
cardinality of integer power combinations in the range [2,31] = 814
cardinality of integer power combinations in the range [2,32] = 856
cardinality of integer power combinations in the range [2,33] = 915
cardinality of integer power combinations in the range [2,34] = 976
cardinality of integer power combinations in the range [2,35] = 1039
cardinality of integer power combinations in the range [2,36] = 1085
cardinality of integer power combinations in the range [2,37] = 1156
cardinality of integer power combinations in the range [2,38] = 1224
cardinality of integer power combinations in the range [2,39] = 1295
cardinality of integer power combinations in the range [2,40] = 1365
cardinality of integer power combinations in the range [2,41] = 1444
cardinality of integer power combinations in the range [2,42] = 1519
cardinality of integer power combinations in the range [2,43] = 1602
cardinality of integer power combinations in the range [2,44] = 1681
cardinality of integer power combinations in the range [2,45] = 1762
cardinality of integer power combinations in the range [2,46] = 1846
cardinality of integer power combinations in the range [2,47] = 1937
cardinality of integer power combinations in the range [2,48] = 2023
cardinality of integer power combinations in the range [2,49] = 2095
cardinality of integer power combinations in the range [2,50] = 2184
cardinality of integer power combinations in the range [2,51] = 2279
cardinality of integer power combinations in the range [2,52] = 2373
cardinality of integer power combinations in the range [2,53] = 2476
cardinality of integer power combinations in the range [2,54] = 2574
cardinality of integer power combinations in the range [2,55] = 2677
cardinality of integer power combinations in the range [2,56] = 2779
cardinality of integer power combinations in the range [2,57] = 2886
cardinality of integer power combinations in the range [2,58] = 2993
cardinality of integer power combinations in the range [2,59] = 3108
cardinality of integer power combinations in the range [2,60] = 3216
cardinality of integer power combinations in the range [2,61] = 3335
cardinality of integer power combinations in the range [2,62] = 3450
cardinality of integer power combinations in the range [2,63] = 3569
cardinality of integer power combinations in the range [2,64] = 3648
cardinality of integer power combinations in the range [2,65] = 3771
cardinality of integer power combinations in the range [2,66] = 3890
cardinality of integer power combinations in the range [2,67] = 4021
cardinality of integer power combinations in the range [2,68] = 4147
cardinality of integer power combinations in the range [2,69] = 4277
cardinality of integer power combinations in the range [2,70] = 4406
cardinality of integer power combinations in the range [2,71] = 4545
cardinality of integer power combinations in the range [2,72] = 4676
cardinality of integer power combinations in the range [2,73] = 4819
cardinality of integer power combinations in the range [2,74] = 4957
cardinality of integer power combinations in the range [2,75] = 5098
cardinality of integer power combinations in the range [2,76] = 5240
cardinality of integer power combinations in the range [2,77] = 5391
cardinality of integer power combinations in the range [2,78] = 5534
cardinality of integer power combinations in the range [2,79] = 5689
cardinality of integer power combinations in the range [2,80] = 5838
cardinality of integer power combinations in the range [2,81] = 5946
cardinality of integer power combinations in the range [2,82] = 6099
cardinality of integer power combinations in the range [2,83] = 6262
cardinality of integer power combinations in the range [2,84] = 6416
cardinality of integer power combinations in the range [2,85] = 6579
cardinality of integer power combinations in the range [2,86] = 6740
cardinality of integer power combinations in the range [2,87] = 6906
cardinality of integer power combinations in the range [2,88] = 7070
cardinality of integer power combinations in the range [2,89] = 7245
cardinality of integer power combinations in the range [2,90] = 7412
cardinality of integer power combinations in the range [2,91] = 7591
cardinality of integer power combinations in the range [2,92] = 7763
cardinality of integer power combinations in the range [2,93] = 7941
cardinality of integer power combinations in the range [2,94] = 8118
cardinality of integer power combinations in the range [2,95] = 8301
cardinality of integer power combinations in the range [2,96] = 8479
cardinality of integer power combinations in the range [2,97] = 8670
cardinality of integer power combinations in the range [2,98] = 8855
cardinality of integer power combinations in the range [2,99] = 9045
cardinality of integer power combinations in the range [2,100] = 9183
 */


text:
package br.com.objectos.jabuticava.serasa.relato.factoring;

import static br.com.objectos.testing.MoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

import org.testng.annotations.Test;

/**
 * @author marcio.endo@objectos.com.br (Marcio Endo)
 */
public class TituloNormalTest {

  @Test
  public void size() {
    String res = TituloNormalFake.TITULO_0001.toString();
    assertThat(res.length(), equalTo(130 + 1));
  }

}


text:
package serial

import "io/ioutil"
import "regexp"
import "strings"
import "syscall"
import "unsafe"

// Opaque type that implements SerialPort interface for linux
type SerialPort struct {
	handle int
}

// Close the serial port
func (port *SerialPort) Close() error {
	port.releaseExclusiveAccess()
	return syscall.Close(port.handle)
}

// Stores data received from the serial port into the provided byte array
// buffer. The function returns the number of bytes read.
//
// The Read function blocks until (at least) one byte is received from
// the serial port or an error occurs.
func (port *SerialPort) Read(p []byte) (n int, err error) {
	return syscall.Read(port.handle, p)
}

// Send the content of the data byte array to the serial port.
// Returns the number of bytes written.
func (port *SerialPort) Write(p []byte) (n int, err error) {
	return syscall.Write(port.handle, p)
}

// Set all parameters of the serial port. See the Mode structure for more
// info.
func (port *SerialPort) SetMode(mode *Mode) error {
	settings, err := port.getTermSettings()
	if err != nil {
		return err
	}
	if err := setTermSettingsBaudrate(mode.BaudRate, settings); err != nil {
		return err
	}
	if err := setTermSettingsParity(mode.Parity, settings); err != nil {
		return err
	}
	if err := setTermSettingsDataBits(mode.DataBits, settings); err != nil {
		return err
	}
	if err := setTermSettingsStopBits(mode.StopBits, settings); err != nil {
		return err
	}
	return port.setTermSettings(settings)
}

// Open the serial port using the specified modes
func OpenPort(portName string, mode *Mode) (*SerialPort, error) {
	h, err := syscall.Open(portName, syscall.O_RDWR|syscall.O_NOCTTY|syscall.O_NDELAY, 0)
	if err != nil {
		switch err {
		case syscall.EBUSY:
			return nil, &SerialPortError{code: ERROR_PORT_BUSY}
		case syscall.EACCES:
			return nil, &SerialPortError{code: ERROR_PERMISSION_DENIED}
		}
		return nil, err
	}
	port := &SerialPort{
		handle: h,
	}

	// Setup serial port
	if port.SetMode(mode) != nil {
		port.Close()
		return nil, &SerialPortError{code: ERROR_INVALID_SERIAL_PORT}
	}

	// Set raw mode
	settings, err := port.getTermSettings()
	if err != nil {
		port.Close()
		return nil, &SerialPortError{code: ERROR_INVALID_SERIAL_PORT}
	}
	setRawMode(settings, mode)
	if port.setTermSettings(settings) != nil {
		port.Close()
		return nil, &SerialPortError{code: ERROR_INVALID_SERIAL_PORT}
	}

	syscall.SetNonblock(h, false)

	port.acquireExclusiveAccess()

	return port, nil
}

func GetPortsList() ([]string, error) {
	files, err := ioutil.ReadDir(devFolder)
	if err != nil {
		return nil, err
	}

	ports := make([]string, 0, len(files))
	for _, f := range files {
		// Skip folders
		if f.IsDir() {
			continue
		}

		// Keep only devices with the correct name
		match, err := regexp.MatchString(regexFilter, f.Name())
		if err != nil {
			return nil, err
		}
		if !match {
			continue
		}

		portName := devFolder + "/" + f.Name()

		// Check if serial port is real or is a placeholder serial port "ttySxx"
		if strings.HasPrefix(f.Name(), "ttyS") {
			port, err := OpenPort(portName, &Mode{})
			if err != nil {
				serr, ok := err.(*SerialPortError)
				if ok && serr.Code() == ERROR_INVALID_SERIAL_PORT {
					continue
				}
			} else {
				port.Close()
			}
		}

		// Save serial port in the resulting list
		ports = append(ports, portName)
	}

	return ports, nil
}

// termios manipulation functions

func setTermSettingsBaudrate(speed int, settings *syscall.Termios) error {
	baudrate, ok := baudrateMap[speed]
	if !ok {
		return &SerialPortError{code: ERROR_INVALID_PORT_SPEED}
	}
	// revert old baudrate
	BAUDMASK := 0
	for _, rate := range baudrateMap {
		BAUDMASK |= rate
	}
	settings.Cflag &= ^termiosMask(BAUDMASK)
	// set new baudrate
	settings.Cflag |= termiosMask(baudrate)
	settings.Ispeed = termiosMask(baudrate)
	settings.Ospeed = termiosMask(baudrate)
	return nil
}

func setTermSettingsParity(parity Parity, settings *syscall.Termios) error {
	switch parity {
	case PARITY_NONE:
		settings.Cflag &= ^termiosMask(syscall.PARENB | syscall.PARODD | tc_CMSPAR)
		settings.Iflag &= ^termiosMask(syscall.INPCK)
	case PARITY_ODD:
		settings.Cflag |= termiosMask(syscall.PARENB | syscall.PARODD)
		settings.Cflag &= ^termiosMask(tc_CMSPAR)
		settings.Iflag |= termiosMask(syscall.INPCK)
	case PARITY_EVEN:
		settings.Cflag &= ^termiosMask(syscall.PARODD | tc_CMSPAR)
		settings.Cflag |= termiosMask(syscall.PARENB)
		settings.Iflag |= termiosMask(syscall.INPCK)
	case PARITY_MARK:
		settings.Cflag |= termiosMask(syscall.PARENB | syscall.PARODD | tc_CMSPAR)
		settings.Iflag |= termiosMask(syscall.INPCK)
	case PARITY_SPACE:
		settings.Cflag &= ^termiosMask(syscall.PARODD)
		settings.Cflag |= termiosMask(syscall.PARENB | tc_CMSPAR)
		settings.Iflag |= termiosMask(syscall.INPCK)
	}
	return nil
}

func setTermSettingsDataBits(bits int, settings *syscall.Termios) error {
	databits, ok := databitsMap[bits]
	if !ok {
		return &SerialPortError{code: ERROR_INVALID_PORT_DATA_BITS}
	}
	settings.Cflag &= ^termiosMask(syscall.CSIZE)
	settings.Cflag |= termiosMask(databits)
	return nil
}

func setTermSettingsStopBits(bits StopBits, settings *syscall.Termios) error {
	switch bits {
	case STOPBITS_ONE:
		settings.Cflag &= ^termiosMask(syscall.CSTOPB)
	case STOPBITS_ONEPOINTFIVE, STOPBITS_TWO:
		settings.Cflag |= termiosMask(syscall.CSTOPB)
	}
	return nil
}

func setRawMode(settings *syscall.Termios, mode *Mode) {
	// Set local mode
	settings.Cflag |= termiosMask(syscall.CREAD | syscall.CLOCAL)

	// Set raw mode
	settings.Lflag &= ^termiosMask(syscall.ICANON | syscall.ECHO | syscall.ECHOE | syscall.ECHOK |
		syscall.ECHONL | syscall.ECHOCTL | syscall.ECHOPRT | syscall.ECHOKE | syscall.ISIG | syscall.IEXTEN)
	settings.Iflag &= ^termiosMask(syscall.IXON | syscall.IXOFF | syscall.IXANY | syscall.INPCK |
		syscall.IGNPAR | syscall.PARMRK | syscall.ISTRIP | syscall.IGNBRK | syscall.BRKINT | syscall.INLCR |
		syscall.IGNCR | syscall.ICRNL | tc_IUCLC)
	settings.Oflag &= ^termiosMask(syscall.OPOST)

	if mode.Vmin == 0 && mode.Vtimeout == 0 {
		// Switch to default mode
		// Block reads until at least one char is available (no timeout)
		mode.Vmin = 1
	}

	settings.Cc[syscall.VMIN] = mode.Vmin
	settings.Cc[syscall.VTIME] = mode.Vtimeout
}

// native syscall wrapper functions

func (port *SerialPort) getTermSettings() (*syscall.Termios, error) {
	settings := &syscall.Termios{}
	err := ioctl(port.handle, ioctl_tcgetattr, uintptr(unsafe.Pointer(settings)))
	return settings, err
}

func (port *SerialPort) setTermSettings(settings *syscall.Termios) error {
	return ioctl(port.handle, ioctl_tcsetattr, uintptr(unsafe.Pointer(settings)))
}

func (port *SerialPort) acquireExclusiveAccess() error {
	return ioctl(port.handle, syscall.TIOCEXCL, 0)
}

func (port *SerialPort) releaseExclusiveAccess() error {
	return ioctl(port.handle, syscall.TIOCNXCL, 0)
}

func (port *SerialPort) SetDTR(level bool) error {
	var status uint
	_, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(port.handle), uintptr(syscall.TIOCMGET), uintptr(unsafe.Pointer(&status)))
	if err == 0 {
		if level == false {
			status &= ^uint(syscall.TIOCM_DTR)
		} else {
			status |= syscall.TIOCM_DTR
		}
		_, _, err = syscall.Syscall(syscall.SYS_IOCTL, uintptr(port.handle), uintptr(syscall.TIOCMSET), uintptr(unsafe.Pointer(&status)))
	}
	return err
}


text:
/* @flow */

import { List, Seq, Set } from 'immutable'
import Connection         from 'imap'
import * as Kefir         from 'kefir'
import { inspect }        from 'util'
import { lift1, lift0 }   from '../../util/promises'

import type { Box, ImapMessage, ImapOpts, MessageAttributes } from 'imap'
import type { Stream }           from 'kefir'
import type { ReadStream }       from 'fs'
import type { OauthCredentials } from './google-oauth'
import type { XOAuth2Generator } from './tokenGenerator'

export {
  fetchMessages,
  fetchConversations,
  getConnection,
  openInbox,
  openAllMail,
  openDrafts,
  openImportant,
  openSent,
  openFlagged,
  openTrash,
  boxByAttribute,
  openBox,
}

export type Message = ReadStream

function getConnection(tokenGen: XOAuth2Generator): Promise<Connection> {
  return lift1(cb => tokenGen.getToken(cb))
  .then(auth => initImap({
    xoauth2: auth,
    host: 'imap.gmail.com',
    port: 993,
    tls: true,
  }))
}

// query is a Gmail search query.
// E.g.: newer_than:2d
function fetchMessages(query: string, imap: Connection): Stream<Message,any> {
  return _fetchMessages([['X-GM-RAW', query]], imap)
}

function _fetchMessages(criteria: any[], imap: Connection): Stream<Message,any> {
  const uidsPromise = openAllMail(true, imap).then(box => (
    lift1(cb => imap.search(criteria, cb))
  ))
  return Kefir.fromPromise(uidsPromise)
  .flatMap(uids => fetch(uids, { bodies: [''] }, imap))
  .flatMap(messageBodyStream)
}

function fetchConversations(query: string, imap: Connection, limit: number = 0): Stream<List<Message>,any> {
  const messageIds = openAllMail(true, imap).then(box => (
    lift1(cb => imap.search([['X-GM-RAW', query]], cb))
  ))

  const threadIds = Kefir.fromPromise(messageIds)
  .flatMap(uids => {
    const uids_ = limit > 0 ? uids.slice(0, limit) : uids
    return fetch(uids_, {/* metadata only */}, imap)
  })
  .flatMap(message => attributes(message))
  .scan(
    (threadIds, msgAttrs) => threadIds.add(msgAttrs['x-gm-thrid']), Set()
  )
  .last()

  return threadIds.flatMap(ids => {
    const threadStreams = ids.toArray().map(
      id => _fetchMessages([['X-GM-THRID', id]], imap).scan(
        (thread, message) => thread.push(message), List()
      )
      .last()
    )
    return Kefir.merge(threadStreams)
  })
}

// TODO: Use 'changedsince' option defined by RFC4551
function fetch(source: imap$MessageSource, opts: imap$FetchOptions, imap: Connection): Stream<ImapMessage,any> {
  return fromEventsWithEnd(imap.fetch(source, opts), 'message', (msg, seqno) => msg)
}

function attributes(message: ImapMessage): Stream<MessageAttributes,any> {
  return fromEventsWithEnd(message, 'attributes')
}

function messageBodyStream(msg: ImapMessage): Stream<Message,any> {
  return fromEventsWithEnd(msg, 'body', (stream, info) => stream)
}

function fromEventsWithEnd<T,S:events$EventEmitter>(
  eventSource: S,
  eventName: string,
  transform: ?((...values: any) => T) = null
): Stream<T,mixed> {
  return Kefir.stream(emitter => {
    eventSource.on(eventName, (...values) => {
      const value = transform ? transform(...values) : values[0]
      emitter.emit(value)
    })
    eventSource.on('error', err => { emitter.emit(err); emitter.end() })
    eventSource.once('end', () => { emitter.end() })
  })
}

// attributes example:
//
// { struct:
//    [ { type: 'alternative',
//        params: { boundary: '----=_Part_437079_307021065.1442840682149' },
//        disposition: null,
//        language: null },
//      [ { partID: '1',
//          type: 'text',
//          subtype: 'plain',
//          params: { charset: 'UTF-8' },
//          id: 'text-body',
//          description: null,
//          encoding: 'QUOTED-PRINTABLE',
//          size: 4117,
//          lines: 101,
//          md5: null,
//          disposition: null,
//          language: null } ],
//      [ { partID: '2',
//          type: 'text',
//          subtype: 'html',
//          params: { charset: 'UTF-8' },
//          id: 'html-body',
//          description: null,
//          encoding: 'QUOTED-PRINTABLE',
//          size: 79675,
//          lines: 1455,
//          md5: null,
//          disposition: null,
//          language: null } ] ],
//   date: Mon Sep 21 2015 06:04:59 GMT-0700 (PDT),
//   flags: [],
//   uid: 83528,
//   modseq: '1347582',
//   'x-gm-labels': [ '\\Inbox' ],
//   'x-gm-msgid': '1512928130170660058',
//   'x-gm-thrid': '1512928130170660058' }

function initImap(opts: ImapOpts): Promise<Connection> {
  var imap = new Connection(opts)
  var p = new Promise((resolve, reject) => {
    imap.once('ready', () => resolve(imap))
    imap.once('error', reject)
  })
  imap.connect()
  return p
}

function openInbox(readonly: boolean, imap: Connection): Promise<Box> {
  return lift1(cb => imap.openBox('INBOX', readonly, cb))
}

function openAllMail(readonly: boolean, imap: Connection): Promise<Box> {
  return openBox(boxByAttribute('\\All'), readonly, imap)
}

function openDrafts(readonly: boolean, imap: Connection): Promise<Box> {
  return openBox(boxByAttribute('\\Drafts'), readonly, imap)
}

function openImportant(readonly: boolean, imap: Connection): Promise<Box> {
  return openBox(boxByAttribute('\\Important'), readonly, imap)
}

function openSent(readonly: boolean, imap: Connection): Promise<Box> {
  return openBox(boxByAttribute('\\Sent'), readonly, imap)
}

function openFlagged(readonly: boolean, imap: Connection): Promise<Box> {
  return openBox(boxByAttribute('\\Flagged'), readonly, imap)
}

function openTrash(readonly: boolean, imap: Connection): Promise<Box> {
  return openBox(boxByAttribute('\\Trash'), readonly, imap)
}

function boxByAttribute(attribute: string): (box: Box) => boolean {
  return box => box.attribs.some(a => a === attribute)
}

function openBox(p: (box: imap$Box) => boolean, readonly: boolean, imap: Connection): Promise<Box> {
  return lift1(cb => imap.getBoxes(cb)).then(boxes => {
    var match = findBox(p, boxes)
    if (match) {
      var [path, box] = match
      return lift1(cb => imap.openBox(path, readonly, cb))
    }
    else {
      return Promise.reject(new Error("Box not found"))
    }
  })
}

function findBox(p: (box: imap$Box) => boolean, boxes: imap$Boxes, path?: string = ''): ?[string, imap$Box] {
  var pairs = Object.keys(boxes).map(k => [k, boxes[k]])
  var match = pairs.find(([_,b]) => p(b))
  if (match) {
    var [name, box] = match
    return [path + name, box]
  }
  else {
    return Seq(pairs).map(([n, b]) => (
      b.children ? findBox(p, b.children, n + b.delimiter) : null
    ))
    .filter(child => !!child)
    .first()
  }
}


text:
<?php

namespace backend\models\customer;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\customer\PublishedSite;
use backend\models\Seller;

/**
 * PublishedSiteSearch represents the model behind the search form about `backend\models\customer\PublishedSite`.
 */
class PublishedSiteSearch extends PublishedSite
{
    public $websiteDescription;
    public $domainName;
    public $themeName;
    public $customerName;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'website_id', 'designer_id', 'seller_id', 'customer_id', 'created_by', 'updated_by'], 'integer'],
            [['url', 'created_at', 'updated_at'], 'safe'],
            [['url_status'], 'boolean'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = PublishedSite::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'url_status' => $this->url_status,
            'website_id' => $this->website_id,
            'designer_id' => $this->designer_id,
            'seller_id' => $this->seller_id,
            'customer_id' => $this->customer_id,
            'created_at' => $this->created_at,
            'created_by' => $this->created_by,
            'updated_at' => $this->updated_at,
            'updated_by' => $this->updated_by,
        ]);

        $query->andFilterWhere(['like', 'url', $this->url]);

        return $dataProvider;
    }

    public function searchMyTemporaryPublishedWebsites($params)
    {
        $seller_id = Seller::findOne(['user_id' => $params['seller_user_id']])->id;

        $query = PublishedSiteSearch::find();

        $dataProvider = (new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                    'pageSize' => 10,
                ],
            ]));

        $dataProvider->setSort([
            'attributes' => [
                'id' => [
                    'asc' => ['published_site.id' => SORT_ASC],
                    'desc' => ['published_site.id' => SORT_DESC],
                    'label' => 'Id'
                ],
                'website_id' => [
                    'asc' => ['website_id' => SORT_ASC],
                    'desc' => ['website_id' => SORT_DESC],
                    'label' => 'Website Id'
                ],
                'url' => [
                    'asc' => ['url' => SORT_ASC],
                    'desc' => ['url' => SORT_DESC],
                    'label' => 'URL'
                ],
                'customer_id' => [
                    'asc' => ['customer_id' => SORT_ASC],
                    'desc' => ['customer_id' => SORT_DESC],
                    'label' => 'Customer Id'
                ],
                'customerName' => [
                    'asc' => ['customer.name' => SORT_ASC],
                    'desc' => ['customer.name' => SORT_DESC],
                    'label' => 'Full Name'
                ],
                'domainName' => [
                    'asc' => ['domain.name' => SORT_ASC],
                    'desc' => ['domain.name' => SORT_DESC],
                    'label' => 'Domain Name'
                ],
                'themeName' => [
                    'asc' => ['theme.name' => SORT_ASC],
                    'desc' => ['theme.name' => SORT_DESC],
                    'label' => 'Theme Name'
                ],
                'websiteDescription' => [
                    'asc' => ['website.description' => SORT_ASC],
                    'desc' => ['website.description' => SORT_DESC],
                    'label' => 'Website Description'
                ],
            ]
        ]);

        $query->select([
                'published_site.id',
                'website_id',
                'website.description AS websiteDescription',
                'url',
                'url_status',
                'domain.name AS domainName',
                'theme.name AS themeName',
                'customer.name AS customerName',
            ])
            ->innerJoin('website', 'website.id = website_id')
            ->innerJoin('seller', ['seller.id' => $seller_id]) // This seller
            ->innerJoin('domain','domain.id = website.domain_id')
            ->innerJoin('theme','theme.id = website.theme_id')
            ->innerJoin('customer','customer.id = published_site.customer_id')
            ->where('domain.domain_status_value=40')
            ->all();

        $this->load($params);

        return $dataProvider;
    }

    public function searchMyPublishedWebsites($params)
    {
        $seller_id = Seller::findOne(['user_id' => $params['seller_user_id']])->id;

        $query = PublishedSiteSearch::find();

        $dataProvider = (new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                    'pageSize' => 10,
                ],
            ]));

        $dataProvider->setSort([
            'attributes' => [
                'id' => [
                    'asc' => ['published_site.id' => SORT_ASC],
                    'desc' => ['published_site.id' => SORT_DESC],
                    'label' => 'Id'
                ],
                'website_id' => [
                    'asc' => ['website_id' => SORT_ASC],
                    'desc' => ['website_id' => SORT_DESC],
                    'label' => 'Website Id'
                ],
                'url' => [
                    'asc' => ['url' => SORT_ASC],
                    'desc' => ['url' => SORT_DESC],
                    'label' => 'URL'
                ],
                'customer_id' => [
                    'asc' => ['customer_id' => SORT_ASC],
                    'desc' => ['customer_id' => SORT_DESC],
                    'label' => 'Customer Id'
                ],
                'customerName' => [
                    'asc' => ['customer.name' => SORT_ASC],
                    'desc' => ['customer.name' => SORT_DESC],
                    'label' => 'Full Name'
                ],
                'domainName' => [
                    'asc' => ['domain.name' => SORT_ASC],
                    'desc' => ['domain.name' => SORT_DESC],
                    'label' => 'Domain Name'
                ],
                'themeName' => [
                    'asc' => ['theme.name' => SORT_ASC],
                    'desc' => ['theme.name' => SORT_DESC],
                    'label' => 'Theme Name'
                ],
                'websiteDescription' => [
                    'asc' => ['website.description' => SORT_ASC],
                    'desc' => ['website.description' => SORT_DESC],
                    'label' => 'Website Description'
                ],
            ]
        ]);

        $query->select([
                'published_site.id',
                'website_id',
                'website.description AS websiteDescription',
                'url',
                'url_status',
                'domain.name AS domainName',
                'theme.name AS themeName',
                'customer.name AS customerName',
            ])
            ->innerJoin('website', 'website.id = website_id')
            ->innerJoin('seller', ['seller.id' => $seller_id]) // This seller
            ->innerJoin('domain','domain.id = website.domain_id')
            ->innerJoin('theme','theme.id = website.theme_id')
            ->innerJoin('customer','customer.id = published_site.customer_id')
            ->where('domain.domain_status_value=70')
            ->all();

        $this->load($params);

        return $dataProvider;
    }
}


text:
package com.vaadin.tests.components.combobox;

import java.util.LinkedHashMap;

import com.vaadin.server.Resource;
import com.vaadin.shared.ui.combobox.FilteringMode;
import com.vaadin.tests.components.select.AbstractSelectTestCase;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.ComboBox.ItemStyleGenerator;

public class ComboBoxes2<T extends ComboBox> extends AbstractSelectTestCase<T> {

    private Command<T, String> inputPromptCommand = new Command<T, String>() {
        @Override
        public void execute(T c, String value, Object data) {
            c.setInputPrompt(value);
        }
    };
    private Command<T, FilteringMode> filteringModeCommand = new Command<T, FilteringMode>() {

        @Override
        public void execute(T c, FilteringMode value, Object data) {
            c.setFilteringMode(value);
        }
    };

    private Command<T, ItemStyleGenerator> itemStyleGeneratorCommand = new Command<T, ItemStyleGenerator>() {
        @Override
        public void execute(T c, ItemStyleGenerator value, Object data) {
            c.setItemStyleGenerator(value);
        }
    };

    @Override
    protected Class<T> getTestClass() {
        return (Class<T>) ComboBox.class;
    }

    @Override
    protected void createActions() {
        super.createActions();
        createItemIconSelect(CATEGORY_DATA_SOURCE);
        createInputPromptAction(CATEGORY_FEATURES);
        createFilteringModeAction(CATEGORY_FEATURES);
        createItemStyleGeneratorAction(CATEGORY_FEATURES);
        createNewItemsAllowedAction(CATEGORY_STATE);
        createTextInputAlowedAction(CATEGORY_STATE);
    }

    private void createTextInputAlowedAction(String category) {
        createBooleanAction("Text input allowed", category, true,
                new Command<T, Boolean>() {
                    @Override
                    public void execute(T c, Boolean value, Object data) {
                        c.setTextInputAllowed(value.booleanValue());
                    }
                });
    }

    private void createNewItemsAllowedAction(String category) {
        createBooleanAction("New items allowed", category, false,
                new Command<T, Boolean>() {
                    @Override
                    public void execute(T c, Boolean value, Object data) {
                        c.setNewItemsAllowed(value.booleanValue());
                    }
                });
    }

    private void createFilteringModeAction(String category) {
        LinkedHashMap<String, FilteringMode> options = new LinkedHashMap<String, FilteringMode>();
        options.put("Off", FilteringMode.OFF);
        options.put("Contains", FilteringMode.CONTAINS);
        options.put("Starts with", FilteringMode.STARTSWITH);

        createSelectAction("Filtering mode", category, options, "Contains",
                filteringModeCommand);

    }

    private void createItemStyleGeneratorAction(String category) {
        LinkedHashMap<String, ItemStyleGenerator> options = new LinkedHashMap<String, ItemStyleGenerator>();
        options.put("-", null);
        options.put("Bold fives", new ItemStyleGenerator() {
            @Override
            public String getStyle(ComboBox source, Object itemId) {
                if (String.valueOf(itemId).indexOf('5') != -1) {
                    return "bold";
                } else {
                    return null;
                }
            }
        });
        createSelectAction("Item style generator", category, options, "-",
                itemStyleGeneratorCommand);
    }

    private void createInputPromptAction(String category) {
        LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();
        options.put("-", null);
        options.put("Enter a value", "Enter a value");
        options.put("- Click here -", "- Click here -");
        createSelectAction("Input prompt", category, options, "-",
                inputPromptCommand);

    }

    private void createItemIconSelect(String category) {

        createSelectAction("Icon", category, createIconOptions(false), "-",
                new Command<T, Resource>() {

                    @Override
                    public void execute(T c, Resource value, Object data) {
                        for (Object id : c.getItemIds()) {
                            if (value == null) {
                                c.setItemIcon(id, null);
                            } else {
                                c.setItemIcon(id, value);
                            }
                        }
                    }
                });
    }

}


text:
ActiveRecord::Schema.define(version: 20171128190949) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "security_groups", force: :cascade do |t|
    t.string   "name",          :null=>false, :index=>{:name=>"index_security_groups_on_name", :unique=>true, :using=>:btree}
    t.boolean  "admin",         :default=>false, :null=>false
    t.boolean  "read_user",     :default=>false, :null=>false
    t.boolean  "read_audit",    :default=>false, :null=>false
    t.datetime "created_at"
    t.datetime "updated_at"
    t.boolean  "create_parent", :default=>false, :null=>false
  end

  create_table "user_statuses", force: :cascade do |t|
    t.string   "name",           :null=>false, :index=>{:name=>"index_user_statuses_on_name", :unique=>true, :using=>:btree}
    t.boolean  "active",         :default=>false, :null=>false
    t.boolean  "validate_email", :default=>true, :null=>false
    t.datetime "created_at",     :null=>false
    t.datetime "updated_at",     :null=>false
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  :limit=>255, :default=>"", :null=>false, :index=>{:name=>"index_users_on_email", :unique=>true, :using=>:btree}
    t.string   "encrypted_password",     :limit=>255, :default=>"", :null=>false
    t.string   "reset_password_token",   :limit=>255, :index=>{:name=>"index_users_on_reset_password_token", :unique=>true, :using=>:btree}
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          :default=>0, :null=>false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip",     :limit=>255
    t.string   "last_sign_in_ip",        :limit=>255
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "confirmation_token",     :limit=>255, :index=>{:name=>"index_users_on_confirmation_token", :unique=>true, :using=>:btree}
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string   "unconfirmed_email",      :limit=>255
    t.string   "first_name",             :limit=>255, :index=>{:name=>"index_users_on_first_name", :using=>:btree}
    t.string   "last_name",              :limit=>255, :index=>{:name=>"index_users_on_last_name", :using=>:btree}
    t.string   "username",               :limit=>255, :index=>{:name=>"index_users_on_username", :unique=>true, :using=>:btree}
    t.string   "mobile_phone",           :limit=>255
    t.string   "facebook_id",            :limit=>255
    t.text     "facebook_access_token"
    t.datetime "facebook_expires_at"
    t.string   "timezone",               :limit=>255
    t.string   "provider_avatar",        :limit=>255
    t.string   "avatar_file_name",       :limit=>255
    t.string   "avatar_content_type",    :limit=>255
    t.integer  "avatar_file_size"
    t.datetime "avatar_updated_at"
    t.boolean  "admin",                  :default=>false, :null=>false
    t.boolean  "optional_emails",        :default=>true, :null=>false
    t.string   "global_search_default",  :limit=>255
    t.boolean  "super_admin",            :default=>false, :null=>false
    t.integer  "security_group_id",      :null=>false, :index=>{:name=>"fk__users_security_group_id", :using=>:btree}, :foreign_key=>{:references=>"security_groups", :name=>"fk_users_security_group_id", :on_update=>:no_action, :on_delete=>:no_action}
    t.integer  "user_status_id",         :null=>false, :index=>{:name=>"fk__users_user_status_id", :using=>:btree}, :foreign_key=>{:references=>"user_statuses", :name=>"fk_users_user_status_id", :on_update=>:no_action, :on_delete=>:no_action}
  end

  create_table "audits", force: :cascade do |t|
    t.integer  "auditable_id",    :index=>{:name=>"auditable_index", :with=>["auditable_type"], :using=>:btree}
    t.string   "auditable_type"
    t.integer  "associated_id",   :index=>{:name=>"associated_index", :with=>["associated_type"], :using=>:btree}
    t.string   "associated_type"
    t.integer  "user_id",         :index=>{:name=>"fk__audits_user_id", :using=>:btree}, :foreign_key=>{:references=>"users", :name=>"fk_audits_user_id", :on_update=>:no_action, :on_delete=>:no_action}
    t.string   "user_type"
    t.string   "username"
    t.string   "action"
    t.text     "audited_changes"
    t.integer  "version",         :default=>0
    t.string   "comment"
    t.string   "remote_address"
    t.string   "request_uuid",    :index=>{:name=>"index_audits_on_request_uuid", :using=>:btree}
    t.datetime "created_at",      :index=>{:name=>"index_audits_on_created_at", :using=>:btree}

    t.index ["user_id", "user_type"], :name=>"user_index", :using=>:btree
  end

  create_table "companies", force: :cascade do |t|
    t.string   "name",                       :limit=>255, :null=>false
    t.string   "phone_number",               :limit=>255, :null=>false
    t.string   "website",                    :limit=>255, :null=>false
    t.string   "email",                      :limit=>255, :null=>false
    t.string   "address_1",                  :limit=>255, :null=>false
    t.string   "address_2",                  :limit=>255
    t.string   "city",                       :limit=>255, :null=>false
    t.string   "state",                      :limit=>255, :null=>false
    t.string   "zipcode",                    :limit=>255, :null=>false
    t.datetime "created_at"
    t.datetime "updated_at"
    t.boolean  "company_logo_includes_name", :default=>false, :null=>false
    t.boolean  "app_logo_includes_name",     :default=>false, :null=>false
    t.datetime "validity_checked_at"
  end

  create_table "divisions", force: :cascade do |t|
    t.string   "name",       :null=>false
    t.string   "code",       :null=>false
    t.integer  "owner_id",   :null=>false, :index=>{:name=>"fk__divisions_owner_id", :using=>:btree}, :foreign_key=>{:references=>"users", :name=>"fk_divisions_owner_id", :on_update=>:no_action, :on_delete=>:no_action}
    t.datetime "created_at", :null=>false
    t.datetime "updated_at", :null=>false
  end

end


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

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="64dp"
        android:background="@color/bg_red" >

        <TextView
            android:id="@+id/tv_search"
            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:background="@drawable/tv_search_bg"
            android:drawableLeft="@android:drawable/ic_menu_search"
            android:drawablePadding="10dp"
            android:gravity="center_vertical"
            android:text="鸡蛋 大米 猪肉"
            android:textColor="@color/text_gray"
            android:textSize="15sp" />
    </RelativeLayout>

    <ListView
        android:id="@+id/lv_products"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

</LinearLayout>


text:
"""
Test experiments
"""

import unittest
import shutil
from numpy.testing import assert_array_equal, assert_almost_equal, assert_equal
from expfactory.experiment import validate, load_experiment, load_experiments, \
get_experiments, make_lookup
from expfactory.utils import copy_directory, get_installdir
import tempfile
import json
import os

class TestExperiment(unittest.TestCase):

    def setUp(self):
        self.pwd = get_installdir()
        self.battery_folder = "%s/testing/data" %self.pwd
        self.experiment = os.path.abspath("%s/testing/data/test_task/" %self.pwd)
        self.config = json.load(open("%s/testing/data/test_task/config.json" %self.pwd,"rb"))
        self.tmpdir = tempfile.mkdtemp()

    def tearDown(self):
        shutil.rmtree(self.tmpdir)

    def test_find_experiments(self):

        # Test loading experiment folder path
        experiments = get_experiments(self.battery_folder)
        assert_equal(len(experiments),1)
        self.assertTrue(isinstance(experiments[0],str))

        # Test loading experiment dictionary
        config = get_experiments(self.battery_folder,load=True)
        self.assertTrue(isinstance(config[0][0],dict))

        loaded_experiment = load_experiment(self.experiment)
        self.assertTrue(isinstance(loaded_experiment[0],dict))

    def test_make_lookup(self):
        lookup = make_lookup([self.config],"exp_id")
        self.assertTrue("test_task" in lookup)

    def test_validate(self):
        validation = validate(self.experiment)
        self.assertTrue(validation)

        # Create temporary directory and test invalid config.json
        broken_experiment = "%s/broken_experiment" %self.tmpdir
        copy_directory(self.experiment,broken_experiment)

        # Missing file specified
        shutil.copyfile("%s/experiment.js" %broken_experiment,"%s/pizza.js" %broken_experiment)
        os.remove("%s/experiment.js" %broken_experiment)
        self.assertFalse(validate(broken_experiment))
        shutil.copyfile("%s/pizza.js" %broken_experiment,"%s/experiment.js" %broken_experiment)

        # Invalid field for template
        broken_config = self.config[:]
        broken_config[0]["template"] = "invalid_framework"
        self.save_config(broken_config,broken_experiment)
        self.assertFalse(validate(broken_experiment))

        # Missing required field
        broken_config = self.config[:]
        del broken_config[0]["exp_id"]
        self.save_config(broken_config,broken_experiment)
        self.assertFalse(validate(broken_experiment))

    def save_config(self,config_file,directory):
        json.dumps(config_file,open("%s/config.json"%directory,"w"))

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


text:
package org.javamvc.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;

/**
 * Base class for controllers. It implements some common convenience methods and
 * performs necessary initialization. A controller instance is not expected to
 * keep any per-request information, i.e., a controller is expected to be a
 * stateless object. A new instance of a controller will be created for each
 * HTTP request targeted to be handled by a controller.
 *
 * Any view rendered via a {@link #View()} method of this class will expect the
 * view templates to be present under Views directory under the web root.
 * For example, in case of the following content present under web root:
 *

 *
 * |-WEB-INF
 * |-Views
 *     |-SomeController
 *          |-home.html
 *          |-listing.html
 *

 *
 * invoking URL http://server:port/MyContext/SomeController/home.a
 * will result in action home() getting called on controller named
 * SomeController. Inside home() you can render a
 * view by calling suitable {@link #View()} methods. (Here we assumed that
 * controller servlet is configured to take all requests ending in .a).
 *
 * A view can only be rendered via a controller.
 * @author Balwinder Sodhi
 */
public abstract class Controller {

    protected HttpServletRequest request;
    protected ServletContext context;
    protected HttpServletResponse response;
    protected ViewProvider viewProvider;
    protected MemCacheProvider cache;
    private Logger logger = Logger.getLogger(Controller.class.getName());

    /**
     * Initializes the controller instance. It injects a suitable
     * {@link ViewProvider} and also the {@link HttpServletRequest},
     * {@link HttpServletResponse} and {@link ServletContext} objects
     * associated with current request.
     * @param cache Cached data across the application.
     * @param context ServletContext reference.
     * @param req Request object being handled.
     * @param res Response object.
     * @param vp View provider instance to be used for producing the view.
     */
    public void init(MemCacheProvider cache, ServletContext context,
            HttpServletRequest req, HttpServletResponse res, ViewProvider vp) {
        this.cache = cache;
        this.context = context;
        this.request = req;
        this.response = res;
        this.viewProvider = vp;
        try {
            trace();
        } catch (Exception ex) {
            /**
             * Initializing a controller should not stop due to any errors in
             * trace method. So we simply print the error and continue.
             */
            ex.printStackTrace();
        }
    }

    /**
     * You can log any request specific information by overriding this method in
     * a controller subclass. Default implementation provided by this class does
     * nothing.
     */
    public void trace() {
        // Do nothing. Subclass should log trace info if needed.
    }

    /**
     * Returns the value of specified extra config property.
     * @see ControllerServlet
     * @param key Name of the extra config property.
     * @return Value of the property if found, else returns null.
     */
    public String getConfigValue(String key) {
        String value=null;
        Properties conf = (Properties) context.
                getAttribute(ControllerServlet.EXTRA_CONFIG);
        if (conf != null) {
            value = conf.getProperty(key);
        }
        return value;
    }

    /**
     * Sends the error response via JSON message to the client. HTTP response is
     * flushed.
     *
     * @param httpStatusCode Error status code to send.
     * @param message JSON string.
     * @throws IOException
     */
    public void sendJsonErrorResponse(int httpStatusCode, String message) throws IOException {
        response.setContentType("application/json");
        response.setStatus(httpStatusCode);
        response.getWriter().write(message);
        response.flushBuffer();
    }

    /**
     * Checks for the presence of json in Accept
     * header of HTTP request.
     *
     * @return
     */
    public boolean isJsonRequest() {
        String accept = request.getHeader("Accept");
        return accept.toLowerCase().contains("json");
    }

    /**
     * Reads the string data line by line from {@link BufferedReader} object of
     * the current HTTP request.
     *
     * @return Request data as string.
     * @throws IOException
     */
    public String getJsonData() throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        try {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } finally {
            reader.close();
        }
        String json = sb.toString();
        logger.fine("JSON data extracted from request: "+json);
        return json;
    }

    /**
     * Returns reference to the {@link ViewProvider} configured for the
     * {@link ControllerServlet}. Default is {@link FreemarkerViewProvider}.
     *
     * @return
     */
    public ViewProvider getViewProvider() {
        return viewProvider;
    }

    /**
     * Returns the reference to current HTTP request being handled.
     *
     * @return
     */
    public HttpServletRequest getRequest() {
        return request;
    }

    /**
     * Returns the reference to response object for current HTTP request.
     *
     * @return
     */
    public HttpServletResponse getResponse() {
        return response;
    }

    public MemCacheProvider getMemCache() {
        return cache;
    }

    public ServletContext getContext() {
        return context;
    }

    /**
     * Populates specified template with given model.
     * @param templatePath Path of the template to be filled.
     * @param model Model with which to fill the template
     * @return Filled template as a string
     * @throws IOException
     */
    public String populateTemplate(String templatePath, Object model) throws IOException {
        logger.fine("Populating template "+templatePath+" with model: "+model);
        return viewProvider.renderView(templatePath, model);
    }

    /**
     * Finds the template for given view name and fills it with the supplied
     * model object's data. The filled template is then sent back to client as
     * string response. View template must be present under
     * {Web root}/Views/{Controller name} folder.
     *
     * @param viewName
     * @param model
     * @throws IOException
     */
    public void View(String viewName, Object model) throws IOException {
        String result = viewProvider.renderView(findViewName(viewName), model);
        logger.fine("Rendered view: "+result);
        sendViewResponse(result);
    }

    /**
     * Finds the template for default view name (which is same as action name)
     * and fills it with the supplied model object's data. The filled template
     * is then sent back to client as string response. View template
     * must be present under {Web root}/Views/{Controller name}
     * folder.
     * @param model
     * @throws IOException
     */
    public void View(Object model) throws IOException {
        View(null, model);
    }

    /**
     * Finds the template for default view name (which is same as action name)
     * and sent the empty view back to client as string response. View template
     * must be present under {Web root}/Views/{Controller name}
     * folder.
     *
     * @throws IOException
     */
    public void View() throws IOException {
        View(null, null);
    }

    /**
     * Sends the given string as response to the client. Suitable headers are
     * set on response so as to prevent caching by browser. Content type is set
     * as "text/html;charset=UTF-8".
     *
     * @param result
     * @throws IOException
     */
    private void sendViewResponse(String result) throws IOException {
        // No caching
        response.setHeader("Expires", "Tue, 03 Jul 1990 06:00:00 GMT");
        response.setDateHeader("Last-Modified", new Date().getTime());
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter w = response.getWriter();
        w.write(result);
        w.flush();
    }

    /**
     * Sends given JSON string as response to the client.
     *
     * @param json
     * @throws IOException
     */
    public void Json(String json) throws IOException {
        response.setContentType("text/json;charset=UTF-8");
        PrintWriter w = response.getWriter();
        w.write(json);
        w.flush();
        logger.fine("Sent JSON response: "+json);
    }

    /**
     * Sends given JSON string as response to the client.
     *
     * @param json
     * @throws IOException
     */
    public void JsonScript(String json) throws IOException {
        response.setContentType("text/javascript;charset=UTF-8");
        PrintWriter w = response.getWriter();
        w.write(json);
        w.flush();
    }

    /**
     * Calculates the full path of the given view. If supplied view name is
     * null, then name of calling method in controller is taken as view name.
     * Final name is of the form: Views/MyController/MyView.
     *
     * @param viewNm
     * @return
     */
    private String findViewName(String viewNm) {
        if (viewNm == null) {
            // By default view name is same as calling method name in controller.
            StackTraceElement[] st = Thread.currentThread().getStackTrace();
            viewNm = st[4].getMethodName();
        }
        String ct = getClass().getSimpleName();
        String view = "Views/" + ct + "/" + viewNm;
        logger.fine("View path: "+view);
        return view;
    }

    protected <T> void fromRequestParamsToObj(T obj)
            throws IllegalAccessException, InvocationTargetException {
        BeanUtils.populate(obj, request.getParameterMap());
    }

}


text:
   /**
    *  Gets URI that identifies the test.
    *  @return uri identifier of test
    */
function getTargetURI() {
      return "http://www.w3.org/2001/DOM-Test-Suite/level3/core/nodeinsertbefore14";
   }

var docsLoaded = -1000000;
var builder = null;

//
//   This function is called by the testing framework before
//      running the test suite.
//
//   If there are no configuration exceptions, asynchronous
//        document loading is started.  Otherwise, the status
//        is set to complete and the exception is immediately
//        raised when entering the body of the test.
//
function setUpPage() {
   setUpPageStatus = 'running';
   try {
     //
     //   creates test document builder, may throw exception
     //
     builder = createConfiguredBuilder();
       setImplementationAttribute("namespaceAware", true);

      docsLoaded = 0;

      var docRef = null;
      if (typeof(this.doc) != 'undefined') {
        docRef = this.doc;
      }
      docsLoaded += preload(docRef, "doc", "hc_staff");

       if (docsLoaded == 1) {
          setUpPageStatus = 'complete';
       }
    } catch(ex) {
    	catchInitializationError(builder, ex);
        setUpPageStatus = 'complete';
    }
}

//
//   This method is called on the completion of
//      each asychronous load started in setUpTests.
//
//   When every synchronous loaded document has completed,
//      the page status is changed which allows the
//      body of the test to be executed.
function loadComplete() {
    if (++docsLoaded == 1) {
        setUpPageStatus = 'complete';
    }
}

/**
*
	The method insertBefore inserts the node newChild before the existing child node refChild.
	If refChild is null, insert newChild at the end of the list of children.
	A NO_MODIFICATION_ALLOWED_ERR is raised if the node is read-only.

	Using insertBefore on this Document node attempt to insert a new Attr node before
	this DocumentType node and verfiy if a NO_MODIFICATION_ALLOWED_ERR is raised.
	(This can also raise a HIERARCHY_REQUEST_ERR and NOT_FOUND_ERR)

* @author IBM
* @author Neil Delima
* @see http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core#ID-952280727
*/
function nodeinsertbefore14() {
   var success;
    if(checkInitialization(builder, "nodeinsertbefore14") != null) return;
    var doc;
      var docType;
      var newAttr;
      var inserted;

      var docRef = null;
      if (typeof(this.doc) != 'undefined') {
        docRef = this.doc;
      }
      doc = load(docRef, "doc", "hc_staff");
      docType = doc.doctype;

      newAttr = doc.createAttribute("dom3:attr");

	{
		success = false;
		try {
            inserted = docType.insertBefore(newAttr,docType);
        }
		catch(ex) {
      success = (typeof(ex.code) != 'undefined' && ex.code == 7);
		}
		assertTrue("NO_MODIFICATION_ALLOWED_ERR_nodeinsertbefore14",success);
	}

}

function runTest() {
   nodeinsertbefore14();
}


text:
using Stream::FileStream;

/// \note when a file on a floppy or cdrom drive is tried to open without a disc in the drive,
///       a message box appears asking for a disc in the drive. Use SetErrorMode with flag
///       SEM_FAILCRITICALERRORS to prevent this.
/// \exception StreamException thrown when file couldn't be opened
FileStream::FileStream(LPCTSTR filename, EFileMode fileMode, EFileAccess fileAccess, EFileShare fileShare)
   :m_fileAccess(fileAccess),
   m_atEndOfFile(true),
   m_fileLength((ULONGLONG)-1)
{
   ATLASSERT(filename != NULL);

#if defined(DEBUG) || defined(_DEBUG)
   if (fileMode == modeTruncate) // write access needed in modeTruncate
      ATLASSERT((fileAccess & FileStream::accessWrite) != 0);
#endif

   HANDLE fileHandle = CreateFile(filename,
      static_cast<DWORD>(fileAccess), // desired access
      static_cast<DWORD>(fileShare), // share mode
      NULL, // security attributes
      static_cast<DWORD>(fileMode == modeAppend ? modeOpen : fileMode),
      FILE_ATTRIBUTE_NORMAL,
      NULL); // template file handle

   if (fileHandle == INVALID_HANDLE_VALUE)
      throw Stream::StreamException(Win32::ErrorMessage().ToString() + filename, __FILE__, __LINE__);

   m_spHandle = std::shared_ptr<void>(fileHandle, CloseHandle);

   m_atEndOfFile = false;

   if (fileMode == modeAppend)
      Seek(0L, FileStream::seekEnd);

   // cppcheck-suppress resourceLeak
}

/// \exception StreamException thrown when reading fails
bool FileStream::Read(void* buffer, DWORD maxBufferLength, DWORD& numBytesRead)
{
   ATLASSERT(m_spHandle.get() != NULL);
   ATLASSERT(true == CanRead());

   numBytesRead = 0;
   BOOL ret = ::ReadFile(m_spHandle.get(), buffer, maxBufferLength, &numBytesRead, NULL);

   if (ret == FALSE)
      throw Stream::StreamException(_T("Read: ") + Win32::ErrorMessage().ToString(), __FILE__, __LINE__);

   return numBytesRead != 0;
}

bool FileStream::AtEndOfStream() const
{
   if (!IsOpen() || m_atEndOfFile)
      return true;

   try
   {
      FileStream& rThis = const_cast<FileStream&>(*this);

      // find out current file pointer
      ULONGLONG currentPos = rThis.Position();
      ULONGLONG endPos = rThis.Length();

      if (currentPos == endPos)
         return true;
   }
   catch (const Stream::StreamException&)
   {
      // exception while seek: possibly on end of stream
      return true;
   }

   return false;
}

/// \exception StreamException thrown when writing fails
void FileStream::Write(const void* dataToWrite, DWORD lengthInBytes, DWORD& numBytesWritten)
{
   ATLASSERT(m_spHandle.get() != NULL);
   ATLASSERT(true == CanWrite());

   numBytesWritten = 0;
   BOOL ret = ::WriteFile(m_spHandle.get(), dataToWrite,
      lengthInBytes, &numBytesWritten, NULL);

   if (ret == FALSE)
      throw Stream::StreamException(_T("Write: ") + Win32::ErrorMessage().ToString(), __FILE__, __LINE__);

   if (m_fileLength != (ULONGLONG)-1)
   {
      // invalidate file length when writing beyond current end of file
      ULONGLONG position = Position();
      if (position > m_fileLength)
         m_fileLength = (ULONGLONG)-1;
   }
}

/// \exception StreamException thrown when setting file position fails
ULONGLONG FileStream::Seek(LONGLONG seekOffset, ESeekOrigin origin)
{
   ATLASSERT(m_spHandle.get() != NULL);
   ATLASSERT(true == CanSeek());

   LARGE_INTEGER li;
   li.QuadPart = seekOffset;

   li.LowPart = ::SetFilePointer(m_spHandle.get(),
      li.LowPart,
      &li.HighPart,
      static_cast<DWORD>(origin));

   // win32 may have returned error, or the low part just was 0xffffffff
   if (li.LowPart == INVALID_SET_FILE_POINTER)
   {
      // ... so also check last error
      DWORD dwLastError = GetLastError();
      if (dwLastError != ERROR_SUCCESS)
         throw Stream::StreamException(_T("Seek: ") + Win32::ErrorMessage().ToString(), __FILE__, __LINE__);
   }

   return li.QuadPart;
}

/// \exception StreamException thrown when getting position fails
ULONGLONG FileStream::Position()
{
   return Seek(0L, seekCurrent);
}

/// \exception StreamException thrown when getting file size fails
ULONGLONG FileStream::Length()
{
   ATLASSERT(m_spHandle.get() != NULL);

   if (m_fileLength != (ULONGLONG)-1)
      return m_fileLength;

#ifdef _WIN32_WCE
   // CE has no GetFileSizeEx, so we have to use GetFileSize
   LARGE_INTEGER fileSize; fileSize.QuadPart = 0;
   DWORD dwRet = ::GetFileSize(m_spHandle.get(), reinterpret_cast<ULONG*>(&fileSize.HighPart));
   if (dwRet == 0xffffffff)
   {
      DWORD dwError = GetLastError();

      if (dwError != NO_ERROR)
         throw Stream::StreamException(_T("Length: ") + Tools::CWin32ErrorMessage(dwError).GetMessage(), __FILE__, __LINE__);
   }
#else
   LARGE_INTEGER fileSize; fileSize.QuadPart = 0;
   BOOL ret = ::GetFileSizeEx(m_spHandle.get(), &fileSize);

   if (ret == FALSE)
      throw Stream::StreamException(_T("Length: ") + Win32::ErrorMessage().ToString(), __FILE__, __LINE__);
#endif

   // cache in case we need it later
   m_fileLength = fileSize.QuadPart;

   return fileSize.QuadPart;
}

/// \exception StreamException thrown when flushing the file fails
void FileStream::Flush()
{
   ATLASSERT(m_spHandle.get() != NULL);
   ATLASSERT(true == CanWrite());

   BOOL ret = ::FlushFileBuffers(m_spHandle.get());

   if (ret == FALSE)
      throw Stream::StreamException(_T("Flush: ") + Win32::ErrorMessage().ToString(), __FILE__, __LINE__);
}

void FileStream::Close()
{
   ATLASSERT(m_spHandle.get() != NULL);

   m_spHandle.reset();

   m_atEndOfFile = true;
}