text:
using System;
using Platibus.Config;
using System.Linq;
using System.Threading.Tasks;
using Xunit;

namespace Platibus.UnitTests.Config
{
    [Trait("Category", "UnitTests")]
    public class PlatibusConfigurationManagerTests
    {
        protected PlatibusConfiguration Configuration;

        [Fact]
        public async Task HandlingRulesAreAdded()
        {
            GivenEmptyConfiguration();
            await WhenProcessingConfigurationHooks();
            AssertHandlingRulesAreAdded();
        }

        protected void GivenEmptyConfiguration()
        {
            Configuration = new PlatibusConfiguration();
        }

        protected Task WhenProcessingConfigurationHooks()
        {
            var configurationManager = new PlatibusConfigurationManager();
#pragma warning disable 612
            return configurationManager.FindAndProcessConfigurationHooks(Configuration);
#pragma warning restore 612
        }

        protected void AssertHandlingRulesAreAdded()
        {
            var handlingRules = Configuration.HandlingRules.ToList();
            Assert.Single(handlingRules);
            Assert.IsType<MessageNamePatternSpecification>(handlingRules[0].Specification);

            var namePatternSpec = (MessageNamePatternSpecification)handlingRules[0].Specification;
            Assert.Equal(".*(?i)example.*", namePatternSpec.NameRegex.ToString());
            Assert.IsType<MessageHandlerStub>(handlingRules[0].MessageHandler);
        }

        [Obsolete]
        public class TestConfigurationHook : IConfigurationHook
        {
            public void Configure(PlatibusConfiguration configuration)
            {
                configuration.AddHandlingRule(".*(?i)example.*", new MessageHandlerStub());
            }
        }
    }
}


text:
class CreateBlogArticles < ActiveRecord::Migration
    def change
        create_table :blog_articles do |t|
            t.string :title, null: false
            t.string :tagline
            t.string :slug, null: false
            t.references :blog, index: true, null: false, references: :apps
            t.text :body, null: false

            t.timestamps null: false
        end

        add_index :blog_articles, :slug, unique: true
        add_foreign_key :blog_articles, :apps, column: :blog_id
    end
end

redpajama_set_name: RedPajamaGithub


text:
/*
 * bootstrap-tagsinput v0.3.9 by Tim Schlechter
 *
 */
!function (a) {
    "use strict";
    function b(b, c) {
        this.itemsArray = [], this.$element = a(b), this.$element.hide(), this.isSelect = "SELECT" === b.tagName, this.multiple = this.isSelect && b.hasAttribute("multiple"), this.objectItems = c && c.itemValue, this.placeholderText = b.hasAttribute("placeholder") ? this.$element.attr("placeholder") : "", this.inputSize = Math.max(1, this.placeholderText.length), this.$container = a('

'), this.$input = a('<input size="' + this.inputSize + '" type="text" placeholder="' + this.placeholderText + '"/>').appendTo(this.$container), this.$element.after(this.$container), this.build(c)
    }

    function c(a, b) {
        if ("function" != typeof a[b]) {
            var c = a[b];
            a[b] = function (a) {
                return a[c]
            }
        }
    }

    function d(a, b) {
        if ("function" != typeof a[b]) {
            var c = a[b];
            a[b] = function () {
                return c
            }
        }
    }

    function e(a) {
        return a ? h.text(a).html() : ""
    }

    function f(a) {
        var b = 0;
        if (document.selection) {
            a.focus();
            var c = document.selection.createRange();
            c.moveStart("character", -a.value.length), b = c.text.length
        } else(a.selectionStart || "0" == a.selectionStart) && (b = a.selectionStart);
        return b
    }

    var g = {
        tagClass: function () {
            return "label label-info"
        }, itemValue: function (a) {
            return a ? a.toString() : a
        }, itemText: function (a) {
            return this.itemValue(a)
        }, freeInput: !0, maxTags: void 0, confirmKeys: [13], onTagExists: function (a, b) {
            b.hide().fadeIn()
        }
    };
    b.prototype = {
        constructor: b, add: function (b, c) {
            var d = this;
            if (!(d.options.maxTags && d.itemsArray.length >= d.options.maxTags || b !== !1 && !b)) {
                if ("object" == typeof b && !d.objectItems)throw"Can't add objects when itemValue option is not set";
                if (!b.toString().match(/^\s*$/)) {
                    if (d.isSelect && !d.multiple && d.itemsArray.length > 0 && d.remove(d.itemsArray[0]), "string" == typeof b && "INPUT" === this.$element[0].tagName) {
                        var f = b.split(",");
                        if (f.length > 1) {
                            for (var g = 0; g < f.length; g++)this.add(f[g], !0);
                            return c || d.pushVal(), void 0
                        }
                    }
                    var h = d.options.itemValue(b), i = d.options.itemText(b), j = d.options.tagClass(b), k = a.grep(d.itemsArray, function (a) {
                        return d.options.itemValue(a) === h
                    })[0];
                    if (k) {
                        if (d.options.onTagExists) {
                            var l = a(".tag", d.$container).filter(function () {
                                return a(this).data("item") === k
                            });
                            d.options.onTagExists(b, l)
                        }
                    } else {
                        d.itemsArray.push(b);
                        var m = a('' + e(i) + '');
                        if (m.data("item", b), d.findInputWrapper().before(m), m.after(" "), d.isSelect && !a('option[value="' + escape(h) + '"]', d.$element)[0]) {
                            var n = a("<option selected>" + e(i) + "</option>");
                            n.data("item", b), n.attr("value", h), d.$element.append(n)
                        }
                        c || d.pushVal(), d.options.maxTags === d.itemsArray.length && d.$container.addClass("bootstrap-tagsinput-max"), d.$element.trigger(a.Event("itemAdded", {item: b}))
                    }
                }
            }
        }, remove: function (b, c) {
            var d = this;
            d.objectItems && (b = "object" == typeof b ? a.grep(d.itemsArray, function (a) {
                return d.options.itemValue(a) == d.options.itemValue(b)
            })[0] : a.grep(d.itemsArray, function (a) {
                return d.options.itemValue(a) == b
            })[0]), b && (a(".tag", d.$container).filter(function () {
                return a(this).data("item") === b
            }).remove(), a("option", d.$element).filter(function () {
                return a(this).data("item") === b
            }).remove(), d.itemsArray.splice(a.inArray(b, d.itemsArray), 1)), c || d.pushVal(), d.options.maxTags > d.itemsArray.length && d.$container.removeClass("bootstrap-tagsinput-max"), d.$element.trigger(a.Event("itemRemoved", {item: b}))
        }, removeAll: function () {
            var b = this;
            for (a(".tag", b.$container).remove(), a("option", b.$element).remove(); b.itemsArray.length > 0;)b.itemsArray.pop();
            b.pushVal(), b.options.maxTags && !this.isEnabled() && this.enable()
        }, refresh: function () {
            var b = this;
            a(".tag", b.$container).each(function () {
                var c = a(this), d = c.data("item"), f = b.options.itemValue(d), g = b.options.itemText(d), h = b.options.tagClass(d);
                if (c.attr("class", null), c.addClass("tag " + e(h)), c.contents().filter(function () {
                        return 3 == this.nodeType
                    })[0].nodeValue = e(g), b.isSelect) {
                    var i = a("option", b.$element).filter(function () {
                        return a(this).data("item") === d
                    });
                    i.attr("value", f)
                }
            })
        }, items: function () {
            return this.itemsArray
        }, pushVal: function () {
            var b = this, c = a.map(b.items(), function (a) {
                return b.options.itemValue(a).toString()
            });
            b.$element.val(c, !0).trigger("change")
        }, build: function (b) {
            var e = this;
            e.options = a.extend({}, g, b);
            var h = e.options.typeahead || {};
            e.objectItems && (e.options.freeInput = !1), c(e.options, "itemValue"), c(e.options, "itemText"), c(e.options, "tagClass"), e.options.source && (h.source = e.options.source), h.source && a.fn.typeahead && (d(h, "source"), e.$input.typeahead({
                source: function (b, c) {
                    function d(a) {
                        for (var b = [], d = 0; d < a.length; d++) {
                            var g = e.options.itemText(a[d]);
                            f[g] = a[d], b.push(g)
                        }
                        c(b)
                    }

                    this.map = {};
                    var f = this.map, g = h.source(b);
                    a.isFunction(g.success) ? g.success(d) : a.when(g).then(d)
                }, updater: function (a) {
                    e.add(this.map[a])
                }, matcher: function (a) {
                    return -1 !== a.toLowerCase().indexOf(this.query.trim().toLowerCase())
                }, sorter: function (a) {
                    return a.sort()
                }, highlighter: function (a) {
                    var b = new RegExp("(" + this.query + ")", "gi");
                    return a.replace(b, "$1")
                }
            })), e.$container.on("click", a.proxy(function () {
                e.$input.focus()
            }, e)), e.$container.on("keydown", "input", a.proxy(function (b) {
                var c = a(b.target), d = e.findInputWrapper();
                switch (b.which) {
                    case 8:
                        if (0 === f(c[0])) {
                            var g = d.prev();
                            g && e.remove(g.data("item"))
                        }
                        break;
                    case 46:
                        if (0 === f(c[0])) {
                            var h = d.next();
                            h && e.remove(h.data("item"))
                        }
                        break;
                    case 37:
                        var i = d.prev();
                        0 === c.val().length && i[0] && (i.before(d), c.focus());
                        break;
                    case 39:
                        var j = d.next();
                        0 === c.val().length && j[0] && (j.after(d), c.focus());
                        break;
                    default:
                        e.options.freeInput && a.inArray(b.which, e.options.confirmKeys) >= 0 && (e.add(c.val()), c.val(""), b.preventDefault())
                }
                c.attr("size", Math.max(this.inputSize, c.val().length))
            }, e)), e.$container.on("click", "[data-role=remove]", a.proxy(function (b) {
                e.remove(a(b.target).closest(".tag").data("item"))
            }, e)), e.options.itemValue === g.itemValue && ("INPUT" === e.$element[0].tagName ? e.add(e.$element.val()) : a("option", e.$element).each(function () {
                e.add(a(this).attr("value"), !0)
            }))
        }, destroy: function () {
            var a = this;
            a.$container.off("keypress", "input"), a.$container.off("click", "[role=remove]"), a.$container.remove(), a.$element.removeData("tagsinput"), a.$element.show()
        }, focus: function () {
            this.$input.focus()
        }, input: function () {
            return this.$input
        }, findInputWrapper: function () {
            for (var b = this.$input[0], c = this.$container[0]; b && b.parentNode !== c;)b = b.parentNode;
            return a(b)
        }
    }, a.fn.tagsinput = function (c, d) {
        var e = [];
        return this.each(function () {
            var f = a(this).data("tagsinput");
            if (f) {
                var g = f[c](d);
                void 0 !== g && e.push(g)
            } else f = new b(this, c), a(this).data("tagsinput", f), e.push(f), "SELECT" === this.tagName && a("option", a(this)).attr("selected", "selected"), a(this).val(a(this).val())
        }), "string" == typeof c ? e.length > 1 ? e : e[0] : e
    }, a.fn.tagsinput.Constructor = b;
    var h = a("
");
    a(function () {
        a("input[data-role=tagsinput], select[multiple][data-role=tagsinput]").tagsinput()
    })
}(window.jQuery);
/*
 //@ sourceMappingURL=bootstrap-tagsinput.min.js.map
 */


text:
windows_grabber
===============


text:
/* Created by "go tool cgo" - DO NOT EDIT. */

/* package command-line-arguments */

/* Start of preamble from import "C" comments.  */

/* End of preamble from import "C" comments.  */

/* Start of boilerplate cgo prologue.  */

#ifndef GO_CGO_PROLOGUE_H
#define GO_CGO_PROLOGUE_H

typedef signed char GoInt8;
typedef unsigned char GoUint8;
typedef short GoInt16;
typedef unsigned short GoUint16;
typedef int GoInt32;
typedef unsigned int GoUint32;
typedef long long GoInt64;
typedef unsigned long long GoUint64;
typedef GoInt32 GoInt;
typedef GoUint32 GoUint;
typedef __SIZE_TYPE__ GoUintptr;
typedef float GoFloat32;
typedef double GoFloat64;
typedef float _Complex GoComplex64;
typedef double _Complex GoComplex128;

/*
  static assertion to make sure the file is being used on architecture
  at least with matching size of GoInt.
*/

typedef struct { const char *p; GoInt n; } GoString;
typedef void *GoMap;
typedef void *GoChan;
typedef struct { void *t; void *v; } GoInterface;
typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;

#endif

/* End of boilerplate cgo prologue.  */

#ifdef __cplusplus
extern "C" {
#endif

extern void Send(char* p0, GoUint8 p1);

extern char* Receive();

#ifdef __cplusplus
}
#endif


text:
require 'mock_redis'
require 'sidekiq/redis_connection'

RSpec.configure do |config|
  config.before do
    redis = MockRedis.new

    connection = {
      location: '127.0.0.1:1234',
      db: '0'
    }

    redis.define_singleton_method(:connection) { connection }

    allow(Sidekiq::RedisConnection).to receive(:create).and_return(ConnectionPool.new({}) {
      redis
    })
  end
end


text:
namespace ORSL {

extern void init();

extern bool reserve(int device);
extern bool try_reserve(int device);
extern void release(int device);

} // namespace ORSL

#endif // OFFLOAD_ORSL_H_INCLUDED


text:
package model

import (
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/utils"

	"strings"
)

// Request Object
type CreatePostPaidServersRequest struct {
	Body *CreatePostPaidServersRequestBody `json:"body,omitempty"`
}

func (o CreatePostPaidServersRequest) String() string {
	data, err := utils.Marshal(o)
	if err != nil {
		return "CreatePostPaidServersRequest struct{}"
	}

	return strings.Join([]string{"CreatePostPaidServersRequest", string(data)}, " ")
}


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

namespace BuildTools.Tests
{
    public class AssemblyInfoBuilderTests
    {
        [Fact]
        public void Ctor_WithNullProvider_ThrowsArgumentNull()
        {
            Assert.Throws<ArgumentNullException>(() => new AssemblyInfoBuilder(null));
        }

        [Fact]
        public void Ctor_WithNonNullProvider_DoesNotThrow()
        {
            new AssemblyInfoBuilder(new CSharpCodeProvider());
        }

        [Fact]
        public void WithCLSCompliant_WithTrue_BuildsCorrectAssemblyInfo()
        {
            var builder = new AssemblyInfoBuilder(new CSharpCodeProvider());
            builder.WithCLSCompliant(true);
            var assemblyInfo = builder.Build();

            Assert.Contains("[assembly: System.CLSCompliantAttribute(true)]", assemblyInfo);
        }

        [Fact]
        public void WithCLSCompliant_WithFalse_BuildsCorrectAssemblyInfo()
        {
            var builder = new AssemblyInfoBuilder(new CSharpCodeProvider());
            builder.WithCLSCompliant(false);
            var assemblyInfo = builder.Build();

            Assert.Contains("[assembly: System.CLSCompliantAttribute(false)]", assemblyInfo);
        }

        [Fact]
        public void WithCLSCompliant_CanBeCalledMoreThanOnce()
        {
            var builder = new AssemblyInfoBuilder(new CSharpCodeProvider());
            builder
                .WithCLSCompliant(true)
                .WithCLSCompliant(false);
            var assemblyInfo = builder.Build();

            Assert.Contains("[assembly: System.CLSCompliantAttribute(false)]", assemblyInfo);
        }

        [Fact]
        public void WithAssemblyVersion_WithVersion_BuildsCorrectAssemblyInfo()
        {
            var builder = new AssemblyInfoBuilder(new CSharpCodeProvider());
            builder.WithAssemblyVersion(new Version(4, 3, 2, 1));
            var assemblyInfo = builder.Build();

            Assert.Contains("[assembly: System.Reflection.AssemblyVersionAttribute(\"4.3.2.1\")]", assemblyInfo);
        }

        [Fact]
        public void WithAssemblyVersion_CanBeCalledMoreThanOnce()
        {
            var builder = new AssemblyInfoBuilder(new CSharpCodeProvider());
            builder
                .WithAssemblyVersion(new Version(4, 3, 2, 1))
                .WithAssemblyVersion(new Version(3, 0, 0, 0));
            var assemblyInfo = builder.Build();

            Assert.Contains("[assembly: System.Reflection.AssemblyVersionAttribute(\"3.0.0.0\")]", assemblyInfo);
        }

        [Fact]
        public void WithAssemblyFileVersion_WithVersion_BuildsCorrectAssemblyInfo()
        {
            var builder = new AssemblyInfoBuilder(new CSharpCodeProvider());
            builder.WithAssemblyFileVersion(new Version(4, 3, 2, 1));
            var assemblyInfo = builder.Build();

            Assert.Contains("[assembly: System.Reflection.AssemblyFileVersionAttribute(\"4.3.2.1\")]", assemblyInfo);
        }

        [Fact]
        public void WithAssemblyFileVersion_CanBeCalledMoreThanOnce()
        {
            var builder = new AssemblyInfoBuilder(new CSharpCodeProvider());
            builder
                .WithAssemblyFileVersion(new Version(4, 3, 2, 1))
                .WithAssemblyFileVersion(new Version(1, 2, 3, 4));
            var assemblyInfo = builder.Build();

            Assert.Contains("[assembly: System.Reflection.AssemblyFileVersionAttribute(\"1.2.3.4\")]", assemblyInfo);
        }

        [Fact]
        public void WithAssemblyInformationalVersion_WithVersion_BuildsCorrectAssemblyInfo()
        {
            var builder = new AssemblyInfoBuilder(new CSharpCodeProvider());
            builder.WithAssemblyInformationalVersion("4.3.2.1 Beta 4");
            var assemblyInfo = builder.Build();

            Assert.Contains("[assembly: System.Reflection.AssemblyInformationalVersionAttribute(\"4.3.2.1 Beta 4\")]", assemblyInfo);
        }

        [Fact]
        public void WithAssemblyInformationalVersion_WithSpecialChars_BuildsCorrectAssemblyInfo()
        {
            var builder = new AssemblyInfoBuilder(new CSharpCodeProvider());
            builder.WithAssemblyInformationalVersion("4.3.2.1 code-named \"Maverick\"");
            var assemblyInfo = builder.Build();

            Assert.Contains("[assembly: System.Reflection.AssemblyInformationalVersionAttribute(\"4.3.2.1 code-named \\\"Maverick\\\"\")]", assemblyInfo);
        }

        [Fact]
        public void WithAssemblyInformationalVersion_CanBeCalledMoreThanOnce()
        {
            var builder = new AssemblyInfoBuilder(new CSharpCodeProvider());
            builder
                .WithAssemblyInformationalVersion("4.3.2.1 code-named \"Maverick\"")
                .WithAssemblyInformationalVersion("3.0 code-named \"Maverick\"");
            var assemblyInfo = builder.Build();

            Assert.Contains("[assembly: System.Reflection.AssemblyInformationalVersionAttribute(\"3.0 code-named \\\"Maverick\\\"\")]", assemblyInfo);
        }
    }
}


text:
/**
 * @author mrdoob / http://mrdoob.com/
 */

var THREE = window.THREE || require('three');
var OBJLoader = void 0;

OBJLoader = function OBJLoader(manager) {

  this.manager = manager !== undefined ? manager : THREE.DefaultLoadingManager;

  this.materials = null;

  this.regexp = {
    // v float float float
    vertex_pattern: /^v\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
    // vn float float float
    normal_pattern: /^vn\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
    // vt float float
    uv_pattern: /^vt\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
    // f vertex vertex vertex
    face_vertex: /^f\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)(?:\s+(-?\d+))?/,
    // f vertex/uv vertex/uv vertex/uv
    face_vertex_uv: /^f\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+))?/,
    // f vertex/uv/normal vertex/uv/normal vertex/uv/normal
    face_vertex_uv_normal: /^f\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+)\/(-?\d+))?/,
    // f vertex//normal vertex//normal vertex//normal
    face_vertex_normal: /^f\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)(?:\s+(-?\d+)\/\/(-?\d+))?/,
    // o object_name | g group_name
    object_pattern: /^[og]\s*(.+)?/,
    // s boolean
    smoothing_pattern: /^s\s+(\d+|on|off)/,
    // mtllib file_reference
    material_library_pattern: /^mtllib /,
    // usemtl material_name
    material_use_pattern: /^usemtl /
  };
};

OBJLoader.prototype = {

  constructor: OBJLoader,

  load: function load(url, onLoad, onProgress, onError) {

    var scope = this;

    var loader = new THREE.XHRLoader(scope.manager);
    loader.setPath(this.path);
    loader.load(url, function (text) {

      onLoad(scope.parse(text));
    }, onProgress, onError);
  },

  setPath: function setPath(value) {

    this.path = value;
  },

  setMaterials: function setMaterials(materials) {

    this.materials = materials;
  },

  _createParserState: function _createParserState() {

    var state = {
      objects: [],
      object: {},

      vertices: [],
      normals: [],
      uvs: [],

      materialLibraries: [],

      startObject: function startObject(name, fromDeclaration) {

        // If the current object (initial from reset) is not from a g/o declaration in the parsed
        // file. We need to use it for the first parsed g/o to keep things in sync.
        if (this.object && this.object.fromDeclaration === false) {

          this.object.name = name;
          this.object.fromDeclaration = fromDeclaration !== false;
          return;
        }

        if (this.object && typeof this.object._finalize === 'function') {

          this.object._finalize();
        }

        var previousMaterial = this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined;

        this.object = {
          name: name || '',
          fromDeclaration: fromDeclaration !== false,

          geometry: {
            vertices: [],
            normals: [],
            uvs: []
          },
          materials: [],
          smooth: true,

          startMaterial: function startMaterial(name, libraries) {

            var previous = this._finalize(false);

            // New usemtl declaration overwrites an inherited material, except if faces were declared
            // after the material, then it must be preserved for proper MultiMaterial continuation.
            if (previous && (previous.inherited || previous.groupCount <= 0)) {

              this.materials.splice(previous.index, 1);
            }

            var material = {
              index: this.materials.length,
              name: name || '',
              mtllib: Array.isArray(libraries) && libraries.length > 0 ? libraries[libraries.length - 1] : '',
              smooth: previous !== undefined ? previous.smooth : this.smooth,
              groupStart: previous !== undefined ? previous.groupEnd : 0,
              groupEnd: -1,
              groupCount: -1,
              inherited: false,

              clone: function clone(index) {
                return {
                  index: typeof index === 'number' ? index : this.index,
                  name: this.name,
                  mtllib: this.mtllib,
                  smooth: this.smooth,
                  groupStart: this.groupEnd,
                  groupEnd: -1,
                  groupCount: -1,
                  inherited: false
                };
              }
            };

            this.materials.push(material);

            return material;
          },

          currentMaterial: function currentMaterial() {

            if (this.materials.length > 0) {
              return this.materials[this.materials.length - 1];
            }

            return undefined;
          },

          _finalize: function _finalize(end) {

            var lastMultiMaterial = this.currentMaterial();
            if (lastMultiMaterial && lastMultiMaterial.groupEnd === -1) {

              lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
              lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
              lastMultiMaterial.inherited = false;
            }

            // Guarantee at least one empty material, this makes the creation later more straight forward.
            if (end !== false && this.materials.length === 0) {
              this.materials.push({
                name: '',
                smooth: this.smooth
              });
            }

            return lastMultiMaterial;
          }
        };

        // Inherit previous objects material.
        // Spec tells us that a declared material must be set to all objects until a new material is declared.
        // If a usemtl declaration is encountered while this new object is being parsed, it will
        // overwrite the inherited material. Exception being that there was already face declarations
        // to the inherited material, then it will be preserved for proper MultiMaterial continuation.

        if (previousMaterial && previousMaterial.name && typeof previousMaterial.clone === "function") {

          var declared = previousMaterial.clone(0);
          declared.inherited = true;
          this.object.materials.push(declared);
        }

        this.objects.push(this.object);
      },

      finalize: function finalize() {

        if (this.object && typeof this.object._finalize === 'function') {

          this.object._finalize();
        }
      },

      parseVertexIndex: function parseVertexIndex(value, len) {

        var index = parseInt(value, 10);
        return (index >= 0 ? index - 1 : index + len / 3) * 3;
      },

      parseNormalIndex: function parseNormalIndex(value, len) {

        var index = parseInt(value, 10);
        return (index >= 0 ? index - 1 : index + len / 3) * 3;
      },

      parseUVIndex: function parseUVIndex(value, len) {

        var index = parseInt(value, 10);
        return (index >= 0 ? index - 1 : index + len / 2) * 2;
      },

      addVertex: function addVertex(a, b, c) {

        var src = this.vertices;
        var dst = this.object.geometry.vertices;

        dst.push(src[a + 0]);
        dst.push(src[a + 1]);
        dst.push(src[a + 2]);
        dst.push(src[b + 0]);
        dst.push(src[b + 1]);
        dst.push(src[b + 2]);
        dst.push(src[c + 0]);
        dst.push(src[c + 1]);
        dst.push(src[c + 2]);
      },

      addVertexLine: function addVertexLine(a) {

        var src = this.vertices;
        var dst = this.object.geometry.vertices;

        dst.push(src[a + 0]);
        dst.push(src[a + 1]);
        dst.push(src[a + 2]);
      },

      addNormal: function addNormal(a, b, c) {

        var src = this.normals;
        var dst = this.object.geometry.normals;

        dst.push(src[a + 0]);
        dst.push(src[a + 1]);
        dst.push(src[a + 2]);
        dst.push(src[b + 0]);
        dst.push(src[b + 1]);
        dst.push(src[b + 2]);
        dst.push(src[c + 0]);
        dst.push(src[c + 1]);
        dst.push(src[c + 2]);
      },

      addUV: function addUV(a, b, c) {

        var src = this.uvs;
        var dst = this.object.geometry.uvs;

        dst.push(src[a + 0]);
        dst.push(src[a + 1]);
        dst.push(src[b + 0]);
        dst.push(src[b + 1]);
        dst.push(src[c + 0]);
        dst.push(src[c + 1]);
      },

      addUVLine: function addUVLine(a) {

        var src = this.uvs;
        var dst = this.object.geometry.uvs;

        dst.push(src[a + 0]);
        dst.push(src[a + 1]);
      },

      addFace: function addFace(a, b, c, d, ua, ub, uc, ud, na, nb, nc, nd) {

        var vLen = this.vertices.length;

        var ia = this.parseVertexIndex(a, vLen);
        var ib = this.parseVertexIndex(b, vLen);
        var ic = this.parseVertexIndex(c, vLen);
        var id = void 0;

        if (d === undefined) {

          this.addVertex(ia, ib, ic);
        } else {

          id = this.parseVertexIndex(d, vLen);

          this.addVertex(ia, ib, id);
          this.addVertex(ib, ic, id);
        }

        if (ua !== undefined) {

          var uvLen = this.uvs.length;

          ia = this.parseUVIndex(ua, uvLen);
          ib = this.parseUVIndex(ub, uvLen);
          ic = this.parseUVIndex(uc, uvLen);

          if (d === undefined) {

            this.addUV(ia, ib, ic);
          } else {

            id = this.parseUVIndex(ud, uvLen);

            this.addUV(ia, ib, id);
            this.addUV(ib, ic, id);
          }
        }

        if (na !== undefined) {

          // Normals are many times the same. If so, skip function call and parseInt.
          var nLen = this.normals.length;
          ia = this.parseNormalIndex(na, nLen);

          ib = na === nb ? ia : this.parseNormalIndex(nb, nLen);
          ic = na === nc ? ia : this.parseNormalIndex(nc, nLen);

          if (d === undefined) {

            this.addNormal(ia, ib, ic);
          } else {

            id = this.parseNormalIndex(nd, nLen);

            this.addNormal(ia, ib, id);
            this.addNormal(ib, ic, id);
          }
        }
      },

      addLineGeometry: function addLineGeometry(vertices, uvs) {

        this.object.geometry.type = 'Line';

        var vLen = this.vertices.length;
        var uvLen = this.uvs.length;

        for (var vi = 0, l = vertices.length; vi < l; vi++) {

          this.addVertexLine(this.parseVertexIndex(vertices[vi], vLen));
        }

        for (var uvi = 0, _l = uvs.length; uvi < _l; uvi++) {

          this.addUVLine(this.parseUVIndex(uvs[uvi], uvLen));
        }
      }

    };

    state.startObject('', false);

    return state;
  },

  parse: function parse(text) {
    var state = this._createParserState();

    if (text.indexOf('\r\n') !== -1) {

      // This is faster than String.split with regex that splits on both
      text = text.replace('\r\n', '\n');
    }

    var lines = text.split('\n');
    var line = '',
        lineFirstChar = '',
        lineSecondChar = '';
    var lineLength = 0;
    var result = [];

    // Faster to just trim left side of the line. Use if available.
    var trimLeft = typeof ''.trimLeft === 'function';

    for (var i = 0, l = lines.length; i < l; i++) {

      line = lines[i];

      line = trimLeft ? line.trimLeft() : line.trim();

      lineLength = line.length;

      if (lineLength === 0) continue;

      lineFirstChar = line.charAt(0);

      // @todo invoke passed in handler if any
      if (lineFirstChar === '#') continue;

      if (lineFirstChar === 'v') {

        lineSecondChar = line.charAt(1);

        if (lineSecondChar === ' ' && (result = this.regexp.vertex_pattern.exec(line)) !== null) {

          // 0                  1      2      3
          // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]

          state.vertices.push(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]));
        } else if (lineSecondChar === 'n' && (result = this.regexp.normal_pattern.exec(line)) !== null) {

          // 0                   1      2      3
          // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]

          state.normals.push(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]));
        } else if (lineSecondChar === 't' && (result = this.regexp.uv_pattern.exec(line)) !== null) {

          // 0               1      2
          // ["vt 0.1 0.2", "0.1", "0.2"]

          state.uvs.push(parseFloat(result[1]), parseFloat(result[2]));
        } else {

          throw new Error("Unexpected vertex/normal/uv line: '" + line + "'");
        }
      } else if (lineFirstChar === "f") {

        if ((result = this.regexp.face_vertex_uv_normal.exec(line)) !== null) {

          // f vertex/uv/normal vertex/uv/normal vertex/uv/normal
          // 0                        1    2    3    4    5    6    7    8    9   10         11         12
          // ["f 1/1/1 2/2/2 3/3/3", "1", "1", "1", "2", "2", "2", "3", "3", "3", undefined, undefined, undefined]

          state.addFace(result[1], result[4], result[7], result[10], result[2], result[5], result[8], result[11], result[3], result[6], result[9], result[12]);
        } else if ((result = this.regexp.face_vertex_uv.exec(line)) !== null) {

          // f vertex/uv vertex/uv vertex/uv
          // 0                  1    2    3    4    5    6   7          8
          // ["f 1/1 2/2 3/3", "1", "1", "2", "2", "3", "3", undefined, undefined]

          state.addFace(result[1], result[3], result[5], result[7], result[2], result[4], result[6], result[8]);
        } else if ((result = this.regexp.face_vertex_normal.exec(line)) !== null) {

          // f vertex//normal vertex//normal vertex//normal
          // 0                     1    2    3    4    5    6   7          8
          // ["f 1//1 2//2 3//3", "1", "1", "2", "2", "3", "3", undefined, undefined]

          state.addFace(result[1], result[3], result[5], result[7], undefined, undefined, undefined, undefined, result[2], result[4], result[6], result[8]);
        } else if ((result = this.regexp.face_vertex.exec(line)) !== null) {

          // f vertex vertex vertex
          // 0            1    2    3   4
          // ["f 1 2 3", "1", "2", "3", undefined]

          state.addFace(result[1], result[2], result[3], result[4]);
        } else {

          throw new Error("Unexpected face line: '" + line + "'");
        }
      } else if (lineFirstChar === "l") {

        var lineParts = line.substring(1).trim().split(" ");
        var lineVertices = [],
            lineUVs = [];

        if (line.indexOf("/") === -1) {

          lineVertices = lineParts;
        } else {

          for (var li = 0, llen = lineParts.length; li < llen; li++) {

            var parts = lineParts[li].split("/");

            if (parts[0] !== "") lineVertices.push(parts[0]);
            if (parts[1] !== "") lineUVs.push(parts[1]);
          }
        }
        state.addLineGeometry(lineVertices, lineUVs);
      } else if ((result = this.regexp.object_pattern.exec(line)) !== null) {

        // o object_name
        // or
        // g group_name

        var name = result[0].substr(1).trim();
        state.startObject(name);
      } else if (this.regexp.material_use_pattern.test(line)) {

        // material

        state.object.startMaterial(line.substring(7).trim(), state.materialLibraries);
      } else if (this.regexp.material_library_pattern.test(line)) {

        // mtl file

        state.materialLibraries.push(line.substring(7).trim());
      } else if ((result = this.regexp.smoothing_pattern.exec(line)) !== null) {

        // smooth shading

        // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
        // but does not define a usemtl for each face set.
        // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
        // This requires some care to not create extra material on each smooth value for "normal" obj files.
        // where explicit usemtl defines geometry groups.
        // Example asset: examples/models/obj/cerberus/Cerberus.obj

        var value = result[1].trim().toLowerCase();
        state.object.smooth = value === '1' || value === 'on';

        var material = state.object.currentMaterial();
        if (material) {

          material.smooth = state.object.smooth;
        }
      } else {

        // Handle null terminated files without exception
        if (line === '\0') continue;

        throw new Error("Unexpected line: '" + line + "'");
      }
    }

    state.finalize();

    var container = new THREE.Group();
    container.materialLibraries = [].concat(state.materialLibraries);

    for (var _i = 0, _l2 = state.objects.length; _i < _l2; _i++) {

      var object = state.objects[_i];
      var geometry = object.geometry;
      var materials = object.materials;
      var isLine = geometry.type === 'Line';

      // Skip o/g line declarations that did not follow with any faces
      if (geometry.vertices.length === 0) continue;

      var buffergeometry = new THREE.BufferGeometry();

      buffergeometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(geometry.vertices), 3));

      if (geometry.normals.length > 0) {

        buffergeometry.addAttribute('normal', new THREE.BufferAttribute(new Float32Array(geometry.normals), 3));
      } else {

        buffergeometry.computeVertexNormals();
      }

      if (geometry.uvs.length > 0) {

        buffergeometry.addAttribute('uv', new THREE.BufferAttribute(new Float32Array(geometry.uvs), 2));
      }

      // Create materials

      var createdMaterials = [];

      for (var mi = 0, miLen = materials.length; mi < miLen; mi++) {

        var sourceMaterial = materials[mi];
        var _material = undefined;

        if (this.materials !== null) {

          _material = this.materials.create(sourceMaterial.name);

          // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
          if (isLine && _material && !(_material instanceof THREE.LineBasicMaterial)) {

            var materialLine = new THREE.LineBasicMaterial();
            materialLine.copy(_material);
            _material = materialLine;
          }
        }

        if (!_material) {

          _material = !isLine ? new THREE.MeshPhongMaterial() : new THREE.LineBasicMaterial();
          _material.name = sourceMaterial.name;
        }

        if (!sourceMaterial.smooth) _material.flatShading = true;

        createdMaterials.push(_material);
      }

      // Create mesh

      var mesh = void 0;

      if (createdMaterials.length > 1) {

        for (var _mi = 0, _miLen = materials.length; _mi < _miLen; _mi++) {

          var _sourceMaterial = materials[_mi];
          buffergeometry.addGroup(_sourceMaterial.groupStart, _sourceMaterial.groupCount, _mi);
        }

        var multiMaterial = new THREE.MultiMaterial(createdMaterials);
        mesh = !isLine ? new THREE.Mesh(buffergeometry, multiMaterial) : new THREE.Line(buffergeometry, multiMaterial);
      } else {

        mesh = !isLine ? new THREE.Mesh(buffergeometry, createdMaterials[0]) : new THREE.Line(buffergeometry, createdMaterials[0]);
      }

      mesh.name = object.name;

      container.add(mesh);
    }

    return container;
  }

};

module.exports = OBJLoader;


text:
ALTER TABLE jforum_search_results RENAME time TO search_time;
ALTER TABLE jforum_search_topics RENAME time TO search_time;
ALTER TABLE jforum_roles RENAME type TO role_type;
ALTER TABLE jforum_role_values RENAME type TO role_type;
ALTER TABLE jforum_role_values RENAME value TO role_value;

ALTER TABLE jforum_posts ADD tmp TIMESTAMP;
UPDATE jforum_posts SET tmp = ABSTIME(SUBSTRING(post_time, 1, 10)::INT);
ALTER TABLE jforum_posts DROP COLUMN post_time;
ALTER TABLE jforum_posts RENAME tmp TO post_time;

ALTER TABLE jforum_posts ADD tmp TIMESTAMP;
UPDATE jforum_posts SET tmp = ABSTIME(SUBSTRING(post_edit_time, 1, 10)::INT);
ALTER TABLE jforum_posts DROP COLUMN post_edit_time;
ALTER TABLE jforum_posts RENAME tmp TO post_edit_time;

DELETE FROM jforum_sessions;
ALTER TABLE jforum_sessions DROP session_time;
ALTER TABLE jforum_sessions ADD session_time BIGINT;
ALTER TABLE jforum_sessions DROP session_start;
ALTER TABLE jforum_sessions ADD session_start TIMESTAMP;

ALTER TABLE jforum_topics ADD tmp TIMESTAMP;
UPDATE jforum_topics SET tmp = ABSTIME(SUBSTRING(topic_time, 1, 10)::INT);
ALTER TABLE jforum_topics DROP COLUMN topic_time;
ALTER TABLE jforum_topics RENAME tmp TO topic_time;
ALTER TABLE jforum_topics ALTER topic_time SET DEFAULT NOW();

ALTER TABLE jforum_privmsgs ADD tmp TIMESTAMP;
UPDATE jforum_privmsgs SET tmp = ABSTIME(SUBSTRING(privmsgs_date, 1, 10)::INT);
ALTER TABLE jforum_privmsgs DROP COLUMN privmsgs_date;
ALTER TABLE jforum_privmsgs RENAME tmp TO privmsgs_date;
ALTER TABLE jforum_privmsgs ALTER privmsgs_date SET DEFAULT NOW();

ALTER TABLE jforum_users DROP user_session_time;
ALTER TABLE jforum_users ADD user_session_time TIMESTAMP;

ALTER TABLE jforum_users ADD tmp TIMESTAMP;
UPDATE jforum_users SET tmp = ABSTIME(SUBSTRING(user_regdate, 1, 10)::INT);
ALTER TABLE jforum_users DROP COLUMN user_regdate;
ALTER TABLE jforum_users RENAME tmp TO user_regdate;
ALTER TABLE jforum_users ALTER user_regdate SET DEFAULT NOW();

ALTER TABLE jforum_users DROP user_emailtime;
ALTER TABLE jforum_users ADD user_emailtime TIMESTAMP;

ALTER TABLE jforum_users DROP user_lastvisit;
ALTER TABLE jforum_users ADD user_lastvisit TIMESTAMP;

ALTER TABLE jforum_users DROP user_last_privmsg;
ALTER TABLE jforum_users ADD user_last_privmsg TIMESTAMP;

DELETE FROM jforum_search_topics;
ALTER TABLE jforum_search_topics DROP topic_time;
ALTER TABLE jforum_search_topics ADD topic_time TIMESTAMP;
ALTER TABLE jforum_search_topics ALTER topic_time SET DEFAULT NOW();

UPDATE jforum_users SET user_lastvisit = NULL;
UPDATE jforum_users SET user_emailtime = NULL;
UPDATE jforum_users SET user_session_time = NULL;
UPDATE jforum_users SET user_regdate = NOW() where user_regdate = 0;


text:
using namespace arangodb;
using namespace arangodb::aql;
using namespace arangodb::graph;
using namespace arangodb::transaction;
using namespace arangodb::traverser;

ShortestPathResult::ShortestPathResult() : _readDocuments(0) {}

ShortestPathResult::~ShortestPathResult() = default;

/// @brief Clears the path
void ShortestPathResult::clear() {
  _vertices.clear();
  _edges.clear();
}

AqlValue ShortestPathResult::edgeToAqlValue(TraverserCache* cache, size_t position) const {
  if (position == 0) {
    // First Edge is defined as NULL
    return AqlValue(AqlValueHintNull());
  }
  TRI_ASSERT(position - 1 < _edges.size());
  return cache->fetchEdgeAqlResult(_edges[position - 1]);
}

AqlValue ShortestPathResult::vertexToAqlValue(TraverserCache* cache, size_t position) const {
  TRI_ASSERT(position < _vertices.size());
  return cache->fetchVertexAqlResult(_vertices[position]);
}

void ShortestPathResult::addVertex(arangodb::velocypack::StringRef v) {
  TRI_ASSERT(_edges.size() == _vertices.size());
  _vertices.emplace_back(v);
}
void ShortestPathResult::addEdge(arangodb::graph::EdgeDocumentToken e) {
  TRI_ASSERT(_edges.size() + 1 == _vertices.size());
  _edges.emplace_back(e);
}


text:
import keyword
import sys
import os
import types
import importlib
import importlib.machinery
from urllib.parse import urlparse

DEBUG = False

import pyparsing as pp

# define basic exception for invalid state transitions - state machine classes will subclass to
# define their own specific exception type
class InvalidTransitionException(Exception):
    pass

ident = pp.Word(pp.alphas + "_", pp.alphanums + "_$")

# add parse-time condition to make sure we do not allow any Python keywords to be used as
# statemachine identifiers
def no_keywords_allowed(s, l, t):
    wd = t[0]
    return not keyword.iskeyword(wd)

ident.addCondition(
    no_keywords_allowed,
    message="cannot use a Python keyword for state or transition identifier",
)

stateTransition = ident("from_state") + "->" + ident("to_state")
stateMachine = (
    pp.Keyword("statemachine")
    + ident("name")
    + ":"
    + pp.OneOrMore(pp.Group(stateTransition))("transitions")
)

namedStateTransition = (
    ident("from_state") + "-(" + ident("transition") + ")->" + ident("to_state")
)
namedStateMachine = (
    pp.Keyword("statemachine")
    + ident("name")
    + ":"
    + pp.OneOrMore(pp.Group(namedStateTransition))("transitions")
)

def expand_state_definition(source, loc, tokens):
    """
    Parse action to convert statemachine to corresponding Python classes and methods
    """
    indent = " " * (pp.col(loc, source) - 1)
    statedef = []

    # build list of states
    states = set()
    fromTo = {}
    for tn in tokens.transitions:
        states.add(tn.from_state)
        states.add(tn.to_state)
        fromTo[tn.from_state] = tn.to_state

    # define base class for state classes
    baseStateClass = tokens.name
    statedef.extend(
        [
            "class %s(object):" % baseStateClass,
            "    def __str__(self):",
            "        return self.__class__.__name__",
            "    @classmethod",
            "    def states(cls):",
            "        return list(cls.__subclasses__())",
            "    def next_state(self):",
            "        return self._next_state_class()",
        ]
    )

    # define all state classes
    statedef.extend("class {}({}): pass".format(s, baseStateClass) for s in states)

    # define state->state transitions
    statedef.extend(
        "{}._next_state_class = {}".format(s, fromTo[s]) for s in states if s in fromTo
    )

    statedef.extend(
        [
            "class {baseStateClass}Mixin:".format(baseStateClass=baseStateClass),
            "    def __init__(self):",
            "        self._state = None",
            "    def initialize_state(self, init_state):",
            "        if issubclass(init_state, {baseStateClass}):".format(
                baseStateClass=baseStateClass
            ),
            "            init_state = init_state()",
            "        self._state = init_state",
            "    @property",
            "    def state(self):",
            "        return self._state",
            "    # get behavior/properties from current state",
            "    def __getattr__(self, attrname):",
            "        attr = getattr(self._state, attrname)",
            "        return attr",
            "    def __str__(self):",
            "       return '{0}: {1}'.format(self.__class__.__name__, self._state)",
        ]
    )

    return ("\n" + indent).join(statedef) + "\n"

stateMachine.setParseAction(expand_state_definition)

def expand_named_state_definition(source, loc, tokens):
    """
    Parse action to convert statemachine with named transitions to corresponding Python
    classes and methods
    """
    indent = " " * (pp.col(loc, source) - 1)
    statedef = []
    # build list of states and transitions
    states = set()
    transitions = set()

    baseStateClass = tokens.name

    fromTo = {}
    for tn in tokens.transitions:
        states.add(tn.from_state)
        states.add(tn.to_state)
        transitions.add(tn.transition)
        if tn.from_state in fromTo:
            fromTo[tn.from_state][tn.transition] = tn.to_state
        else:
            fromTo[tn.from_state] = {tn.transition: tn.to_state}

    # add entries for terminal states
    for s in states:
        if s not in fromTo:
            fromTo[s] = {}

    # define state transition class
    statedef.extend(
        [
            "class {baseStateClass}Transition:".format(baseStateClass=baseStateClass),
            "    def __str__(self):",
            "        return self.transitionName",
        ]
    )
    statedef.extend(
        "{tn_name} = {baseStateClass}Transition()".format(
            tn_name=tn, baseStateClass=baseStateClass
        )
        for tn in transitions
    )
    statedef.extend(
        "{tn_name}.transitionName = '{tn_name}'".format(tn_name=tn)
        for tn in transitions
    )

    # define base class for state classes
    statedef.extend(
        [
            "class %s(object):" % baseStateClass,
            "    from statemachine import InvalidTransitionException as BaseTransitionException",
            "    class InvalidTransitionException(BaseTransitionException): pass",
            "    def __str__(self):",
            "        return self.__class__.__name__",
            "    @classmethod",
            "    def states(cls):",
            "        return list(cls.__subclasses__())",
            "    @classmethod",
            "    def next_state(cls, name):",
            "        try:",
            "            return cls.tnmap[name]()",
            "        except KeyError:",
            "            raise cls.InvalidTransitionException('%s does not support transition %r'% (cls.__name__, name))",
            "    def __bad_tn(name):",
            "        def _fn(cls):",
            "            raise cls.InvalidTransitionException('%s does not support transition %r'% (cls.__name__, name))",
            "        _fn.__name__ = name",
            "        return _fn",
        ]
    )

    # define default 'invalid transition' methods in base class, valid transitions will be implemented in subclasses
    statedef.extend(
        "    {tn_name} = classmethod(__bad_tn({tn_name!r}))".format(tn_name=tn)
        for tn in transitions
    )

    # define all state classes
    statedef.extend("class {}({}): pass".format(s, baseStateClass) for s in states)

    # define state transition methods for valid transitions from each state
    for s in states:
        trns = list(fromTo[s].items())
        # statedef.append("%s.tnmap = {%s}" % (s, ", ".join("%s:%s" % tn for tn in trns)))
        statedef.extend(
            "{}.{} = classmethod(lambda cls: {}())".format(s, tn_, to_)
            for tn_, to_ in trns
        )

    statedef.extend(
        [
            "{baseStateClass}.transitions = classmethod(lambda cls: [{transition_class_list}])".format(
                baseStateClass=baseStateClass,
                transition_class_list=", ".join(
                    "cls.{}".format(tn) for tn in transitions
                ),
            ),
            "{baseStateClass}.transition_names = [tn.__name__ for tn in {baseStateClass}.transitions()]".format(
                baseStateClass=baseStateClass
            ),
        ]
    )

    # define <state>Mixin class for application classes that delegate to the state
    statedef.extend(
        [
            "class {baseStateClass}Mixin:".format(baseStateClass=baseStateClass),
            "    def __init__(self):",
            "        self._state = None",
            "    def initialize_state(self, init_state):",
            "        if issubclass(init_state, {baseStateClass}):".format(
                baseStateClass=baseStateClass
            ),
            "            init_state = init_state()",
            "        self._state = init_state",
            "    @property",
            "    def state(self):",
            "        return self._state",
            "    # get behavior/properties from current state",
            "    def __getattr__(self, attrname):",
            "        attr = getattr(self._state, attrname)",
            "        return attr",
            "    def __str__(self):",
            "       return '{0}: {1}'.format(self.__class__.__name__, self._state)",
        ]
    )

    # define transition methods to be delegated to the _state instance variable
    statedef.extend(
        "    def {tn_name}(self): self._state = self._state.{tn_name}()".format(
            tn_name=tn
        )
        for tn in transitions
    )
    return ("\n" + indent).join(statedef) + "\n"

namedStateMachine.setParseAction(expand_named_state_definition)

# ======================================================================
# NEW STUFF - Matt Anderson, 2009-11-26
# ======================================================================
class SuffixImporter:
    """An importer designed using the mechanism defined in :pep:`302`. I read
    the PEP, and also used Doug Hellmann's PyMOTW article `Modules and
    Imports`_, as a pattern.

    .. _`Modules and Imports`: http://www.doughellmann.com/PyMOTW/sys/imports.html

    Define a subclass that specifies a :attr:`suffix` attribute, and
    implements a :meth:`process_filedata` method. Then call the classmethod
    :meth:`register` on your class to actually install it in the appropriate
    places in :mod:`sys`."""

    scheme = "suffix"
    suffix = None
    path_entry = None

    @classmethod
    def trigger_url(cls):
        if cls.suffix is None:
            raise ValueError("%s.suffix is not set" % cls.__name__)
        return "suffix:%s" % cls.suffix

    @classmethod
    def register(cls):
        sys.path_hooks.append(cls)
        sys.path.append(cls.trigger_url())

    def __init__(self, path_entry):
        pr = urlparse(str(path_entry))
        if pr.scheme != self.scheme or pr.path != self.suffix:
            raise ImportError()
        self.path_entry = path_entry
        self._found = {}

    def checkpath_iter(self, fullname):
        for dirpath in sys.path:
            # if the value in sys.path_importer_cache is None, then this
            # path *should* be imported by the builtin mechanism, and the
            # entry is thus a path to a directory on the filesystem;
            # if it's not None, then some other importer is in charge, and
            # it probably isn't even a filesystem path
            finder = sys.path_importer_cache.get(dirpath)
            if isinstance(finder, (type(None), importlib.machinery.FileFinder)):
                checkpath = os.path.join(dirpath, "{}.{}".format(fullname, self.suffix))
                yield checkpath

    def find_module(self, fullname, path=None):
        for checkpath in self.checkpath_iter(fullname):
            if os.path.isfile(checkpath):
                self._found[fullname] = checkpath
                return self
        return None

    def load_module(self, fullname):
        assert fullname in self._found
        if fullname in sys.modules:
            module = sys.modules[fullname]
        else:
            sys.modules[fullname] = module = types.ModuleType(fullname)
        data = None
        with open(self._found[fullname]) as f:
            data = f.read()

        module.__dict__.clear()
        module.__file__ = self._found[fullname]
        module.__name__ = fullname
        module.__loader__ = self
        self.process_filedata(module, data)
        return module

    def process_filedata(self, module, data):
        pass

class PystateImporter(SuffixImporter):
    suffix = "pystate"

    def process_filedata(self, module, data):
        # MATT-NOTE: re-worked :func:`get_state_machine`

        # convert any statemachine expressions
        stateMachineExpr = (stateMachine | namedStateMachine).ignore(
            pp.pythonStyleComment
        )
        generated_code = stateMachineExpr.transformString(data)

        if DEBUG:
            print(generated_code)

        # compile code object from generated code
        # (strip trailing spaces and tabs, compile doesn't like
        # dangling whitespace)
        COMPILE_MODE = "exec"

        codeobj = compile(generated_code.rstrip(" \t"), module.__file__, COMPILE_MODE)

        exec(codeobj, module.__dict__)

PystateImporter.register()

if DEBUG:
    print("registered {!r} importer".format(PystateImporter.suffix))


text:
package org.jfree.chart.urls;

import java.io.Serializable;

import org.jfree.data.general.PieDataset;
import org.jfree.util.ObjectUtilities;

/**
 * A URL generator for pie charts.  Instances of this class are immutable.
 */
public class StandardPieURLGenerator implements PieURLGenerator, Serializable {

    /** For serialization. */
    private static final long serialVersionUID = 1626966402065883419L;

    /** The prefix. */
    private String prefix = "index.html";

    /** The category parameter name. */
    private String categoryParameterName = "category";

    /** The pie index parameter name. */
    private String indexParameterName = "pieIndex";

    /**
     * Default constructor.
     */
    public StandardPieURLGenerator() {
        this("index.html");
    }

    /**
     * Creates a new generator.
     *
     * @param prefix  the prefix (null not permitted).
     */
    public StandardPieURLGenerator(String prefix) {
        this(prefix, "category");
    }

    /**
     * Creates a new generator.
     *
     * @param prefix  the prefix (null not permitted).
     * @param categoryParameterName  the category parameter name
     *     (null not permitted).
     */
    public StandardPieURLGenerator(String prefix,
                                   String categoryParameterName) {
        this(prefix, categoryParameterName, "pieIndex");
    }

    /**
     * Creates a new generator.
     *
     * @param prefix  the prefix (null not permitted).
     * @param categoryParameterName  the category parameter name
     *     (null not permitted).
     * @param indexParameterName  the index parameter name (null
     *     permitted).
     */
    public StandardPieURLGenerator(String prefix,
                                   String categoryParameterName,
                                   String indexParameterName) {
        if (prefix == null) {
            throw new IllegalArgumentException("Null 'prefix' argument.");
        }
        if (categoryParameterName == null) {
            throw new IllegalArgumentException(
                    "Null 'categoryParameterName' argument.");
        }
        this.prefix = prefix;
        this.categoryParameterName = categoryParameterName;
        this.indexParameterName = indexParameterName;
    }

    /**
     * Generates a URL.
     *
     * @param dataset  the dataset (ignored).
     * @param key  the item key (null not permitted).
     * @param pieIndex  the pie index.
     *
     * @return A string containing the generated URL.
     */
    public String generateURL(PieDataset dataset, Comparable key,
            int pieIndex) {
        String url = this.prefix;
        if (url.indexOf("?") > -1) {
            url += "&" + this.categoryParameterName + "="
                    + URLUtilities.encode(key.toString(), "UTF-8");
        }
        else {
            url += "?" + this.categoryParameterName + "="
                    + URLUtilities.encode(key.toString(), "UTF-8");
        }
        if (this.indexParameterName != null) {
            url += "&" + this.indexParameterName + "="
                   + String.valueOf(pieIndex);
        }
        return url;
    }

    /**
     * Tests if this object is equal to another.
     *
     * @param obj  the object (null permitted).
     *
     * @return A boolean.
     */
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof StandardPieURLGenerator)) {
            return false;
        }
        StandardPieURLGenerator that = (StandardPieURLGenerator) obj;
        if (!this.prefix.equals(that.prefix)) {
            return false;
        }
        if (!this.categoryParameterName.equals(that.categoryParameterName)) {
            return false;
        }
        if (!ObjectUtilities.equal(this.indexParameterName,
                that.indexParameterName)) {
            return false;
        }
        return true;
    }
}


text:
package org.apache.oodt.cas.filemgr.cli.action;

//OODT imports
import org.apache.oodt.cas.cli.exception.CmdLineActionException;
import org.apache.oodt.cas.filemgr.structs.FileTransferStatus;

/**
 * A {@link CmdLineAction} which get the current {@link Product} file transfer.
 *
 * @author bfoster (Brian Foster)
 */
public class GetCurrentTransferCliAction extends FileManagerCliAction {

   @Override
   public void execute(ActionMessagePrinter printer)
         throws CmdLineActionException {
      try {
         FileTransferStatus status = getClient().getCurrentFileTransfer();
         if (status == null) {
            throw new NullPointerException(
                  "FileManager returned null transfer status");
         }
         printer.println("File Transfer: [ref={orig="
               + status.getFileRef().getOrigReference() + ",ds="
               + status.getFileRef().getDataStoreReference() + "},product="
               + status.getParentProduct().getProductName() + ",fileSize="
               + status.getFileRef().getFileSize() + ",amtTransferred="
               + status.getBytesTransferred() + ",pct="
               + status.computePctTransferred() + "]");
      } catch (Exception e) {
         throw new CmdLineActionException(
               "Failed to get current file transfer : " + e.getMessage(), e);
      }
   }
}


text:
#ifndef UTILS_EZTRACE_H
#define UTILS_EZTRACE_H

#include "Trace.h"
#include <sstream>

/** @ingroup Utils
 * @brief A Trace that dumps on destruction.  Only one may be active at
 * any time.
 *
 * All EZCallTrace functions log to the current trace.
 */
struct EZTrace
{
  EZTrace();
  ~EZTrace();

  bool dumpStats,dumpTrace;
  Trace myTrace;

  static Trace* curTrace;
};

/** @ingroup Utils
 * @brief Helper class that eases function call tracing
 *
 * On entry to a function, instantiate an EZCallTrace object.
 * On exit, optionally pass the return value to Return().
 * If this isn't done, "void" is passed to EZTrace as the
 * return value.
 * e.g.
 *
 * int foo() {
 *   EZCallTrace tr("foo");
 *   ...
 *   return tr.Return(bar);
 * }
 */
struct EZCallTrace
{
  EZCallTrace(const char* name);
  EZCallTrace(const char* name,const char* args,...);
  ~EZCallTrace();

  template <class T>
  const T& Return(const T& val) {
    std::stringstream ss;
    ss<<val;
    retval = ss.str();
    return val;
  }

  std::string name;
  std::string retval;
};

#endif


text:
namespace ch1 {
namespace s1 {
namespace ex24 {

size_t GreatestCommonDivisor(size_t left, size_t right) {
    if (not right) {
        return left;
    }
    left %= right;
    return GreatestCommonDivisor(right, left);
}

}  // namespace ex24
}  // namespace s1
}  // namespace ch1


text:
package org.globsframework.utils;

import org.globsframework.utils.exceptions.InvalidParameter;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

public class TablePrinter {

    private Object[] header;
    private List<Object[]> rows = new ArrayList<Object[]>();
    private boolean sorted;

    public TablePrinter() {
        this(false);
    }

    public TablePrinter(boolean sorted) {
        this.sorted = sorted;
    }

    public void setHeader(Object... titles) {
        header = titles;
    }

    public void addRow(Object... items) {
        rows.add(items);
    }

    public void print(PrintWriter printer) {
        if (header == null) {
            if (rows.isEmpty()) {
                return;
            }
        }
        print(header, rows, sorted, printer);
    }

    public void print() {
        print(new PrintWriter(System.out));
    }

    public String toString() {
        StringWriter writer = new StringWriter();
        print(new PrintWriter(writer));
        return writer.toString();
    }

    public static String toString(Object[] headerRow, List<Object[]> rows) {
        StringWriter writer = new StringWriter();
        print(headerRow, rows, true, new PrintWriter(writer));
        return writer.toString();
    }

    public static void print(Object[] headerRow, List<Object[]> rows, boolean sorted, PrintWriter printer) {
        List<Object[]> aggregated = new ArrayList<Object[]>();
        if (headerRow != null) {
            aggregated.add(headerRow);
        }
        aggregated.addAll(rows);
        if (aggregated.isEmpty()) {
            return;
        }

        Object[] firstRow = aggregated.get(0);
        int[] sizes = new int[firstRow.length];
        Arrays.fill(sizes, 0);

        for (Object[] row : aggregated) {
            if (row.length > firstRow.length) {
                throw new InvalidParameter("Row larger than the first row: " + Arrays.toString(row));
            }
        }

        for (Object[] row : aggregated) {
            updateSizes(row, sizes);
        }

        if (headerRow != null) {
            printer.println(toString(headerRow, sizes));
        }
        List<String> strings = new ArrayList<String>();
        for (Object[] row : rows) {
            strings.add(toString(row, sizes));
        }
        if (sorted) {
            strings = Utils.sort(strings);
        }
        for (String string : strings) {
            printer.println(string);
        }

        printer.flush();
    }

    private static void updateSizes(Object[] row, int[] sizes) {
        int index = 0;
        for (Object cell : row) {
            String str = toString(cell);
            sizes[index] = Math.max(sizes[index], str.length());
            index++;
        }
    }

    private static String toString(Object[] row, int[] sizes) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < row.length; i++) {
            builder.append("| ");
            String string = toString(row[i]);
            builder.append(string);
            int space = sizes[i] - string.length();
            for (int j = 0; j < space; j++) {
                builder.append(' ');
            }
            builder.append(' ');
        }
        builder.append('|');
        return builder.toString();
    }

    private static String toString(Object cell) {
        if (cell == null) {
            return "";
        }
        if (cell instanceof Double) {
            return new DecimalFormat("#.00", new DecimalFormatSymbols(Locale.US)).format(cell);
        }
        return cell.toString();
    }
}


text:
<?php
/*
 * khoaofgod@gmail.com
 * Website: http://www.phpfastcache.com
 * Example at our website, any bugs, problems, please visit http://faster.phpfastcache.com
 */

class phpfastcache_wincache extends BasePhpFastCache implements phpfastcache_driver  {

    function checkdriver() {
        if(extension_loaded('wincache') && function_exists("wincache_ucache_set"))
        {
            return true;
        }
	    $this->fallback = true;
        return false;
    }

    function __construct($config = array()) {
        $this->setup($config);
        if(!$this->checkdriver() && !isset($config['skipError'])) {
	        $this->fallback = true;
        }

    }

    function driver_set($keyword, $value = "", $time = 300, $option = array() ) {
        if(isset($option['skipExisting']) && $option['skipExisting'] == true) {
            return wincache_ucache_add($keyword, $value, $time);
        } else {
            return wincache_ucache_set($keyword, $value, $time);
        }
    }

    function driver_get($keyword, $option = array()) {
        // return null if no caching
        // return value if in caching

        $x = wincache_ucache_get($keyword,$suc);

        if($suc == false) {
            return null;
        } else {
            return $x;
        }
    }

    function driver_delete($keyword, $option = array()) {
        return wincache_ucache_delete($keyword);
    }

    function driver_stats($option = array()) {
        $res = array(
            "info"  =>  "",
            "size"  =>  "",
            "data"  =>  wincache_scache_info(),
        );
        return $res;
    }

    function driver_clean($option = array()) {
        wincache_ucache_clear();
        return true;
    }

    function driver_isExisting($keyword) {
        if(wincache_ucache_exists($keyword)) {
            return true;
        } else {
            return false;
        }
    }

}


text:
package com.amazonaws.services.logs.model.transform;

import java.io.ByteArrayInputStream;
import java.util.Collections;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.logs.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.protocol.json.*;

/**
 * GetLogEventsRequest Marshaller
 */
public class GetLogEventsRequestMarshaller implements
        Marshaller<Request<GetLogEventsRequest>, GetLogEventsRequest> {

    private final SdkJsonProtocolFactory protocolFactory;

    public GetLogEventsRequestMarshaller(SdkJsonProtocolFactory protocolFactory) {
        this.protocolFactory = protocolFactory;
    }

    public Request<GetLogEventsRequest> marshall(
            GetLogEventsRequest getLogEventsRequest) {

        if (getLogEventsRequest == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        Request<GetLogEventsRequest> request = new DefaultRequest<GetLogEventsRequest>(
                getLogEventsRequest, "AWSLogs");
        request.addHeader("X-Amz-Target", "Logs_20140328.GetLogEvents");

        request.setHttpMethod(HttpMethodName.POST);

        request.setResourcePath("");

        try {
            final StructuredJsonGenerator jsonGenerator = protocolFactory
                    .createGenerator();

            jsonGenerator.writeStartObject();

            if (getLogEventsRequest.getLogGroupName() != null) {
                jsonGenerator.writeFieldName("logGroupName").writeValue(
                        getLogEventsRequest.getLogGroupName());
            }
            if (getLogEventsRequest.getLogStreamName() != null) {
                jsonGenerator.writeFieldName("logStreamName").writeValue(
                        getLogEventsRequest.getLogStreamName());
            }
            if (getLogEventsRequest.getStartTime() != null) {
                jsonGenerator.writeFieldName("startTime").writeValue(
                        getLogEventsRequest.getStartTime());
            }
            if (getLogEventsRequest.getEndTime() != null) {
                jsonGenerator.writeFieldName("endTime").writeValue(
                        getLogEventsRequest.getEndTime());
            }
            if (getLogEventsRequest.getNextToken() != null) {
                jsonGenerator.writeFieldName("nextToken").writeValue(
                        getLogEventsRequest.getNextToken());
            }
            if (getLogEventsRequest.getLimit() != null) {
                jsonGenerator.writeFieldName("limit").writeValue(
                        getLogEventsRequest.getLimit());
            }
            if (getLogEventsRequest.getStartFromHead() != null) {
                jsonGenerator.writeFieldName("startFromHead").writeValue(
                        getLogEventsRequest.getStartFromHead());
            }

            jsonGenerator.writeEndObject();

            byte[] content = jsonGenerator.getBytes();
            request.setContent(new ByteArrayInputStream(content));
            request.addHeader("Content-Length",
                    Integer.toString(content.length));
            request.addHeader("Content-Type", jsonGenerator.getContentType());
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }

        return request;
    }

}


text:
@interface NSObject @end
@interface XX : NSObject @end

@implementation XX
- (void)encodeValuesOfObjCTypes:(const char *)types, ... {
   va_list ap;
   va_start(ap, types);
   while (*types) ;
   va_end(ap);
}

@end


text:
<?php

namespace Application\Model;

use Application\Lib\Api;
use Application\Lib\Cache;
use Application\Lib\Arr;
use Application\Lib\Auth;

class Pages
{

    public static function removeCache($_id)
    {
        $key = PAGE_DETAIL . $_id;
        Cache::remove($key);
    }

    public static function getDetail($pageId = null)
    {

    }

}


text:
using UnityEngine;

namespace Leap.Unity.Interaction {

  /**
  * IMoveToController defines the interface used by the Interaction Engine
  * to move an object from its current position and orientation
  * to a target position and orientation.
  *
  * The Interaction Engine provides the MoveToControllerKinematic and MoveToControllerVelocity
  * implementations for this controller.
  * @since 4.1.4
  */
  public abstract class IMoveToController : IControllerBase {

    /**
    * Move the interactable object to or towards the Interaction Engine's desired position.
    *
    * If info.shouldTeleport is true, this function must move the object using a teleport-style
    * movement, ie.e by changing the transform.position and transform.rotation, or the
    * RigidBody.position and RigidBody.rotation properties directly. InteractionBehaviour.NotifyTeleport() does
    * not be called in MoveTo().
    *
    * If info.shouldTeleport is false, this function must move the object using linear and angular
    * forces and velocities.
    *
    * @param hands the list of Leap.Hand objects involved in the interaction.
    * @param info hints about the move.
    * @param solvedPosition the target position calculated by the Interaction Engine.
    * @param solvedRotation the target rotation calculated by the Interaction Engine.
    * @since 4.1.4
    */
    public abstract void MoveTo(ReadonlyList<Hand> hands, PhysicsMoveInfo info, Vector3 solvedPosition, Quaternion solvedRotation);
    /**
    * Set the object to a state appropriate for being held in a hand.
    * @since 4.1.4
    */
    public abstract void SetGraspedState();
    /**
    * Called when the object is grasped by a hand.
    *
    * You should only change the following properties in this method:
    *
    * * InteractionBehavior.IsKinematic
    * * InteractionBehavior.UseGravity
    * * RigidBody.drag
    * * RigidBody.angularDrag
    *
    * These properties are automatically restored when the object leaves the grabbed state.
    * @since 4.1.4
    */
    public abstract void OnGraspBegin();
    /**
    * Called when the object is released by all hands.
    * @since 4.1.4
    */
    public abstract void OnGraspEnd();
  }

  /**
  * Provides hints for moving an interactable object that is being held.
  */
  public struct PhysicsMoveInfo {
    /** Whether you should move the object by changing its Transform.position property. */
    public bool shouldTeleport;
    /** The distance between the object's final position and its target position in the
    previous Unity frame. */
    public float remainingDistanceLastFrame;
  }
}


text:
/* -*- Mode: js2; indent-tabs-mode: nil; tab-width: 4; js2-indent-offset: 4; js2-basic-offset: 4; -*-
 * vim: set ts=4 sw=4 et tw=99 ft=js:
 */

import { reportError } from "../errors";
import { TransformPass } from "../node-visitor";
import { getNewTarget_id } from "../common-ids";
import { intrinsic } from "../echo-util";
import * as b from "../ast-builder";

export class DesugarMetaProperties extends TransformPass {
    visitAssignmentExpression(n) {
        if (n.left.type === b.MetaProperty)
            reportError(
                SyntaxError,
                `'${n.left.meta}.${n.left.property}' not permitted on left hand side of assignment`,
                this.filename,
                n.left.loc
            );
        return super.visitAssignmentExpression(n);
    }

    visitMetaProperty(n) {
        if (n.meta === "new" && n.property === "target") return intrinsic(getNewTarget_id, []);
        reportError(
            SyntaxError,
            `unknown meta property '${n.meta}.${n.property}'`,
            this.filename,
            n.loc
        );
    }
}


text:
var FCKToolbarSpecialCombo = function()
{
	this.SourceView			= false ;
	this.ContextSensitive	= true ;
}

function FCKToolbarSpecialCombo_OnSelect( itemId, item )
{
	this.Command.Execute( itemId, item ) ;
}

FCKToolbarSpecialCombo.prototype.CreateInstance = function( parentToolbar )
{
	this._Combo = new FCKSpecialCombo( this.GetLabel() ) ;
	this._Combo.FieldWidth = 100 ;
	this._Combo.PanelWidth = 150 ;
	this._Combo.PanelMaxHeight = 150 ;

	this.CreateItems( this._Combo ) ;

	this._Combo.Create( parentToolbar.DOMRow.insertCell(-1) ) ;

	this._Combo.Command = this.Command ;

	this._Combo.OnSelect = FCKToolbarSpecialCombo_OnSelect ;
}

function FCKToolbarSpecialCombo_RefreshActiveItems( combo, value )
{
	combo.DeselectAll() ;
	combo.SelectItem( value ) ;
	combo.SetLabelById( value ) ;
}

FCKToolbarSpecialCombo.prototype.RefreshState = function()
{
	// Gets the actual state.
	var eState ;

//	if ( FCK.EditMode == FCK_EDITMODE_SOURCE && ! this.SourceView )
//		eState = FCK_TRISTATE_DISABLED ;
//	else
//	{
		var sValue = this.Command.GetState() ;

		if ( sValue != FCK_TRISTATE_DISABLED )
		{
			eState = FCK_TRISTATE_ON ;

			if ( this.RefreshActiveItems )
				this.RefreshActiveItems( this._Combo, sValue ) ;
			else
				FCKToolbarSpecialCombo_RefreshActiveItems( this._Combo, sValue ) ;
		}
		else
			eState = FCK_TRISTATE_DISABLED ;
//	}

	// If there are no state changes then do nothing and return.
	if ( eState == this.State ) return ;

	if ( eState == FCK_TRISTATE_DISABLED )
	{
		this._Combo.DeselectAll() ;
		this._Combo.SetLabel( '' ) ;
	}

	// Sets the actual state.
	this.State = eState ;

	// Updates the graphical state.
	this._Combo.SetEnabled( eState != FCK_TRISTATE_DISABLED ) ;
}

FCKToolbarSpecialCombo.prototype.Enable = function()
{
	this.RefreshState() ;
}

FCKToolbarSpecialCombo.prototype.Disable = function()
{
	this.State = FCK_TRISTATE_DISABLED ;
	this._Combo.DeselectAll() ;
	this._Combo.SetLabel( '' ) ;
	this._Combo.SetEnabled( false ) ;
}


text:
<?php

declare(strict_types=1);

namespace MarcusJaschen\Collmex\Tests\Unit\Type;

use MarcusJaschen\Collmex\Type\AbstractType;
use MarcusJaschen\Collmex\Type\AccountBalance;
use MarcusJaschen\Collmex\Type\TypeInterface;
use PHPUnit\Framework\TestCase;

class AccountBalanceTest extends TestCase
{
    /**
     * @test
     */
    public function isAbstractType(): void
    {
        $subject = new AccountBalance([]);

        self::assertInstanceOf(AbstractType::class, $subject);
    }

    /**
     * @test
     */
    public function implementsTypeInterface(): void
    {
        $subject = new AccountBalance([]);

        self::assertInstanceOf(TypeInterface::class, $subject);
    }
}


text:
const selectorsPattern = /(?:^|\})?\s*([^\{\}]+)\s*\{/g;
const commentsPattern = /\/\*.*?\*\//g;
const selectorUnitPattern = /((?:(?:\[[^\]+]\])|(?:[^\s\+\>\~:]))+)((?::[^\s\+\>\~\(]+(?:\([^\)]+\))?)?\s*[\s\+\>\~]?)\s*/g;
const mediaQueryPattern = /^@media/;
const dataRvcGuidPattern = /\[data-ractive-css~="\{[a-z0-9-]+\}"]/g;

function trim ( str ) {
	return str.trim();
}

function extractString ( unit ) {
	return unit.str;
}

function transformSelector ( selector, parent ) {
	let selectorUnits = [];
	let match;

	while ( match = selectorUnitPattern.exec( selector ) ) {
		selectorUnits.push({
			str: match[0],
			base: match[1],
			modifiers: match[2]
		});
	}

	// For each simple selector within the selector, we need to create a version
	// that a) combines with the id, and b) is inside the id
	const base = selectorUnits.map( extractString );

	let transformed = [];
	let i = selectorUnits.length;

	while ( i-- ) {
		let appended = base.slice();

		// Pseudo-selectors should go after the attribute selector
		const unit = selectorUnits[i];
		appended[i] = unit.base + parent + unit.modifiers || '';

		let prepended = base.slice();
		prepended[i] = parent + ' ' + prepended[i];

		transformed.push( appended.join( ' ' ), prepended.join( ' ' ) );
	}

	return transformed.join( ', ' );
}

export default function transformCss ( css, id ) {
	const dataAttr = `[data-ractive-css~="{${id}}"]`;

	let transformed;

	if ( dataRvcGuidPattern.test( css ) ) {
		transformed = css.replace( dataRvcGuidPattern, dataAttr );
	} else {
		transformed = css
		.replace( commentsPattern, '' )
		.replace( selectorsPattern, ( match, $1 ) => {
			// don't transform media queries!
			if ( mediaQueryPattern.test( $1 ) ) return match;

			const selectors = $1.split( ',' ).map( trim );
			const transformed = selectors
				.map( selector => transformSelector( selector, dataAttr ) )
				.join( ', ' ) + ' ';

			return match.replace( $1, transformed );
		});
	}

	return transformed;
}


text:
package main // import "go-hep.org/x/hep/groot/cmd/root-srv"

import (
	"crypto/tls"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"

	"golang.org/x/crypto/acme/autocert"
)

var (
	addrFlag = flag.String("addr", ":8080", "server address:port")
	servFlag = flag.String("serv", "http", "server protocol")
	hostFlag = flag.String("host", "", "server domain name for TLS ")
)

func main() {
	flag.Usage = func() {
		fmt.Fprintf(
			os.Stderr,
			`Usage: root-srv [options]

ex:

 $> root-srv -addr :8080 -serv https -host example.com
 2017/04/06 15:13:59 https server listening on :8080 at example.com

options:
`,
		)
		flag.PrintDefaults()
	}

	flag.Parse()

	log.SetPrefix("root-srv: ")
	log.SetFlags(0)

	dir, err := os.MkdirTemp("", "groot-rsrv-")
	if err != nil {
		log.Panicf("could not create temporary directory: %v", err)
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)

	run(dir, c)
}

func run(dir string, c chan os.Signal) {
	defer func() {
		log.Printf("shutdown sequence...")
		os.RemoveAll(dir)
	}()

	log.Printf("%s server listening on %s", *servFlag, *addrFlag)

	srv := newServer(*hostFlag == "", dir, http.DefaultServeMux)
	defer srv.Shutdown()

	go func() {
		if *servFlag == "http" {
			log.Fatal(http.ListenAndServe(*addrFlag, nil))
		} else if *servFlag == "https" {
			m := autocert.Manager{
				Prompt:     autocert.AcceptTOS,
				HostPolicy: autocert.HostWhitelist(*hostFlag),
				Cache:      autocert.DirCache("certs"), //folder for storing certificates
			}
			server := &http.Server{
				Addr: *addrFlag,
				TLSConfig: &tls.Config{
					GetCertificate: m.GetCertificate,
				},
			}
			log.Fatal(server.ListenAndServeTLS("", ""))
		}
	}()
	<-c
}


text:
angular.module('picka', [])

  .directive('picka', function() {
    return {
      restrict: 'E',
      require: 'ngModel',
      scope: {},
      link: function(scope, element, attrs, ngModel) {
        ngModel.$viewChangeListeners.push(function() {
          scope.$eval(attrs.ngChange);
        })

        ngModel.$render = function() {
          scope.date = ngModel.$modelValue
        }

        function getDate() {
          return scope.date ? scope.date : (scope.date = new Date())
        }

        Object.defineProperty(scope, 'year', {
          get: function() { if (scope.date) return scope.date.getFullYear() },
          set: function(v) { if (angular.isNumber(v)) ngModel.$setViewValue(new Date(getDate().setFullYear(v))) },
        })

        Object.defineProperty(scope, 'month', {
          get: function() { if (scope.date) return scope.date.getMonth() + 1 },
          set: function(v) { if (angular.isNumber(v)) ngModel.$setViewValue(new Date(getDate().setMonth(v - 1))) },
        })

        Object.defineProperty(scope, 'day', {
          get: function() { if (scope.date) return scope.date.getDate() },
          set: function(v) { if (angular.isNumber(v)) ngModel.$setViewValue(new Date(getDate().setDate(v))) },
        })

        Object.defineProperty(scope, 'hour', {
          get: function() { if (scope.date) return scope.date.getHours() },
          set: function(v) { if (angular.isNumber(v)) ngModel.$setViewValue(new Date(getDate().setHours(v))) },
        })

        Object.defineProperty(scope, 'minute', {
          get: function() { if (scope.date) return scope.date.getMinutes() },
          set: function(v) { if (angular.isNumber(v)) ngModel.$setViewValue(new Date(getDate().setMinutes(v))) },
        })

        scope.now = function() {
          ngModel.$setViewValue(scope.date = new Date())
        }

        scope.today = function() {
          var d = new Date()
          d = new Date(d.getFullYear(), d.getMonth(), d.getDate())
          ngModel.$setViewValue(scope.date = d)
        }

        scope.clear = function() {
          ngModel.$setViewValue(scope.date = undefined)
        }
      },
      // templateUrl: 'picka.html'
      template: function(tElem, tAttrs) {
        var format = angular.isString(tAttrs.format) ? tAttrs.format : '%Y / %M / %D - %h : %m %t %n %c'
        var template = ''
        var rx = /%./g
        var matches = []
        var match

        while (match = rx.exec(format))
          matches.push(match)

        var fillIndex = 0

        for (var match of matches) {
          var expr = match[0]
          var fillLength = match.index - fillIndex
          template += format.substr(fillIndex, fillLength)

          switch(expr.substr(1)) {
            case 'Y': {
              template += '<input type="number" class="picka-comp picka-comp-year" ng-model="year">'
              break
            }
            case 'M': {
              template += '<input type="number" class="picka-comp picka-comp-month" ng-model="month">'
              break
            }
            case 'D': {
              template += '<input type="number" class="picka-comp picka-comp-day" ng-model="day">'
              break
            }
            case 'h': {
              template += '<input type="number" class="picka-comp picka-comp-hour" ng-model="hour">'
              break
            }
            case 'm': {
              template += '<input type="number" class="picka-comp picka-comp-minute" ng-model="minute">'
              break
            }
            case 'n': {
              template += '<button class="btn btn-xs btn-default" ng-click="now()">now</button>'
              break
            }
            case 't': {
              template += '<button class="btn btn-xs btn-default" ng-click="today()">today</button>'
              break
            }
            case 'c': {
              template += '<button class="btn btn-xs btn-default" ng-click="clear()">✕</button>'
              break
            }
          }

          fillIndex = match.index + expr.length
        }

        template += format.substr(fillIndex)

        tElem.addClass('picka')
        tElem.append(template)
      }
    }
  })


text:
require 'git_bpf/lib/gitflow'
require 'git_bpf/lib/git-helpers'

#
# recreate_branch: Recreate a branch based on the merge commits it's comprised of.
#
class RecreateBranch < GitFlow/'recreate-branch'

  include GitHelpersMixin

  @@prefix = "BRANCH-PER-FEATURE-PREFIX"

  @documentation = "Recreates the source branch in place or as a new branch by re-merging all of the merge commits."

  def options(opts)
    opts.base = 'master'
    opts.exclude = []
    opts.whitelist_file_name = ''

    [
      ['-a', '--base NAME',
        "A reference to the commit from which the source branch is based, defaults to #{opts.base}.",
        lambda { |n| opts.base = n }],
        ['-b', '--branch NAME',
          "Instead of deleting the source branch and replacng it with a new branch of the same name, leave the source branch and create a new branch called NAME.",
          lambda { |n| opts.branch = n }],
          ['-x', '--exclude NAME',
            "Specify a list of branches to be excluded.",
            lambda { |n| opts.exclude.push(n) }],
            ['-l', '--list',
              "Process source branch for merge commits and list them. Will not make any changes to any branches.",
              lambda { |n| opts.list = true }],
              ['-d', '--discard',
                "Discard the existing local source branch and checkout a new source branch from the remote if one exists. If no remote is specified with -r, gitbpf will use the configured remote, or origin if none is configured.",
                lambda { |n| opts.discard = true }],
                ['-r', '--remote NAME',
                  "Specify the remote repository to work with. Only works with the -d option.",
                  lambda { |n| opts.remote = n }],
                  ['-w', '--whitelist-file-name NAME',
                   "Specify the white list file of a carriage-return delimited list of branch names to whitelist.",
                   lambda { |n| opts.whitelist_file_name = n }],
                 ]
               end

               def execute(opts, argv)
                if argv.length != 1
                  run('recreate-branch', '--help')
                  terminate
                end

                source = argv.pop

    # If no new branch name provided, replace the source branch.
    opts.branch = source if opts.branch == nil

    if not refExists? opts.base
      terminate "Cannot find reference '#{opts.base}' to use as a base for new branch: #{opts.branch}."
    end

    if opts.discard
      unless opts.remote
        repo = Repository.new(Dir.getwd)
        remote_name = repo.config(true, "--get", "gitbpf.remotename").chomp
        opts.remote = remote_name.empty? ? 'origin' : remote_name
      end
      git('fetch', opts.remote)
      if branchExists?(source, opts.remote)
        opoo "This will delete your local '#{source}' branch if it exists and create it afresh from the #{opts.remote} remote."
        if not promptYN "Continue?"
          terminate "Aborting."
        end
        git('checkout', opts.base)
        git('branch', '-D', source) if branchExists? source
        git('checkout', source)
      end
    end

    # Perform some validation.
    if not branchExists? source
      terminate "Cannot recreate branch #{source} as it doesn't exist."
    end

    if opts.branch != source and branchExists? opts.branch
      terminate "Cannot create branch #{opts.branch} as it already exists."
    end

    #
    # 1. Compile a list of merged branches from source branch.
    #
    ohai "1. Processing branch '#{source}' for merge-commits..."

    branches = opts.whitelist_file_name.length > 0 ? getWhiteListBranches(opts.whitelist_file_name) : getMergedBranches(opts.base, source)

    if branches.empty?
      terminate "No feature branches detected, '#{source}' matches '#{opts.base}'."
    end

    if opts.list
      terminate "Branches to be merged:\n#{branches.shell_list}"
    end

    # Remove from the list any branches that have been explicity excluded using
    # the -x option
    branches.reject! do |item|
      stripped = item.gsub /^remotes\/\w+\/([\w\-\/]+)$/, '\1'
      opts.exclude.include? stripped
    end

    # Prompt to continue.
    opoo "The following branches will be merged when the new #{opts.branch} branch is created:\n#{branches.shell_list}"
    puts
    puts "If you see something unexpected check:"
    puts "a) that your '#{source}' branch is up to date"
puts "b) if '#{opts.base}' is a branch, make sure it is also up to date."
opoo "If there are any non-merge commits in '#{source}', they will not be included in '#{opts.branch}'. You have been warned."
if not promptYN "Proceed with #{source} branch recreation?"
  terminate "Aborting."
end

    #
    # 2. Backup existing local source branch.
    #
    tmp_source = "#{@@prefix}-#{source}"
    ohai "2. Creating backup of '#{source}', '#{tmp_source}'..."

    if branchExists? tmp_source
      terminate "Cannot create branch #{tmp_source} as one already exists. To continue, #{tmp_source} must be removed."
    end

    git('branch', '-m', source, tmp_source)

    #
    # 3. Create new branch based on 'base'.
    #
    ohai "3. Creating new '#{opts.branch}' branch based on '#{opts.base}'..."

    git('checkout', '-b', opts.branch, opts.base, '--quiet')

    #
    # 4. Begin merging in feature branches.
    #
    ohai "4. Merging in feature branches..."

    branches.each do |branch|
      begin
        puts " - '#{branch}'"
        # Attempt to merge in the branch. If there is no conflict at all, we
        # just move on to the next one.
        git('merge', '--quiet', '--no-ff', '--no-edit', branch)
      rescue
        # There was a conflict. If there's no available rerere for it then it is
        # unresolved and we need to abort as there's nothing that can be done
        # automatically.
        conflicts = git('rerere', 'status').chomp.split("\n")

        if conflicts.length != 0
          puts "\n"
          puts "There is a merge conflict with branch #{branch} that has no rerere."
          puts "Record a resoloution by resolving the conflict."
          puts "Then run the following command to return your repository to its original state."
          puts "\n"
          puts "git checkout #{tmp_source} && git branch -D #{opts.branch} && git branch -m #{opts.branch}"
          puts "\n"
          puts "If you do not want to resolve the conflict, it is safe to just run the above command to restore your repository to the state it was in before executing this command."
          terminate
        else
          # Otherwise, we have a rerere and the changes have been staged, so we
          # just need to commit.
          git('commit', '-a', '--no-edit')
        end
      end
    end

    #
    # 5. Clean up.
    #
    ohai "5. Cleaning up temporary branches ('#{tmp_source}')."

    if source != opts.branch
      git('branch', '-m', tmp_source, source)
    else
      git('branch', '-D', tmp_source)
    end
  end

  def getWhiteListBranches(file)
    branches = []
    File.open(file, "r") do |file_handle|
     file_handle.each_line do |branch|
       name = branch.strip
       branches.push name unless branches.include? name
     end
   end
   return branches
 end

 def getMergedBranches(base, source)
  branches = []
  merges = git('rev-list', '--parents', '--merges', '--reverse', "#{base}...#{source}").strip

  merges.split("\n").each do |commits|
    parents = commits.split("\s")
    commit = parents.shift

    parents.each do |parent|
      name = git('name-rev', parent, '--name-only').strip
      alt_base = git('name-rev', base, '--name-only').strip
      remote_heads = /remote\/\w+\/HEAD/
      unless name.include? source or name.include? alt_base or name.match remote_heads
          # Make sure not to include the tilde part of a branch name (e.g. '~2')
          # as this signifies a commit that's behind the head of the branch but
          # we want to merge in the head of the branch.
          name = name.partition('~')[0]
          # This can lead to duplicate branches, because the name may have only
          # differed in the tilde portion ('mybranch~1', 'mybranch~2', etc.)
          branches.push name unless branches.include? name
        end
      end
    end

    return branches
  end
end


text:
enum interrupt_state_e
{
	INTERRUPT_ENABLE = 0,
	INTERRUPT_DISABLE
};

void interrupt_init();
void interrupt_set_state(enum interrupt_state_e state);

#endif  //  !__INTERRUPT_H__


text:
<?xml version="1.0"?>
<!DOCTYPE service_bundle SYSTEM "/usr/share/lib/xml/dtd/service_bundle.dtd.1">
<service_bundle type="manifest" name="syncthing">
	<service name="site/syncthing" type="service" version="1">
		<create_default_instance enabled="true"/>
		<single_instance/>

		<dependency name="network" grouping="require_all" restart_on="error" type="service">
			<service_fmri value="svc:/milestone/network:default"/>
		</dependency>

		<dependency name="filesystem" grouping="require_all" restart_on="error" type="service">
			<service_fmri value="svc:/system/filesystem/local"/>
		</dependency>

		<method_context>
			<method_credential user="jb" group="other"/>
		</method_context>

		<exec_method type="method" name="start" exec="/home/jb/bin/syncthing" timeout_seconds="60">
			<method_context>
				<method_environment>
                    <envvar name="HOME" value="/home/jb"/>
					<envvar name="STNORESTART" value="1"/>
				</method_environment>
			</method_context>
		</exec_method>
		<exec_method type="method" name="stop" exec=":kill" timeout_seconds="60"/>

		<property_group name="startd" type="framework">
			<propval name="duration" type="astring" value="child"/>
			<propval name="ignore_error" type="astring" value="core,signal"/>
		</property_group>

		<property_group name="application" type="application">
		</property_group>

		<stability value="Evolving"/>

		<template>
			<common_name>
				<loctext xml:lang="C">
					Syncthing
				</loctext>
			</common_name>
		</template>
	</service>
</service_bundle>