text:
package org.terasology.rendering.shader;

import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.terasology.asset.Assets;
import org.terasology.config.Config;
import org.terasology.math.geom.Vector3f;
import org.terasology.registry.CoreRegistry;
import org.terasology.rendering.assets.material.Material;
import org.terasology.rendering.assets.texture.Texture;
import org.terasology.rendering.cameras.Camera;
import org.terasology.rendering.opengl.FBO;
import org.terasology.rendering.opengl.LwjglRenderingProcess;
import org.terasology.rendering.world.WorldRenderer;

import static org.lwjgl.opengl.GL11.glBindTexture;

/**
 * Shader parameters for the LightBufferPass shader program.
 *
 */
public class ShaderParametersLightGeometryPass extends ShaderParametersBase {

    @Override
    public void applyParameters(Material program) {
        super.applyParameters(program);

        LwjglRenderingProcess renderingProcess = CoreRegistry.get(LwjglRenderingProcess.class);
        FBO sceneOpaque = renderingProcess.getFBO("sceneOpaque");

        int texId = 0;
        if (sceneOpaque != null) {
            GL13.glActiveTexture(GL13.GL_TEXTURE0 + texId);
            sceneOpaque.bindDepthTexture();
            program.setInt("texSceneOpaqueDepth", texId++, true);

            GL13.glActiveTexture(GL13.GL_TEXTURE0 + texId);
            sceneOpaque.bindNormalsTexture();
            program.setInt("texSceneOpaqueNormals", texId++, true);

            GL13.glActiveTexture(GL13.GL_TEXTURE0 + texId);
            sceneOpaque.bindLightBufferTexture();
            program.setInt("texSceneOpaqueLightBuffer", texId++, true);
        }

        if (CoreRegistry.get(Config.class).getRendering().isDynamicShadows()) {
            GL13.glActiveTexture(GL13.GL_TEXTURE0 + texId);
            renderingProcess.bindFboDepthTexture("sceneShadowMap");
            program.setInt("texSceneShadowMap", texId++, true);

            Camera lightCamera = CoreRegistry.get(WorldRenderer.class).getLightCamera();
            Camera activeCamera = CoreRegistry.get(WorldRenderer.class).getActiveCamera();

            if (lightCamera != null && activeCamera != null) {
                program.setMatrix4("lightViewProjMatrix", lightCamera.getViewProjectionMatrix(), true);
                program.setMatrix4("invViewProjMatrix", activeCamera.getInverseViewProjectionMatrix(), true);

                Vector3f activeCameraToLightSpace = new Vector3f();
                activeCameraToLightSpace.sub(activeCamera.getPosition(), lightCamera.getPosition());
                program.setFloat3("activeCameraToLightSpace", activeCameraToLightSpace.x, activeCameraToLightSpace.y, activeCameraToLightSpace.z, true);
            }

            if (CoreRegistry.get(Config.class).getRendering().isCloudShadows()) {
                Texture clouds = Assets.getTexture("engine:perlinNoiseTileable").get();

                GL13.glActiveTexture(GL13.GL_TEXTURE0 + texId);
                glBindTexture(GL11.GL_TEXTURE_2D, clouds.getId());
                program.setInt("texSceneClouds", texId++, true);
            }
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Syntaxiom.Exceptions;
using Syntaxiom.Liquid.Symbols.Factories;
using Syntaxiom.Liquid.Symbols.Parsers;
using Syntaxiom.Liquid.Tokens.Parsers;
using Syntaxiom.Liquid.Tokens;
using Syntaxiom.Symbols;
using Syntaxiom.Symbols.Factories;

namespace Syntaxiom.Liquid.Tests.Integration.Original.Tags
{
    [TestFixture]
    public class ForTagTests : TagTestsBase
    {
        private readonly ISymbolFactory _symbolFactory = new LiquidSymbolFactory();

        [TestCase(" yo  yo  yo  yo ", "{%for item in testglobal%} yo {%endfor%}", 1, 4)]
        [TestCase("yoyo", "{%for item in testglobal%}yo{%endfor%}", 1, 2)]
        [TestCase(" yo ", "{%for item in testglobal%} yo {%endfor%}", 1, 1)]
        [TestCase("", "{%for item in testglobal%}{%endfor%}", 1, 2)]
        [TestCase(
            @"

yo

yo

yo
",
            @"
{%for item in testglobal%}
yo
{%endfor%}", 1, 3)]
        public void TestFor(string expected, string source, int from, int to)
        {
            AssertTemplateResult(expected, source,
                _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(@from), _symbolFactory.CreateConstant(to)));
        }

        [Test]
        public void TestForReversed()
        {
            AssertTemplateResult(
                "321",
                "{%for item in testglobal reversed %}{{item}}{%endfor%}",
                _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(3)));
        }

        [Test]
        public void TestForWithRange()
        {
            AssertTemplateResult(" 1  2  3 ", "{%for item in (1..3) %} {{item}} {%endfor%}");
        }

        [Test]
        public void TestForWithVariableRange()
        {
            AssertTemplateResult(" 1  2  3 ", "{%for item in (1..testglobal) %} {{item}} {%endfor%}",
                _symbolFactory.CreateConstant(3));
        }

        [Test]
        public void TestForWithHashValueRange()
        {
            // DictionarySymbols are equivalent to Liquid hashes
            var dictionary = new Dictionary<string, ISymbol> {{"value", _symbolFactory.CreateConstant(3)}};
            var symbol = _symbolFactory.CreateFromProperties(dictionary);
            AssertTemplateResult(" 1  2  3 ", "{%for item in (1..testglobal.value) %} {{item}} {%endfor%}", symbol);
        }

        [Test]
        public void TestForWithDropValueRange()
        {
            // Custom symbols are equivalent to Liquid drops
            var symbol = new ThingWithValueSymbol(new ThingWithValue());
            AssertTemplateResult(" 1  2  3 ", "{%for item in (1..testglobal.value) %} {{item}} {%endfor%}", symbol);
        }

        [Test, TestCaseSource(nameof(TestForWithVariable_Source))]
        public void TestForWithVariable(string expected, string source, ISymbol symbol)
        {
            AssertTemplateResult(expected, source, symbol);
        }

        [TestCase(" 1/3  2/3  3/3 ", "{%for item in testglobal%} {{forloop.index}}/{{forloop.length}} {%endfor%}")]
        [TestCase(" 1  2  3 ", "{%for item in testglobal%} {{forloop.index}} {%endfor%}")]
        [TestCase(" 0  1  2 ", "{%for item in testglobal%} {{forloop.index0}} {%endfor%}")]
        [TestCase(" 2  1  0 ", "{%for item in testglobal%} {{forloop.rindex0}} {%endfor%}")]
        [TestCase(" 3  2  1 ", "{%for item in testglobal%} {{forloop.rindex}} {%endfor%}")]
        [TestCase(" true  false  false ", "{%for item in testglobal%} {{forloop.first}} {%endfor%}")]
        [TestCase(" false  false  true ", "{%for item in testglobal%} {{forloop.last}} {%endfor%}")]
        public void TestForHelpers(string expected, string source)
        {
            var symbol = _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(3));
            AssertTemplateResult(expected, source, symbol);
        }

        [Test]
        public void TestForAndIf()
        {
            AssertTemplateResult("+--",
                "{%for item in testglobal%}{% if forloop.first %}+{% else %}-{% endif %}{%endfor%}",
                _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(3)));
        }

        [Test, TestCaseSource(nameof(TestForElse_Source))]
        public void TestForElse(string expected, ISymbol symbol)
        {
            AssertTemplateResult(expected, "{%for item in testglobal%}+{%else%}-{%endfor%}", symbol);
        }

        [TestCase("12", "{%for i in testglobal limit:2 %}{{ i }}{%endfor%}")]
        [TestCase("1234", "{%for i in testglobal limit:4 %}{{ i }}{%endfor%}")]
        [TestCase("3456", "{%for i in testglobal limit:4 offset:2 %}{{ i }}{%endfor%}")]
        [TestCase("3456", "{%for i in testglobal limit: 4 offset: 2 %}{{ i }}{%endfor%}")]
        public void TestLimiting(string expected, string source)
        {
            AssertTemplateResult(expected, source, _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(9)));
        }

        [Test]
        public void TestDynamicVariableLimiting()
        {
            var scope = new Scope();
            scope.SetValue("testglobal", _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(9)));
            scope.SetValue("offset", _symbolFactory.CreateConstant(1));
            scope.SetValue("limit", _symbolFactory.CreateConstant(3));

            AssertTemplateResult("234", "{%for i in testglobal limit: limit offset: offset %}{{ i }}{%endfor%}", scope);
        }

        [Test]
        public void TestNestedFor()
        {
            var inner = new List<ISymbol>
            {
                _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(2)),
                _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(3), _symbolFactory.CreateConstant(4)),
                _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(5), _symbolFactory.CreateConstant(6))
            };

            var assigns = _symbolFactory.CreateEnumerable(inner);

            AssertTemplateResult("123456", "{%for item in testglobal%}{%for i in item%}{{ i }}{%endfor%}{%endfor%}",
                assigns);
        }

        [Test]
        public void TestOffsetOnly()
        {
            AssertTemplateResult("789", "{%for i in testglobal offset:6 %}{{ i }}{%endfor%}", _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(9)));
        }

        [Test]
        public void TestPauseResume()
        {
            const string markup =
                @"{%for i in testglobal limit: 3 %}{{i}}{%endfor%}
next
{%for i in testglobal offset:continue limit: 3 %}{{i}}{%endfor%}
next
{%for i in testglobal offset:continue limit: 3 %}{{i}}{%endfor%}";

            const string expected =
                @"123
next
456
next
789";

            AssertTemplateResult(expected, markup,
                _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(10)));
        }

        [Test]
        public void TestPauseResumeLimit()
        {
            const string markup =
@"{%for i in testglobal limit:3 %}{{i}}{%endfor%}
next
{%for i in testglobal offset:continue limit:3 %}{{i}}{%endfor%}
next
{%for i in testglobal offset:continue limit:1 %}{{i}}{%endfor%}";

            const string expected =
                @"123
next
456
next
7";

            AssertTemplateResult(expected, markup,
                _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(10)));
        }

        [Test]
        public void TestPauseResumeBigLimit()
        {
            const string markup =
@"{%for i in testglobal limit:3 %}{{i}}{%endfor%}
next
{%for i in testglobal offset:continue limit:3 %}{{i}}{%endfor%}
next
{%for i in testglobal offset:continue limit:1000 %}{{i}}{%endfor%}";

            const string expected =
@"123
next
456
next
789";

            AssertTemplateResult(expected, markup, _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(9)));
        }

        [Test]
        public void TestPauseResumeBigOffset()
        {
            const string source =
@"{%for i in testglobal limit:3 %}{{i}}{%endfor%}
next
{%for i in testglobal offset:continue limit:3 %}{{i}}{%endfor%}
next
{%for i in testglobal offset:continue limit:3 offset:1000 %}{{i}}{%endfor%}";

            const string expected =
                @"123
next
456
next
";

            AssertTemplateResult(expected, source, _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(9)));
        }

        [TestCase("", "{% for i in testglobal %}{% break %}{% endfor %}")]
        [TestCase("1", "{% for i in testglobal %}{{ i }}{% break %}{% endfor %}")]
        [TestCase("", "{% for i in testglobal %}{% break %}{{ i }}{% endfor %}")]
        [TestCase("1234", "{% for i in testglobal %}{{ i }}{% if i > 3 %}{% break %}{% endif %}{% endfor %}")]
        [TestCase("123456789", "{% for i in testglobal %}{% if i == 9999 %}{% break %}{% endif %}{{ i }}{% endfor %}")]
        public void TestForWithBreak(string expected, string source)
        {
            AssertTemplateResult(expected, source, _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(9)));
        }

        [Test]
        public void TestBreakAffectsClosestForLoopOnly()
        {
            var inner = new List<ISymbol>
            {
                _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(2)),
                _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(3), _symbolFactory.CreateConstant(4)),
                _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(5), _symbolFactory.CreateConstant(6))
            };

            var assigns = _symbolFactory.CreateEnumerable(inner);

            const string source =
                "{% for item in testglobal %}{% for i in item %}{% if i == 1 %}{% break %}{% endif %}{{ i }}{% endfor %}{% endfor %}";

            AssertTemplateResult("3456", source, assigns);
        }

        [TestCase("", "{% for i in testglobal %}{% continue %}{% endfor %}")]
        [TestCase("12345", "{% for i in testglobal %}{{ i }}{% continue %}{% endfor %}")]
        [TestCase("", "{% for i in testglobal %}{% continue %}{{ i }}{% endfor %}")]
        [TestCase("123", "{% for i in testglobal %}{% if i > 3 %}{% continue %}{% endif %}{{ i }}{% endfor %}")]
        [TestCase("1245",
            "{% for i in testglobal %}{% if i == 3 %}{% continue %}{% else %}{{ i }}{% endif %}{% endfor %}")]
        [TestCase("12345", "{% for i in testglobal %}{% if i == 9999 %}{% continue %}{% endif %}{{ i }}{% endfor %}")]
        public void TestForWithContinue(string expected, string source)
        {
            AssertTemplateResult(expected, source,
                _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(5)));
        }

        [Test]
        public void TestContinueAffectsClosestForLoopOnly()
        {
            var inner = new List<ISymbol>
            {
                _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(2)),
                _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(3), _symbolFactory.CreateConstant(4)),
                _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(5), _symbolFactory.CreateConstant(6))
            };

            var assigns = _symbolFactory.CreateEnumerable(inner);

            const string source =
                "{% for item in testglobal %}{% for i in item %}{% if i == 1 %}{% continue %}{% endif %}{{ i }}{% endfor %}{% endfor %}";

            AssertTemplateResult("23456", source, assigns);
        }

        [TestCase("test string", "{%for val in testglobal%}{{val}}{%endfor%}")]
        [TestCase("test string", "{%for val in testglobal limit:1%}{{val}}{%endfor%}")]
        [TestCase(
            "val-string-1-1-0-1-0-true-true-test string",
            "{%for val in testglobal%}{{forloop.name}}-{{forloop.index}}-{{forloop.length}}-{{forloop.index0}}-{{forloop.rindex}}-{{forloop.rindex0}}-{{forloop.first}}-{{forloop.last}}-{{val}}{%endfor%}"
            )]
        public void TestForTagString(string expected, string source)
        {
            // These tests are for backward compatibility with a Ruby 1.8.7 feature
            // that Syntaxiom replaces with per-character iteration.
            // They have been included for completeness only.
            // ============================
            //
            // Comment per the original tests found at https://github.com/Shopify/liquid/blob/master/test/integration/tags/for_tag_test.rb
            // -------------------------------------------
            // ruby 1.8.7 "String".each => Enumerator with single "String" element.
            // ruby 1.9.3 no longer supports .each on String though we mimic
            // the functionality for backwards compatibility
            // AssertTemplateResult(expected, source, _symbolFactory.CreateConstant("test string"));
        }

        [Test]
        public void TestBlankStringNotIterable()
        {
            AssertTemplateResult("", "{% for char in characters %}I WILL NOT BE OUTPUT{% endfor %}",
                _symbolFactory.CreateConstant(string.Empty));
        }

        [Test, ExpectedException(typeof (SyntaxException))]
        public void TestBadVariableNamingInForLoop()
        {
            var tokens = new LiquidTokenizer().Tokenize("{% for a/b in x %}{% endfor %}");
            var symbolFactory = new LiquidSymbolFactory();
            var symbolParser = new LiquidSymbolParser(symbolFactory);
            new LiquidTokenCollectionParser(symbolFactory, symbolParser).ParseCollection(tokens);
        }

        [Test]
        public void TestSpacingWithVariableNamingInForLoop()
        {
            AssertTemplateResult("12345", "{% for       item   in   testglobal %}{{item}}{% endfor %}",
                _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(5)));
        }

        #region LoaderDrop Tests

        /// <summary>
        /// These tests are somewhere between unit test and integration test.
        /// They have been included in this port of the integration tests for completeness only.
        /// </summary>
        [Test]
        public void TestIterateWithEachWhenNoLimitApplied()
        {
            //var loader = new LoaderDrop(new [] { 1, 2, 3, 4, 5 });
            //AssertTemplateResult("12345", "{% for item in testglobal %}{{item}}{% endfor %}", loader);
            //Assert.IsTrue(loader.EachCalled);
            //Assert.IsFalse(loader.LoadSliceCalled);
        }

        /// <summary>
        /// These tests are somewhere between unit test and integration test.
        /// They have been included in this port of the integration tests for completeness only.
        /// </summary>
        [Test]
        public void TestIterateWithLoadSliceWhenLimitApplied()
        {
            //var loader = new LoaderDrop(new [] { 1, 2, 3, 4, 5 });
            //AssertTemplateResult("1", "{% for item in testglobal limit:1 %}{{item}}{% endfor %}", loader);
            //Assert.IsFalse(loader.EachCalled);
            //Assert.IsTrue(loader.LoadSliceCalled);
        }

        /// <summary>
        /// These tests are somewhere between unit test and integration test.
        /// They have been included in this port of the integration tests for completeness only.
        /// </summary>
        [Test]
        public void TestIterateWithLoadSliceWhenLimitAndOffsetApplied()
        {
            //var loader = new LoaderDrop(new [] { 1, 2, 3, 4, 5 });
            //AssertTemplateResult("34", "{% for item in items offset:2 limit:2 %}{{item}}{% endfor %}", loader);
            //Assert.IsFalse(loader.EachCalled);
            //Assert.IsTrue(loader.LoadSliceCalled);
        }

        /// <summary>
        /// These tests are somewhere between unit test and integration test.
        /// They have been included in this port of the integration tests for completeness only.
        /// </summary>
        [Test]
        public void TestIterateWithLoadSliceReturnsSameResultsAsWithout()
        {
            //var loader = new LoaderDrop(new [] { 1, 2, 3, 4, 5 });
            //var array = new IntegerRange(1, 5);
            //AssertTemplateResult("34", "{% for item in testglobal limit:1 %}{{item}}{% endfor %}", loader);
            //AssertTemplateResult("34", "{% for item in testglobal limit:1 %}{{item}}{% endfor %}", array);
        }

        #endregion

        #region Test Data

        private class ThingWithValue
        {
            public int Value => 3;
        }

        private class ThingWithValueSymbol : ISymbol
        {
            private readonly ISymbolFactory _symbolFactory = new LiquidSymbolFactory();
            private readonly ThingWithValue _source;

            public ThingWithValueSymbol(ThingWithValue source)
            {
                _source = source;
            }

            public bool ResolveEquals(IEvaluationContext context, ISymbol other)
            {
                throw new NotImplementedException();
            }

            public int ResolveCompareTo(IEvaluationContext context, ISymbol other)
            {
                throw new NotImplementedException();
            }

            public ISymbol ResolveReference(IEvaluationContext context)
            {
                return this;
            }

            public ISymbol ResolveProperty(IEvaluationContext context, string propertyName)
            {
                return propertyName == "value"
                    ? _symbolFactory.CreateConstant(_source.Value)
                    : null;
            }

            public bool ResolveTruthiness(IEvaluationContext context)
            {
                throw new NotImplementedException();
            }
        }

        public object[] TestForWithVariable_Source()
        {
            return new object[]
            {
                new object[]
                {
                    " 1  2  3 ", "{%for item in testglobal%} {{item}} {%endfor%}",
                    _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(3))
                },
                new object[]
                {
                    "123", "{%for item in testglobal%}{{item}}{%endfor%}",
                    _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(3))
                },
                new object[]
                {
                    "123", "{% for item in testglobal %}{{item}}{% endfor %}",
                    _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(3))
                },
                new object[]
                {
                    "abcd", "{%for item in testglobal%}{{item}}{%endfor%}",
                    _symbolFactory.CreateEnumerable(new[] {"a", "b", "c", "d"}.Select(_symbolFactory.CreateConstant))
                },
                new object[]
                {
                    "a b c", "{%for item in testglobal%}{{item}}{%endfor%}",
                    _symbolFactory.CreateEnumerable(new[] {"a", " ", "b", " ", "c"}.Select(_symbolFactory.CreateConstant))
                },
                new object[]
                {
                    "abc", "{%for item in testglobal%}{{item}}{%endfor%}",
                    _symbolFactory.CreateEnumerable(new[] {"a", "", "b", "", "c"}.Select(_symbolFactory.CreateConstant))
                }
            };
        }

        public object[] TestForElse_Source()
        {
            return new object[]
            {
                new object[]
                {
                    "+++", _symbolFactory.CreateNamed("range", _symbolFactory.CreateConstant(1), _symbolFactory.CreateConstant(3))
                },
                new object[]
                {
                    "-", _symbolFactory.CreateEnumerable(new ISymbol[0])
                },
                new object[]
                {
                    "-", null
                }
            };
        }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @file
 * CKEditor implementation of {@link Drupal.editors} API.
 */

(function (Drupal, debounce, CKEDITOR, $) {

  "use strict";

  /**
   * @namespace
   */
  Drupal.editors.ckeditor = {

    /**
     * Editor attach callback.
     *
     * @param {HTMLElement} element
     * @param {string} format
     *
     * @return {bool}
     */
    attach: function (element, format) {
      this._loadExternalPlugins(format);
      // Also pass settings that are Drupal-specific.
      format.editorSettings.drupal = {
        format: format.format
      };

      // Set a title on the CKEditor instance that includes the text field's
      // label so that screen readers say something that is understandable
      // for end users.
      var label = $('label[for=' + element.getAttribute('id') + ']').html();
      format.editorSettings.title = Drupal.t("Rich Text Editor, !label field", {'!label': label});

      // CKEditor initializes itself in a read-only state if the 'disabled'
      // attribute is set. It does not respect the 'readonly' attribute,
      // however, so we set the 'readOnly' configuration property manually in
      // that case, for the CKEditor instance that's about to be created.
      format.editorSettings.readOnly = element.hasAttribute('readonly');

      return !!CKEDITOR.replace(element, format.editorSettings);
    },

    /**
     * Editor detach callback.
     *
     * @param {HTMLElement} element
     * @param {string} format
     * @param {string} trigger
     *
     * @return {bool}
     */
    detach: function (element, format, trigger) {
      var editor = CKEDITOR.dom.element.get(element).getEditor();
      if (editor) {
        if (trigger === 'serialize') {
          editor.updateElement();
        }
        else {
          editor.destroy();
          element.removeAttribute('contentEditable');
        }
      }
      return !!editor;
    },

    /**
     *
     * @param {HTMLElement} element
     * @param {function} callback
     *
     * @return {bool}
     */
    onChange: function (element, callback) {
      var editor = CKEDITOR.dom.element.get(element).getEditor();
      if (editor) {
        editor.on('change', debounce(function () {
          callback(editor.getData());
        }, 400));
      }
      return !!editor;
    },

    /**
     *
     * @param {HTMLElement} element
     * @param {object} format
     * @param {string} mainToolbarId
     * @param {string} floatedToolbarId
     *
     * @return {bool}
     */
    attachInlineEditor: function (element, format, mainToolbarId, floatedToolbarId) {
      this._loadExternalPlugins(format);
      // Also pass settings that are Drupal-specific.
      format.editorSettings.drupal = {
        format: format.format
      };

      var settings = $.extend(true, {}, format.editorSettings);

      // If a toolbar is already provided for "true WYSIWYG" (in-place editing),
      // then use that toolbar instead: override the default settings to render
      // CKEditor UI's top toolbar into mainToolbar, and don't render the bottom
      // toolbar at all. (CKEditor doesn't need a floated toolbar.)
      if (mainToolbarId) {
        var settingsOverride = {
          extraPlugins: 'sharedspace',
          removePlugins: 'floatingspace,elementspath',
          sharedSpaces: {
            top: mainToolbarId
          }
        };

        // Find the "Source" button, if any, and replace it with "Sourcedialog".
        // (The 'sourcearea' plugin only works in CKEditor's iframe mode.)
        var sourceButtonFound = false;
        for (var i = 0; !sourceButtonFound && i < settings.toolbar.length; i++) {
          if (settings.toolbar[i] !== '/') {
            for (var j = 0; !sourceButtonFound && j < settings.toolbar[i].items.length; j++) {
              if (settings.toolbar[i].items[j] === 'Source') {
                sourceButtonFound = true;
                // Swap sourcearea's "Source" button for sourcedialog's.
                settings.toolbar[i].items[j] = 'Sourcedialog';
                settingsOverride.extraPlugins += ',sourcedialog';
                settingsOverride.removePlugins += ',sourcearea';
              }
            }
          }
        }

        settings.extraPlugins += ',' + settingsOverride.extraPlugins;
        settings.removePlugins += ',' + settingsOverride.removePlugins;
        settings.sharedSpaces = settingsOverride.sharedSpaces;
      }

      // CKEditor requires an element to already have the contentEditable
      // attribute set to "true", otherwise it won't attach an inline editor.
      element.setAttribute('contentEditable', 'true');

      return !!CKEDITOR.inline(element, settings);
    },

    /**
     * @param {object} format
     */
    _loadExternalPlugins: function (format) {
      var externalPlugins = format.editorSettings.drupalExternalPlugins;
      // Register and load additional CKEditor plugins as necessary.
      if (externalPlugins) {
        for (var pluginName in externalPlugins) {
          if (externalPlugins.hasOwnProperty(pluginName)) {
            CKEDITOR.plugins.addExternal(pluginName, externalPlugins[pluginName], '');
          }
        }
        delete format.editorSettings.drupalExternalPlugins;
      }
    }

  };

  Drupal.ckeditor = {

    /**
     * Variable storing the current dialog's save callback.
     *
     * @type {?function}
     */
    saveCallback: null,

    /**
     * Open a dialog for a Drupal-based plugin.
     *
     * This dynamically loads jQuery UI (if necessary) using the Drupal AJAX
     * framework, then opens a dialog at the specified Drupal path.
     *
     * @param {CKEditor} editor
     *   The CKEditor instance that is opening the dialog.
     * @param {string} url
     *   The URL that contains the contents of the dialog.
     * @param {object} existingValues
     *   Existing values that will be sent via POST to the url for the dialog
     *   contents.
     * @param {function} saveCallback
     *   A function to be called upon saving the dialog.
     * @param {object} dialogSettings
     *   An object containing settings to be passed to the jQuery UI.
     */
    openDialog: function (editor, url, existingValues, saveCallback, dialogSettings) {
      // Locate a suitable place to display our loading indicator.
      var $target = $(editor.container.$);
      if (editor.elementMode === CKEDITOR.ELEMENT_MODE_REPLACE) {
        $target = $target.find('.cke_contents');
      }

      // Remove any previous loading indicator.
      $target.css('position', 'relative').find('.ckeditor-dialog-loading').remove();

      // Add a consistent dialog class.
      var classes = dialogSettings.dialogClass ? dialogSettings.dialogClass.split(' ') : [];
      classes.push('editor-dialog');
      dialogSettings.dialogClass = classes.join(' ');
      dialogSettings.autoResize = Drupal.checkWidthBreakpoint(600);

      // Add a "Loading…" message, hide it underneath the CKEditor toolbar,
      // create a Drupal.Ajax instance to load the dialog and trigger it.
      var $content = $('
' + Drupal.t('Loading...') + '
');
      $content.appendTo($target);

      var ckeditorAjaxDialog = Drupal.ajax({
        dialog: dialogSettings,
        dialogType: 'modal',
        selector: '.ckeditor-dialog-loading-link',
        url: url,
        progress: {'type': 'throbber'},
        submit: {
          editor_object: existingValues
        }
      });
      ckeditorAjaxDialog.execute();

      // After a short delay, show "Loading…" message.
      window.setTimeout(function () {
        $content.find('span').animate({top: '0px'});
      }, 1000);

      // Store the save callback to be executed when this dialog is closed.
      Drupal.ckeditor.saveCallback = saveCallback;
    }
  };

  // Moves the dialog to the top of the CKEDITOR stack.
  $(window).on('dialogcreate', function (e, dialog, $element, settings) {
    $('.editor-dialog').css("zIndex", CKEDITOR.config.baseFloatZIndex + 1);
  });

  // Respond to new dialogs that are opened by CKEditor, closing the AJAX loader.
  $(window).on('dialog:beforecreate', function (e, dialog, $element, settings) {
    $('.ckeditor-dialog-loading').animate({top: '-40px'}, function () {
      $(this).remove();
    });
  });

  // Respond to dialogs that are saved, sending data back to CKEditor.
  $(window).on('editor:dialogsave', function (e, values) {
    if (Drupal.ckeditor.saveCallback) {
      Drupal.ckeditor.saveCallback(values);
    }
  });

  // Respond to dialogs that are closed, removing the current save handler.
  $(window).on('dialog:afterclose', function (e, dialog, $element) {
    if (Drupal.ckeditor.saveCallback) {
      Drupal.ckeditor.saveCallback = null;
    }
  });

})(Drupal, Drupal.debounce, CKEDITOR, jQuery);


text:
'use strict';

/**
 * Azure resource SKU definition.
 *
 */
class AzureResourceSku {
  /**
   * Create a AzureResourceSku.
   * @property {string} [resourceType] Resource Namespace and Type.
   * @property {object} [sku] The SKU details.
   * @property {string} [sku.name] SKU name. Possible values include: 'D13_v2',
   * 'D14_v2', 'L8', 'L16', 'D11_v2', 'D12_v2', 'L4'
   * @property {number} [sku.capacity] SKU capacity.
   * @property {object} [capacity] The SKU capacity.
   * @property {string} [capacity.scaleType] Scale type. Possible values
   * include: 'automatic', 'manual', 'none'
   * @property {number} [capacity.minimum] Minimum allowed capacity.
   * @property {number} [capacity.maximum] Maximum allowed capacity.
   * @property {number} [capacity.default] The default capacity that would be
   * used.
   */
  constructor() {
  }

  /**
   * Defines the metadata of AzureResourceSku
   *
   * @returns {object} metadata of AzureResourceSku
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'AzureResourceSku',
      type: {
        name: 'Composite',
        className: 'AzureResourceSku',
        modelProperties: {
          resourceType: {
            required: false,
            serializedName: 'resourceType',
            type: {
              name: 'String'
            }
          },
          sku: {
            required: false,
            serializedName: 'sku',
            type: {
              name: 'Composite',
              className: 'AzureSku'
            }
          },
          capacity: {
            required: false,
            serializedName: 'capacity',
            type: {
              name: 'Composite',
              className: 'AzureCapacity'
            }
          }
        }
      }
    };
  }
}

module.exports = AzureResourceSku;


text:
package tls

import (
	"bytes"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"math/big"
	"net"
	"time"
)

func Certificate(host ...string) (tls.Certificate, error) {
	priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return tls.Certificate{}, err
	}

	notBefore := time.Now()
	notAfter := notBefore.Add(time.Hour * 24 * 365)

	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		return tls.Certificate{}, err
	}

	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			Organization: []string{"Acme Co"},
		},
		NotBefore: notBefore,
		NotAfter:  notAfter,

		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
	}

	for _, h := range host {
		if ip := net.ParseIP(h); ip != nil {
			template.IPAddresses = append(template.IPAddresses, ip)
		} else {
			template.DNSNames = append(template.DNSNames, h)
		}
	}

	template.IsCA = true
	template.KeyUsage |= x509.KeyUsageCertSign

	derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
	if err != nil {
		return tls.Certificate{}, err
	}

	// create public key
	certOut := bytes.NewBuffer(nil)
	pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})

	// create private key
	keyOut := bytes.NewBuffer(nil)
	b, err := x509.MarshalECPrivateKey(priv)
	if err != nil {
		return tls.Certificate{}, err
	}
	pem.Encode(keyOut, &pem.Block{Type: "EC PRIVATE KEY", Bytes: b})

	return tls.X509KeyPair(certOut.Bytes(), keyOut.Bytes())
}


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\View;

class MainController extends Controller
{
    public function downloadFindingsReportPDF() {

      // //PDF file is stored under project/public/download/info.pdf
      // $file= public_path()."/content/documents/clark_county_amphibian_report.pdf";
      //
      // $headers = array(
      //   'Content-Type: application/pdf',
      // );
      //
      // // return \Response::download($file, 'filename.pdf', $headers);
      // return response()->download($file, 'REPORT_2009.pdf', $headers);
    }
}


text:
import os

##############################################################################
# setup environment setup
def setup(i):
    """
    Input:  {
              cfg              - meta of this soft entry
              self_cfg         - meta of module soft
              ck_kernel        - import CK kernel module (to reuse functions)

              host_os_uoa      - host OS UOA
              host_os_uid      - host OS UID
              host_os_dict     - host OS meta

              target_os_uoa    - target OS UOA
              target_os_uid    - target OS UID
              target_os_dict   - target OS meta

              target_device_id - target device ID (if via ADB)

              tags             - list of tags used to search this entry

              env              - updated environment vars from meta
              customize        - updated customize vars from meta

              deps             - resolved dependencies for this soft

              interactive      - if 'yes', can ask questions, otherwise quiet
            }

    Output: {
              return       - return code =  0, if successful
                                         >  0, if error
              (error)      - error text if return > 0

              bat          - prepared string for bat file
            }

    """

    # Get variables
    cus = i.get('customize',{})

    env = i['env']
    ep = cus['env_prefix']

    full_path = cus.get('full_path','')
    install_dir, model_filename = os.path.split(full_path)

    install_env = cus.get('install_env', {})

    # Init common variables, they are expected to be set for all models
    env[ep+'_FILE'] = os.path.join(install_dir, install_env['LABELMAP_FILE'])

    return {'return': 0, 'bat': ''}


text:
bg: "p1.png"
layout: post
title:  "Integrating To Quickbooks"
crawlertitle: ""
summary: ""
date:   2016-11-28 20:09:47 +0700
categories: posts
tags: ['.Net', 'Integration', 'Quickbooks']
author: Mohan Kodali
---
In this post we will see how we can integrate QuickBooks Desktop / Server version with an Asp.Net web application. After going through the Intuit developer's portal I understood that we need to use QuickBooks Web Connector tool to integrate a desktop version with a web application.

Here is a pictorial representation of communication model and data flow.
[![DataFlow]({{ site.images }}/qb1.png)]({{ site.images }}/qb1.png)

There are few options available to for integration but, I will provide a link to the QuickBooks Web Connector Programmer's Guide that will explain why QBWC is the best and easy way to do it. The guide is very helpful in terms of getting started but the links are not updated. It took me a week to put everything together and make it work. I don't want you to waste your time and get started right away with the template provided. Please get the WCF project from here.

##### QuickBooks Web Connector Program Guide. [Click Here]({{ site.baseurl }}{% link /assets/files/QBWC_proguide.pdf %})

##### Sample WCF Servie Solution to get started with. Click Here

The QuickBooks Web Connector (QBWC) is a Microsoft Windows application that that enables specially designed web services (interface driven) to exchange data with QuickBooks desktop products (QuickBooks Financial Software and QuickBooks Point of Sale). For QWBC to talk to our web application we need to build a WCF service with operation that QBWC understand and expose our data through that web service. Download the tool here. Click Here

In any integration we have two sides and each side has their own responsibilities. Let me quickly explain the responsibilities of each side in simple steps

## Your Customer Side
- Your Customer need to download the most recent version of QBWC tool from the link provided here and install it on his machine.
- You will provide a QWC File, this is a XML configuration file that will provide all the necessary information for the QBWC to connect to your web service. It will have the end point URL, the User ID.
- Provide an option in your web application using which your end user should download the QWC configuration file. In my application, user can download the config file from his profile setup.
- You will provide the password for the User ID that you included in the QWC config file that you shared with the customer. In my application once user downloads the QWC file, I email the system generated random password to him email id.
- Your customer will use this file to setup the integration as shown below.
- Once everything is setup he can select the integration definition and press the update selected button to exchange data between QuickBooks and your web service.

## Your Side
- As I said above you will create the Web Service with operations that QuickBooks Web Connector know to call in a sequence.
	- Authenticate
    - ClientVersion
	- CloseConnection
	- ConnectionError
	- GetLastError
	- ReceiveResponseXML
	- SendRequestXML
- The developers guide will explain clearly the need for each operation. Every operation has its own purpose, but SendRequestXML is the key operation using which we will control the data flow.
- For every request XML you send, QBWC will send the response to the ReceiveResponseXML operation. You can parse the XML to get the response for your request.
- GetLastError method will help you to understand any errors that might occur during the data sync. The Developer guide will walk you through that flow. The code samples will help us understand it better.
- During development mode, enable logging and see the sequence of operation calls. Make the flow break and see how the operations are handling errors.
- You will create a QWC Configuration file that will used by your customer to setup the integration in the QBWC application.
- You will include the following details in the QWC file. In detail description of these fields is provided in the integration guide on page 35.
	- AppName
	- AppID
	- AppURL
	- AppDescription
	- AppSupport
	- OwnerID
	- FileID
	- UserName
	- QBType
	- Style
	- AuthFlags
      [![SampleQWC]({{ site.images }}/qb2.png)]({{ site.images }}/qb2.png)
- You have to create a password for the user id that you have included in the QWC file and share it with the customer.
- One important thing to remember is that QBWC integration will work on HTTP only when your end point address is running locally, meaning only when the host name is localhost. It needs HTTPS when you deploy it to your QA or PROD environment.


text:
package main

import (
	"bufio"
	"flag"
	"fmt"
	"log"
	"os"
	"path/filepath"

	_ "github.com/golang/glog" // init glog flags
	"github.com/vbehar/openshift-cucumber/reporter"
	"github.com/vbehar/openshift-cucumber/steps"

	"github.com/lsegal/gucumber"
	"github.com/spf13/pflag"
)

var (
	gitCommit   string
	buildNumber string
)

func init() {
	// disable glog logging to stderr by default
	// because we don't want port-forwarding info messages in the console output
	flag.Set("logtostderr", "false")
}

func main() {
	flags := pflag.NewFlagSet("openshift-cucumber", pflag.ExitOnError)
	printVersion := flags.BoolP("version", "v", false, "print version")
	featuresFilesOrDirs := flags.StringSliceP("features", "f", []string{}, "paths to .feature files or directories")
	reporterName := flags.StringP("reporter", "r", "", "reporter (junit)")
	outputFile := flags.StringP("output", "o", "", "output file")
	flags.AddGoFlagSet(flag.CommandLine)
	flags.Parse(os.Args[1:])

	if *printVersion {
		if len(gitCommit) == 0 {
			fmt.Printf("openshift-cucumber - DEV\n")
		} else if len(buildNumber) == 0 {
			fmt.Printf("openshift-cucumber - Commit %s\n", gitCommit)
		} else {
			fmt.Printf("openshift-cucumber - Commit %s Build #%s\n", gitCommit, buildNumber)
		}
		os.Exit(0)
	}

	if len(*featuresFilesOrDirs) == 0 {
		flags.PrintDefaults()
		os.Exit(1)
	}

	features := []string{}
	for _, dir := range *featuresFilesOrDirs {
		info, err := os.Stat(dir)
		if err != nil {
			log.Printf("Failed to open path %s: %v", dir, err)
			continue
		}

		if info.IsDir() {
			if files, _ := filepath.Glob(filepath.Join(dir, "*.feature")); files != nil {
				features = append(features, files...)
			}
			if files, _ := filepath.Glob(filepath.Join(dir, "**", "*.feature")); files != nil {
				features = append(features, files...)
			}
		} else {
			features = append(features, dir)
		}
	}

	c := steps.NewContext(&gucumber.GlobalContext)
	runner, err := c.RunFiles(features)
	if err != nil {
		log.Fatalf("Got error %v\n", err)
	}

	if *reporterName == "junit" {
		junit := &reporter.JunitReporter{}
		f, err := os.Create(*outputFile)
		if err != nil {
			log.Fatalf("Failed to create output file %s: %v", *outputFile, err)
		} else {
			defer f.Close()

			w := bufio.NewWriter(f)
			if err = junit.GenerateReport(runner.Results, w); err != nil {
				log.Fatalf("Failed to generate JUnit Report to %s: %v", *outputFile, err)
			}
		}

	}

}


text:
package org.xmlcml.ami2.plugins.phylotree.nexml;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.xmlcml.cmine.args.DefaultArgProcessor;
import org.xmlcml.diagrams.DiagramTree;
import org.xmlcml.euclid.Int2;
import org.xmlcml.euclid.Util;
import org.xmlcml.image.pixel.PixelEdge;
import org.xmlcml.image.pixel.PixelEdgeList;
import org.xmlcml.image.pixel.PixelNode;
import org.xmlcml.image.pixel.PixelNodeList;

/** creates NexmlTrees initially from diagram trees
 *
 * @author pm286
 *
 */
public class NexmlFactory {

	private static final Logger LOG = Logger.getLogger(NexmlFactory.class);
	static {
		LOG.setLevel(Level.DEBUG);
	}

	static final String TRUE = "true";
	private static final String TREE_ID = "T";
	private static final String OTU = "otu";

	private NexmlNEXML nexmlNEXML;
	private NexmlOtus nexmlOtus;
	private NexmlTrees nexmlTrees;
	private Map<PixelNode, NexmlNode> pixelNodeToNexmlNodeMap;
	private Map<String, NexmlNode> idToNexmlNodeMap;
	private PixelNode rootPixelNode;
	private NexmlNode rootNexmlNode;
	private List<NexmlEdge> nexmlEdgeList;
	private NexmlTree nexmlTree;
	private int recursionCounter;
	private Set<NexmlEdge> processedEdges;
	private DefaultArgProcessor argProcessor;

	public NexmlFactory() {
		this(new DefaultArgProcessor());
	}

	public NexmlFactory(DefaultArgProcessor argProcessor) {
		pixelNodeToNexmlNodeMap = new HashMap<PixelNode, NexmlNode>();
		idToNexmlNodeMap = new HashMap<String, NexmlNode>();
		nexmlEdgeList = new ArrayList<NexmlEdge>();
		this.argProcessor = argProcessor;
	}

	/**
<nexml xmlns="http://www.nexml.org/2009" xmlns:nex="http://www.nexml.org/2009"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:svgx="http://www.xml-cml.org/schema/svgx"
	id="tree.null">
	<otus id="tax1" label="RootTaxaBlock">
		<otu id="t1" />
		...
		<otu id="t5" />
	</otus>
	<trees label="TreesBlockFromXML" id="Trees" otus="tax1">
		<tree id="tree1" label="tree1" xsi:type="FloatTree">
			<node id="N1" otu="t1" label="Luscinia" x="397.018" y="102.384"/>
			...
			<node id="N5" otu="t5" label="Sturnus" x="394.055" y="133.774"/>
			<node id="N6" label="N6" x="318.938" y="129.848"/>
			<node id="N7" label="N7" root="true" x="290.932" y="121.022"/>
			<node id="N8" label="N8" x="303.421" y="112.197"/>
			<node id="N9" label="N9" x="342.88" y="106.311"/>
			<edge id="polyline.14" label="polyline.14" source="N9" target="N1"
				svgx:length="54.138" />
			<edge id="polyline.16" label="polyline.16" source="N9" target="N2"
				svgx:length="66.062" />
				...
			<edge id="polyline.15" label="polyline.15" source="N8" target="N9"
				svgx:length="39.459" />
		</tree>
	</trees>
</nexml>
	 * @return
	 */
	public NexmlNEXML getOrCreateNexmlNEXML() {
		if (nexmlNEXML == null) {
			nexmlNEXML = new NexmlNEXML();
			nexmlOtus = new NexmlOtus();
			nexmlOtus.setLabel("RootTaxaBlock");
			nexmlNEXML.appendChild(nexmlOtus);
			nexmlTrees = new NexmlTrees();
			nexmlNEXML.appendChild(nexmlTrees);
		}
		return nexmlNEXML;
	}

	public NexmlTree createAndAddNexmlTree(DiagramTree diagramTree) {
		getOrCreateNexmlNEXML();
		nexmlTree = new NexmlTree();
		nexmlTrees.appendChild(nexmlTree);
		String treeId = TREE_ID+nexmlTrees.getOrCreateTreeList().size();
		nexmlTree.setId(treeId);
		PixelNodeList pixelNodeList = diagramTree.getGraph().getNodeList();
		if (rootPixelNode == null) {
			rootPixelNode = diagramTree.getGraph().getRootPixelNode();
			if (rootPixelNode == null) {
				LOG.error("NO ROOT NODE");
			}
		}
		addNodes(pixelNodeList, rootPixelNode);
		PixelEdgeList pixelEdgeList = diagramTree.getGraph().getEdgeList();
		addEdges(nexmlTree, pixelEdgeList);
		checkEdges();
		addEdgesToNodes();
		if (rootNexmlNode == null) {
			LOG.error("NULL ROOT NODE");
		} else {
			recursionCounter = nexmlEdgeList.size()+50;
			processedEdges = new HashSet<NexmlEdge>();
			addChildrenAndDirectionality(rootNexmlNode);
		}
		return nexmlTree;
	}

	private void checkEdges() {
		Set<String> targetSourceSet = new HashSet<String>();
		for (int i = 0; i < nexmlEdgeList.size(); i++) {
			NexmlEdge edge = nexmlEdgeList.get(i);
			if (edge.getId() == null) {
				edge.setId("e."+i);
			}
			String targetId = edge.getTargetId();
			String sourceId = edge.getSourceId();
			if (targetId == null || sourceId == null) continue;
			int compare = targetId.compareTo(sourceId);
			if (compare == 0) {
				argProcessor.TREE_LOG().error("edge target "+targetId+" == source "+sourceId);
				continue;
			} else if (compare < 0) {
				targetId = edge.getSourceId();
				sourceId = edge.getTargetId();
			}
			String targetSourceIds = targetId+"=>"+sourceId;
			LOG.trace("ts "+targetSourceIds);
			if(targetSourceSet.contains(targetSourceIds)) {
				argProcessor.TREE_LOG().error("duplicate edge: "+edge);
			} else {
				targetSourceSet.add(targetSourceIds);
			}
		}
	}

	private void addNodes(PixelNodeList pixelNodeList,
			PixelNode rootNode) {
		for (PixelNode pixelNode : pixelNodeList) {
			NexmlNode nexmlNode = null;
			PixelEdgeList edgeList = pixelNode.getEdges();
			if (edgeList.size() == 1) {
				nexmlNode = addTerminalNodeAsOtu(pixelNode);
			} else if (edgeList.size() == 2) {
				LOG.trace("node2 remove me??: "+pixelNode.toString()+"; "+pixelNode.getEdges().size());
			} else if (edgeList.size() == 3) {
				nexmlNode = createAndAddNexmlNode(pixelNode);
				LOG.trace("node3: "+pixelNode.toString()+"; "+pixelNode.getEdges().size());
			} else if (edgeList.size() >= 4) {
				nexmlNode = createAndAddNexmlNode(pixelNode);
				LOG.trace("node >= 4 connections: "+pixelNode.toString()+"; "+pixelNode.getEdges().size());
			} else {
				// ???
			}
			if (nexmlNode != null) {
				pixelNodeToNexmlNodeMap.put(pixelNode, nexmlNode);
				String id = nexmlNode.getId();
				if (id != null) {
					idToNexmlNodeMap.put(id, nexmlNode);
				} else {
					LOG.debug("null id for "+nexmlNode);
				}
			}
			// have to compare coords as Ids, etc have changed
			// have reduced the offset to zero.
			if (nexmlNode != null) {
				Int2 xy0 = rootPixelNode.getInt2();
				Int2 xy1 = pixelNode.getInt2();
				LOG.trace("coords "+xy0+"; "+xy1);
				if (Int2.isEqual(xy0, xy1) || kludgeRoot()) {
					nexmlNode.setRoot(TRUE);
					LOG.trace("ROOT TRUE "+nexmlNode);
					this.rootNexmlNode = nexmlNode;
				} else {
					LOG.trace("failed to create ROOT: "+xy0+"//"+xy1);
				}
			}
		}

//		pixelNodeList.sort();
	}

	// this seems to work partially but we can't afford the time to check it
	private boolean kludgeRoot() {
//		LOG.debug("KLUDGED TREE ROOT, check");
//		return true;
		return false;
	}

	private void addEdges(NexmlTree nexmlTree, PixelEdgeList pixelEdgeList) {
		LOG.trace("add pixelEdges: "+pixelEdgeList.size());
		for (PixelEdge pixelEdge : pixelEdgeList) {
			LOG.trace("edge: "+pixelEdge.toString());
			if (pixelEdge.getNodes().get(0) == null || pixelEdge.getNodes().get(1) == null) {
				argProcessor.TREE_LOG().warn("null node in edge: "+pixelEdge );
			}
			NexmlEdge nexmlEdge = createAndAddNexmlEdge(nexmlTree, pixelEdge);
			nexmlEdgeList.add(nexmlEdge);
		}
	}

	private void addEdgesToNodes() {
		for (NexmlEdge nexmlEdge : nexmlEdgeList) {
			addEdgeToEndsNodes(nexmlEdge);
		}
	}

	private void addEdgeToEndsNodes(NexmlEdge nexmlEdge) {
		NexmlNode node0 = nexmlEdge.getNexmlNode(0);
		node0.addNexmlEdge(nexmlEdge);
		NexmlNode node1 = nexmlEdge.getNexmlNode(1);
		if (node1 != null) {
			node1.addNexmlEdge(nexmlEdge);
		}
	}

//	private void addChildrenAndDirectionality1(NexmlNode parentNexmlNode) {
//		if (parentNexmlNode == null) {
//			LOG.debug("cannot find rootNexmlNode");
//			return;
//		}
//		String parentId = parentNexmlNode.getId();
//		if (parentId == null) {
//			throw new RuntimeException("No id for parentNode");
//		}
//		LOG.debug("parent "+parentId);
//		LOG.debug("edges FIXME "+parentNexmlNode.nexmlEdges.size());
//		for (NexmlEdge nexmlEdge : parentNexmlNode.nexmlEdges) {
//			String edgeSourceId = nexmlEdge.getSourceId();
//			String edgeTargetId = nexmlEdge.getTargetId();
//			if (edgeSourceId == null || edgeTargetId == null) {
//				LOG.error("edge with null Ids");
//				continue;
//			}
//			// wrong directionality
//			if (parentId.equals(edgeSourceId)) {
//				nexmlEdge.setTarget(edgeSourceId);
//				nexmlEdge.setSource(edgeTargetId);
//				edgeTargetId = nexmlEdge.getTargetId();
//				edgeSourceId = nexmlEdge.getSourceId();
//			}
//			LOG.debug("edge S "+edgeSourceId+"; T  "+edgeTargetId);
//			if (parentId.equals(edgeTargetId)) {
//				parentNexmlNode.setParentNexmlNode(idToNexmlNodeMap.get(edgeSourceId));
//				NexmlNode childNexmlNode = nexmlEdge.getOtherNode(parentNexmlNode);
//				if (childNexmlNode == null) {
//					LOG.debug("null node in edge? "+parentNexmlNode);
//				} else {
//					nexmlEdge.setSource(parentId);
//					nexmlEdge.setTarget(childNexmlNode.getId());
//					addChildrenAndDirectionality1(childNexmlNode);
//					parentNexmlNode.addChildNode(childNexmlNode);
//				}
//			}
//		}
//	}

	private void addChildrenAndDirectionality(NexmlNode parentNexmlNode) {
		if (recursionCounter-- <= 0) {
			throw new RuntimeException("Too much recursion");
		}
		LOG.trace("recursionCounter: "+recursionCounter);
		if (parentNexmlNode == null) {
			LOG.error("cannot find rootNexmlNode");
			return;
		}
		NexmlNode grandParentNode = parentNexmlNode.getParentNexmlNode();
		if (grandParentNode != null) {
			LOG.error(parentNexmlNode.getId()+" parent already has parent: "+grandParentNode);
			return;
		}
		String parentId = parentNexmlNode.getId();
		if (parentId == null) {
			LOG.error("parent has no Id");
			return;
		}
		for (NexmlEdge nexmlEdge : parentNexmlNode.nexmlEdges) {
			if (processedEdges.contains(nexmlEdge)) {
				LOG.trace("skipping processed "+nexmlEdge);
				continue;
			} else {
				processedEdges.add(nexmlEdge);
			}
			String edgeSourceId = nexmlEdge.getSourceId();
			String edgeTargetId = nexmlEdge.getTargetId();
			LOG.trace(edgeSourceId+"=>"+edgeTargetId+": "+nexmlEdge.getId()+" :: "+parentNexmlNode.getId());
			if (parentId.equals(edgeTargetId)) {
				grandParentNode = idToNexmlNodeMap.get(edgeSourceId);
			} else if (parentId.equals(edgeSourceId)) {
				grandParentNode = idToNexmlNodeMap.get(edgeTargetId);
				LOG.trace("swapped source/target");
			} else {
				throw new RuntimeException("bad edge");
			}
			if (grandParentNode == null) {
				LOG.warn("null grandParent");
			} else {
				parentNexmlNode.setParentNexmlNode(grandParentNode);
				NexmlNode childNexmlNode = nexmlEdge.getOtherNode(parentNexmlNode);
				if (childNexmlNode != null) {
					nexmlEdge.setSource(parentId);
					nexmlEdge.setTarget(childNexmlNode.getId());
					addChildrenAndDirectionality(childNexmlNode);
					parentNexmlNode.addChildNode(childNexmlNode);
					childNexmlNode.setParentNexmlNode(parentNexmlNode);
				} else {
					throw new RuntimeException("null child node");
				}
			}
		}
	}
	private NexmlEdge createAndAddNexmlEdge(NexmlTree nexmlTree, PixelEdge pixelEdge) {
		NexmlNode nexmlNode0 = pixelNodeToNexmlNodeMap.get(pixelEdge.getNodes().get(0));
		NexmlNode nexmlNode1 = pixelNodeToNexmlNodeMap.get(pixelEdge.getNodes().get(1));
		NexmlEdge nexmlEdge = new NexmlEdge(nexmlNode0, nexmlNode1);
		nexmlTree.appendChild(nexmlEdge);
		return nexmlEdge;
	}

	private NexmlNode addTerminalNodeAsOtu(PixelNode pixelNode) {
		NexmlNode nexmlNode = createAndAddNexmlNode(pixelNode);
		NexmlOtu otu = new NexmlOtu();
		nexmlOtus.appendChild(otu);
		String otuId = OTU+nexmlOtus.getChildCount();
		otu.setId(otuId);
		nexmlNode.setOtuRef(otuId);
		return nexmlNode;
	}

	private NexmlNode createAndAddNexmlNode(PixelNode pixelNode) {
		NexmlNode nexmlNode = new NexmlNode(nexmlTree);
		nexmlTree.appendChild(nexmlNode);
		String nodeId = "N"+nexmlTree.getId()+"."+nexmlTree.getChildCount();
		nexmlNode.setId(nodeId);
		nexmlNode.setLabel(nodeId); // could be overwritten later
		nexmlNode.setXY2(pixelNode.getReal2());
		return nexmlNode;
	}

	public void setRootPixelNode(PixelNode rootPixelNode) {
		this.rootPixelNode = rootPixelNode;
		LOG.trace("set rootPixelNode: "+rootPixelNode);
	}
}


text:
(function () {

	"use strict";

	var greeed;

	function goGreeed (grid, method, options) {

		var target = document.querySelector(grid);
		if (target !== null) {
			method.call(null, target, options);
		}
	}

	function add (grid, options) {

		greeed = new Greeed(grid, options);
		greeed.init();

	}

	function remove (grid) {

		greeed.destroy();

	}

	function Greeed (elem, options) {

		this.grid = elem;
		this.nbColumns = 0;
		this.childs = this.columns = this.options = [];

		this.rootFontSize = getComputedStyle(document.documentElement).getPropertyValue('font-size').replace('px','');

		for(var key in options){
			if(options.hasOwnProperty(key)){
				this.defaults[key] = options[key];
			}
		}
		this.options = this.defaults;

	}

	Greeed.prototype = {

		defaults: {
			elementColumn: 'li',
			elementColumnInner: 'ul',
			classColumn: 'Greeed-column',
			classColumnInner: 'Greeed-column-inner',
			classItem: 'Greeed-item',
			classFakeItem: 'Greeed-item--fake',
			layout: 'table',
			units: 'fluid'
		},

		init: function () {

			// Get elements
			this.childs = Array.prototype.slice.call(this.grid.children);
			// DOM columns
			this.columnsDOM = [];

			this.checkMQ();

			var scope = this;
			this.startCheckMQ = function(event) { scope.checkMQ(event); };

			window.addEventListener('resize', this.startCheckMQ, false);

			if ( this.options.afterInit ) {
				this.options.afterInit();
			}

		},

		destroy: function () {
			window.removeEventListener('resize', this.startCheckMQ, false);
		},

		createColumns: function ( greeedWidth ) {

			// create an Array of columns
			this.columns = new Array(this.nbColumns);
			for (var i = 0; i < this.nbColumns; i++) {
				this.columns[i] = [];
				// set height
				this.columns[i]._offsetHeight = 0;
			}

			for (var i = 0; i < this.childs.length; i++) {

				// find the smallest column to place the next child
				var columnsHeight = [];
				for (var j = 0; j < this.columns.length; j++) {
					var columnHeight = this.columns[j]._offsetHeight;
					columnsHeight.push(columnHeight);
				}
				var smallestColumnIndex = columnsHeight.indexOf(Math.min.apply(Math, columnsHeight));

				// add child to the smallest height column
				this.columns[smallestColumnIndex].push(this.childs[i]);

				// add an id (keep the old position)
				this.childs[i]._id = i;

				// update column height
				this.columns[smallestColumnIndex]._offsetHeight += this.childs[i].offsetHeight;

			}

			// find the max-height column
			var maxHeightColumn = 0;
			for (var i = 0; i < this.columns.length; i++) {

				var height = this.columns[i]._offsetHeight;

				if( height >= maxHeightColumn){
					maxHeightColumn = height;
				}

			}

			var grid = document.createDocumentFragment();

			for (var i = 0; i < this.columns.length; i++) {

				var column = document.createElement(this.options.elementColumn);
					column.className = this.options.classColumn;

					if (this.options.layout === 'table') {
						column.style.display = 'table-cell';
						column.style.verticalAlign = 'top';
					} else {
						column.style.styleFloat = column.style.cssFloat = 'left';
						column.style.display = 'block';
						if (this.options.units === 'fixed') {
							column.style.width = Math.floor( greeedWidth / this.nbColumns ) + 'px';
						} else {
							column.style.width = (100 / this.nbColumns ) + '%';
						}
					}

				if (this.options.elementColumnInner) {
					var columnElement = document.createElement(this.options.elementColumnInner);
						columnElement.className = this.options.classColumnInner;
				} else {
					var columnElement = column;
				}

				for (var j = 0; j < this.columns[i].length; j++) {
					this.columns[i][j].classList.add(this.options.classItem);
					columnElement.appendChild(this.columns[i][j]);
				}

				if( this.columns[i]._offsetHeight < maxHeightColumn && this.options.classFakeItem){

					var fake_elem = document.createElement(this.options.elementColumn);
						fake_elem.className = this.options.classItem + ' ' + this.options.classFakeItem;
						fake_elem.style.height = maxHeightColumn - this.columns[i]._offsetHeight + 'px';

						columnElement.appendChild(fake_elem);
				}

				if (this.options.elementColumnInner) {
					column.appendChild(columnElement);
				}

				// add the column to the DOM columns array
				this.columnsDOM[i] = column;

				grid.appendChild(column);

			}

			this.grid.innerHTML = '';
			this.grid.appendChild(grid);

			if (this.options.layout === 'table') {
				this.grid.style.display = 'table';
				this.grid.style.tableLayout = 'fixed';
			}

			if( this.options.afterLayout ){
				this.options.afterLayout();
			}

		},

		setColumnsWidth: function ( greeedWidth ) {

			// update width to match parent width
			var newColumnWidth = Math.floor( greeedWidth / this.nbColumns );
			var greeedWidthCalc = newColumnWidth * this.nbColumns;
			var pixelsLeft = greeedWidth - greeedWidthCalc;

			for (var i = 0; i < this.columnsDOM.length; i++) {
				var colWidth = (pixelsLeft > 0) ? newColumnWidth + 1 : newColumnWidth;
				pixelsLeft--;
				this.columnsDOM[i].style.width = colWidth + 'px';
			}

		},

		checkMQ: function (event) {

			var lastNbColumns = this.nbColumns;

			this.windowWidth = window.innerWidth;

			// for each breakpoints
			for (var i = 0; i < this.options.breakpoints.length; i++) {
				var point = this.options.breakpoints[i],
					size = point * this.rootFontSize;

				// set how many columns to create
				if( window.innerWidth < size ) {
					this.nbColumns = i + 1;
					break;
				} else {
					this.nbColumns = i + 2;
				}

			}

			if (this.options.units === 'fixed') {

				// Get the width of the greeed, every time
				var greeedWidth = Math.floor(getComputedStyle(this.grid).getPropertyValue('width').replace('px',''));

				// create columns
				this.createColumns( greeedWidth );

				// set columns width, every time
				this.setColumnsWidth( greeedWidth );

			} else {

				// create columns
				this.createColumns();

			}

		}
	};

	window.greeed = {
		bind: function (elem, options) {
			goGreeed(elem, add, options);
		},
		unbind: function (elem) {
			goGreeed(elem, remove);
		}
	};

})();


text:
// Copyright (c) 2013-2016 Jae-jun Kang
// See the file LICENSE for details.

using System;

namespace x2
{
    /// <summary>
    /// Represents a read-only collection in which each item of type T can be
    /// accessed with an integer index.
    /// </summary>
    public interface IIndexable<T>
    {
        /// <summary>
        /// Gets the length of this collection.
        /// </summary>
        int Length { get; }

        /// <summary>
        /// Gets the value of the item at the specified index.
        /// </summary>
        T this[int index] { get; }
    }

    /// <summary>
    /// Provides an offset-based indexer for the underlying IIndexable(T) object.
    /// </summary>
    public struct Capo<T> : IIndexable<T>
    {
        private IIndexable<T> indexable;
        private readonly int offset;

        /// <summary>
        /// Gets the effective length of this offset-based window.
        /// </summary>
        public int Length { get { return (indexable.Length - offset); } }

        /// <summary>
        /// Initializes a new Capo(T) value with the specified underlying
        /// IIndexable(T) object and the base offset.
        /// </summary>
        public Capo(IIndexable<T> indexable, int offset)
        {
            // Never throws.
            this.indexable = indexable;
            this.offset = offset;
        }

        /// <summary>
        /// Gets the value of the item at the actual index of (offset + index).
        /// </summary>
        public T this[int index]
        {
            get
            {
                int actualIndex = offset + index;
                // Just return a default value on out-of-range condition,
                // instead of throwing an exception.
                if (actualIndex < 0 || indexable.Length <= actualIndex)
                {
                    return default(T);
                }
                return indexable[actualIndex];
            }
        }
    }
}


text:
package main

import (
	"context"

	binaryauthorization "cloud.google.com/go/binaryauthorization/apiv1"
	binaryauthorizationpb "cloud.google.com/go/binaryauthorization/apiv1/binaryauthorizationpb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := binaryauthorization.NewBinauthzManagementClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &binaryauthorizationpb.GetAttestorRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/binaryauthorization/apiv1/binaryauthorizationpb#GetAttestorRequest.
	}
	resp, err := c.GetAttestor(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

// [END binaryauthorization_v1_generated_BinauthzManagementServiceV1_GetAttestor_sync]


text:
<?php

namespace PhpDisruptorTest;

use PhpDisruptor\MultiProducerSequencer;
use PhpDisruptor\WaitStrategy\BlockingWaitStrategy;

class MultiProducerSequencerTest extends \PHPUnit_Framework_TestCase
{
    public function testShouldOnlyAllowMessagesToBeAvailableIfSpecificallyPublished()
    {
        $waitingStrategy = new BlockingWaitStrategy();
        $publisher = new MultiProducerSequencer(1024, $waitingStrategy);
        $publisher->publish(3);
        $publisher->publish(5);

        $this->assertFalse($publisher->isAvailable(0));
        $this->assertFalse($publisher->isAvailable(1));
        $this->assertFalse($publisher->isAvailable(2));
        $this->assertTrue($publisher->isAvailable(3));
        $this->assertFalse($publisher->isAvailable(4));
        $this->assertTrue($publisher->isAvailable(5));
        $this->assertFalse($publisher->isAvailable(6));
    }
}


text:
/*
 * Do not modify this file. This file is generated from the opsworks-2013-02-18.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;

using Amazon.OpsWorks.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;

namespace Amazon.OpsWorks.Model.Internal.MarshallTransformations
{
    /// <summary>
    /// UpdateInstance Request Marshaller
    /// </summary>
    public class UpdateInstanceRequestMarshaller : IMarshaller<IRequest, UpdateInstanceRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
    {
        /// <summary>
        /// Marshaller the request object to the HTTP request.
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public IRequest Marshall(AmazonWebServiceRequest input)
        {
            return this.Marshall((UpdateInstanceRequest)input);
        }

        /// <summary>
        /// Marshaller the request object to the HTTP request.
        /// </summary>
        /// <param name="publicRequest"></param>
        /// <returns></returns>
        public IRequest Marshall(UpdateInstanceRequest publicRequest)
        {
            IRequest request = new DefaultRequest(publicRequest, "Amazon.OpsWorks");
            string target = "OpsWorks_20130218.UpdateInstance";
            request.Headers["X-Amz-Target"] = target;
            request.Headers["Content-Type"] = "application/x-amz-json-1.1";
            request.HttpMethod = "POST";

            string uriResourcePath = "/";
            request.ResourcePath = uriResourcePath;
            using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();
                var context = new JsonMarshallerContext(request, writer);
                if(publicRequest.IsSetAgentVersion())
                {
                    context.Writer.WritePropertyName("AgentVersion");
                    context.Writer.Write(publicRequest.AgentVersion);
                }

                if(publicRequest.IsSetAmiId())
                {
                    context.Writer.WritePropertyName("AmiId");
                    context.Writer.Write(publicRequest.AmiId);
                }

                if(publicRequest.IsSetArchitecture())
                {
                    context.Writer.WritePropertyName("Architecture");
                    context.Writer.Write(publicRequest.Architecture);
                }

                if(publicRequest.IsSetAutoScalingType())
                {
                    context.Writer.WritePropertyName("AutoScalingType");
                    context.Writer.Write(publicRequest.AutoScalingType);
                }

                if(publicRequest.IsSetEbsOptimized())
                {
                    context.Writer.WritePropertyName("EbsOptimized");
                    context.Writer.Write(publicRequest.EbsOptimized);
                }

                if(publicRequest.IsSetHostname())
                {
                    context.Writer.WritePropertyName("Hostname");
                    context.Writer.Write(publicRequest.Hostname);
                }

                if(publicRequest.IsSetInstallUpdatesOnBoot())
                {
                    context.Writer.WritePropertyName("InstallUpdatesOnBoot");
                    context.Writer.Write(publicRequest.InstallUpdatesOnBoot);
                }

                if(publicRequest.IsSetInstanceId())
                {
                    context.Writer.WritePropertyName("InstanceId");
                    context.Writer.Write(publicRequest.InstanceId);
                }

                if(publicRequest.IsSetInstanceType())
                {
                    context.Writer.WritePropertyName("InstanceType");
                    context.Writer.Write(publicRequest.InstanceType);
                }

                if(publicRequest.IsSetLayerIds())
                {
                    context.Writer.WritePropertyName("LayerIds");
                    context.Writer.WriteArrayStart();
                    foreach(var publicRequestLayerIdsListValue in publicRequest.LayerIds)
                    {
                            context.Writer.Write(publicRequestLayerIdsListValue);
                    }
                    context.Writer.WriteArrayEnd();
                }

                if(publicRequest.IsSetOs())
                {
                    context.Writer.WritePropertyName("Os");
                    context.Writer.Write(publicRequest.Os);
                }

                if(publicRequest.IsSetSshKeyName())
                {
                    context.Writer.WritePropertyName("SshKeyName");
                    context.Writer.Write(publicRequest.SshKeyName);
                }

                writer.WriteObjectEnd();
                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }

            return request;
        }

    }
}


text:
require 'active_support'
event_types = EventType.create([{event_type: 't_only'},{event_type: 't_with'},{event_type: 'y_only'},{event_type: 'y_with'}])
events = Event.create([{event_name: '食費'},{event_name: 'ガス'},{event_name: '電気'},{event_name: '水道'},{event_name: '衣類'},{event_name: 'その他'}])

prev_last_month = Time.now.prev_month.prev_month

ClosedAmount.create(t_amount: 0, y_amount: 0, monthly_payment: 0, carried_amount: 0, closed_date: prev_last_month.end_of_month)


text:
{-# LANGUAGE
    FlexibleInstances
  , MultiParamTypeClasses #-}
module Control.Monad.FD.Internal.State
       ( StateT
       , evalStateT
       , get
       , put
       , modify
       , gets
       ) where

import Control.Applicative
import Control.Monad
import Control.Monad.IO.Class (MonadIO (liftIO))
import Control.Monad.Logic.Class
import Control.Monad.Trans.Class (MonadTrans (lift))

newtype StateT s m a = StateT { runStateT :: s -> m (Pair a s) }

data Pair a b = a :*: !b

evalStateT :: Monad m => StateT s m a -> s -> m a
evalStateT m s = do
  a :*: _ <- runStateT m s
  return a

state :: Monad m => (s -> Pair a s) -> StateT s m a
state f = StateT $ \ s -> return $! f s

instance Functor m => Functor (StateT s m) where
  fmap f m = StateT $ \ s ->
    fmap (\ (a :*: s') -> f a :*: s') $ runStateT m s

instance (Functor m, Monad m) => Applicative (StateT s m) where
  pure = return
  (<*>) = ap

instance (Functor m, MonadPlus m) => Alternative (StateT s m) where
  empty = mzero
  (<|>) = mplus

instance Monad m => Monad (StateT s m) where
  return a = state $ \ s -> a :*: s
  m >>= k = StateT $ \ s -> do
    a :*: s' <- runStateT m s
    runStateT (k a) s'
  fail str = StateT $ \ _ -> fail str

instance MonadPlus m => MonadPlus (StateT s m) where
  mzero = StateT $ \ _ -> mzero
  m `mplus` n = StateT $ \ s -> runStateT m s `mplus` runStateT n s

instance MonadTrans (StateT s) where
  lift m = StateT $ \ s -> do
    a <- m
    return $ a :*: s

instance MonadIO m => MonadIO (StateT s m) where
  liftIO = lift . liftIO

instance MonadLogic m => MonadLogic (StateT s m) where
  msplit m = StateT $ \ s -> do
    r <- msplit $ runStateT m s
    case r of
      Nothing -> return $ Nothing :*: s
      Just (a :*: s', m') -> return $ Just (a, StateT (\ _ -> m')) :*: s'

get :: Monad m => StateT s m s
get = state $ \ s -> s :*: s

put :: Monad m => s -> StateT s m ()
put s = s `seq` state $ \ _ -> () :*: s

modify :: Monad m => (s -> s) -> StateT s m ()
modify f = state $ \ s -> () :*: f s

gets :: Monad m => (s -> a) -> StateT s m a
gets f = state $ \ s -> f s :*: s


text:
#include "config/stm32plus.h"
#include "config/timer.h"

using namespace stm32plus;

/**
 * Timer demonstration: Output a 1Hz toggle on/off signal on PA0.
 *
 * To achieve the alternating 1Hz signal on PA0 (TIM2_CH1) we first
 * set up Timer2 to tick at 10kHz with its auto-reload register set to 9999.
 * It will take 2 seconds for the timer to tick up to 9999 at which point it
 * will reset back to zero.
 *
 * We configure the channel 1 compare value to be 9999 with an action of
 * "toggle" and we enable GPIO output for channel 1 on its default port of PA0.
 *
 * To see the output, connect PA0 to a LED. e.g. on the F0 and F1 VL discovery
 * boards you can connect PA0 to PC8.
 *
 *
 * Compatible MCU:
 *   STM32F0
 *   STM32F1
 *   STM32F4
 *
 * Tested on devices:
 *   STM32F051R8T6
 *   STM32F103ZET6
 *   STM32F407VGT6
 */

class TimerGpioOutTest {

  public:

    void run() {

      /*
       * Initialise timer2 running from the internal APB2 clock with channel-1 and GPIO output features.
       * The GPIO output feature is itself configured with a channel-1 output feature.
       */

      Timer2<
        Timer2InternalClockFeature,       // the timer clock source is HCLK/2
        TimerChannel1Feature,             // we're going to use channel 1
        Timer2GpioFeature<                // we want to output something to GPIO
          TIMER_REMAP_NONE,               // the GPIO output will not be remapped
          TIM2_CH1_OUT                    // we will output channel 1 to GPIO
        >
      > timer;

      /*
       * Set an up-timer up to tick at 1000Hz with an auto-reload value of 9999
       * The timer will count from 0 to 9999 inclusive then reset back to 0.
       * It will take exactly 1 second to do this.
       *
       * Note that the lowest frequency on the F1 that you can set is 1098 for a
       * 72Mhz timer clock source. This is because the maximum prescaler value is
       * 65536 (72Mhz/65536 = 1098Hz).
       */

      timer.setTimeBaseByFrequency(10000,9999);

      /*
       * Initialise the channel 1 output compare value to 9999 with the default
       * action of toggle.
       */

      timer.initCompare(9999);

      /*
       * Start the timer. Each time it ticks up to 9999 (which will take 1 second)
       * the channel 1 compare value will be triggered and the TIM2_CH1 GPIO pin on PA0
       * will be toggled. Since we've hooked this up to a LED we should see it flashing
       * at 1Hz.
       */

      timer.enablePeripheral();

      /*
       * It's all running automatically now
       */

      for(;;);
    }
};

/*
 * Main entry point
 */

int main() {

  TimerGpioOutTest test;
  test.run();

  // not reached
  return 0;
}


text:
namespace MaxMelcher.QueryLogger.Monitor
{
    /// <copyright>
    /// This class is copied from the SharePoint LogViewer: http://sharepointlogviewer.codeplex.com/SourceControl/latest#SharePointLogViewer/SPUtility.cs
    /// Copyright (c) 2010 Overroot Inc.
    /// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
    /// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
    /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    /// </copyright>
    public enum TraceSeverity
    {
        Verbose,
        Information,
        Warning,
        Medium,
        High,
        CriticalEvent,
        Exception,
        Unexpected
    }
}


text:
				{{ if categories_list }}
		          {{ categories_url_list }}
		        {{ endif }}

{{ title }}

	        0 Comments
			{{ if date }}

<time pubdate datetime="{{ datestamp format="Y-m-d" }}">Posted on {{ date }}</time> by
			 {{ author }}
	        {{ endif }}

			{{ contentSummary }}
			...Continue Reading


text:
package org.opensingular.lib.commons.pdf;

import com.google.common.collect.Lists;
import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

import static org.junit.Assert.*;

/**
 * @author Daniel C. Bordin on 22/01/2017.
 */
public class TestPDFUtil {

    private static final String SIMPLE_EXAMPLE_HTML = "Hello Word<htmll>";

    @Before
    public void setupEnviroment() {
        Assume.assumeTrue(!"false".equals(System.getProperty("singular.test.native.enabled")));
        PDFUtil.clearHome();
        File dir;
        if (PDFUtil.isWindows()) {
            dir = new File("src\\test\\wkhtmltopdf\\windows");
        } else if (PDFUtil.isMac()){
            dir = new File("src/test/wkhtmltopdf/mac");
        } else {
            dir = new File("src/test/wkhtmltopdf/unix");
        }
        System.setProperty(PDFUtil.SINGULAR_WKHTML2PDF_HOME, dir.getAbsolutePath());
    }

    @Test
    public void testHomeDirNotConfigured() {
        PDFUtil.clearHome();
        System.clearProperty(PDFUtil.SINGULAR_WKHTML2PDF_HOME);
        try {
            PDFUtil.getInstance().convertHTML2PDF(SIMPLE_EXAMPLE_HTML);
            fail();
        } catch (SingularPDFException e) {
            assertException(e, "property 'singular.wkhtml2pdf.home' not set");
        }
    }

    @Test
    public void testWrongHomeDirConfigured() {
        try {
            PDFUtil.clearHome();
            System.setProperty(PDFUtil.SINGULAR_WKHTML2PDF_HOME, File.separator + "xpto");
            File result = PDFUtil.getInstance().convertHTML2PDF(SIMPLE_EXAMPLE_HTML);
            System.out.println(result.getAbsolutePath());
            fail();
        } catch (SingularPDFException e) {
            assertException(e, "configured for a directory that nos exists");
        }
    }

    @Test
    public void testSimpleToPdf() {
        File result = PDFUtil.getInstance().convertHTML2PDF(SIMPLE_EXAMPLE_HTML);
        assertPDF(result, 1);
    }

    @Test
    public void testSimpleToPng() {
        File result = PDFUtil.getInstance().convertHTML2PNG(SIMPLE_EXAMPLE_HTML);
        assertFile(result, ".png");
    }

    @Test
    public void testMergeSimple() throws FileNotFoundException {
        File pg1 = PDFUtil.getInstance().convertHTML2PDF(SIMPLE_EXAMPLE_HTML);
        File pg2 = PDFUtil.getInstance().convertHTML2PDF(SIMPLE_EXAMPLE_HTML);
        File pg3 = PDFUtil.getInstance().convertHTML2PDF(SIMPLE_EXAMPLE_HTML);

        File result = PDFUtil.getInstance().merge(
                Lists.newArrayList(new FileInputStream(pg1), new FileInputStream(pg2), new FileInputStream(pg3)));
        assertPDF(result, 3);
    }

    private void assertPDF(File file, int expectedPages) {
        assertPDF(file, expectedPages, true);
    }

    private void assertPDF(File file, int expectedPages, boolean delete) {
        assertFile(file, ".pdf");
        assertEquals(expectedPages, countPages(file));
        if(delete) {
            if(!file.delete()) {
                fail();
            }
        }
    }

    private int countPages(File file) {
        try (RandomAccessBufferedFileInputStream in = new RandomAccessBufferedFileInputStream(file)) {
            PDFParser parser = new PDFParser(in);
            parser.parse();
            PDDocument doc = parser.getPDDocument();
            int pages = doc.getNumberOfPages();
            doc.close();
            return pages;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void assertFile(File result, String expectedExtension) {
        assertTrue(result.exists());
        assertTrue(result.length() > 0);
        assertTrue(result.getName().endsWith(expectedExtension));
    }

    private void assertException(Exception e, String expectedContent) {
        if (!e.getMessage().contains(expectedContent)) {
            assertEquals(expectedContent, e.getMessage());
        }
    }

    @Test
    public void createPDFSepartingHeaderBodyAndFooterTest(){
        String header = "<title>Test</title>";
        String body = "
Some string to fill
";
        String footer = "";

        PDFUtil pdfUtil = PDFUtil.getInstance();
        pdfUtil.setPageOrientation(PDFUtil.PageOrientation.PAGE_LANDSCAPE);
        pdfUtil.setPageSize(PDFUtil.PageSize.PAGE_A4);
        pdfUtil.setJavascriptDelay(0);

        File instance = pdfUtil.convertHTML2PDF(header, body, footer, new ArrayList<>());

        Assert.assertTrue(instance.exists());
        instance.delete();
    }
}


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

namespace InventoryManager.Services.Contracts
{
    public interface IClothesService
    {
        void AddNewClothes(Clothes clothes);

        IQueryable<Clothes> GetAllClothes();

        Clothes GetClothesById(Guid id);

        IQueryable<Clothes> GetClothesByName(string name);

        void UpdateClothesInformation(Clothes clothesToUpdate);

        void DeleteClothes(Guid id);
    }
}


text:
<query id="getNotiEndpoint" action="select">
    <tables>
        <table name="noti_endpoint" />
    </tables>
    <columns>
        <column name="*" />
    </columns>
    <conditions>
        <condition operation="equal" column="endpoint_srl" var="endpoint_srl" notnull="notnull" />
    </conditions>
</query>


text:
package api.protocol

import spray.json.DefaultJsonProtocol
import api.model.{ FileUploaded, NodeDetails, Status }

trait ApiProtocol extends DefaultJsonProtocol {
  implicit val statusFormat = jsonFormat4(Status.apply)
  implicit val nodeDetailsFormat = jsonFormat4(NodeDetails.apply)
  implicit val fileUploadedFormat = jsonFormat3(FileUploaded.apply)
}


text:
			<img src="<?php print $this->request->getThemeUrlPath(); ?>/graphics/footer-logo.jpg" width="113px" height="24px" alt="New York State Education Department" />

				The New York State Archives is part of the Office of Cultural Education, an office
				of the New York State Education Department.

About Us

News

Directions

Contact Us

Site Map

New York Archives Magazine

Archives Partnership Trust

New York State Historical Records

Advisory Board

Online Catalog

Office of Cultural Education

New York State Education Department

New York State

Privacy Policy

Terms of Use

<?php print $this->request->config->get('page_footer_text'); ?>

<?php
print TooltipManager::getLoadHTML();
?>


text:
using System;

namespace pjank.BossaAPI
{
	/// <summary>
	/// Interfejs pozwalający na lepszą separację podstawowych elementów biblioteki i ułatwiający np. pisanie testów.
	/// Domyślna implementacja w klasie "BossaApi" - używanej też wewnętrznie przez główną klasę biblioteki: "Bossa".
	/// </summary>
	public interface IBossaApi
	{
		bool Connected { get; }

		IBosClient Connection { get; }

		BosAccounts Accounts { get; }

		BosInstruments Instruments { get; }

		event EventHandler OnUpdate;

		void Connect(IBosClient client);

		void Disconnect();

		void Clear();
	}
}


text:
package ${package}.gwt.client;

import com.google.gwt.core.client.EntryPoint;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Application entry point
 *
 */

public class Application implements EntryPoint
{

    static final String JSON_URL = "/hello/";

    private VerticalPanel vp = new VerticalPanel();

    public void onModuleLoad()
    {
        final TextBox tb = new TextBox();
        tb.setTitle("Enter your username");
        tb.addKeyPressHandler(new KeyPressHandler() {
            public void onKeyPress(KeyPressEvent event)
            {
                if(event.getCharCode()==13)
                {
                    sendRequest(tb.getText());
                }
            }
        });
        Button button = new Button("Send", new ClickHandler() {
            public void onClick(ClickEvent event)
            {
                sendRequest(tb.getText());
            }
        });
        FlowPanel fp = new FlowPanel();
        fp.add(tb);
        fp.add(button);

        vp.setSpacing(5);
        vp.add(fp);
        RootPanel.get().add(vp);
    }

    void sendRequest(String name)
    {
        Greet greet = Greet.create();
        greet.setName(name);
        greet.setStatus(Greet.Status.NEW);
        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, JSON_URL);
        try
        {
            builder.setHeader("Content-Type", "application/json");
            builder.sendRequest(Greet.stringify(greet), new RequestCallback() {
                public void onError(Request request, Throwable exception)
                {
                    displayError("Couldn't retrieve JSON");
                }
                public void onResponseReceived(Request request, Response response)
                {
                    if (response.getStatusCode() == 200)
                        showGreet(Greet.parse(response.getText()));
                    else
                        displayError("Couldn't retrieve JSON");
                }
            });
        }
        catch (RequestException e)
        {
            displayError("Couldn't retrieve JSON");
        }
    }

    void showGreet(Greet greet)
    {
        vp.add(new Label("Greet #" + greet.getId() + ": " + greet.getMessage() + " | " + greet.getStatus().getNumber()));
    }

    static void displayError(String error)
    {
        Window.alert(error);
    }

}


text:
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.marekasf.troughput;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.concurrent.Semaphore;
import java.util.stream.IntStream;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
import org.marekasf.troughput.histogram.AdaptiveHistogram;

public class XYHistogramChart extends ApplicationFrame
{
	private static final long serialVersionUID = 1052668809088392899L;

	public static void display(final AdaptiveHistogram h, final String title)
	{

		final XYHistogramChart demo = new XYHistogramChart(h, title);
		demo.pack();
		RefineryUtilities.centerFrameOnScreen(demo);
		demo.setVisible(true);
		final Semaphore semaphore = new Semaphore(0);
		demo.addWindowListener(new WindowAdapter()
		{
			@Override
			public void windowClosing(final WindowEvent we)
			{
				semaphore.release();
			}
		});
		try
		{
			semaphore.acquire();
		}
		catch (final InterruptedException e)
		{
			//
		}
	}

	public XYHistogramChart(final AdaptiveHistogram h, final String title)
	{

		super(title);
		final XYSeries series = new XYSeries(title);

		IntStream.rangeClosed(0, 100).forEach(i -> series.add(i, h.getValueForPercentile(i)));

		final XYSeriesCollection data = new XYSeriesCollection(series);
		final JFreeChart chart = ChartFactory.createXYLineChart("XY Histogram Chart " + title, "X", "Y", data,
				PlotOrientation.VERTICAL, true, true, false);

		final ChartPanel chartPanel = new ChartPanel(chart);
		chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
		setContentPane(chartPanel);
	}
}


text:
/**
* Chess figures test package.
*
* @author Karetko Victor (vitoss@inbox.ru)
* @version 1.0
* @since 10.11.2016
*/
package vkaretko;


text:
/**
 * doitgen.h: This file is part of the PolyBench/C 3.2 test suite.
 *
 *
 * Contact: Louis-Noel Pouchet <pouchet@cse.ohio-state.edu>
 * Web address: http://polybench.sourceforge.net
 */
#ifndef DOITGEN_H
# define DOITGEN_H

/* Default to STANDARD_DATASET. */
# if !defined(MINI_DATASET) && !defined(SMALL_DATASET) && !defined(LARGE_DATASET) && !defined(EXTRALARGE_DATASET)
#  define STANDARD_DATASET
# endif

/* Do not define anything if the user manually defines the size. */
# if !defined(NQ) && !defined(NR) && !defined(NP)
/* Define the possible dataset sizes. */
#  ifdef MINI_DATASET
#   define NQ 10
#   define NR 10
#   define NP 10
#  endif

#  ifdef SMALL_DATASET
#   define NQ 32
#   define NR 32
#   define NP 32
#  endif

#  ifdef STANDARD_DATASET /* Default if unspecified. */
#   define NQ 128
#   define NR 128
#   define NP 128
#  endif

#  ifdef LARGE_DATASET
#   define NQ 256
#   define NR 256
#   define NP 256
#  endif

#  ifdef EXTRALARGE_DATASET
#   define NQ 1000
#   define NR 1000
#   define NP 1000
#  endif
# endif /* !N */

# define _PB_NQ POLYBENCH_LOOP_BOUND(NQ,nq)
# define _PB_NR POLYBENCH_LOOP_BOUND(NR,nr)
# define _PB_NP POLYBENCH_LOOP_BOUND(NP,np)

# ifndef DATA_TYPE
#  define DATA_TYPE double
#  define DATA_PRINTF_MODIFIER "%0.2lf "
# endif

#endif /* !DOITGEN */


text:
require 'spec_helper'

describe DigitalObject, :type => :model do

  $digital_object_path = aspace_sample_paths[:digital_object]
  $digital_object_response = $session.get($digital_object_path, resolve: ['linked_agents','subjects'])
  $digital_object_data = JSON.parse($digital_object_response.body)

  it "creates digital object and linked subjects/agents from api" do
    DigitalObject.create_from_api($digital_object_path, $options)
    expect(DigitalObject.where(uri: $digital_object_path)).to exist
    d = DigitalObject.find_by_uri($digital_object_path)
    total_subjects = $digital_object_data['subjects'].length
    total_agents = $digital_object_data['linked_agents'].length
    expect(d.agents.length).to eq(total_agents)
    expect(d.subjects.length).to eq(total_subjects)
  end

  it "adds ArchivesSpace file_versions to unit-data as :files" do
    d = DigitalObject.create_from_api($digital_object_path, $options)
    data = d.presenter_data
    expect(data[:files].length).to eq($digital_object_data['file_versions'].length)
  end
end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace CodeIt.Models
{
    //Model used for the Creating View of the Comment
    public class CommentViewModel
    {
        [Key]
        public int Id { get; set; }

        [Required]
        [Display(Name = "Code Comments")]
        [AllowHtml]
        public string Content { get; set; }

        public int CodeId { get; set; }

        public string AuthorId { get; set; }

        public virtual User Author { get; set; }

        public List<string> Code { get; set; }

        public DateTime TimeCreated { get; set; }
    }
}


text:
using System;

namespace dstemplate
{
    public class Note
    {
        public string Filename { get; set; }
        public string Text { get; set; }
        public DateTime Date { get; set; }

        public bool CanDelete
        {
            get { return !string.IsNullOrEmpty(Filename); }
        }
    }
}