text:
package org.komamitsu.fluency.aws.s3;

import org.komamitsu.fluency.Fluency;
import org.komamitsu.fluency.aws.s3.ingester.DefaultS3DestinationDecider;
import org.komamitsu.fluency.aws.s3.ingester.S3DestinationDecider;
import org.komamitsu.fluency.aws.s3.recordformat.AwsS3RecordFormatter;
import org.komamitsu.fluency.aws.s3.recordformat.CsvRecordFormatter;
import org.komamitsu.fluency.aws.s3.recordformat.JsonlRecordFormatter;
import org.komamitsu.fluency.aws.s3.recordformat.MessagePackRecordFormatter;
import org.komamitsu.fluency.aws.s3.ingester.AwsS3Ingester;
import org.komamitsu.fluency.aws.s3.ingester.sender.AwsS3Sender;
import org.msgpack.core.annotations.VisibleForTesting;
import software.amazon.awssdk.services.s3.S3Client;

import java.time.ZoneId;
import java.util.List;

public class FluencyBuilderForAwsS3
        extends org.komamitsu.fluency.FluencyBuilder
{
    private FormatType formatType;
    private List<String> formatCsvColumnNames;
    private String awsEndpoint;
    private String awsRegion;
    private String awsAccessKeyId;
    private String awsSecretAccessKey;
    private Integer senderRetryMax;
    private Integer senderRetryIntervalMillis;
    private Integer senderMaxRetryIntervalMillis;
    private Float senderRetryFactor;
    private Integer senderWorkBufSize;
    private boolean compressionEnabled = true;
    private String s3KeyPrefix;
    private String s3KeySuffix;
    private ZoneId s3KeyTimeZoneId;
    private S3DestinationDecider customS3DestinationDecider;

    public enum FormatType {
        MESSAGE_PACK,
        JSONL,
        CSV
    }

    public FluencyBuilderForAwsS3()
    {
        setBufferChunkRetentionTimeMillis(30 * 1000);
        setBufferChunkInitialSize(4 * 1024 * 1024);
        setBufferChunkRetentionSize(64 * 1024 * 1024);
    }

    public FormatType getFormatType()
    {
        return formatType;
    }

    public void setFormatType(FormatType formatType)
    {
        this.formatType = formatType;
    }

    public List<String> getFormatCsvColumnNames()
    {
        return formatCsvColumnNames;
    }

    public void setFormatCsvColumnNames(List<String> formatCsvColumnNames)
    {
        this.formatCsvColumnNames = formatCsvColumnNames;
    }

    public String getAwsEndpoint()
    {
        return awsEndpoint;
    }

    public void setAwsEndpoint(String awsEndpoint)
    {
        this.awsEndpoint = awsEndpoint;
    }

    public String getAwsRegion()
    {
        return awsRegion;
    }

    public void setAwsRegion(String awsRegion)
    {
        this.awsRegion = awsRegion;
    }

    public String getAwsAccessKeyId()
    {
        return awsAccessKeyId;
    }

    public void setAwsAccessKeyId(String senderAwsAccessKeyId)
    {
        this.awsAccessKeyId = senderAwsAccessKeyId;
    }

    public String getAwsSecretAccessKey()
    {
        return awsSecretAccessKey;
    }

    public void setAwsSecretAccessKey(String senderAwsSecretAccessKey)
    {
        this.awsSecretAccessKey = senderAwsSecretAccessKey;
    }

    public Integer getSenderRetryMax()
    {
        return senderRetryMax;
    }

    public void setSenderRetryMax(Integer senderRetryMax)
    {
        this.senderRetryMax = senderRetryMax;
    }

    public Integer getSenderRetryIntervalMillis()
    {
        return senderRetryIntervalMillis;
    }

    public void setSenderRetryIntervalMillis(Integer senderRetryIntervalMillis)
    {
        this.senderRetryIntervalMillis = senderRetryIntervalMillis;
    }

    public Integer getSenderMaxRetryIntervalMillis()
    {
        return senderMaxRetryIntervalMillis;
    }

    public void setSenderMaxRetryIntervalMillis(Integer senderMaxRetryIntervalMillis)
    {
        this.senderMaxRetryIntervalMillis = senderMaxRetryIntervalMillis;
    }

    public Float getSenderRetryFactor()
    {
        return senderRetryFactor;
    }

    public void setSenderRetryFactor(Float senderRetryFactor)
    {
        this.senderRetryFactor = senderRetryFactor;
    }

    public Integer getSenderWorkBufSize()
    {
        return senderWorkBufSize;
    }

    public void setSenderWorkBufSize(Integer senderWorkBufSize)
    {
        this.senderWorkBufSize = senderWorkBufSize;
    }

    public boolean isCompressionEnabled()
    {
        return compressionEnabled;
    }

    public void setCompressionEnabled(boolean compressionEnabled)
    {
        this.compressionEnabled = compressionEnabled;
    }

    public String getS3KeyPrefix()
    {
        return s3KeyPrefix;
    }

    public void setS3KeyPrefix(String s3KeyPrefix)
    {
        this.s3KeyPrefix = s3KeyPrefix;
    }

    public String getS3KeySuffix()
    {
        return s3KeySuffix;
    }

    public void setS3KeySuffix(String s3KeySuffix)
    {
        this.s3KeySuffix = s3KeySuffix;
    }

    public ZoneId getS3KeyTimeZoneId()
    {
        return s3KeyTimeZoneId;
    }

    public void setS3KeyTimeZoneId(ZoneId s3KeyTimeZoneId)
    {
        this.s3KeyTimeZoneId = s3KeyTimeZoneId;
    }

    public S3DestinationDecider getCustomS3DestinationDecider()
    {
        return customS3DestinationDecider;
    }

    public void setCustomS3DestinationDecider(S3DestinationDecider customS3DestinationDecider)
    {
        this.customS3DestinationDecider = customS3DestinationDecider;
    }

    private String defaultKeyPrefix(AwsS3RecordFormatter recordFormatter)
    {
        return "." + recordFormatter.formatName();
    }

    public Fluency build(AwsS3RecordFormatter recordFormatter, AwsS3Sender.Config senderConfig)
    {
        return buildFromIngester(recordFormatter, createIngester(recordFormatter, senderConfig));
    }

    public Fluency build(AwsS3RecordFormatter recordFormatter)
    {
        AwsS3Sender.Config senderConfig = createSenderConfig();

        return build(recordFormatter, senderConfig);
    }

    public Fluency build()
    {
        return build(createRecordFormatter());
    }

    @VisibleForTesting
    AwsS3Sender createSender(AwsS3Sender.Config senderConfig)
    {
        return new AwsS3Sender(S3Client.builder(), senderConfig);
    }

    private AwsS3Ingester createIngester(AwsS3RecordFormatter recordFormatter, AwsS3Sender.Config senderConfig)
    {
        S3DestinationDecider s3DestinationDecider;
        if (getCustomS3DestinationDecider() == null) {
            DefaultS3DestinationDecider.Config config = new DefaultS3DestinationDecider.Config();

            if (getS3KeyPrefix() != null) {
                config.setKeyPrefix(getS3KeyPrefix());
            }

            if (getS3KeySuffix() != null) {
                config.setKeySuffix(getS3KeySuffix());
            }
            else {
                config.setKeySuffix(
                        defaultKeyPrefix(recordFormatter) + (isCompressionEnabled() ? ".gz" : ""));
            }

            if (getS3KeyTimeZoneId() != null) {
                config.setZoneId(getS3KeyTimeZoneId());
            }
            s3DestinationDecider = new DefaultS3DestinationDecider(config);
        }
        else {
            s3DestinationDecider = getCustomS3DestinationDecider();
        }

        AwsS3Sender sender = createSender(senderConfig);
        return new AwsS3Ingester(sender, s3DestinationDecider);
    }

    private AwsS3RecordFormatter createRecordFormatter()
    {
        if (formatType == null) {
            throw new IllegalArgumentException("format type must be set");
        }

        AwsS3RecordFormatter recordFormatter;
        switch (getFormatType()) {
            case MESSAGE_PACK:
                recordFormatter = new MessagePackRecordFormatter();
                break;
            case JSONL:
                recordFormatter = new JsonlRecordFormatter();
                break;
            case CSV:
                CsvRecordFormatter.Config config = new CsvRecordFormatter.Config();
                config.setColumnNames(getFormatCsvColumnNames());
                recordFormatter = new CsvRecordFormatter(config);
                break;
            default:
                throw new IllegalArgumentException("Unexpected format type: " + getFormatType());
        }

        return recordFormatter;
    }

    private AwsS3Sender.Config createSenderConfig()
    {
        AwsS3Sender.Config config = new AwsS3Sender.Config();

        if (getAwsEndpoint() != null) {
            config.setEndpoint(getAwsEndpoint());
        }

        if (getAwsRegion()!= null) {
            config.setRegion(getAwsRegion());
        }

        if (getAwsAccessKeyId() != null) {
            config.setAwsAccessKeyId(getAwsAccessKeyId());
        }

        if (getAwsSecretAccessKey() != null) {
            config.setAwsSecretAccessKey(getAwsSecretAccessKey());
        }

        if (getSenderRetryMax() != null) {
            config.setRetryMax(getSenderRetryMax());
        }

        if (getSenderRetryIntervalMillis() != null) {
            config.setRetryIntervalMs(getSenderRetryIntervalMillis());
        }

        if (getSenderMaxRetryIntervalMillis() != null) {
            config.setMaxRetryIntervalMs(getSenderMaxRetryIntervalMillis());
        }

        if (getSenderRetryFactor() != null) {
            config.setRetryFactor(getSenderRetryFactor());
        }

        if (getErrorHandler() != null) {
            config.setErrorHandler(getErrorHandler());
        }

        if (getSenderWorkBufSize() != null) {
            config.setWorkBufSize(getSenderWorkBufSize());
        }

        config.setCompressionEnabled(isCompressionEnabled());

        return config;
    }

    @Override
    public String toString()
    {
        return "FluencyBuilderForAwsS3{" +
                "formatType=" + formatType +
                ", formatCsvColumnNames=" + formatCsvColumnNames +
                ", awsEndpoint='" + awsEndpoint + '\'' +
                ", awsRegion='" + awsRegion + '\'' +
                ", senderRetryMax=" + senderRetryMax +
                ", senderRetryIntervalMillis=" + senderRetryIntervalMillis +
                ", senderMaxRetryIntervalMillis=" + senderMaxRetryIntervalMillis +
                ", senderRetryFactor=" + senderRetryFactor +
                ", senderWorkBufSize=" + senderWorkBufSize +
                ", compressionEnabled=" + compressionEnabled +
                ", s3KeyPrefix='" + s3KeyPrefix + '\'' +
                ", s3KeySuffix='" + s3KeySuffix + '\'' +
                ", s3KeyTimeZoneId=" + s3KeyTimeZoneId +
                ", customS3DestinationDecider=" + customS3DestinationDecider +
                "} " + super.toString();
    }
}


text:
$(document).on("ready",main);
var tabInicial=1;
function main(){
	$("#tabs a").on("click",abrirTab);
	$(".tabContent").eq(tabInicial-1).fadeIn();
	$("#tabs a").eq(tabInicial-1).addClass("tabActual");

}

function abrirTab(){
	//alert($(this).index());
	$(".tabContent").hide();
	$("#tabs a").removeClass("tabActual");
	$(".tabContent").eq($(this).index()).fadeIn();
	$(this).addClass("tabActual");

	return false;
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.IO;
using ApiContractGenerator.AssemblyReferenceResolvers;
using ApiContractGenerator.MetadataReferenceResolvers;
using ApiContractGenerator.Source;

namespace ApiContractGenerator.Console
{
    using Console = System.Console;

    public static class Program
    {
        public static int Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: <assembly path> <output path>");
                return 1;
            }

            try
            {
                Run(args[0], args[1]);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return 1;
            }

            return 0;
        }

        public static void Run(string assemblyPath, string outputPath)
        {
            var generator = new ApiContractGenerator
            {
                IgnoredNamespaces = { "NUnit.Framework.Internal" }
            };

            var assemblyResolver = new CompositeAssemblyReferenceResolver(
                new GacAssemblyReferenceResolver(),
                new SameDirectoryAssemblyReferenceResolver(Path.GetDirectoryName(assemblyPath)),
                new SameDirectoryAssemblyReferenceResolver(Path.GetDirectoryName(typeof(object).Assembly.Location)));

            using var metadataReferenceResolver = new MetadataReaderReferenceResolver(() => File.OpenRead(assemblyPath), assemblyResolver);
            using var source = new MetadataReaderSource(File.OpenRead(assemblyPath), metadataReferenceResolver);
            using var outputFile = File.CreateText(outputPath);
            generator.Generate(source, metadataReferenceResolver, new CSharpTextFormatter(outputFile, metadataReferenceResolver));
        }
    }
}


text:
require_relative "basic"
require "fileutils"
require 'digest/md5'

module MikuTwitter::Cache
  CACHE_EXPIRE = 60 * 60 * 24 * 2

  def cache(api, url, options, method)
    if :get == method and options[:cache]
      if(:keep == options[:cache])
        _cache_keep(api, url, options, method, &Proc.new)
      else
        _cache_get(api, url, options, method, &Proc.new) end
    else
      yield end end

  def cache_write(path, body)
    begin
      cachefn = cache_file_path(path)
      FileUtils.mkdir_p(File::dirname(cachefn))
      FileUtils.rm_rf(cachefn) if FileTest.exist?(cachefn) and not FileTest.file?(cachefn)
      file_put_contents(cachefn, body)
    rescue => e
      warn "cache write failed"
      warn e end end

  def cache_clear(path)
    begin
      FileUtils.rm_rf(cache_file_path(path))
    rescue => e
      warn "cache clear failed"
      warn e end end

  def get_cache(path)
    begin
      cache_path = cache_file_path(path)
      if FileTest.file?(cache_path)
        return Class.new{
          define_method(:body){
            file_get_contents(cache_path) }
          define_method(:code){
            '200' } }.new end
    rescue => e
      warn "cache read failed"
      warn e
      nil end end

  # パスからAPIのキャッシュファイルを返す
  # ==== Args
  # [path] APIのパス。例: "statuses/home_timeline.json?include_entities=1"
  # ==== Return
  # キャッシュファイルのローカルのパス
  def cache_file_path(path)
    cache_path = File.join(Environment::CACHE, 'mikutwitter'.freeze, account_identity, path)
    name, query_string = *cache_path.split('?', 2)
    if(query_string)
      md5_query_string = Digest::MD5.hexdigest(query_string)
      File::expand_path(File.join("#{name}.q", md5_query_string[0], md5_query_string))
    else
      File::expand_path(name)
    end
  end

  def self.garbage_collect
    begin
      delete_files = Dir.glob(File.expand_path(File.join(Environment::CACHE, '**'.freeze, '*'.freeze))).select(&method(:is_tooold))
      FileUtils.rm_rf(delete_files)
      delete_files
    rescue => e
      error e end end

  # キャッシュファイル _file_ が期限切れの場合真を返す。
  # ==== Args
  # [file] ファイル名
  # ==== Return
  # 削除すべきなら真
  def self.is_tooold(file)
    Time.now - File.mtime(file) > CACHE_EXPIRE end

  private
  def _cache_keep(api, url, options, method)
    path = "#{api}.json" + get_args(options)
    result = yield
    if result and '200' == result.code
      cache_write(path, result.body)
    else
      cached_value = get_cache(path)
      if cached_value
        return cached_value end end
    result
  rescue => e
    cached_value = get_cache(path)
    if cached_value
      cached_value
    else
      raise e end end

  def _cache_get(api, url, options, method)
    path = "#{api}.json" + get_args(options)
    cached_value = get_cache(path)
    if cached_value
      return cached_value end
    result = yield
    if result and '200' == result.code
      cache_write(path, result.body) end
    result end

end

class MikuTwitter; include MikuTwitter::Cache end


text:
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation.  All rights reserved.
// See LICENSE file in the project root for full license information.
//

#ifndef LZW_H
#define LZW_H

#include <stdlib.h>
#include <string.h>
#include "lzwutil.h"

#define __int32 int
#define __int16 short
#define __int8 char

/*****************************************************************************
    A class which holds the information which is shared between LZW (GIF)
    compression and decompression.
******************************************************************* JohnBo **/
struct LZW
{
  protected:
    inline void LZWInit(unsigned int bcodeSize)
    {
        m_bcodeSize = LZW_B8(bcodeSize);

        LZW_ASSERT(bcodeSize >= 2 && bcodeSize <= 8);
    }

    /* METHODS */
    /* Standard GIF definitions. */
    inline unsigned __int16 WClear(void) const
    {
        return LZW_B16(1U << m_bcodeSize);
    }
    inline unsigned __int16 WEOD(void) const
    {
        return LZW_B16(1U + (1U << m_bcodeSize));
    }

    /* DATA TYPES */
    /* Basic types. */
    typedef unsigned __int32 TokenValue;
    typedef unsigned __int16 TokenIndex;

    /* Constants. */
    enum
    {
        ctokenBits = 12,
        ctokens = (1U << ctokenBits),
    };

    /* DATA */
    unsigned char m_bcodeSize; // The LZW initial code size
};

/*****************************************************************************
    A class which also holds the current token size.
******************************************************************* JohnBo **/
struct LZWState : protected LZW
{
  protected:
    inline void LZWStateInit(unsigned int bcodeSize)
    {
        m_ibitsToken = LZW_B8(bcodeSize + 1);
        m_itokenLast = WEOD();

        LZWInit(bcodeSize);
    }

    unsigned char m_ibitsToken; // The (current) number of bits in a token
    TokenIndex m_itokenLast;    // The last token to be allocated
};

#endif // LZW_H


text:
<?php
/**
 * credentials.php
 * @author Revin Roman
 * @link https://rmrevin.com
 */

if (file_exists(__DIR__ . DIRECTORY_SEPARATOR . '.credentials.php')) {
    require_once __DIR__ . DIRECTORY_SEPARATOR . '.credentials.php';
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.IO;
using System.Resources;
using System.Reflection;

using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.Build.Shared;
using Xunit;

namespace Microsoft.Build.UnitTests
{
    public class TaskLoggingHelperTests
    {
        [Fact]
        public void CheckMessageCode()
        {
            Task t = new MockTask();

            // normal
            string messageOnly;
            string code = t.Log.ExtractMessageCode("AL001: This is a message.", out messageOnly);
            Assert.Equal("AL001", code);
            Assert.Equal("This is a message.", messageOnly);

            // whitespace before code and after colon is ok
            messageOnly = null;
            code = t.Log.ExtractMessageCode("  AL001:   This is a message.", out messageOnly);
            Assert.Equal("AL001", code);
            Assert.Equal("This is a message.", messageOnly);

            // whitespace after colon is not ok
            messageOnly = null;
            code = t.Log.ExtractMessageCode("AL001 : This is a message.", out messageOnly);
            Assert.Null(code);
            Assert.Equal("AL001 : This is a message.", messageOnly);

            // big code is ok
            messageOnly = null;
            code = t.Log.ExtractMessageCode("  RESGEN7905001:   This is a message.", out messageOnly);
            Assert.Equal("RESGEN7905001", code);
            Assert.Equal("This is a message.", messageOnly);

            // small code is ok
            messageOnly = null;
            code = t.Log.ExtractMessageCode("R7: This is a message.", out messageOnly);
            Assert.Equal("R7", code);
            Assert.Equal("This is a message.", messageOnly);

            // lowercase code is ok
            messageOnly = null;
            code = t.Log.ExtractMessageCode("alink3456: This is a message.", out messageOnly);
            Assert.Equal("alink3456", code);
            Assert.Equal("This is a message.", messageOnly);

            // whitespace in code is not ok
            messageOnly = null;
            code = t.Log.ExtractMessageCode("  RES 7905:   This is a message.", out messageOnly);
            Assert.Null(code);
            Assert.Equal("  RES 7905:   This is a message.", messageOnly);

            // only digits in code is not ok
            messageOnly = null;
            code = t.Log.ExtractMessageCode("7905: This is a message.", out messageOnly);
            Assert.Null(code);
            Assert.Equal("7905: This is a message.", messageOnly);

            // only letters in code is not ok
            messageOnly = null;
            code = t.Log.ExtractMessageCode("ALINK: This is a message.", out messageOnly);
            Assert.Null(code);
            Assert.Equal("ALINK: This is a message.", messageOnly);

            // digits before letters in code is not ok
            messageOnly = null;
            code = t.Log.ExtractMessageCode("6780ALINK: This is a message.", out messageOnly);
            Assert.Null(code);
            Assert.Equal("6780ALINK: This is a message.", messageOnly);

            // mixing digits and letters in code is not ok
            messageOnly = null;
            code = t.Log.ExtractMessageCode("LNK658A: This is a message.", out messageOnly);
            Assert.Null(code);
            Assert.Equal("LNK658A: This is a message.", messageOnly);
        }

        /// <summary>
        /// LogMessageFromStream parses the stream and decides if it is an error/warning/message.
        /// The way it figures out if a message is an error or warning is by parsing it against
        /// the canonical error/warning format.  If it happens to be an error this method returns
        /// true ... isError.  This unit test ensures that passing a cannonical error format results
        /// in this method returning true and passing a non canonical message results in it returning
        /// false
        /// </summary>
        [Fact]
        public void CheckMessageFromStreamParsesErrorsAndMessagesCorrectly()
        {
            IBuildEngine2 mockEngine = new MockEngine();
            Task t = new MockTask();
            t.BuildEngine = mockEngine;

            // This should return true since I am passing a canonical error as the stream
            StringReader sr = new StringReader("error MSB4040: There is no target in the project.");
            Assert.True(t.Log.LogMessagesFromStream(sr, MessageImportance.High));

            // This should return false since I am passing a canonical warning as the stream
            sr = new StringReader("warning ABCD123MyCode: Felix is a cat.");
            Assert.False(t.Log.LogMessagesFromStream(sr, MessageImportance.Low));

            // This should return false since I am passing a non canonical message in the stream
            sr = new StringReader("Hello World");
            Assert.False(t.Log.LogMessagesFromStream(sr, MessageImportance.High));
        }

        [Fact]
        public void LogCommandLine()
        {
            MockEngine mockEngine = new MockEngine();
            Task t = new MockTask();
            t.BuildEngine = mockEngine;

            t.Log.LogCommandLine("MySuperCommand");
            Assert.True(mockEngine.Log.Contains("MySuperCommand"));
        }

        /// <summary>
        /// This verifies that we don't try to run FormatString on a string
        /// that isn't a resource (if we did, the unmatched curly would give an exception)
        /// </summary>
        [Fact]
        public void LogMessageWithUnmatchedCurly()
        {
            MockEngine mockEngine = new MockEngine();
            Task t = new MockTask();
            t.BuildEngine = mockEngine;

            t.Log.LogMessage("echo {");
            t.Log.LogMessageFromText("{1", MessageImportance.High);
            t.Log.LogCommandLine("{2");
            t.Log.LogWarning("{3");
            t.Log.LogError("{4");

            mockEngine.AssertLogContains("echo {");
            mockEngine.AssertLogContains("{1");
            mockEngine.AssertLogContains("{2");
            mockEngine.AssertLogContains("{3");
            mockEngine.AssertLogContains("{4");
        }

        [Fact]
        public void LogFromResources()
        {
            MockEngine mockEngine = new MockEngine();
            Task t = new MockTask();
            t.BuildEngine = mockEngine;

            t.Log.LogErrorFromResources("MySubcategoryResource", null,
                "helpkeyword", "filename", 1, 2, 3, 4, "MyErrorResource", "foo");

            t.Log.LogErrorFromResources("MyErrorResource", "foo");

            t.Log.LogWarningFromResources("MySubcategoryResource", null,
                "helpkeyword", "filename", 1, 2, 3, 4, "MyWarningResource", "foo");

            t.Log.LogWarningFromResources("MyWarningResource", "foo");

            Assert.True(mockEngine.Log.Contains("filename(1,2,3,4): Romulan error : Oops I wiped your harddrive foo"));
            Assert.True(mockEngine.Log.Contains("filename(1,2,3,4): Romulan warning : Be nice or I wipe your harddrive foo"));
            Assert.True(mockEngine.Log.Contains("Oops I wiped your harddrive foo"));
            Assert.True(mockEngine.Log.Contains("Be nice or I wipe your harddrive foo"));
        }

        [Fact]
        public void CheckLogMessageFromFile()
        {
            string file = null;

            try
            {
                file = FileUtilities.GetTemporaryFile();

                string contents = @"a message here
                    error abcd12345: hey jude.
                    warning xy11: I wanna hold your hand.
                    this is not an error or warning
                    nor is this
                    error def222: norwegian wood";

                // This closes the reader
                File.WriteAllText(file, contents);

                MockEngine mockEngine = new MockEngine();
                Task t = new MockTask();
                t.BuildEngine = mockEngine;
                t.Log.LogMessagesFromFile(file, MessageImportance.High);

                Assert.Equal(2, mockEngine.Errors);
                Assert.Equal(1, mockEngine.Warnings);
                Assert.Equal(3, mockEngine.Messages);

                mockEngine = new MockEngine();
                t = new MockTask();
                t.BuildEngine = mockEngine;
                t.Log.LogMessagesFromFile(file);

                Assert.Equal(2, mockEngine.Errors);
                Assert.Equal(1, mockEngine.Warnings);
                Assert.Equal(3, mockEngine.Messages);
            }
            finally
            {
                if (null != file) File.Delete(file);
            }
        }

        [Fact]
        public void CheckResourcesRegistered()
        {
            Assert.Throws<InvalidOperationException>(() =>
            {
                Task t = new MockTask(false /*don't register resources*/);

                try
                {
                    t.Log.FormatResourceString("bogus");
                }
                catch (Exception e)
                {
                    // so I can see the exception message in NUnit's "Standard Out" window
                    Console.WriteLine(e.Message);
                    throw;
                }
            }
           );
        }
        /// <summary>
        /// Verify the LogErrorFromException & LogWarningFromException methods
        /// </summary>
        [Fact]
        public void TestLogFromException()
        {
            string message = "exception message";
            string stackTrace = "TaskLoggingHelperTests.TestLogFromException";

            MockEngine engine = new MockEngine();
            MockTask task = new MockTask();
            task.BuildEngine = engine;

            // need to throw and catch an exception so that its stack trace is initialized to something
            try
            {
                Exception inner = new InvalidOperationException();
                throw new Exception(message, inner);
            }
            catch (Exception e)
            {
                // log error without stack trace
                task.Log.LogErrorFromException(e);
                engine.AssertLogContains(message);
                engine.AssertLogDoesntContain(stackTrace);
                engine.AssertLogDoesntContain("InvalidOperationException");

                engine.Log = string.Empty;

                // log warning with stack trace
                task.Log.LogWarningFromException(e);
                engine.AssertLogContains(message);
                engine.AssertLogDoesntContain(stackTrace);

                engine.Log = string.Empty;

                // log error with stack trace
                task.Log.LogErrorFromException(e, true);
                engine.AssertLogContains(message);
                engine.AssertLogContains(stackTrace);
                engine.AssertLogDoesntContain("InvalidOperationException");

                engine.Log = string.Empty;

                // log warning with stack trace
                task.Log.LogWarningFromException(e, true);
                engine.AssertLogContains(message);
                engine.AssertLogContains(stackTrace);
                engine.Log = string.Empty;

                // log error with stack trace and inner exceptions
                task.Log.LogErrorFromException(e, true, true, "foo.cs");
                engine.AssertLogContains(message);
                engine.AssertLogContains(stackTrace);
                engine.AssertLogContains("InvalidOperationException");
            }
        }
    }
}


text:
using Assets.Kanau.AFrameScene;
using Assets.Kanau.AFrameScene.Materials;
using Assets.Kanau.ThreeScene;
using Assets.Kanau.ThreeScene.Geometries;
using Assets.Kanau.ThreeScene.Materials;
using Assets.Kanau.ThreeScene.Objects;
using Assets.Kanau.ThreeScene.Textures;
using Assets.Kanau.UnityScene;
using Assets.Kanau.UnityScene.SceneGraph;
using Assets.Kanau.Utils;
using LitJson;
using System.Text;
using UnityEngine;

namespace Assets.Kanau {
    public class SceneExporter {
        readonly UnitySceneRoot unitySceneRoot;

        public SceneExporter(GameObject[] gos) {
            unitySceneRoot = BuildUnitySceneRoot(gos);
        }

        public void Export(SceneFormat fmt) {
            // 유니티 씬을 제대로 읽었는지 확인
            bool useDump = false;
            if(useDump) {
                DumpUnitySceneRoot(unitySceneRoot);
            }

            // 유니티씬을 threejs 씬으로 변환
            ThreeSceneRoot threeSceneRoot = BuildThreeSceneRoot(unitySceneRoot);

            WriteTextureFiles(threeSceneRoot, fmt);
            WriteModelFiles(threeSceneRoot, fmt);

            switch(fmt) {
                case SceneFormat.AFrame:
                    WriteToAFrame(threeSceneRoot);
                    break;
                case SceneFormat.ThreeJS:
                    WriteToThreeJS(threeSceneRoot);
                    break;
                default:
                    Debug.Assert(false, "unknown format");
                    break;
            }
        }

        void WriteTextureFiles(ThreeSceneRoot root, SceneFormat fmt) {
            var pathHelper = ExportPathHelper.Instance;
            // 일반 텍스쳐 export
            foreach (var el in root.SharedNodeTable.GetEnumerable<ImageElem>()) {
                el.ExpoortImageFile(pathHelper);
            }
        }

        void WriteModelFiles(ThreeSceneRoot root, SceneFormat fmt) {
            // three.js는 단일 파일로 출력하는게 목적이라서 model 파일을 생성하지 않는다
            var pathHelper = ExportPathHelper.Instance;

            if (fmt == SceneFormat.AFrame) {
                foreach(var el in root.SharedNodeTable.GetEnumerable<MeshElem>()) {
                    var bufferGeom = el.Geometry as BufferGeometryElem;
                    if (bufferGeom != null) {
                        string filepath = pathHelper.ToModelPath(bufferGeom.CreateMeshFileName(".obj"));
                        ObjExporter.MeshToFile(bufferGeom.Mesh, filepath);
                    }

                    var mtl = MaterialFacade.Instance.CreateMaterial(el.Material);
                    if(bufferGeom != null) {
                        string filepath = pathHelper.ToModelPath(bufferGeom.CreateMeshFileName(".mtl"));
                        MtlExporter.ToFile(mtl, bufferGeom.SafeName, filepath);
                    }
                }
            }
        }

        void WriteMaterialFiles (ThreeSceneRoot root, SceneFormat fmt) {
            var pathHelper = ExportPathHelper.Instance;

            if (fmt == SceneFormat.AFrame) {
                foreach (var el in root.SharedNodeTable.GetEnumerable<MaterialElem>()) {
                    var aframeMtl = MaterialFacade.Instance.CreateMaterial(el);
                    var name = el.Name;
                    string filepath = pathHelper.ToModelPath(name + ".mtl");
                    MtlExporter.ToFile(aframeMtl, name, filepath);
                }
            }
        }

        void WriteExportedTextFile(string text) {
            var pathHelper = ExportPathHelper.Instance;
            FileHelper.SaveContentsAsFile(text, pathHelper.SceneFilePath);
        }

        ThreeSceneRoot BuildThreeSceneRoot(UnitySceneRoot root) {
            var report = new Report("ThreeSceneConvert");
            report.UseConsole = false;
            var visitor = new ThreeSceneConvertVisitor(report);
            return visitor.Run(unitySceneRoot);
        }

        void DumpUnitySceneRoot(UnitySceneRoot root) {
            var report = new Report("unity-scene-dump");
            report.UseConsole = false;

            var dumpVisitor = new DumpVisitor(report);
            dumpVisitor.Run(root);

            report.SaveReport("unity-scene.log");
        }

        UnitySceneRoot BuildUnitySceneRoot(GameObject[] gos) {
            var root = new UnitySceneRoot();
            foreach (var go in gos) {
                root.Add(go);
            }
            return root;
        }

        void WriteToAFrame(ThreeSceneRoot root) {
            var sb = new StringBuilder();
            var node = root.ExportAFrame();
            node.BuildSource(sb);

            var aframe = ExportSettings.Instance.aframe;
            var source = sb.ToString() + "\n";
            var text = aframe.TemplateHead + source + aframe.TemplateAppend + aframe.TemplateEnd;

            text = text.Replace("&TITLE&", aframe.title);
            text = text.Replace("&LIBRARY&", aframe.libraryAddress);

            WriteExportedTextFile(text);
        }

        void WriteToThreeJS(ThreeSceneRoot root) {
            // wrilte to text file
            var sb = new StringBuilder();
            var writer = new JsonWriter(sb);
            writer.PrettyPrint = true;
            writer.IndentValue = 2;

            root.ExportJson(writer);
            var content = sb.ToString();
            WriteExportedTextFile(content);
        }
    }
}


text:
from django.db.models.sql.query import *  # NOQA
from django.db.models.sql.query import Query
from django.db.models.sql.subqueries import *  # NOQA
from django.db.models.sql.where import AND, OR, XOR

__all__ = ["Query", "AND", "OR", "XOR"]


text:
import { describe, test, beforeEach, jest, expect } from '@jest/globals';
import initEnv from './ProxyedENV.js';
import type { LogService } from 'common-services';

describe('initEnv', () => {
  const log = jest.fn<LogService>();
  const readFile = jest.fn<(path: string) => Promise<Buffer>>();

  beforeEach(() => {
    log.mockReset();
    readFile.mockReset();
  });

  test('should work', async () => {
    readFile.mockResolvedValueOnce(
      Buffer.from(
        `DB_PASSWORD=oudelali
DB_HOST = 'localhost'
`,
      ),
    );

    const ENV = await initEnv({
      PROXYED_ENV_VARS: ['DB_PASSWORD'],
      NODE_ENV: 'development',
      BASE_ENV: { KEY_BASE_ENV: 'test' },
      PROCESS_ENV: { KEY_PROCESS_ENV: 'test' },
      PWD: '/home/whoami/my-whook-project',
      log,
      readFile,
    });

    expect({
      ENV,
      logCalls: log.mock.calls.filter(([type]) => !type.endsWith('stack')),
      readFileCalls: readFile.mock.calls,
    }).toMatchInlineSnapshot(`
      {
        "ENV": {
          "DB_PASSWORD": "oudelali",
          "NODE_ENV": "development",
        },
        "logCalls": [
          [
            "debug",
            "♻ - Loading the environment service.",
          ],
          [
            "warning",
            "🖥 - Using local env.",
          ],
          [
            "warning",
            "💾 - Using .env file at "/home/whoami/my-whook-project/.env.development".",
          ],
          [
            "debug",
            "♻ -Filtering environment for build.",
          ],
        ],
        "readFileCalls": [
          [
            "/home/whoami/my-whook-project/.env.development",
          ],
        ],
      }
    `);
  });
});


text:
package com.puresoltechnologies.xo.titan.test.filesystem;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.net.URISyntaxException;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import com.buschmais.xo.api.ResultIterable;
import com.buschmais.xo.api.ResultIterator;
import com.buschmais.xo.api.XOManager;
import com.buschmais.xo.api.bootstrap.XOUnit;
import com.puresoltechnologies.xo.titan.test.AbstractXOTitanTest;
import com.puresoltechnologies.xo.titan.test.XOTitanTestUtils;

@RunWith(Parameterized.class)
public class FileSystemIT extends AbstractXOTitanTest {

    public FileSystemIT(XOUnit xoUnit) {
	super(xoUnit);
    }

    @Parameterized.Parameters
    public static Collection<XOUnit[]> getXOUnits() throws URISyntaxException {
	return XOTitanTestUtils.xoUnits(Directory.class, File.class);
    }

    @Test
    public void fileSystemTree() {
	XOManager xoManager = getXOManager();
	xoManager.currentTransaction().begin();

	Directory root = xoManager.create(Directory.class);
	root.setName("rootdir");
	Directory subDirectory = xoManager.create(Directory.class);
	subDirectory.setName("subdir");

	File rootFile1 = xoManager.create(File.class);
	rootFile1.setName("rootfile1");
	File rootFile2 = xoManager.create(File.class);
	rootFile2.setName("rootfile2");
	File subDirFile1 = xoManager.create(File.class);
	subDirFile1.setName("subdirfile1");
	File subDirFile2 = xoManager.create(File.class);
	subDirFile2.setName("subdirfile2");

	root.getDirectories().add(subDirectory);
	root.getFiles().add(rootFile1);
	root.getFiles().add(rootFile2);

	subDirectory.getFiles().add(subDirFile1);
	subDirectory.getFiles().add(subDirFile2);

	xoManager.currentTransaction().commit();

	xoManager.currentTransaction().begin();
	ResultIterable<Directory> fsRootResultIterable = xoManager.find(
		Directory.class, "rootdir");
	assertTrue(fsRootResultIterable.hasResult());
	ResultIterator<Directory> fsRootIterator = fsRootResultIterable
		.iterator();
	assertTrue(fsRootIterator.hasNext());
	Directory fsRoot = fsRootIterator.next();
	assertFalse(fsRootIterator.hasNext());
	printFilesystem(fsRoot, 0);
	xoManager.currentTransaction().commit();
    }

    private void printFilesystem(Directory fsNode, int depth) {
	intent(depth);
	System.out.print("/");
	System.out.print(fsNode.getName());
	System.out.println("/");
	depth++;
	for (File file : fsNode.getFiles()) {
	    intent(depth);
	    System.out.println(file.getName());
	}
	for (Directory directory : fsNode.getDirectories()) {
	    printFilesystem(directory, depth);
	}
    }

    private void intent(int depth) {
	for (int i = 0; i < depth * 4; i++) {
	    System.out.print(' ');
	}
    }

}


text:
package org.classdump.luna.compiler.ir;

import java.util.List;
import java.util.Objects;

public class VList {

  private final List<Val> addrs;
  private final MultiVal suffix;  // may be null

  public VList(List<Val> addrs, MultiVal suffix) {
    this.addrs = Objects.requireNonNull(addrs);
    this.suffix = suffix;
  }

  public List<Val> addrs() {
    return addrs;
  }

  public boolean isMulti() {
    return suffix != null;
  }

  public MultiVal suffix() {
    return suffix;
  }

}


text:
	Location (required)
	<input type="text" class="form-control" id="eventLocation" name="eventLocation" ng-model="event.location" placeholder="Ex: 123 Fake St. Springfield, NT" aria-required="true" aria-invalid="{{input.$invalid ? 'true' : 'false'}}" required places-autocomplete>
	<required-error-message></required-error-message>


text:
package com.orientechnologies.orient.core.config;

public interface OStorageClusterConfiguration {

	public int getId();

	public String getName();

	public String getLocation();

	public int getDataSegmentId();
}


text:
#include "Benchmark.h"
#include "SkColorPriv.h"
#include "SkMatrix.h"
#include "SkPaint.h"
#include "SkRandom.h"
#include "SkString.h"

static float sk_fsel(float pred, float result_ge, float result_lt) {
    return pred >= 0 ? result_ge : result_lt;
}

static float fast_floor(float x) {
//    float big = sk_fsel(x, 0x1.0p+23, -0x1.0p+23);
    float big = sk_fsel(x, (float)(1 << 23), -(float)(1 << 23));
    return (x + big) - big;
}

class MathBench : public Benchmark {
    enum {
        kBuffer = 100,
    };
    SkString    fName;
    float       fSrc[kBuffer], fDst[kBuffer];
public:
    MathBench(const char name[])  {
        fName.printf("math_%s", name);

        SkRandom rand;
        for (int i = 0; i < kBuffer; ++i) {
            fSrc[i] = rand.nextSScalar1();
        }
    }

    bool isSuitableFor(Backend backend) override {
        return backend == kNonRendering_Backend;
    }

    virtual void performTest(float* SK_RESTRICT dst,
                              const float* SK_RESTRICT src,
                              int count) = 0;

protected:
    virtual int mulLoopCount() const { return 1; }

    const char* onGetName() override {
        return fName.c_str();
    }

    void onDraw(const int loops, SkCanvas*) override {
        int n = loops * this->mulLoopCount();
        for (int i = 0; i < n; i++) {
            this->performTest(fDst, fSrc, kBuffer);
        }
    }

private:
    typedef Benchmark INHERITED;
};

class MathBenchU32 : public MathBench {
public:
    MathBenchU32(const char name[]) : INHERITED(name) {}

protected:
    virtual void performITest(uint32_t* SK_RESTRICT dst,
                              const uint32_t* SK_RESTRICT src,
                              int count) = 0;

    void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) override {
        uint32_t* d = SkTCast<uint32_t*>(dst);
        const uint32_t* s = SkTCast<const uint32_t*>(src);
        this->performITest(d, s, count);
    }
private:
    typedef MathBench INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

class NoOpMathBench : public MathBench {
public:
    NoOpMathBench() : INHERITED("noOp") {}
protected:
    void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) override {
        for (int i = 0; i < count; ++i) {
            dst[i] = src[i] + 1;
        }
    }
private:
    typedef MathBench INHERITED;
};

class SkRSqrtMathBench : public MathBench {
public:
    SkRSqrtMathBench() : INHERITED("sk_float_rsqrt") {}
protected:
    void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) override {
        for (int i = 0; i < count; ++i) {
            dst[i] = sk_float_rsqrt(src[i]);
        }
    }
private:
    typedef MathBench INHERITED;
};

class SlowISqrtMathBench : public MathBench {
public:
    SlowISqrtMathBench() : INHERITED("slowIsqrt") {}
protected:
    void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) override {
        for (int i = 0; i < count; ++i) {
            dst[i] = 1.0f / sk_float_sqrt(src[i]);
        }
    }
private:
    typedef MathBench INHERITED;
};

static inline float SkFastInvSqrt(float x) {
    float xhalf = 0.5f*x;
    int i = *SkTCast<int*>(&x);
    i = 0x5f3759df - (i>>1);
    x = *SkTCast<float*>(&i);
    x = x*(1.5f-xhalf*x*x);
//    x = x*(1.5f-xhalf*x*x); // this line takes err from 10^-3 to 10^-6
    return x;
}

class FastISqrtMathBench : public MathBench {
public:
    FastISqrtMathBench() : INHERITED("fastIsqrt") {}
protected:
    void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) override {
        for (int i = 0; i < count; ++i) {
            dst[i] = SkFastInvSqrt(src[i]);
        }
    }
private:
    typedef MathBench INHERITED;
};

static inline uint32_t QMul64(uint32_t value, U8CPU alpha) {
    SkASSERT((uint8_t)alpha == alpha);
    const uint32_t mask = 0xFF00FF;

    uint64_t tmp = value;
    tmp = (tmp & mask) | ((tmp & ~mask) << 24);
    tmp *= alpha;
    return (uint32_t) (((tmp >> 8) & mask) | ((tmp >> 32) & ~mask));
}

class QMul64Bench : public MathBenchU32 {
public:
    QMul64Bench() : INHERITED("qmul64") {}
protected:
    void performITest(uint32_t* SK_RESTRICT dst,
                      const uint32_t* SK_RESTRICT src,
                      int count) override {
        for (int i = 0; i < count; ++i) {
            dst[i] = QMul64(src[i], (uint8_t)i);
        }
    }
private:
    typedef MathBenchU32 INHERITED;
};

class QMul32Bench : public MathBenchU32 {
public:
    QMul32Bench() : INHERITED("qmul32") {}
protected:
    void performITest(uint32_t* SK_RESTRICT dst,
                      const uint32_t* SK_RESTRICT src,
                      int count) override {
        for (int i = 0; i < count; ++i) {
            dst[i] = SkAlphaMulQ(src[i], (uint8_t)i);
        }
    }
private:
    typedef MathBenchU32 INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

static bool isFinite_int(float x) {
    uint32_t bits = SkFloat2Bits(x);    // need unsigned for our shifts
    int exponent = bits << 1 >> 24;
    return exponent != 0xFF;
}

static bool isFinite_float(float x) {
    return SkToBool(sk_float_isfinite(x));
}

static bool isFinite_mulzero(float x) {
    float y = x * 0;
    return y == y;
}

static bool isfinite_and_int(const float data[4]) {
    return  isFinite_int(data[0]) && isFinite_int(data[1]) && isFinite_int(data[2]) && isFinite_int(data[3]);
}

static bool isfinite_and_float(const float data[4]) {
    return  isFinite_float(data[0]) && isFinite_float(data[1]) && isFinite_float(data[2]) && isFinite_float(data[3]);
}

static bool isfinite_and_mulzero(const float data[4]) {
    return  isFinite_mulzero(data[0]) && isFinite_mulzero(data[1]) && isFinite_mulzero(data[2]) && isFinite_mulzero(data[3]);
}

#define mulzeroadd(data)    (data[0]*0 + data[1]*0 + data[2]*0 + data[3]*0)

static bool isfinite_plus_int(const float data[4]) {
    return  isFinite_int(mulzeroadd(data));
}

static bool isfinite_plus_float(const float data[4]) {
    return  !sk_float_isnan(mulzeroadd(data));
}

static bool isfinite_plus_mulzero(const float data[4]) {
    float x = mulzeroadd(data);
    return x == x;
}

typedef bool (*IsFiniteProc)(const float[]);

#define MAKEREC(name)   { name, #name }

static const struct {
    IsFiniteProc    fProc;
    const char*     fName;
} gRec[] = {
    MAKEREC(isfinite_and_int),
    MAKEREC(isfinite_and_float),
    MAKEREC(isfinite_and_mulzero),
    MAKEREC(isfinite_plus_int),
    MAKEREC(isfinite_plus_float),
    MAKEREC(isfinite_plus_mulzero),
};

#undef MAKEREC

static bool isFinite(const SkRect& r) {
    // x * 0 will be NaN iff x is infinity or NaN.
    // a + b will be NaN iff either a or b is NaN.
    float value = r.fLeft * 0 + r.fTop * 0 + r.fRight * 0 + r.fBottom * 0;

    // value is either NaN or it is finite (zero).
    // value==value will be true iff value is not NaN
    return value == value;
}

class IsFiniteBench : public Benchmark {
    enum {
        N = 1000,
    };
    float fData[N];
public:

    IsFiniteBench(int index)  {
        SkRandom rand;

        for (int i = 0; i < N; ++i) {
            fData[i] = rand.nextSScalar1();
        }

        if (index < 0) {
            fProc = NULL;
            fName = "isfinite_rect";
        } else {
            fProc = gRec[index].fProc;
            fName = gRec[index].fName;
        }
    }

    bool isSuitableFor(Backend backend) override {
        return backend == kNonRendering_Backend;
    }

protected:
    void onDraw(const int loops, SkCanvas*) override {
        IsFiniteProc proc = fProc;
        const float* data = fData;
        // do this so the compiler won't throw away the function call
        int counter = 0;

        if (proc) {
            for (int j = 0; j < loops; ++j) {
                for (int i = 0; i < N - 4; ++i) {
                    counter += proc(&data[i]);
                }
            }
        } else {
            for (int j = 0; j < loops; ++j) {
                for (int i = 0; i < N - 4; ++i) {
                    const SkRect* r = reinterpret_cast<const SkRect*>(&data[i]);
                    if (false) { // avoid bit rot, suppress warning
                        isFinite(*r);
                    }
                    counter += r->isFinite();
                }
            }
        }

        SkPaint paint;
        if (paint.getAlpha() == 0) {
            SkDebugf("%d\n", counter);
        }
    }

    const char* onGetName() override {
        return fName;
    }

private:
    IsFiniteProc    fProc;
    const char*     fName;

    typedef Benchmark INHERITED;
};

class FloorBench : public Benchmark {
    enum {
        ARRAY = 1000,
    };
    float fData[ARRAY];
    bool fFast;
public:

    FloorBench(bool fast) : fFast(fast) {
        SkRandom rand;

        for (int i = 0; i < ARRAY; ++i) {
            fData[i] = rand.nextSScalar1();
        }

        if (fast) {
            fName = "floor_fast";
        } else {
            fName = "floor_std";
        }
    }

    bool isSuitableFor(Backend backend) override {
        return backend == kNonRendering_Backend;
    }

    virtual void process(float) {}

protected:
    void onDraw(const int loops, SkCanvas*) override {
        SkRandom rand;
        float accum = 0;
        const float* data = fData;

        if (fFast) {
            for (int j = 0; j < loops; ++j) {
                for (int i = 0; i < ARRAY; ++i) {
                    accum += fast_floor(data[i]);
                }
                this->process(accum);
            }
        } else {
            for (int j = 0; j < loops; ++j) {
                for (int i = 0; i < ARRAY; ++i) {
                    accum += sk_float_floor(data[i]);
                }
                this->process(accum);
            }
        }
    }

    const char* onGetName() override {
        return fName;
    }

private:
    const char*     fName;

    typedef Benchmark INHERITED;
};

class CLZBench : public Benchmark {
    enum {
        ARRAY = 1000,
    };
    uint32_t fData[ARRAY];
    bool fUsePortable;

public:
    CLZBench(bool usePortable) : fUsePortable(usePortable) {

        SkRandom rand;
        for (int i = 0; i < ARRAY; ++i) {
            fData[i] = rand.nextU();
        }

        if (fUsePortable) {
            fName = "clz_portable";
        } else {
            fName = "clz_intrinsic";
        }
    }

    bool isSuitableFor(Backend backend) override {
        return backend == kNonRendering_Backend;
    }

    // just so the compiler doesn't remove our loops
    virtual void process(int) {}

protected:
    void onDraw(const int loops, SkCanvas*) override {
        int accum = 0;

        if (fUsePortable) {
            for (int j = 0; j < loops; ++j) {
                for (int i = 0; i < ARRAY; ++i) {
                    accum += SkCLZ_portable(fData[i]);
                }
                this->process(accum);
            }
        } else {
            for (int j = 0; j < loops; ++j) {
                for (int i = 0; i < ARRAY; ++i) {
                    accum += SkCLZ(fData[i]);
                }
                this->process(accum);
            }
        }
    }

    const char* onGetName() override {
        return fName;
    }

private:
    const char* fName;

    typedef Benchmark INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

class NormalizeBench : public Benchmark {
    enum {
        ARRAY =1000,
    };
    SkVector fVec[ARRAY];

public:
    NormalizeBench() {
        SkRandom rand;
        for (int i = 0; i < ARRAY; ++i) {
            fVec[i].set(rand.nextSScalar1(), rand.nextSScalar1());
        }

        fName = "point_normalize";
    }

    bool isSuitableFor(Backend backend) override {
        return backend == kNonRendering_Backend;
    }

    // just so the compiler doesn't remove our loops
    virtual void process(int) {}

protected:
    void onDraw(const int loops, SkCanvas*) override {
        int accum = 0;

        for (int j = 0; j < loops; ++j) {
            for (int i = 0; i < ARRAY; ++i) {
                accum += fVec[i].normalize();
            }
            this->process(accum);
        }
    }

    const char* onGetName() override {
        return fName;
    }

private:
    const char* fName;

    typedef Benchmark INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

class FixedMathBench : public Benchmark {
    enum {
        N = 1000,
    };
    float fData[N];
    SkFixed fResult[N];
public:

    FixedMathBench()  {
        SkRandom rand;
        for (int i = 0; i < N; ++i) {
            fData[i] = rand.nextSScalar1();
        }

    }

    bool isSuitableFor(Backend backend) override {
        return backend == kNonRendering_Backend;
    }

protected:
    void onDraw(const int loops, SkCanvas*) override {
        for (int j = 0; j < loops; ++j) {
            for (int i = 0; i < N - 4; ++i) {
                fResult[i] = SkFloatToFixed(fData[i]);
            }
        }

        SkPaint paint;
        if (paint.getAlpha() == 0) {
            SkDebugf("%d\n", fResult[0]);
        }
    }

    const char* onGetName() override {
        return "float_to_fixed";
    }

private:
    typedef Benchmark INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

template <typename T>
class DivModBench : public Benchmark {
    SkString fName;
public:
    explicit DivModBench(const char* name) {
        fName.printf("divmod_%s", name);
    }

    bool isSuitableFor(Backend backend) override {
        return backend == kNonRendering_Backend;
    }

protected:
    const char* onGetName() override {
        return fName.c_str();
    }

    void onDraw(const int loops, SkCanvas*) override {
        volatile T a = 0, b = 0;
        T div = 0, mod = 0;
        for (int i = 0; i < loops; i++) {
            if ((T)i == 0) continue;  // Small T will wrap around.
            SkTDivMod((T)(i+1), (T)i, &div, &mod);
            a ^= div;
            b ^= mod;
        }
    }
};
DEF_BENCH(return new DivModBench<uint8_t>("uint8_t"))
DEF_BENCH(return new DivModBench<uint16_t>("uint16_t"))
DEF_BENCH(return new DivModBench<uint32_t>("uint32_t"))
DEF_BENCH(return new DivModBench<uint64_t>("uint64_t"))

DEF_BENCH(return new DivModBench<int8_t>("int8_t"))
DEF_BENCH(return new DivModBench<int16_t>("int16_t"))
DEF_BENCH(return new DivModBench<int32_t>("int32_t"))
DEF_BENCH(return new DivModBench<int64_t>("int64_t"))

///////////////////////////////////////////////////////////////////////////////

DEF_BENCH( return new NoOpMathBench(); )
DEF_BENCH( return new SkRSqrtMathBench(); )
DEF_BENCH( return new SlowISqrtMathBench(); )
DEF_BENCH( return new FastISqrtMathBench(); )
DEF_BENCH( return new QMul64Bench(); )
DEF_BENCH( return new QMul32Bench(); )

DEF_BENCH( return new IsFiniteBench(-1); )
DEF_BENCH( return new IsFiniteBench(0); )
DEF_BENCH( return new IsFiniteBench(1); )
DEF_BENCH( return new IsFiniteBench(2); )
DEF_BENCH( return new IsFiniteBench(3); )
DEF_BENCH( return new IsFiniteBench(4); )
DEF_BENCH( return new IsFiniteBench(5); )

DEF_BENCH( return new FloorBench(false); )
DEF_BENCH( return new FloorBench(true); )

DEF_BENCH( return new CLZBench(false); )
DEF_BENCH( return new CLZBench(true); )

DEF_BENCH( return new NormalizeBench(); )

DEF_BENCH( return new FixedMathBench(); )


text:
/* A Bison parser, made by GNU Bison 2.5.  */

/* Bison interface for Yacc-like parsers in C

      Copyright (C) 1984, 1989-1990, 2000-2011 Free Software Foundation, Inc.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

/* As a special exception, you may create a larger work that contains
   part or all of the Bison parser skeleton and distribute that work
   under terms of your choice, so long as that work isn't itself a
   parser generator using the skeleton or a modified version thereof
   as a parser skeleton.  Alternatively, if you modify or redistribute
   the parser skeleton itself, you may (at your option) remove this
   special exception, which will cause the skeleton and the resulting
   Bison output files to be licensed under the GNU General Public
   License without this special exception.

   This special exception was added by the Free Software Foundation in
   version 2.2 of Bison.  */

/* Tokens.  */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
   /* Put the tokens into the symbol table, so that GDB and other debuggers
      know about them.  */
   enum yytokentype {
     LLITERAL = 258,
     LASOP = 259,
     LCOLAS = 260,
     LBREAK = 261,
     LCASE = 262,
     LCHAN = 263,
     LCONST = 264,
     LCONTINUE = 265,
     LDDD = 266,
     LDEFAULT = 267,
     LDEFER = 268,
     LELSE = 269,
     LFALL = 270,
     LFOR = 271,
     LFUNC = 272,
     LGO = 273,
     LGOTO = 274,
     LIF = 275,
     LIMPORT = 276,
     LINTERFACE = 277,
     LMAP = 278,
     LNAME = 279,
     LPACKAGE = 280,
     LRANGE = 281,
     LRETURN = 282,
     LSELECT = 283,
     LSTRUCT = 284,
     LSWITCH = 285,
     LTYPE = 286,
     LVAR = 287,
     LANDAND = 288,
     LANDNOT = 289,
     LBODY = 290,
     LCOMM = 291,
     LDEC = 292,
     LEQ = 293,
     LGE = 294,
     LGT = 295,
     LIGNORE = 296,
     LINC = 297,
     LLE = 298,
     LLSH = 299,
     LLT = 300,
     LNE = 301,
     LOROR = 302,
     LRSH = 303,
     NotPackage = 304,
     NotParen = 305,
     PreferToRightParen = 306
   };
#endif
/* Tokens.  */
#define LLITERAL 258
#define LASOP 259
#define LCOLAS 260
#define LBREAK 261
#define LCASE 262
#define LCHAN 263
#define LCONST 264
#define LCONTINUE 265
#define LDDD 266
#define LDEFAULT 267
#define LDEFER 268
#define LELSE 269
#define LFALL 270
#define LFOR 271
#define LFUNC 272
#define LGO 273
#define LGOTO 274
#define LIF 275
#define LIMPORT 276
#define LINTERFACE 277
#define LMAP 278
#define LNAME 279
#define LPACKAGE 280
#define LRANGE 281
#define LRETURN 282
#define LSELECT 283
#define LSTRUCT 284
#define LSWITCH 285
#define LTYPE 286
#define LVAR 287
#define LANDAND 288
#define LANDNOT 289
#define LBODY 290
#define LCOMM 291
#define LDEC 292
#define LEQ 293
#define LGE 294
#define LGT 295
#define LIGNORE 296
#define LINC 297
#define LLE 298
#define LLSH 299
#define LLT 300
#define LNE 301
#define LOROR 302
#define LRSH 303
#define NotPackage 304
#define NotParen 305
#define PreferToRightParen 306

#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef union YYSTYPE
{

/* Line 2068 of yacc.c  */
#line 28 "go.y"

	Node*		node;
	NodeList*		list;
	Type*		type;
	Sym*		sym;
	struct	Val	val;
	int		i;

/* Line 2068 of yacc.c  */
#line 163 "y.tab.h"
} YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1
#endif

extern YYSTYPE yylval;


text:
package com.evolveum.midpoint.provisioning.ucf.impl;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.xml.namespace.QName;

import org.apache.commons.lang.StringUtils;
import org.identityconnectors.framework.common.objects.AttributeInfo;
import org.identityconnectors.framework.common.objects.Name;
import org.identityconnectors.framework.common.objects.ObjectClass;
import org.identityconnectors.framework.common.objects.OperationalAttributeInfos;
import org.identityconnectors.framework.common.objects.Uid;

import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition;
import com.evolveum.midpoint.schema.processor.ResourceAttribute;
import com.evolveum.midpoint.schema.processor.ResourceAttributeContainer;
import com.evolveum.midpoint.schema.processor.ResourceAttributeContainerDefinition;
import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition;
import com.evolveum.midpoint.schema.processor.ResourceSchema;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.schema.util.ShadowUtil;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType;

public class IcfNameMapper {

	private static final String CUSTOM_OBJECTCLASS_PREFIX = "Custom";
	private static final String CUSTOM_OBJECTCLASS_SUFFIX = "ObjectClass";

	private static final Map<String,QName> specialAttributeMapIcf = new HashMap<String,QName>();
	private static final Map<QName,String> specialAttributeMapMp = new HashMap<QName,String>();

	private ResourceSchema resourceSchema = null;
	// Used when there is no schema (schemaless resource)
	private String resourceSchemaNamespace = null;

	public IcfNameMapper(String resourceSchemaNamespace) {
		super();
		this.resourceSchemaNamespace = resourceSchemaNamespace;
	}

	public ResourceSchema getResourceSchema() {
		return resourceSchema;
	}

	public void setResourceSchema(ResourceSchema resourceSchema) {
		this.resourceSchema = resourceSchema;
		if (resourceSchema != null) {
			resourceSchemaNamespace = resourceSchema.getNamespace();
		}
	}

	private static void initialize() {
		addSpecialAttributeMapping(Name.NAME, ConnectorFactoryIcfImpl.ICFS_NAME);
		addSpecialAttributeMapping(Uid.NAME, ConnectorFactoryIcfImpl.ICFS_UID);

		addOperationalAttributeMapping(OperationalAttributeInfos.CURRENT_PASSWORD);
		addOperationalAttributeMapping(OperationalAttributeInfos.DISABLE_DATE);
		addOperationalAttributeMapping(OperationalAttributeInfos.ENABLE);
		addOperationalAttributeMapping(OperationalAttributeInfos.ENABLE_DATE);
		addOperationalAttributeMapping(OperationalAttributeInfos.LOCK_OUT);
		addOperationalAttributeMapping(OperationalAttributeInfos.PASSWORD);
		addOperationalAttributeMapping(OperationalAttributeInfos.PASSWORD_EXPIRATION_DATE);
		addOperationalAttributeMapping(OperationalAttributeInfos.PASSWORD_EXPIRED);

		addOperationalAttributeMapping(SecretIcfOperationalAttributes.DESCRIPTION);
		addOperationalAttributeMapping(SecretIcfOperationalAttributes.GROUPS);
		addOperationalAttributeMapping(SecretIcfOperationalAttributes.LAST_LOGIN_DATE);
	}

	private static void addSpecialAttributeMapping(String icfName, QName qname) {
		specialAttributeMapIcf.put(icfName, qname);
		specialAttributeMapMp.put(qname, icfName);
	}

	private static void addOperationalAttributeMapping(
			SecretIcfOperationalAttributes opAttr) {
		addOperationalAttributeMapping(opAttr.getName());
	}

	private static void addOperationalAttributeMapping(AttributeInfo attrInfo) {
		addOperationalAttributeMapping(attrInfo.getName());
	}

	private static void addOperationalAttributeMapping(String icfName) {
		QName qName = convertUnderscoreAttributeNameToQName(icfName);
		addSpecialAttributeMapping(icfName, qName);
	}

	public QName convertAttributeNameToQName(String icfAttrName, ResourceAttributeContainerDefinition attributesContainerDefinition) {
		return convertAttributeNameToQName(icfAttrName, attributesContainerDefinition.getComplexTypeDefinition());
	}

	public QName convertAttributeNameToQName(String icfAttrName, ObjectClassComplexTypeDefinition ocDef) {
		if (specialAttributeMapIcf.containsKey(icfAttrName)) {
			for (ResourceAttributeDefinition attributeDefinition: ocDef.getAttributeDefinitions()) {
				if (icfAttrName.equals(attributeDefinition.getFrameworkAttributeName())) {
					return attributeDefinition.getName();
				}
			}
			// fallback, compatibility
			return specialAttributeMapIcf.get(icfAttrName);
		}
		QName attrXsdName = new QName(resourceSchemaNamespace, icfAttrName,
				ConnectorFactoryIcfImpl.NS_ICF_RESOURCE_INSTANCE_PREFIX);
		return attrXsdName;
	}

	public QName convertAttributeNameToQName(String icfAttrName, ResourceAttributeDefinition attrDef) {
		if (specialAttributeMapIcf.containsKey(icfAttrName)) {
			if (icfAttrName.equals(attrDef.getFrameworkAttributeName())) {
				return attrDef.getName();
			}
			// fallback, compatibility
			return specialAttributeMapIcf.get(icfAttrName);
		}
		return attrDef.getName();
	}

	public String convertAttributeNameToIcf(ResourceAttribute<?> attribute, ObjectClassComplexTypeDefinition ocDef)
			throws SchemaException {
		ResourceAttributeDefinition attrDef = attribute.getDefinition();
		if (attrDef == null) {
			attrDef = ocDef.findAttributeDefinition(attribute.getElementName());
			if (attrDef == null) {
				throw new SchemaException("No attribute "+attribute.getElementName()+" in object class "+ocDef.getTypeName());
			}
		}
		return convertAttributeNameToIcf(attrDef);
	}

	public <T> String convertAttributeNameToIcf(QName attributeName, ObjectClassComplexTypeDefinition ocDef, String desc)
			throws SchemaException {
		ResourceAttributeDefinition<T> attrDef = ocDef.findAttributeDefinition(attributeName);
		if (attrDef == null) {
			throw new SchemaException("No attribute "+attributeName+" in object class "+ocDef.getTypeName() + " " + desc);
		}
		return convertAttributeNameToIcf(attrDef);
	}

	public String convertAttributeNameToIcf(ResourceAttributeDefinition<?> attrDef)
			throws SchemaException {
		if (attrDef.getFrameworkAttributeName() != null) {
			return attrDef.getFrameworkAttributeName();
		}

		QName attrQName = attrDef.getName();
		if (specialAttributeMapMp.containsKey(attrQName)) {
			return specialAttributeMapMp.get(attrQName);
		}

		if (!attrQName.getNamespaceURI().equals(resourceSchemaNamespace)) {
			throw new SchemaException("No mapping from QName " + attrQName + " to an ICF attribute in resource schema namespace: " + resourceSchemaNamespace);
		}

		return attrQName.getLocalPart();

	}

	private boolean isUnderscoreSyntax(String icfAttrName) {
		return icfAttrName.startsWith("__") && icfAttrName.endsWith("__");
	}

	private static QName convertUnderscoreAttributeNameToQName(String icfAttrName) {
		// Strip leading and trailing underscores
		String inside = icfAttrName.substring(2, icfAttrName.length()-2);

		StringBuilder sb = new StringBuilder();
		int lastIndex = 0;
		while (true) {
			int nextIndex = inside.indexOf("_", lastIndex);
			if (nextIndex < 0) {
				String upcase = inside.substring(lastIndex, inside.length());
				sb.append(toCamelCase(upcase, lastIndex == 0));
				break;
			}
			String upcase = inside.substring(lastIndex, nextIndex);
			sb.append(toCamelCase(upcase, lastIndex == 0));
			lastIndex = nextIndex + 1;
		}

		return new QName(ConnectorFactoryIcfImpl.NS_ICF_SCHEMA, sb.toString());
	}

	private static String toCamelCase(String upcase, boolean lowCase) {
		if (lowCase) {
			return StringUtils.lowerCase(upcase);
		} else {
			return StringUtils.capitalize(StringUtils.lowerCase(upcase));
		}
	}

	/**
	 * Maps ICF native objectclass name to a midPoint QName objctclass name.
	 *

	 * The mapping is "stateless" - it does not keep any mapping database or any
	 * other state. There is a bi-directional mapping algorithm.
	 *

	 * TODO: mind the special characters in the ICF objectclass names.
	 */
	public QName objectClassToQname(ObjectClass icfObjectClass, String schemaNamespace, boolean legacySchema) {
		if (icfObjectClass == null) {
			return null;
		}
		if (icfObjectClass.is(ObjectClass.ALL_NAME)) {
			return null;
		}
		if (legacySchema) {
			if (icfObjectClass.is(ObjectClass.ACCOUNT_NAME)) {
				return new QName(schemaNamespace, ConnectorFactoryIcfImpl.ACCOUNT_OBJECT_CLASS_LOCAL_NAME,
						ConnectorFactoryIcfImpl.NS_ICF_SCHEMA_PREFIX);
			} else if (icfObjectClass.is(ObjectClass.GROUP_NAME)) {
				return new QName(schemaNamespace, ConnectorFactoryIcfImpl.GROUP_OBJECT_CLASS_LOCAL_NAME,
						ConnectorFactoryIcfImpl.NS_ICF_SCHEMA_PREFIX);
			} else {
				return new QName(schemaNamespace, CUSTOM_OBJECTCLASS_PREFIX + icfObjectClass.getObjectClassValue()
						+ CUSTOM_OBJECTCLASS_SUFFIX, ConnectorFactoryIcfImpl.NS_ICF_RESOURCE_INSTANCE_PREFIX);
			}
		} else {
			return new QName(schemaNamespace, icfObjectClass.getObjectClassValue());
		}
	}

	public ObjectClass objectClassToIcf(PrismObject<? extends ShadowType> shadow, String schemaNamespace, ConnectorType connectorType, boolean legacySchema) {

		ShadowType shadowType = shadow.asObjectable();
		QName qnameObjectClass = shadowType.getObjectClass();
		if (qnameObjectClass == null) {
			ResourceAttributeContainer attrContainer = ShadowUtil
					.getAttributesContainer(shadowType);
			if (attrContainer == null) {
				return null;
			}
			ResourceAttributeContainerDefinition objectClassDefinition = attrContainer.getDefinition();
			qnameObjectClass = objectClassDefinition.getTypeName();
		}

		return objectClassToIcf(qnameObjectClass, schemaNamespace, connectorType, legacySchema);
	}

	/**
	 * Maps a midPoint QName objctclass to the ICF native objectclass name.
	 *

	 * The mapping is "stateless" - it does not keep any mapping database or any
	 * other state. There is a bi-directional mapping algorithm.
	 *

	 * TODO: mind the special characters in the ICF objectclass names.
	 */
	public ObjectClass objectClassToIcf(ObjectClassComplexTypeDefinition objectClassDefinition, String schemaNamespace, ConnectorType connectorType, boolean legacySchema) {
		QName qnameObjectClass = objectClassDefinition.getTypeName();
		return objectClassToIcf(qnameObjectClass, schemaNamespace, connectorType, legacySchema);
	}

	public ObjectClass objectClassToIcf(QName qnameObjectClass, String schemaNamespace, ConnectorType connectorType, boolean legacySchema) {
		if (!schemaNamespace.equals(qnameObjectClass.getNamespaceURI())) {
			throw new IllegalArgumentException("ObjectClass QName " + qnameObjectClass
					+ " is not in the appropriate namespace for "
					+ connectorType + ", expected: " + schemaNamespace);
		}

		String lname = qnameObjectClass.getLocalPart();
		if (legacySchema) {
			if (ConnectorFactoryIcfImpl.ACCOUNT_OBJECT_CLASS_LOCAL_NAME.equals(lname)) {
				return ObjectClass.ACCOUNT;
			} else if (ConnectorFactoryIcfImpl.GROUP_OBJECT_CLASS_LOCAL_NAME.equals(lname)) {
				return ObjectClass.GROUP;
			} else if (lname.startsWith(CUSTOM_OBJECTCLASS_PREFIX) && lname.endsWith(CUSTOM_OBJECTCLASS_SUFFIX)) {
				String icfObjectClassName = lname.substring(CUSTOM_OBJECTCLASS_PREFIX.length(), lname.length()
						- CUSTOM_OBJECTCLASS_SUFFIX.length());
				return new ObjectClass(icfObjectClassName);
			} else {
				throw new IllegalArgumentException("Cannot recognize objectclass QName " + qnameObjectClass
						+ " for " + ObjectTypeUtil.toShortString(connectorType) + ", expected: "
						+ schemaNamespace);
			}
		} else {
			return new ObjectClass(lname);
		}
	}

	static {
		initialize();
	}

}


text:
require "rails_helper"
require "active_admin/menu"
require "active_admin/menu_item"

include ActiveAdmin

RSpec.describe ActiveAdmin::Menu do
  context "with no items" do
    it "should have an empty item collection" do
      menu = Menu.new
      expect(menu.items).to be_empty
    end

    it "should accept new items" do
      menu = Menu.new
      menu.add label: "Dashboard"
      expect(menu.items.first.label).to eq "Dashboard"
    end
  end

  context "with many items" do
    let(:menu) do
      Menu.new do |m|
        m.add label: "Dashboard"
        m.add label: "Blog"
      end
    end

    it "should give access to the menu item as an array" do
      expect(menu["Dashboard"].label).to eq "Dashboard"
    end
  end

  describe "adding items with children" do
    it "should add an empty item if the parent does not exist" do
      menu = Menu.new
      menu.add parent: "Admin", label: "Users"

      expect(menu["Admin"]["Users"]).to be_an_instance_of(ActiveAdmin::MenuItem)
    end

    it "should add a child to a parent if it exists" do
      menu = Menu.new
      menu.add parent: "Admin", label: "Users"
      menu.add parent: "Admin", label: "Projects"

      expect(menu["Admin"]["Projects"]).to be_an_instance_of(ActiveAdmin::MenuItem)
    end

    it "should add a child to a non-root parent if it exists" do
      menu = Menu.new
      menu.add parent: "Admin", label: "Users"
      menu.add parent: ["Admin", "Users"], label: "Projects"

      expect(menu["Admin"]["Users"]["Projects"]).to be_an_instance_of(ActiveAdmin::MenuItem)
    end

    it "should assign children regardless of resource file load order" do
      menu = Menu.new
      menu.add parent: "Users", label: "Posts"
      menu.add label: "Users", url: "/some/url"

      expect(menu["Users"].url).to eq "/some/url"
      expect(menu["Users"]["Posts"]).to be_a ActiveAdmin::MenuItem
    end
  end

  describe "determining if node is current" do
    let(:menu) { Menu.new }
    let(:admin_item) { menu.add label: "Admin" }
    let(:users_item) { menu.add parent: "Admin", label: "Users" }
    let(:projects_item) { menu.add parent: ["Admin", "Users"], label: "Projects" }
    let(:posts_item) { menu.add label: "Posts" }

    it "should consider item current in relation to itself" do
      expect(admin_item.current?(admin_item)).to be true
    end

    it "should consider item current in relation to a descendent" do
      expect(admin_item.current?(users_item)).to be true
      expect(admin_item.current?(projects_item)).to be true
    end

    it "should not consider item current in relation to a non-self/non-descendant" do
      expect(admin_item.current?(posts_item)).to be false
    end
  end
end


text:
<?php

namespace Onema\ExampleApiBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

use Symfony\Component\Validator\Constraints;
use JMS\Serializer\Annotation\ExclusionPolicy;  //Ver 0.11+ the namespace has changed from JMS\SerializerBundle\* to JMS\Serializer\*
use JMS\Serializer\Annotation\Groups;

/**
 * @ORM\Entity(repositoryClass="Onema\ExampleApiBundle\Repository\ProductRepository")
 * @ORM\Table(name="product")
 * @ORM\HasLifecycleCallbacks()
 */
class Product
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     * @Groups({"public", "date"})
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=100)
     * @Groups({"public", "date"})
     */
    protected $name;

    /**
     * @ORM\Column(type="decimal", scale=2)
     * @Groups({"public"})
     */
    protected $price;

    /**
     * @ORM\Column(type="text")
     * @Groups({"public"})
     */
    protected $description;

    /**
     * @ORM\Column(type="datetime")
     * @Groups({"date"})
     */
    protected $created;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
        $this->created = new \DateTime();
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Product
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set price
     *
     * @param float $price
     * @return Product
     */
    public function setPrice($price)
    {
        $this->price = $price;

        return $this;
    }

    /**
     * Get price
     *
     * @return float
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return Product
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set category
     *
     * @param \Onema\StoreBundle\Entity\Category $category
     * @return Product
     */
    public function setCategory($category = null)
    {
        $this->category = $category;

        return $this;
    }

    /**
     * Get category
     *
     * @return \Onema\StoreBundle\Entity\Category
     */
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * @ORM\PrePersist
     */
    public function setCreatedValue()
    {
        $this->created = new \DateTime();
    }

    /**
     * Set created
     *
     * @param \DateTime $created
     * @return Product
     */
    public function setCreated($created)
    {
        $this->created = $created;

        return $this;
    }

    /**
     * Get created
     *
     * @return \DateTime
     */
    public function getCreated()
    {
        return $this->created;
    }
}


text:
module WorkPackagesHelper
  def work_package_api_done_ratio_if_enabled(api, issue)
    if Setting.work_package_done_ratio != 'disabled'
      api.done_ratio  issue.done_ratio
    end
  end

  def work_package_breadcrumb
    full_path = ancestors_links.unshift(work_package_index_link)

    breadcrumb_paths(*full_path)
  end

  def ancestors_links
    controller.ancestors.map do |parent|
      link_to '#' + h(parent.id), work_package_path(parent.id)
    end
  end

  def work_package_index_link
    # TODO: will need to change to work_package index
    link_to(t(:label_work_package_plural), {controller: :work_packages, action: :index})
  end

  # Displays a link to +work_package+ with its subject.
  # Examples:
  #
  #   link_to_work_package(package)                             # => Defect #6: This is the subject
  #   link_to_work_package(package, :all_link => true)          # => Defect #6: This is the subject (everything within the link)
  #   link_to_work_package(package, :truncate => 9)             # => Defect #6: This i...
  #   link_to_work_package(package, :subject => false)          # => Defect #6
  #   link_to_work_package(package, :type => false)             # => #6: This is the subject
  #   link_to_work_package(package, :project => true)           # => Foo - Defect #6
  #   link_to_work_package(package, :id_only => true)           # => #6
  #   link_to_work_package(package, :subject_only => true)      # => This is the subject (as link)
  def link_to_work_package(package, options = {})

    if options[:subject_only]
      options.merge!(:type => false,
                     :subject => true,
                     :id => false,
                     :all_link => true)
    elsif options[:id_only]
      options.merge!(:type => false,
                     :subject => false,
                     :id => true,
                     :all_link => true)
    else
      options.reverse_merge!(:type => true,
                             :subject => true,
                             :id => true)
    end

    parts = { :prefix => [],
              :hidden_link => [],
              :link => [],
              :suffix => [],
              :title => [],
              :css_class => ['issue'] }

    # Prefix part

    parts[:prefix] << "#{package.project}" if options[:project]

    # Link part

    parts[:link] << h(options[:before_text].to_s) if options[:before_text]

    parts[:link] << h(package.kind.to_s) if options[:type]

    parts[:link] << "##{h(package.id)}" if options[:id]

    # Hidden link part

    if package.closed?
      parts[:hidden_link] << content_tag(:span,
                                         t(:label_closed_work_packages),
                                         :class => "hidden-for-sighted")

      parts[:css_class] << 'closed'
    end

    # Suffix part

    if options[:subject]
      subject = if options[:subject]
                  subject = package.subject
                  if options[:truncate]
                    subject = truncate(subject, :length => options[:truncate])
                  end

                  subject
                end

      parts[:suffix] << h(subject)
    end

    # title part

    parts[:title] << package.subject

    # combining

    prefix = parts[:prefix].join(" ")
    suffix = parts[:suffix].join(" ")
    link = parts[:link].join(" ").strip
    hidden_link = parts[:hidden_link].join("")
    title = parts[:title].join(" ")
    css_class = parts[:css_class].join(" ")

    text = if options[:all_link]
             link_text = [prefix, link].reject(&:empty?).join(" - ")
             link_text = [link_text, suffix].reject(&:empty?).join(": ")
             link_text = [hidden_link, link_text].reject(&:empty?).join("")

             link_to(link_text.html_safe,
                     work_package_path(package),
                     :title => title,
                     :class => css_class)
           else
             link_text = [hidden_link, link].reject(&:empty?).join("")

             html_link = link_to(link_text.html_safe,
                                 work_package_path(package),
                                 :title => title,
                                 :class => css_class)

             [[prefix, html_link].reject(&:empty?).join(" - "),
              suffix].reject(&:empty?).join(": ")
            end.html_safe
  end

  def work_package_quick_info(work_package)
    changed_dates = {}

    journals = work_package.journals.where(["created_at >= ?", Date.today.to_time - 7.day])
                                    .order("created_at desc")

    journals.each do |journal|
      break if changed_dates["start_date"] && changed_dates["due_date"]

      ["start_date", "due_date"].each do |date|
        if changed_dates[date].nil? &&
           journal.changed_data[date] &&
           journal.changed_data[date].first
              changed_dates[date] = " (#{journal.changed_data[date].first})".html_safe
        end
      end
    end

    link = link_to_work_package(work_package)
    link += " #{work_package.start_date.nil? ? "[?]" : work_package.start_date.to_s}"
    link += changed_dates["start_date"]
    link += " – #{work_package.due_date.nil? ? "[?]" : work_package.due_date.to_s}"
    link += changed_dates["due_date"]

    link
  end

  def work_package_quick_info_with_description(work_package, lines = 3)
    description_lines = work_package.description.to_s.lines.to_a[0,lines]

    if description_lines[lines-1] && work_package.description.to_s.lines.to_a.size > lines
      description_lines[lines-1].strip!

      while !description_lines[lines-1].end_with?("...") do
        description_lines[lines-1] = description_lines[lines-1] + "."
      end
    end

    description = if work_package.description.blank?
                    "-"
                  else
                    textilizable(description_lines.join(""))
                  end

    link = work_package_quick_info(work_package)

    link += content_tag(:div, :class => 'indent quick_info attributes') do

      responsible = if work_package.responsible_id.present?
                      "#{WorkPackage.human_attribute_name(:responsible)}: " +
                      "#{work_package.responsible.name}"
                    end

      assignee = if work_package.assigned_to_id.present?
                   "#{WorkPackage.human_attribute_name(:assigned_to)}: " +
                   "#{work_package.assigned_to.name}"
                 end

      [responsible, assignee].compact.join("
").html_safe
    end

    link += content_tag(:div, description, :class => 'indent quick_info description')

    link
  end

  def work_package_list(work_packages, &block)
    ancestors = []
    work_packages.each do |work_package|
      while (ancestors.any? && !work_package.is_descendant_of?(ancestors.last))
        ancestors.pop
      end
      yield work_package, ancestors.size
      ancestors << work_package unless work_package.leaf?
    end
  end

  def send_notification_option
    checked = params["send_notification"] != "0"

    content_tag(:label,
                l(:label_notify_member_plural),
                  :for => 'send_notification') +
    hidden_field_tag('send_notification', '0', :id => nil) +
    check_box_tag('send_notification', '1', checked)
  end

  def render_work_package_tree_row(work_package, level, relation)
    css_classes = ["work-package"]
    css_classes << "work-package-#{work_package.id}"
    css_classes << "idnt" << "idnt-#{level}" if level > 0

    if relation == "root"
      issue_text = link_to("#{work_package.to_s}",
                             'javascript:void(0)',
                             :style => "color:inherit; font-weight: bold; text-decoration:none; cursor:default;")
    else
      title = []

      if relation == "parent"
        title << content_tag(:span, l(:description_parent_work_package), :class => "hidden-for-sighted")
      elsif relation == "child"
        title << content_tag(:span, l(:description_sub_work_package), :class => "hidden-for-sighted")
      end

      issue_text = link_to(work_package.to_s.html_safe, work_package_path(work_package))
    end

    content_tag :tr, :class => css_classes.join(' ') do
      concat content_tag :td, check_box_tag("ids[]", work_package.id, false, :id => nil), :class => 'checkbox'
      concat content_tag :td, issue_text, :class => 'subject'
      concat content_tag :td, h(work_package.status)
      concat content_tag :td, link_to_user(work_package.assigned_to)
      concat content_tag :td, link_to_version(work_package.fixed_version)
    end
  end

  # Returns a string of css classes that apply to the issue
  def work_package_css_classes(work_package)
    #TODO: remove issue once css is cleaned of it
    s = "issue work_package".html_safe
    s << " status-#{work_package.status.position}" if work_package.status
    s << " priority-#{work_package.priority.position}" if work_package.priority
    s << ' closed' if work_package.closed?
    s << ' overdue' if work_package.overdue?
    s << ' child' if work_package.child?
    s << ' parent' unless work_package.leaf?
    s << ' created-by-me' if User.current.logged? && work_package.author_id == User.current.id
    s << ' assigned-to-me' if User.current.logged? && work_package.assigned_to_id == User.current.id
    s
  end

  WorkPackageAttribute = Struct.new(:attribute, :field)

  def work_package_form_all_middle_attributes(form, work_package, locals = {})
    [
      work_package_form_status_attribute(form, work_package, locals),
      work_package_form_priority_attribute(form, work_package, locals),
      work_package_form_assignee_attribute(form, work_package, locals),
      work_package_form_responsible_attribute(form, work_package, locals),
      work_package_form_category_attribute(form, work_package, locals),
      work_package_form_assignable_versions_attribute(form, work_package, locals),
      work_package_form_start_date_attribute(form, work_package, locals),
      work_package_form_due_date_attribute(form, work_package, locals),
      work_package_form_estimated_hours_attribute(form, work_package, locals),
      work_package_form_done_ratio_attribute(form, work_package, locals),
      work_package_form_custom_values_attribute(form, work_package, locals)
    ].flatten.compact
  end

  def work_package_form_minimal_middle_attributes(form, work_package, locals = {})
    [
      work_package_form_status_attribute(form, work_package, locals),
      work_package_form_assignee_attribute(form, work_package, locals),
      work_package_form_assignable_versions_attribute(form, work_package, locals),
      work_package_form_done_ratio_attribute(form, work_package, locals),
    ].flatten.compact
  end

  def work_package_form_top_attributes(form, work_package, locals = {})
    [
      work_package_form_type_attribute(form, work_package, locals),
      work_package_form_subject_attribute(form, work_package, locals),
      work_package_form_parent_attribute(form, work_package, locals),
      work_package_form_description_attribute(form, work_package, locals)
    ].compact
  end

  def work_package_show_attributes(work_package)
    [
      work_package_show_status_attribute(work_package),
      work_package_show_start_date_attribute(work_package),
      work_package_show_priority_attribute(work_package),
      work_package_show_due_date_attribute(work_package),
      work_package_show_assigned_to_attribute(work_package),
      work_package_show_progress_attribute(work_package),
      work_package_show_responsible_attribute(work_package),
      work_package_show_category_attribute(work_package),
      work_package_show_spent_time_attribute(work_package),
      work_package_show_fixed_version_attribute(work_package),
      work_package_show_estimated_hours_attribute(work_package)
    ].compact
  end

  def work_package_show_table_row(attribute, klass = nil, &block)
    klass = attribute.to_s.dasherize if klass.nil?

    content = content_tag(:th, :class => klass) { "#{WorkPackage.human_attribute_name(attribute)}:" }
    content << content_tag(:td, :class => klass, &block)

    WorkPackageAttribute.new(attribute, content)
  end

  def work_package_show_status_attribute(work_package)
    work_package_show_table_row(:status) do
      work_package.status ?
        work_package.status.name :
        "-"
    end
  end

  def work_package_show_start_date_attribute(work_package)
    work_package_show_table_row(:start_date, 'start-date') do
      work_package.start_date ?
        format_date(work_package.start_date) :
        "-"
    end
  end

  def work_package_show_priority_attribute(work_package)
    work_package_show_table_row(:priority) do
      work_package.priority ?
        work_package.priority.name :
        "-"
    end
  end

  def work_package_show_due_date_attribute(work_package)
    work_package_show_table_row(:due_date) do
      work_package.due_date ?
        format_date(work_package.due_date) :
        "-"
    end
  end

  def work_package_show_assigned_to_attribute(work_package)
    work_package_show_table_row(:assigned_to) do
      content = avatar(work_package.assigned_to, :size => "14").html_safe
      content << (work_package.assigned_to ? link_to_user(work_package.assigned_to) : "-")
      content
    end
  end

  def work_package_show_responsible_attribute(work_package)
    work_package_show_table_row(:responsible) do
      content = avatar(work_package.responsible, :size => "14").html_safe
      content << (work_package.responsible ? link_to_user(work_package.responsible) : "-")
      content
    end
  end

  def work_package_show_progress_attribute(work_package)
    return if WorkPackage.done_ratio_disabled?

    work_package_show_table_row(:progress, 'done-ratio') do
      progress_bar work_package.done_ratio, :width => '80px', :legend => work_package.done_ratio.to_s
    end
  end

  def work_package_show_category_attribute(work_package)
    work_package_show_table_row(:category) do
      work_package.category ?
        work_package.category.name :
        '-'
    end
  end

  def work_package_show_spent_time_attribute(work_package)
    work_package_show_table_row(:spent_time) do
      work_package.spent_hours > 0 ?
        link_to(l_hours(work_package.spent_hours), work_package_time_entries_path(work_package)) :
        "-"
    end
  end

  def work_package_show_fixed_version_attribute(work_package)
    work_package_show_table_row(:fixed_version) do
      work_package.fixed_version ?
        link_to_version(work_package.fixed_version) :
        "-"
    end
  end

  def work_package_show_estimated_hours_attribute(work_package)
    work_package_show_table_row(:estimated_hours) do
      work_package.estimated_hours ?
        l_hours(work_package.estimated_hours) :
        "-"
    end
  end

  def work_package_form_type_attribute(form, work_package, locals = {})
    selectable_types = locals[:project].types.collect {|t| [((t.is_standard) ? '' : t.name), t.id]}

    field = form.select :type_id, selectable_types, :required => true

    url = work_package.new_record? ?
           new_type_project_work_packages_path(locals[:project]) :
           new_type_work_package_path(work_package)

    field += observe_field :work_package_type_id, :url => url,
                                                  :update => :attributes,
                                                  :method => :get,
                                                  :with => "Form.serialize('work_package-form')"

    WorkPackageAttribute.new(:type, field)
  end

  def work_package_form_subject_attribute(form, work_package, locals = {})
    WorkPackageAttribute.new :subject, form.text_field(:subject, :size => 80, :required => true)
  end

  def work_package_form_parent_attribute(form, work_package, locals = {})
    if User.current.allowed_to?(:manage_subtasks, locals[:project])
      field = form.text_field :parent_id, :size => 10, :title => l(:description_autocomplete)
      field += '

'.html_safe
      field += javascript_tag "observeWorkPackageParentField('#{work_packages_auto_complete_path(:id => work_package, :project_id => locals[:project], :escape => false) }')"

      WorkPackageAttribute.new(:parent_issue, field)
    end
  end

  def work_package_form_description_attribute(form, work_package, locals = {})
    field = form.text_area :description,
                           :cols => 60,
                           :rows => (work_package.description.blank? ? 10 : [[10, work_package.description.length / 50].max, 100].min),
                           :accesskey => accesskey(:edit),
                           :class => 'wiki-edit'

    WorkPackageAttribute.new(:description, field)
  end

  def work_package_form_status_attribute(form, work_package, locals = {})
    new_statuses = work_package.new_statuses_allowed_to(locals[:user], true)

    field = if new_statuses.any?
              form.select(:status_id, (new_statuses.map {|p| [p.name, p.id]}), :required => true)
            elsif work_package.status
              form.label(:status) + work_package.status.name
            else
              form.label(:status) + "-"
            end

    WorkPackageAttribute.new(:status, field)
  end

  def work_package_form_priority_attribute(form, work_package, locals = {})
    WorkPackageAttribute.new(:priority,
                             form.select(:priority_id, (locals[:priorities].map {|p| [p.name, p.id]}), {:required => true}, :disabled => attrib_disabled?(work_package, 'priority_id')))
  end

  def work_package_form_assignee_attribute(form, work_package, locals = {})
    WorkPackageAttribute.new(:assignee,
                             form.select(:assigned_to_id, (work_package.assignable_users.map {|m| [m.name, m.id]}), :include_blank => true))
  end

  def work_package_form_responsible_attribute(form, work_package, locals = {})
    WorkPackageAttribute.new(:assignee,
                             form.select(:responsible_id, options_for_responsible(locals[:project]), :include_blank => true))
  end

  def work_package_form_category_attribute(form, work_package, locals = {})
    unless locals[:project].categories.empty?
      field = form.select(:category_id,
                          (locals[:project].categories.collect {|c| [c.name, c.id]}),
                          :include_blank => true)

      field += prompt_to_remote(image_tag('webalys/plus.png', :style => 'vertical-align: middle;'),
                                         t(:label_work_package_category_new),
                                         'category[name]',
                                         project_categories_path(locals[:project]),
                                         :title => t(:label_work_package_category_new)) if authorize_for('categories', 'new')

      WorkPackageAttribute.new(:category, field)
    end
  end

  def work_package_form_assignable_versions_attribute(form, work_package, locals = {})
    unless work_package.assignable_versions.empty?
      field = form.select(:fixed_version_id,
                          version_options_for_select(work_package.assignable_versions, work_package.fixed_version),
                          :include_blank => true)
      field += prompt_to_remote(image_tag('webalys/plus.png', :style => 'vertical-align: middle;'),
                             l(:label_version_new),
                             'version[name]',
                             new_project_version_path(locals[:project]),
                             :title => l(:label_version_new)) if authorize_for('versions', 'new')

      WorkPackageAttribute.new(:fixed_version, field)
    end
  end

  def work_package_form_start_date_attribute(form, work_package, locals = {})
    start_date_field = form.text_field :start_date, :size => 10, :disabled => attrib_disabled?(work_package, 'start_date')
    start_date_field += calendar_for("#{form.object_name}_start_date") unless attrib_disabled?(work_package, 'start_date')

    WorkPackageAttribute.new(:start_date, start_date_field)
  end

  def work_package_form_due_date_attribute(form, work_package, locals = {})
    due_date_field = form.text_field :due_date, :size => 10, :disabled => attrib_disabled?(work_package, 'due_date')
    due_date_field += calendar_for("#{form.object_name}_due_date") unless attrib_disabled?(work_package, 'due_date')

    WorkPackageAttribute.new(:due_date, due_date_field)
  end

  def work_package_form_estimated_hours_attribute(form, work_package, locals = {})
    field = form.text_field :estimated_hours,
                            :size => 3,
                            :disabled => attrib_disabled?(work_package, 'estimated_hours'),
                            :value => number_with_precision(work_package.estimated_hours, :precision => 2)

    field += TimeEntry.human_attribute_name(:hours)

    WorkPackageAttribute.new(:estimated_hours, field)
  end

  def work_package_form_done_ratio_attribute(form, work_package, locals = {})
    if !attrib_disabled?(work_package, 'done_ratio') && WorkPackage.use_field_for_done_ratio?

      field = form.select(:done_ratio, ((0..10).to_a.collect {|r| ["#{r*10} %", r*10] }))

      WorkPackageAttribute.new(:done_ratio, field)
    end
  end

  def work_package_form_custom_values_attribute(form, work_package, locals = {})
    work_package.custom_field_values.map do |value|
      field = custom_field_tag_with_label :work_package, value

      WorkPackageAttribute.new(:"work_package_#{value.id}", field)
    end
  end

  def work_package_associations_to_address(associated)
    ret = "".html_safe

    ret += content_tag(:p, l(:text_destroy_with_associated), :class => "bold" )

    ret += content_tag(:ul) do
      associated.inject("".html_safe) do |list, associated_class|
        list += content_tag(:li, associated_class.model_name.human, :class => "decorated")

        list
      end
    end

    ret
  end
end