text:
import {expect} from "chai"

import * as p from "@bokehjs/core/properties"
import * as enums from "@bokehjs/core/enums"

import {HasProps} from  "@bokehjs/core/has_props"
import {ColumnDataSource} from "@bokehjs/models/sources/column_data_source"
import {svg_colors} from  "@bokehjs/core/util/svg_colors"
import {Transform} from  "@bokehjs/models/transforms/transform"
import {Expression} from  "@bokehjs/models/expressions/expression"

class MyProperty extends p.Property<unknown> {}

class TestTransform extends Transform {
  compute(x: number): number {
    return x+1
  }
  v_compute(xs: number[]): number[] {
    const ret =  []
    for (let i=0; i<xs.length; i++)
      ret.push(xs[i]+i)
    return ret
  }
}

class TestExpression extends Expression {
  _v_compute(source: ColumnDataSource): number[] {
    const ret = []
    for (let i=0; i<source.get_length()!; i++)
      ret.push(i)
    return ret
  }
}

class SomeHasProps extends HasProps {
  a: any
  b: any
}
SomeHasProps.define<any>({
  a: [ p.Any ],
  b: [ p.Any ],
})

class SomeSpecHasProps extends HasProps {
  a: any
  b: any
}
SomeSpecHasProps.define<any>({
  a: [ p.NumberSpec ],
  b: [ p.Any ],
})

class DataSpecProperty extends p.DataSpec<number> {}

describe("properties module", () => {

  function validation_error(prop: any, x: any): void {
    function fn(): void {
      prop.validate(x)
    }
    expect(fn).to.throw(Error, /given invalid value/)
  }

  function enum_validation_errors(prop: any): void {
    validation_error(prop, true)
    validation_error(prop, 10)
    validation_error(prop, 10.2)
    validation_error(prop, "foo")
    validation_error(prop, {})
    validation_error(prop, [])
    validation_error(prop, null)
    validation_error(prop, undefined)
    validation_error(prop, new SomeHasProps())
  }

  const fixed            = {a: 1}
  const spec_expr        = {a: {expr: new TestExpression()}}
  const spec_field       = {a: {field: 'foo'}, b: 30}
  const spec_field_only  = {a: {field: 'foo'}}
  const spec_field_trans = {a: {field: 'foo', transform: new TestTransform()}}
  const spec_value       = {a: {value: 2}}
  const spec_value_trans = {a: {value: 2, transform: new TestTransform()}}
  const spec_value_null  = {a: {value: null}}

  describe("isSpec", () => {

    it("should identify field specs", () => {
      expect(p.isSpec({field: "foo"})).to.be.true
      expect(p.isSpec({field: "field"})).to.be.true // check corner case
    })

    it("should identify value specs", () => {
      expect(p.isSpec({value: "foo"})).to.be.true
    })

    it("should identify expr specs", () => {
      expect(p.isSpec({expr: "foo"})).to.be.true
    })

    it("should reject non-specs", () => {
      expect(p.isSpec(1)).to.be.false
      expect(p.isSpec({})).to.be.false
      expect(p.isSpec([])).to.be.false
      expect(p.isSpec(null)).to.be.false
      expect(p.isSpec(undefined)).to.be.false
    })

    it("should reject bad specs", () => {
      expect(p.isSpec({expr: "foo", value:"bar"})).to.be.false
      expect(p.isSpec({expr: "foo", field:"bar"})).to.be.false
      expect(p.isSpec({field: "foo", value:"bar"})).to.be.false
      expect(p.isSpec({field: "foo", value:"bar", expr: "baz"})).to.be.false
    })
  })

  describe("Property", () => {

    describe("construction", () => {

      it("should set undefined property attr value to null if no default is given", () => {
        const obj = new SomeHasProps({a: {}})
        new MyProperty(obj, 'b')
        expect(obj.b).to.be.null
      })

      // it("should set undefined property attr value if a default is given", () => {
      //   const obj = new SomeHasProps({a: {}})
      //   new MyProperty(obj, 'b', function(): number { return 10 } )
      //   expect(obj.b).to.be.equal(10)
      // })

      // it("should throw an Error for missing specifications", () => {
      //   function fn(): void {
      //     new MyProperty(new SomeHasProps({a: {}}), 'a')
      //   }
      //   expect(fn).to.throw(Error, /^Invalid property specifier .*, must have exactly one of/)
      // })

      // it("should throw an Error for too many specifications", () => {
      //   function fn(): void {
      //     new MyProperty(new SomeHasProps({a: {field: "foo", value:"bar"}}), 'a')
      //   }
      //   expect(fn).to.throw(Error, /^Invalid property specifier .*, must have exactly one of/)
      // })

      /*
      it("should throw an Error if a field spec is not a string", () => {
        function fn(): void {
          new MyProperty(new SomeSpecHasProps({a: {field: 10}}), 'a')
        }
        expect(fn).to.throw(Error, /^field value for property '.*' is not a string$/)
      })
      */

      it("should set a spec for object attr values", () => {
        const p1 = new MyProperty(new SomeHasProps({a: {field: "foo"}}), 'a')
        expect(p1.spec).to.be.deep.equal({field: "foo"})
        const p2 = new MyProperty(new SomeHasProps({a: {value: "foo"}}), 'a')
        expect(p2.spec).to.be.deep.equal({value: "foo"})
      })

      it("should set a value spec for non-object attr values", () => {
        const prop = new MyProperty(new SomeHasProps({a: 10}), 'a')
        expect(prop.spec).to.be.deep.equal({value: 10})
      })
    })

    describe("value", () => {
      it("should return a value if there is a value spec", () => {
        const p1 = new MyProperty(new SomeHasProps(fixed), 'a')
        expect(p1.value()).to.be.equal(1)
        const p2 = new MyProperty(new SomeHasProps(spec_value), 'a')
        expect(p2.value()).to.be.equal(2)
      })

      it("should return a transformed value if there is a value spec with transform", () => {
        const prop = new MyProperty(new SomeHasProps(spec_value_trans), 'a')
        expect(prop.value()).to.be.equal(3)
      })

      it("should allow a fixed null value", () => {
        const prop = new MyProperty(new SomeHasProps(spec_value_null), 'a')
        expect(prop.value()).to.be.null
      })

      it("should throw an Error otherwise", () => {
        function fn(): void {
          const prop = new MyProperty(new SomeHasProps(spec_field_only), 'a')
          prop.value()
        }
        expect(fn).to.throw(Error, "attempted to retrieve property value for property without value specification")
      })
    })

    describe("array", () => {

      it("should return an array if there is a value spec", () => {
        const source = new ColumnDataSource({data: {foo: [0, 1, 2, 3, 10]}})
        const p1 = new DataSpecProperty(new SomeSpecHasProps(fixed), 'a')
        const arr1 = p1.array(source)
        expect(arr1).to.be.instanceof(Array)
        expect(arr1.length).to.be.equal(5)
        expect(arr1[0]).to.be.equal(1)
        expect(arr1[1]).to.be.equal(1)
        expect(arr1[2]).to.be.equal(1)
        expect(arr1[3]).to.be.equal(1)
        expect(arr1[4]).to.be.equal(1)

        const p2 = new DataSpecProperty(new SomeSpecHasProps(spec_value), 'a')
        const arr2 = p2.array(source)
        expect(arr2).to.be.instanceof(Array)
        expect(arr2.length).to.be.equal(5)
        expect(arr2[0]).to.be.equal(2)
        expect(arr2[1]).to.be.equal(2)
        expect(arr2[2]).to.be.equal(2)
        expect(arr2[3]).to.be.equal(2)
        expect(arr2[4]).to.be.equal(2)
      })

      it("should return an array if there is a valid expr spec", () => {
        const source = new ColumnDataSource({data: {foo: [0, 1, 2, 3, 10]}})
        const prop = new DataSpecProperty(new SomeSpecHasProps(spec_expr), 'a')
        const arr = prop.array(source)
        expect(arr).to.be.instanceof(Array)
        expect(arr.length).to.be.equal(5)
        expect(arr[0]).to.be.equal(0)
        expect(arr[1]).to.be.equal(1)
        expect(arr[2]).to.be.equal(2)
        expect(arr[3]).to.be.equal(3)
        expect(arr[4]).to.be.equal(4)
      })

      it("should return an array if there is a valid field spec", () => {
        const source = new ColumnDataSource({data: {foo: [0, 1, 2, 3, 10]}})
        const prop = new DataSpecProperty(new SomeSpecHasProps(spec_field), 'a')
        const arr = prop.array(source)
        expect(arr).to.be.instanceof(Array)
        expect(arr.length).to.be.equal(5)
        expect(arr[0]).to.be.equal(0)
        expect(arr[1]).to.be.equal(1)
        expect(arr[2]).to.be.equal(2)
        expect(arr[3]).to.be.equal(3)
        expect(arr[4]).to.be.equal(10)
      })

      it("should return an array if there is a valid field spec named 'field'", () => {
        const source = new ColumnDataSource({data: {field: [0, 1, 2, 3, 10]}})
        const prop = new DataSpecProperty(new SomeSpecHasProps({a: {field: 'field'}, b: 30}), 'a')
        const arr = prop.array(source)
        expect(arr).to.be.instanceof(Array)
        expect(arr.length).to.be.equal(5)
        expect(arr[0]).to.be.equal(0)
        expect(arr[1]).to.be.equal(1)
        expect(arr[2]).to.be.equal(2)
        expect(arr[3]).to.be.equal(3)
        expect(arr[4]).to.be.equal(10)
      })

      it("should throw an Error otherwise", () => {
        function fn(): void {
          const source = new ColumnDataSource({data: {}})
          const prop = new DataSpecProperty(new SomeSpecHasProps(spec_field), 'a')
          prop.array(source)
        }
        expect(fn).to.throw(Error, /attempted to retrieve property array for nonexistent field 'foo'/)
      })

      it("should apply a spec transform to a field", () => {
        const source = new ColumnDataSource({data: {foo: [0, 1, 2, 3, 10]}})
        const prop = new DataSpecProperty(new SomeSpecHasProps(spec_field_trans), 'a')
        const arr = prop.array(source)
        expect(arr).to.be.instanceof(Array)
        expect(arr.length).to.be.equal(5)
        expect(arr[0]).to.be.equal(0)
        expect(arr[1]).to.be.equal(2)
        expect(arr[2]).to.be.equal(4)
        expect(arr[3]).to.be.equal(6)
        expect(arr[4]).to.be.equal(14)
      })

      it("should apply a spec transform to a value array", () => {
        const source = new ColumnDataSource({data: {foo: [0, 1, 2, 3, 10]}})
        const prop = new DataSpecProperty(new SomeSpecHasProps(spec_value_trans), 'a')
        const arr = prop.array(source)
        expect(arr).to.be.instanceof(Array)
        expect(arr.length).to.be.equal(5)
        expect(arr[0]).to.be.equal(2)
        expect(arr[1]).to.be.equal(3)
        expect(arr[2]).to.be.equal(4)
        expect(arr[3]).to.be.equal(5)
        expect(arr[4]).to.be.equal(6)
      })

      describe("init", () => {
        it("should return nothing by default", () => {
          const prop = new MyProperty(new SomeHasProps({a: {value: "foo"}}), 'a')
          expect(prop.init()).to.be.undefined
        })
      })

      describe("transform", () => {
        it("should be the identity", () => {
          expect(p.Property.prototype.transform(10)).to.be.equal(10)
          expect(p.Property.prototype.transform("foo")).to.be.equal("foo")
          expect(p.Property.prototype.transform(null)).to.be.null
        })

        it("should return the same type as passed", () => {
          const r1 = p.Number.prototype.transform([10, 20, 30])
          expect(r1).to.be.deep.equal([10, 20, 30])
          const r2 = p.Number.prototype.transform(new Float64Array([10, 20, 30]))
          expect(r2).to.be.deep.equal(new Float64Array([10, 20, 30]))
        })
      })

      describe("validate", () => {
        it("should return nothing by default", () => {
          const prop = new MyProperty(new SomeHasProps({a: {value: "foo"}}), 'a')
          expect(prop.validate(undefined)).to.be.undefined
          expect(prop.validate(10)).to.be.undefined
          expect(prop.validate("foo")).to.be.undefined
          expect(prop.validate(null)).to.be.undefined
        })
      })

      describe("changing the property attribute value", () => {
        it("should trigger change on the property", () => {
          const obj = new SomeHasProps({a: {value: "foo"}})
          const prop = obj.properties.a
          const stuff = {called: false}
          prop.change.connect(function fn(): void { stuff.called = true})
          obj.a = {value: "bar"}
          expect(stuff.called).to.be.true
        })
      })

      it("should update the spec", () => {
        const obj = new SomeHasProps({a: {value: "foo"}})
        const prop = obj.properties.a
        obj.a = {value: "bar"}
        expect(prop.spec).to.be.deep.equal({value: "bar"})
      })
    })
  })

  describe("Anchor", () => {
    const prop = new p.Anchor(new SomeHasProps({a: {value: "top_left"}}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {
      it("should return undefined on anchor input", () => {
        for (const x of enums.LegendLocation)
          expect(prop.validate(x)).to.be.undefined
      })

      it("should throw an Error on other input", () => {
        enum_validation_errors(prop)
      })
    })

    describe("transform", () => {
      it("should be Property.transform", () => {
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })

  describe("Any", () => {
    const prop = new p.Any(new SomeHasProps({a: {value: "top_left"}}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {
      it("should return undefined on any input", () => {
        for (const x of [true, null, undefined, 10, 10.2, "foo", [1, 2, 3], {}, new SomeHasProps()])
          expect(prop.validate(x)).to.be.undefined
      })
    })

    describe("transform", () => {
      it("should be Property.transform", () => {
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })

  describe("Angle", () => {

    describe("transform", () => {
      it("should be Property.transform", () => {
        const prop = new p.Angle(new SomeHasProps({a: {value: 10}}), 'a')
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })

  describe("AngleSpec", () => {
    describe("transform", () => {
      it("should multiply radians by -1", () => {
        const prop = new p.AngleSpec(new SomeHasProps({a: {value: 10, units: "rad"}}), 'a')
        expect(prop.transform([-10, 0, 10, 20])).to.be.deep.equal([10, -0, -10, -20])
      })

      it("should convert degrees to -1 * radians", () => {
        const prop = new p.AngleSpec(new SomeHasProps({a: {value: 10, units: "deg"}}), 'a')
        expect(prop.transform([-180, 0, 180])).to.be.deep.equal([Math.PI, -0, -Math.PI])
      })
    })
  })

  describe("Array", () => {
    const prop = new p.Array(new SomeHasProps({a: {field: "foo"}}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {
      it("should return undefined on array input", () => {
        expect(prop.validate([])).to.be.undefined
        expect(prop.validate([1, 2, 3])).to.be.undefined
        expect(prop.validate(new Float64Array([1, 2, 3]))).to.be.undefined
      })

      it("should throw an Error on non-array input", () => {
        validation_error(prop, true)
        validation_error(prop, 10)
        validation_error(prop, 10.2)
        validation_error(prop, "foo")
        validation_error(prop, {})
        validation_error(prop, null)
        validation_error(prop, undefined)
      })
    })

    describe("transform", () => {
      it("should be Property.transform", () => {
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })

  describe("Bool", () => {
    const prop = new p.Boolean(new SomeHasProps({a: {value: true}}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {

      it("should return undefined on bool input", () => {
        expect(prop.validate(true)).to.be.undefined
        expect(prop.validate(false)).to.be.undefined
      })

      it("should throw an Error on non-boolean input", () => {
        validation_error(prop, 10)
        validation_error(prop, 10.2)
        validation_error(prop, "foo")
        validation_error(prop, {})
        validation_error(prop, [])
        validation_error(prop, null)
        validation_error(prop, undefined)
      })
    })

    describe("transform", () => {
      it("should be Property.transform", () => {
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })

  describe("Color", () => {
    const prop = new p.Color(new SomeHasProps({a: {value: "#aabbccdd"}}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {

      const good_tuples = [
        "rgb(255, 0, 0)",
        "rgba(200, 0, 0, 0.5)",
        "rgba(0, 255, 0, 0)",
        "rgba(0, 0, 255, 1)",
      ]

      const bad_tuples = [
        "rgb(254.5, 0, 0)",
        "rgba(245.5, 0, 0, 0.5)",
        "rgba(255.0, 0, 0, 0.5)",
        "rgba(2550, 0, 0, 0.5)",
        "rgba(255, 0, 0, 5)",
        "rgb(255, 0, 0, 0)",
        "rgba(255, 0, 0, 0.5, 0)",
        "rgb( )",
        "rgb(a, b, c)",
      ]

      it("should return undefined on RGBa input", () => {
        expect(prop.validate("#aabbccdd")).to.be.undefined
      })

      describe("should return undefined on good integer rgb and rgba tuples", () => {
        for (const good_tuple of good_tuples) {
          it(`${good_tuple}`, () => {
            expect(prop.validate(good_tuple)).to.be.undefined
          })
        }
      })

      describe("should throw Error on tuple with bad numerical values", () => {
        for (const bad_tuple of bad_tuples) {
          it(`${bad_tuple}`, () => {
            function fn(): void {
              prop.validate(bad_tuple)
            }
            expect(fn).to.throw(Error)
          })
        }
      })

      it("should return undefined on svg color input", () => {
        for (const color in svg_colors)
          expect(prop.validate(color)).to.be.undefined
      })

      it("should throw an Error on other input", () => {
        validation_error(prop, true)
        validation_error(prop, 10)
        validation_error(prop, 10.2)
        validation_error(prop, "foo")
        validation_error(prop, {})
        validation_error(prop, [])
        validation_error(prop, null)
        validation_error(prop, undefined)
      })
    })
  })

  describe("Dimension", () => {
    const prop = new p.Dimension(new SomeHasProps({a: {value: "width"}}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {
      it("should return undefined on dimension input", () => {
        for (const x of enums.Dimension)
          expect(prop.validate(x)).to.be.undefined
      })

      it("should throw an Error on other input", () => {
        enum_validation_errors(prop)
      })
    })

    describe("transform", () => {
      it("should be Property.transform", () => {
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })

  describe("Direction", () => {
    const prop = new p.Direction(new SomeHasProps({a: {value: "clock"}}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {
      it("should return undefined on direction input", () => {
        expect(prop.validate("clock")).to.be.undefined
        expect(prop.validate("anticlock")).to.be.undefined
      })

      it("should throw an Error on other input", () => {
        enum_validation_errors(prop)
      })
    })

    describe("transform", () => {
      it("should convert 'clock' to false", () => {
        const result = prop.transform(["clock"])
        expect(result).to.be.deep.equal(new Uint8Array([0]))
      })

      it("should convert 'anticlock' to true", () => {
        const result = prop.transform(["anticlock"])
        expect(result).to.be.deep.equal(new Uint8Array([1]))
      })

      it("should return a Uint8Array", () => {
        const result = prop.transform(["clock", "anticlock"])
        expect(result).to.be.deep.equal(new Uint8Array([0, 1]))
      })
    })
  })

  describe("DistanceSpec", () => {

    describe("units", () => {
      it("should default to data units", () => {
        const prop = new p.DistanceSpec(new SomeHasProps({a: {value: 10}}), 'a')
        expect(prop.spec.units).to.be.equal("data")
      })

      it("should accept screen units", () => {
        const prop = new p.DistanceSpec(new SomeHasProps({a: {value: 10, units:"screen"}}), 'a')
        expect(prop.spec.units).to.be.equal("screen")
      })

      it("should accept data units", () => {
        const prop = new p.DistanceSpec(new SomeHasProps({a: {value: 10, units:"data"}}), 'a')
        expect(prop.spec.units).to.be.equal("data")
      })

      it("should throw an Error on bad units", () => {
        function fn(): void {
          const x = new SomeHasProps({a: {value: 10, units:"bad"}})
          new p.DistanceSpec(x, 'a')
        }
        expect(fn).to.throw(Error, "units must be one of screen, data; got: bad")
      })
    })

    describe("transform", () => {
      it("should be Property.transform", () => {
        const prop = new p.DistanceSpec(new SomeHasProps({a: {value: 10}}), 'a')
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })

  describe("Font", () => {
    const prop = new p.Font(new SomeHasProps({a: {value: "times"}}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {
      it("should return undefined on font input", () => {
        expect(prop.validate("")).to.be.undefined
        expect(prop.validate("helvetica")).to.be.undefined
      })

      it("should throw an Error on non-string input", () => {
        validation_error(prop, true)
        validation_error(prop, 10)
        validation_error(prop, 10.2)
        validation_error(prop, {})
        validation_error(prop, [])
        validation_error(prop, null)
        validation_error(prop, undefined)
      })
    })

    describe("transform", () => {
      it("should be Property.transform", () => {
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })

  describe("FontStyle", () => {
    const prop = new p.FontStyle(new SomeHasProps({a: {value: "normal"}}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {
      it("should return undefined on font style input", () => {
        for (const x of enums.FontStyle)
          expect(prop.validate(x)).to.be.undefined
      })

      it("should throw an Error on other input", () => {
        enum_validation_errors(prop)
      })
    })

    describe("transform", () => {
      it("should be Property.transform", () => {
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })

  describe("Instance", () => {
    const prop = new p.Instance(new SomeHasProps({a: null}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {
      it("should return undefined on HasProps", () => {
        expect(prop.validate(new SomeHasProps({}))).to.be.undefined
      })

      it.skip("should throw an Error on other input", () => {
        validation_error(prop, true)
        validation_error(prop, 10)
        validation_error(prop, 10.2)
        validation_error(prop, "foo")
        validation_error(prop, {})
        validation_error(prop, [])
      })
    })

    describe("transform", () => {
      it("should be Property.transform", () => {
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })

  describe("LegendLocation", () => {
    const prop = new p.LegendLocation(new SomeHasProps({a: {value: "top_left"}}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {
      it("should return undefined on legend location input", () => {
        for (const x of enums.LegendLocation)
          expect(prop.validate(x)).to.be.undefined
      })

      it("should throw an Error on other input", () => {
        enum_validation_errors(prop)
      })
    })

    describe("transform", () => {
      it("should be Property.transform", () => {
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })

  describe("LineCap", () => {
    const prop = new p.LineCap(new SomeHasProps({a: {value: "butt"}}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {
      it("should return undefined on line cap input", () => {
        for (const x of enums.LineCap)
          expect(prop.validate(x)).to.be.undefined
      })

      it("should throw an Error on other input", () => {
        enum_validation_errors(prop)
      })
    })

    describe("transform", () => {
      it("should be Property.transform", () => {
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })

  describe("LineJoin", () => {
    const prop = new p.LineJoin(new SomeHasProps({a: {value: "miter"}}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {
      it("should return undefined on line join input", () => {
        for (const x of enums.LineJoin)
          expect(prop.validate(x)).to.be.undefined
      })

      it("should throw an Error on other input", () => {
        enum_validation_errors(prop)
      })
    })

    describe("transform", () => {
      it("should be Property.transform", () => {
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })

  describe("Number", () => {
    const prop = new p.Number(new SomeHasProps({a: {value: 10}}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {
      it("should return undefined on numeric input", () => {
        expect(prop.validate(10)).to.be.undefined
        expect(prop.validate(10.2)).to.be.undefined
      })

      it("should throw an Error on non-numeric input", () => {
        // validation_error(prop, true) // XXX should this succeed?
        validation_error(prop, "foo")
        validation_error(prop, {})
        validation_error(prop, [])
        validation_error(prop, null)
        validation_error(prop, undefined)
        validation_error(prop, new SomeHasProps())
      })
    })

    describe("transform", () => {
      it("should be Property.transform", () => {
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })

  describe("Orientation", () => {
    const prop = new p.Orientation(new SomeHasProps({a: {value: "vertical"}}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {
      it("should return undefined on orientation input", () => {
        for (const x of enums.Orientation)
          expect(prop.validate(x)).to.be.undefined
      })

      it("should throw an Error on other input", () => {
        enum_validation_errors(prop)
      })
    })

    describe("transform", () => {
      it("should be Property.transform", () => {
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })

  describe("RenderLevel", () => {
    const prop = new p.RenderLevel(new SomeHasProps({a: {value: "glyph"}}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {
      it("should return undefined on render level input", () => {
        for (const x of enums.RenderLevel)
          expect(prop.validate(x)).to.be.undefined
      })

      it("should throw an Error on other input", () => {
        enum_validation_errors(prop)
      })
    })

    describe("transform", () => {
      it("should be Property.transform", () => {
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })

  describe("RenderMode", () => {
    const prop = new p.RenderMode(new SomeHasProps({a: {value: "canvas"}}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {
      it("should return undefined on render mode input", () => {
        for (const x of enums.RenderMode)
          expect(prop.validate(x)).to.be.undefined
      })

      it("should throw an Error on other input", () => {
        enum_validation_errors(prop)
      })
    })

    describe("transform", () => {
      it("should be Property.transform", () => {
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })

  describe("String", () => {
    const prop = new p.String(new SomeHasProps({a: {value: "foo"}}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {
      it("should return undefined on string input", () => {
        expect(prop.validate("")).to.be.undefined
        expect(prop.validate("foo")).to.be.undefined
        expect(prop.validate("1")).to.be.undefined
      })

      it("should throw an Error on non-string input", () => {
        validation_error(prop, true)
        validation_error(prop, 10)
        validation_error(prop, 10.2)
        validation_error(prop, {})
        validation_error(prop, [])
        validation_error(prop, null)
        validation_error(prop, undefined)
      })
    })

    describe("transform", () => {
      it("should be Property.transform", () => {
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })

  describe("TextAlign", () => {
    const prop = new p.TextAlign(new SomeHasProps({a: {value: "left"}}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {
      it("should return undefined on text align input", () => {
        for (const x of enums.TextAlign)
          expect(prop.validate(x)).to.be.undefined
      })

      it("should throw an Error on other input", () => {
        enum_validation_errors(prop)
      })
    })

    describe("transform", () => {
      it("should be Property.transform", () => {
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })

  describe("TextBaseline", () => {
    const prop = new p.TextBaseline(new SomeHasProps({a: {value: "top"}}), 'a')

    it("should be an instance of Property", () => {
      expect(prop).to.be.instanceof(p.Property)
    })

    describe("validate", () => {
      it("should return undefined on text baseline input", () => {
        for (const x of enums.TextBaseline)
          expect(prop.validate(x)).to.be.undefined
      })

      it("should throw an Error on other input", () => {
        enum_validation_errors(prop)
      })
    })

    describe("transform", () => {
      it("should be Property.transform", () => {
        expect(prop.transform).to.be.equal(p.Property.prototype.transform)
      })
    })
  })
})


text:
using Basement.BLFramework.Core.Context;
using Basement.BLFramework.Core.Factories;
using Basement.Common;

namespace Basement.BLFramework.Essential.Rewards
{
    public abstract class WrappedReward : Reward
    {
        public IReward innerReward { get; protected set; }

        protected WrappedReward(RawNode rawNode, IContext context)
            : base(rawNode, context)
        {
            innerReward = FactoryManager.Build<Reward>(rawNode.GetNode("reward"), context);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package empire

import (
	"io"
	"net/http"

	"github.com/remind101/tugboat/pkg/heroku"
)

type client struct {
	*heroku.Service
}

func newClient(c *http.Client) *client {
	if c == nil {
		c = http.DefaultClient
	}

	return &client{
		Service: heroku.NewService(c),
	}
}

func (c *client) Deploy(image string, w io.Writer) error {
	d := struct {
		Image string `json:"image"`
	}{
		Image: image,
	}

	return c.Post(w, "/deploys", &d)
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Leptothyrium angelicae P. Karst.

### Remarks
null


text:
"""
A tiny, minimal protobuf2 parser that's able to extract enough information
to be useful.
"""

import cStringIO as StringIO

def parse_protobuf(data, schema=None):
    """
    Do a simple parse of a protobuf2 given minimal type information.

    Args:
        data: a string containing the encoded protocol buffer.
        schema: a dict containing information about each field number.
            The keys are field numbers, and the values represent:
                - str: the name of the field
                - dict: schema to recursively decode an embedded message.
                        May contain a 'name' key to name the field.
    Returns:
        dict: mapping from fields to values. The fields may be strings instead of
            numbers if schema named them, and the value will *always* be
            a list of values observed for that key.
    """
    if schema is None:
        schema = {}

    buf = StringIO.StringIO(data)

    def read_varint():
        out = 0
        shift = 0
        c = 0x80
        while c & 0x80:
            c = ord(buf.read(1))
            out = out | ((c & 0x7f) << shift)
            shift += 7
        return out

    values = {}

    while buf.tell() < len(data):
        key = read_varint()
        wire_type = key & 0b111
        field_number = key >> 3
        field_name = field_number
        if wire_type == 0:
            value = read_varint()
        elif wire_type == 1:  # 64-bit
            value = buf.read(8)
        elif wire_type == 2:  # length-delim
            length = read_varint()
            value = buf.read(length)
            if isinstance(schema.get(field_number), basestring):
                field_name = schema[field_number]
            elif field_number in schema:
                # yes, I'm using dynamic features of a dynamic language.
                # pylint: disable=redefined-variable-type
                value = parse_protobuf(value, schema[field_number])
                field_name = schema[field_number].get('name', field_name)
        elif wire_type == 5:  # 32-bit
            value = buf.read(4)
        else:
            raise ValueError('unhandled wire type %d' % wire_type)
        values.setdefault(field_name, []).append(value)

    return values


text:
using System;
using System.Linq;

namespace Rounding_Numbers
{
    public class Rounding_Numbers
    {
        public static void Main()
        {
            double[] realNumbers = Console.ReadLine().Split(' ').Select(double.Parse).ToArray();

            for (int i = 0; i < realNumbers.Length; i++)
            {
                Console.WriteLine("{0} => {1}", realNumbers[i], Math.Round(realNumbers[i], MidpointRounding.AwayFromZero));
            }
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class gov.nih.nci.system.security.acegi.providers.UsernameAuthenticationToken (caCORE SDK 4.5 API Documentation)
</TITLE>

<META NAME="date" CONTENT="2013-08-06">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
gov.nih.nci.system.security.acegi.providers.UsernameAuthenticationToken

Packages that use UsernameAuthenticationToken

gov.nih.nci.system.security.acegi.authentication

Uses of UsernameAuthenticationToken in gov.nih.nci.system.security.acegi.authentication

Methods in gov.nih.nci.system.security.acegi.authentication with parameters of type UsernameAuthenticationToken

protected  void
CSMUsernameAuthenticationProvider.additionalAuthenticationChecks(org.acegisecurity.userdetails.UserDetails userDetails,
                               UsernameAuthenticationToken authentication)

protected  org.acegisecurity.userdetails.UserDetails
CSMUsernameAuthenticationProvider.retrieveUser(java.lang.String username,
             UsernameAuthenticationToken authentication)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

This API was generated by the caCORE Software Development Kit (SDK)


text:
package play.api.cache.caffeine

import java.util.concurrent.Executors
import javax.inject.{ Inject, Provider }

import play.api.cache.{ AsyncCacheApi, SyncCacheApi }
import play.api.inject._
import play.api.test.{ PlaySpecification, WithApplication }
import play.cache.NamedCache

import scala.concurrent.duration._
import scala.concurrent.{ Await, ExecutionContext, Future }

class CaffeineCacheApiSpec extends PlaySpecification {
  sequential

  "CacheApi" should {
    "bind named caches" in new WithApplication(
      _.configure(
        "play.cache.bindCaches" -> Seq("custom")
      )
    ) {
      val controller = app.injector.instanceOf[NamedCacheController]
      val syncCacheName =
        controller.cache.asInstanceOf[SyncCaffeineCacheApi].cache.getName
      val asyncCacheName =
        controller.asyncCache.asInstanceOf[CaffeineCacheApi].cache.getName

      syncCacheName must_== "custom"
      asyncCacheName must_== "custom"
    }

    "configure cache builder by name" in new WithApplication(
      _.configure(
        "play.cache.caffeine.caches.custom.initial-capacity" -> 130,
        "play.cache.caffeine.caches.custom.maximum-size" -> 50,
        "play.cache.caffeine.caches.custom.weak-keys" -> true,
        "play.cache.caffeine.caches.custom.weak-values" -> true,
        "play.cache.caffeine.caches.custom.record-stats" -> true,

        "play.cache.caffeine.caches.custom-two.initial-capacity" -> 140,
        "play.cache.caffeine.caches.custom-two.soft-values" -> true
      )
    ) {
      val caffeineCacheManager: CaffeineCacheManager = app.injector.instanceOf[CaffeineCacheManager]

      val cacheBuilderStrCustom: String = caffeineCacheManager.getCacheBuilder("custom").toString
      val cacheBuilderStrCustomTwo: String = caffeineCacheManager.getCacheBuilder("custom-two").toString

      cacheBuilderStrCustom.contains("initialCapacity=130") must be
      cacheBuilderStrCustom.contains("maximumSize=50") must be
      cacheBuilderStrCustom.contains("keyStrength=weak") must be
      cacheBuilderStrCustom.contains("valueStrength=weak") must be

      cacheBuilderStrCustomTwo.contains("initialCapacity=140") must be
      cacheBuilderStrCustomTwo.contains("valueStrength=soft") must be
    }

    "get values from cache" in new WithApplication() {
      val cacheApi = app.injector.instanceOf[AsyncCacheApi]
      val syncCacheApi = app.injector.instanceOf[SyncCacheApi]
      syncCacheApi.set("foo", "bar")
      Await.result(cacheApi.getOrElseUpdate[String]("foo")(Future.successful("baz")), 1.second) must_== "bar"
      syncCacheApi.getOrElseUpdate("foo")("baz") must_== "bar"
    }

    "get values from cache without deadlocking" in new WithApplication(
      _.overrides(
        bind[ExecutionContext].toInstance(ExecutionContext.fromExecutor(Executors.newFixedThreadPool(1)))
      )
    ) {
      val syncCacheApi = app.injector.instanceOf[SyncCacheApi]
      syncCacheApi.set("foo", "bar")
      syncCacheApi.getOrElseUpdate[String]("foo")("baz") must_== "bar"
    }

    "remove values from cache" in new WithApplication() {
      val cacheApi = app.injector.instanceOf[AsyncCacheApi]
      val syncCacheApi = app.injector.instanceOf[SyncCacheApi]
      syncCacheApi.set("foo", "bar")
      Await.result(cacheApi.getOrElseUpdate[String]("foo")(Future.successful("baz")), 1.second) must_== "bar"
      syncCacheApi.remove("foo")
      Await.result(cacheApi.get("foo"), 1.second) must beNone
    }

    "remove all values from cache" in new WithApplication() {
      val cacheApi = app.injector.instanceOf[AsyncCacheApi]
      val syncCacheApi = app.injector.instanceOf[SyncCacheApi]
      syncCacheApi.set("foo", "bar")
      Await.result(cacheApi.getOrElseUpdate[String]("foo")(Future.successful("baz")), 1.second) must_== "bar"
      Await.result(cacheApi.removeAll(), 1.second) must be(akka.Done)
      Await.result(cacheApi.get("foo"), 1.second) must beNone
    }
  }
}

class CustomCacheManagerProvider @Inject() (cacheManagerProvider: CacheManagerProvider) extends Provider[CaffeineCacheManager] {
  lazy val get = {
    val mgr = cacheManagerProvider.get
    mgr
  }
}

class NamedCacheController @Inject() (
    @NamedCache("custom") val cache: SyncCacheApi,
    @NamedCache("custom") val asyncCache: AsyncCacheApi
)


text:
require "gettext/tools/xgettext"
require "gettext_i18n_rails/gettext_hooks"

module GettextI18nRailsJs
  module Parser
    module Base
      extend self

      # The gettext function name can be configured at the module level as
      # gettext_function. This is to provide a way to avoid
      # conflicts with other javascript libraries. You only need to define
      # the base function name to replace "_" and all the other variants
      # (s_, n_, N_) will be deduced automatically.
      attr_writer :gettext_function

      def gettext_function
        @gettext_function ||= "__"
      end

      # We're lazy and klumsy, so this is a regex based parser that looks for
      # invocations of the various gettext functions. Once captured, we scan
      # them once again to fetch all the function arguments. Invoke regex
      # captures like this:
      #
      # javascript source: "#{ __('hello') } #{ __("wor)ld") }"
      # matches:
      # [0]: __('hello')
      # [1]: __
      # [2]: 'hello'
      #
      # javascript source: __('item', 'items', 33)
      # matches:
      # [0]: __('item', 'items', 33)
      # [1]: __
      # [2]: 'item', 'items', 33
      #
      # handlebars source: "{{ _ "foo"}}"
      # matches:
      # [0]: __('foo')
      # [1]: __
      # [2]: 'foo'
      #
      # handlebars source: "{{ _ "foo" "foos" 3}}"
      # matches:
      # [0]: __('foo', 'foos', 3)
      # [1]: __
      # [2]: 'foo', 'foos', 3
      #
      # The PO file outputs to a "" string.
      # single quotes are unescped (if they are escaped)
      # double quotes are escaped (if they are not already escaped)
      def parse(file, _msgids = [])
        collect_for(file) do |function, arguments, line|
          key = arguments.scan(
            /('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`)/
          ).collect do |match|
            contents = match.first[1..-2]
            contents.gsub(/\\'/, "'").gsub(/(?<=[^\\])"/, "\\\"")
          end.join(separator_for(function))

          next if key == ""

          results_for(key, file, line)
        end
      end

      protected

      def cleanup_multiline_line(value)
        result = value.chomp
        result.strip
      end

      def cleanup_value(value)
        value
          .tr("\n", "\n")
          .tr("\t", "\t")
          .tr("\0", "\0")
      end

      def separator_for(value)
        if value == "n#{gettext_function}"
          "\000"
        else
          "\004"
        end
      end

      def results_for(key, file, line)
        [
          cleanup_value(key),
          [file, line].join(":")
        ]
      end
    end
  end
end


text:
from .core import SOAPRequest
from .soap_dispatch import SOAPDispatcher

__all__ = ['django_dispatcher']

class DjangoEnvironWrapper:
    def __init__(self, environ):
        self.environ = environ

    def get(self, name, default=None):
        name = name.replace('-', '_').upper()
        for key in (name, 'HTTP_' + name):
            if key in self.environ:
                return self.environ[key]
        return default

def django_dispatcher(service, **dispatcher_kwargs):
    from django.http import HttpResponse
    from django.views.decorators.csrf import csrf_exempt

    def django_dispatch(request):
        soap_request = SOAPRequest(DjangoEnvironWrapper(request.META), request.body)
        soap_request._original_request = request
        soap_dispatcher = SOAPDispatcher(service, **dispatcher_kwargs)
        soap_response = soap_dispatcher.dispatch(soap_request)

        response = HttpResponse(soap_response.http_content)
        response.status_code = soap_response.http_status_code
        for k, v in soap_response.http_headers.items():
            response[k] = v
        return response

    return csrf_exempt(django_dispatch)


text:
Title: Submitted
layout: page
---
Submitted!
==========


text:
set -uxeo pipefail

# Run tidy over all HTML
find /tmp/site/ -name '*.html' -print -execdir tidy -q -i -w 120 -m --vertical-space yes --drop-empty-elements no "{}" \;

# Convert all images to WebP
find /tmp/site \( -name '*.jpg' -o -name '*.png' -o -name '*.jpeg' \) -execdir cwebp -m 6 -mt -o "{}.webp" -- "{}" \;


text:
var TokenLock = TokenLock || (function() {
    'use strict';

    var version = '0.2.5',
        lastUpdate = 1473857742,
    	schemaVersion = 0.2,

	ch = function (c) {
		var entities = {
			'<' : 'lt',
			'>' : 'gt',
			"'" : '#39',
			'@' : '#64',
			'{' : '#123',
			'|' : '#124',
			'}' : '#125',
			'[' : '#91',
			']' : '#93',
			'"' : 'quot',
			'-' : 'mdash',
			' ' : 'nbsp'
		};

		if(_.has(entities,c) ){
			return ('&'+entities[c]+';');
		}
		return '';
	},

    getCommandOption_ToggleLock = function() {
        var text = (state.TokenLock.locked ? 'Locked' : 'Unlocked' );
        return '
'+
            'Tokens are now '+
                text+
            '. '+
            ''+
                'Toggle'+
            ''+
        '
';

    },

    getConfigOption_AllowMoveOnTurn = function() {
        var text = (state.TokenLock.config.allowMoveOnTurn ? 'On' : 'Off' );
        return '
'+
            'Allow Move on Turn is currently '+
                text+
            ' '+
            ''+
                'Toggle'+
            ''+
        '
';

    },

	showHelp = function(who) {
		var stateColor = (state.TokenLock.locked) ? ('#990000') : ('#009900'),
		    stateName  = (state.TokenLock.locked) ? ('Locked') : ('Unlocked');

        sendChat('',
            '/w "'+who+'" '+
'
'+
	'
'+
		'
'+stateName+'
'+
		'TokenLock v'+version+
		'

'+
	'
'+
	'
'+
		'
TokenLock allows the GM to selectively prevent players from moving their tokens. '+
		'Since change:graphic events to not specify who changed the '+
		'graphic, determination of player tokens is based on whether that token '+
		'has an entry in the controlled by field of either the token or '+
		'the character it represents.  If controlled by is empty, the '+
		'GM can freely move the token at any point.  If there is any entry in '+
		'controlled by, the token can only be moved when TokenLock is '+
		'unlocked.
'+
		 '
Moving of player controlled cards is still permissible.
'+
	'
'+
	'Commands'+
	'
!tl'+
		'
'+
			'Executing the command with no arguments prints this help.  The following arguments may be supplied in order to change the configuration.  All changes are persisted between script restarts.'+
			'
'+
				'
'+
					'lock -- Locks the player tokens to prevent moving them.'+
				'
 '+
				'
'+
					'unlock -- Unlocks the player tokens allowing them to be moved.'+
				'
 '+
			'
'+
		'
'+
	'
'+
    getCommandOption_ToggleLock()+
	'
'+
		'!tl-config ['+ch('<')+'Options'+ch('>')+'|--help]'+
		'
'+
			'
Swaps the selected Tokens for their counterparts on the other layer.
'+
			'
'+
				'
'+
					'--help '+ch('-')+' Shows the Help screen'+
				'
 '+
				'
'+
					'--toggle-allowmoveonturn '+ch('-')+' Sets whether tokens can be moved if they are at the top of the turn order.'+
				'
 '+
			'
'+
		'
'+
	'
'+
    getConfigOption_AllowMoveOnTurn()+
'
'
            );
    },

	handleInput = function(msg) {
		var args,who;

		if (msg.type !== "api" || !playerIsGM(msg.playerid) ) {
			return;
		}
        who=getObj('player',msg.playerid).get('_displayname');

		args = msg.content.split(/\s+/);
		switch(args.shift()) {
            case '!tl':
                if(_.contains(args,'--help')) {
                    showHelp(who);
                    return;
                }
				switch(args.shift()) {
					case 'lock':
                        state.TokenLock.locked=true;
                        sendChat('TokenLock','/w gm ' +
                            getCommandOption_ToggleLock()
                        );

						break;

					case 'unlock':
                        state.TokenLock.locked=false;
                        sendChat('TokenLock','/w gm ' +
                            getCommandOption_ToggleLock()
                        );
						break;

					case '--toggle-lock':
                        state.TokenLock.locked= !state.TokenLock.locked;
                        sendChat('TokenLock','/w gm ' +
                            getCommandOption_ToggleLock()
                        );
						break;

					default:
						showHelp(who);
						break;
				}
                break;

            case '!tl-config':
                if(_.contains(args,'--help')) {
                    showHelp(who);
                    return;
                }
                if(!args.length) {
                    sendChat('','/w "'+who+'" '+
'
'+
	'
'+
		'TokenLock v'+version+
	'
'+
    getConfigOption_AllowMoveOnTurn()+
'
'
                    );
                    return;
                }
                _.each(args,function(a){
                    var opt=a.split(/\|/);

                    switch(opt.shift()) {
                        case '--toggle-allowmoveonturn':
                            state.TokenLock.config.allowMoveOnTurn = !state.TokenLock.config.allowMoveOnTurn;
                            sendChat('','/w "'+who+'" '+
                                '
'+
                                    getConfigOption_AllowMoveOnTurn()+
                                '
'
                            );
                            break;

                        default:
                            sendChat('','/w "'+who+'" ' +
                                '
Unsupported Option:
 '+a+'
'
                            );
                    }
                });
                break;
		}

	},

	handleMove = function(obj,prev) {

		if(state.TokenLock.locked &&
            'token' === obj.get('subtype') &&
            ( !state.TokenLock.config.allowMoveOnTurn ||
                (( (((JSON.parse(Campaign().get('turnorder'))||[])[0])||{id:false}).id) !== obj.id) ) &&
                ( obj.get('left') !== prev.left || obj.get('top') !== prev.top || obj.get('rotation') !== prev.rotation )
		) {
			if('' !== obj.get('controlledby')) {
				obj.set({left: prev.left, top: prev.top, rotation: prev.rotation});
			} else if('' !== obj.get('represents') ) {
				var character = getObj('character',obj.get('represents'));
				if( character && character.get('controlledby') ) {
					obj.set({left: prev.left, top: prev.top, rotation: prev.rotation});
				}
			}
		}
	},

    checkInstall = function() {
        log('-=> TokenLock v'+version+' <=-  ['+(new Date(lastUpdate*1000))+']');

        if( ! _.has(state,'TokenLock') || state.TokenLock.version !== schemaVersion) {
            log('  > Updating Schema to v'+schemaVersion+' <');
            switch(state.TokenLock && state.TokenLock.version) {
                case 0.1:
                    state.TokenLock.config={
                        allowMoveOnTurn: false
                    };
                    state.TokenLock.version=schemaVersion;
                    break;

                default:
                    state.TokenLock = {
                        version: schemaVersion,
                        config: {
                            allowMoveOnTurn: false
                        },
                        locked: false
                    };
            }
		}
	},

	registerEventHandlers = function() {
		on('chat:message', handleInput);
		on('change:graphic', handleMove);
	};

	return {
		RegisterEventHandlers: registerEventHandlers,
		CheckInstall: checkInstall
	};
}());

on("ready",function(){
	'use strict';

	TokenLock.CheckInstall();
	TokenLock.RegisterEventHandlers();
});


text:
echo ""
echo "[Provision-Script] Installing Log.io (via Yarn)"
echo ""

#yarn global add logio
yarn global add adrielldagasuan/Log.io


text:
   <form name="formBeneficiario" ng-submit="addBeneficiario()" novalidate>
    <fieldset>
        <legend style="background: whitesmoke;">Datos de Beneficiario</legend>
        <alert ng-repeat="alert in alertsBeneficiario" type="{{alert.type}}" close="closeAlert($index)">

        </alert>

                    Numero Documento
                    (*)
                    <input focus-on="focusNumeroDocumentoBeneficiario" type="text" name="numeroDocumento" ng-model="beneficiario.numeroDocumento" ng-maxlength="20" class="form-control" placeholder="Numero Documento" capitalize required autofocus/>

                            Ingrese Numero Documento.

                            Maximo 20 Caracteres.

                    Apellido Paterno
                    (*)
                    <input type="text" name="apellidoPaterno" ng-model="beneficiario.apellidoPaterno" ng-minlength="1" ng-maxlength="40" class="form-control" placeholder="Apellido Paterno" capitalize required/>

                            Ingrese Apellido Paterno.

                            Minimo 1 Caracter.

                            Maximo 40 Caracteres.

                    Apellido Materno
                    (*)
                    <input type="text" name="apellidoMaterno" ng-model="beneficiario.apellidoMaterno" ng-minlength="1" ng-maxlength="40" class="form-control" placeholder="Apellido Materno" capitalize required/>

                            Ingrese Apellido Materno.

                            Minimo 1 Caracter.

                            Maximo 40 Caracteres.

                    Nombres
                    (*)
                    <input type="text" name="nombres" ng-model="beneficiario.nombres" ng-minlength="1" ng-maxlength="50" class="form-control" placeholder="Nombres" capitalize required/>

                            Ingrese Nombres.

                            Minimo 1 Caracter.

                            Maximo 50 Caracteres.

                    Porcentaje %
                    (*)
                    <input type="number" name="porcentajeBeneficio" ng-model="beneficiario.porcentajeBeneficio" ng-minlength="1" ng-maxlength="3" ng-pattern="/^[0-9]+$/" class="form-control" placeholder="Porcentaje" required/>

                            Ingrese Porcentaje Valido.

                            Minimo 1 Caracter.

                            Maximo 3 Caracteres.

                            Ingrese Porcentaje Valido.

                        <button type="submit" class="btn btn-primary">A&ntildeadir</button>
                        <button type="button" class="btn btn-default" ng-click="clear()">Limpiar</button>

    </fieldset>
   </form>
    <fieldset>
        <legend style="background: whitesmoke;">Lista de Beneficiarios</legend>

                            Num. Documento
                            Apellido Paterno
                            Apellido Materno
                            Nombres
                            Porcentaje (%)

                            	%

                            <button type="button" ng-click="removeBeneficiario($index)" class="btn btn-danger btn-xs">Delete</button>

    </fieldset>


text:
import 'reflect-metadata';

import * as D from '../decorator';
import * as graphql from 'graphql';

import { clearFieldTypeCache, clearObjectTypeRepository, fieldTypeFactory, resolverFactory } from '../type-factory';

import { BeforeMiddleware } from '../middleware';
import { FieldMetadata } from '../metadata';
import { getMetadataBuilder } from '../metadata-builder';

const assert = require('assert');

describe('field specs', function () {

  describe('resolverFactory', function () {
    beforeEach(function () {
      clearObjectTypeRepository();
      clearFieldTypeCache();
    });

    it('returns argumentConfigMap. The map has GraphQLFloat type with a function which has number argument', function () {
      class Obj { @D.Field() m( @D.Arg({ name: 'input' }) input: number): void { } }
      const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
      const actual = resolverFactory(Obj, metadata, new Obj()).argumentConfigMap;
      assert(actual['input'].type === graphql.GraphQLFloat);
    });

    it('returns argumentConfigMap. The map has GraphQLFloat type with a function which has Number argument', function () {
      class Obj { @D.Field() m( @D.Arg({ name: 'input' }) input: Number): void { } }
      const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
      const actual = resolverFactory(Obj, metadata, new Obj()).argumentConfigMap;
      assert(actual['input'].type === graphql.GraphQLFloat);
    });

    it('returns argumentConfigMap. The map has GraphQLString type with a function which has string argument', function () {
      class Obj { @D.Field() m( @D.Arg({ name: 'input' }) input: string): void { } }
      const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
      const actual = resolverFactory(Obj, metadata, new Obj()).argumentConfigMap;
      assert(actual['input'].type === graphql.GraphQLString);
    });

    it('returns argumentConfigMap. The map has GraphQLString type with a function which has String argument', function () {
      class Obj { @D.Field() m( @D.Arg({ name: 'input' }) input: String): void { } }
      const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
      const actual = resolverFactory(Obj, metadata, new Obj()).argumentConfigMap;
      assert(actual['input'].type === graphql.GraphQLString);
    });

    it('returns argumentConfigMap. The map has GraphQLBoolean type with a function which has boolean argument', function () {
      class Obj { @D.Field() m( @D.Arg({ name: 'input' }) input: boolean): void { } }
      const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
      const actual = resolverFactory(Obj, metadata, new Obj()).argumentConfigMap;
      assert(actual['input'].type === graphql.GraphQLBoolean);
    });

    it('returns argumentConfigMap. The map has GraphQLBoolean type with a function which has Boolean argument', function () {
      class Obj { @D.Field() m( @D.Arg({ name: 'input' }) input: Boolean): void { } }
      const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
      const actual = resolverFactory(Obj, metadata, new Obj()).argumentConfigMap;
      assert(actual['input'].type === graphql.GraphQLBoolean);
    });

    it('returns argumentConfigMap. The map has GraphQLObjectType with a function which has argument', function () {
      class Obj { @D.Field() m( @D.Arg({ name: 'input' }) input: Boolean): void { } }
      const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
      const actual = resolverFactory(Obj, metadata, new Obj()).argumentConfigMap;
      assert(actual['input'].type === graphql.GraphQLBoolean);
    });

    it('returns fn which is executable', function () {
      class Obj { @D.Field() twice( @D.Arg({ name: 'input' }) input: number): number { return input * 2; } }
      const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
      const fn = resolverFactory(Obj, metadata, new Obj()).fn;
      const actual = fn(new Obj(), { input: 1 });
      assert(actual === 2);
    });

    describe('Before Middleware', () => {

      it('makes sure Before is executed before resolving', function (done) {

        let middleware: BeforeMiddleware = (context: any, args: { [key: string]: any }, next: (error?: Error, value?: any) => any): any => {
          assert(true);
          done();
        };
        class Obj { @D.Field() @D.Before(middleware) twice(input: number): number { console.log(input); return input * 2; } }
        const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
        const fn = resolverFactory(Obj, metadata, new Obj()).fn;
        const actual = fn(new Obj(), { input: 1 });
      });

      it('makes sure middleware can override function execution if next is called with a value', function () {

        let middleware: BeforeMiddleware = (context: any, args: { [key: string]: any }, next: (error?: Error, value?: any) => any): any => {
          next(null, 5);
        };
        class Obj { @D.Field() @D.Before(middleware) twice(input: number): number { return input * 2; } }
        const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
        const fn = resolverFactory(Obj, metadata, new Obj()).fn;
        const actual = fn(new Obj(), { input: 1 });
        assert(actual === 5);
      });

      // tslint:disable-next-line:max-line-length
      it('makes sure middleware can override function execution if next is called with a value even if it is null (as long it ir not undefined)', function () {

        let middleware: BeforeMiddleware = (context: any, args: { [key: string]: any }, next: (error?: Error, value?: any) => any): any => {
          next(null, null);
        };
        class Obj { @D.Field() @D.Before(middleware) twice(input: number): number { return input * 2; } }
        const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
        const fn = resolverFactory(Obj, metadata, new Obj()).fn;
        const actual = fn(new Obj(), { input: 1 });
        assert(actual === null);
      });
    });

  });

  describe('fieldTypeFactory', function () {
    beforeEach(function () {
      clearObjectTypeRepository();
      clearFieldTypeCache();
    });
    describe('with implicit type', function () {
      it('returns null with a class which has no field', function () {
        class Obj { }
        const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
        const actual = fieldTypeFactory(Obj, metadata);
        assert(actual === null);
      });

      it('returns null with a class which has a field without @Field', function () {
        class Obj { title: any; }
        const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
        const actual = fieldTypeFactory(Obj, metadata);
        assert(actual === null);
      });

      it('returns GraphQLFloat with a class which has a number field', function () {
        class Obj { @D.Field() count: number; }
        const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
        const actual = fieldTypeFactory(Obj, metadata);
        assert(actual.type instanceof graphql.GraphQLScalarType);
        assert(actual.type.name === 'Float');
      });

      it('returns GraphQLFloat with a class which has a Number field', function () {
        class Obj { @D.Field() count: Number; }
        const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
        const actual = fieldTypeFactory(Obj, metadata);
        assert(actual.type instanceof graphql.GraphQLScalarType);
        assert(actual.type.name === 'Float');
      });

      it('returns GraphQLString with a class which has a string field', function () {
        class Obj { @D.Field() title: string; }
        const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
        const actual = fieldTypeFactory(Obj, metadata);
        assert(actual.type instanceof graphql.GraphQLScalarType);
        assert(actual.type.name === 'String');
      });

      it('returns GraphQLString with a class which has a String field', function () {
        class Obj { @D.Field() title: String; }
        const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
        const actual = fieldTypeFactory(Obj, metadata);
        assert(actual.type instanceof graphql.GraphQLScalarType);
        assert(actual.type.name === 'String');
      });

      it('returns GraphQLBoolean with a class which has a boolean field', function () {
        class Obj { @D.Field() isEnabled: boolean; }
        const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
        const actual = fieldTypeFactory(Obj, metadata);
        assert(actual.type instanceof graphql.GraphQLScalarType);
        assert(actual.type.name === 'Boolean');
      });

      it('returns GraphQLBoolean with a class which has a Boolean field', function () {
        class Obj { @D.Field() isEnabled: Boolean; }
        const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
        const actual = fieldTypeFactory(Obj, metadata);
        assert(actual.type instanceof graphql.GraphQLScalarType);
        assert(actual.type.name === 'Boolean');
      });

      it('returns GraphQLObjectType with a class which has a field of a class annotated @ObjectType', function () {
        @D.ObjectType() class ChildObj { @D.Field() title: string; }
        class ParentObj { @D.Field() child: ChildObj; }
        const metadata = getMetadataBuilder().buildFieldMetadata(ParentObj.prototype)[0];
        const actual = fieldTypeFactory(ParentObj, metadata);
        assert(actual.type instanceof graphql.GraphQLObjectType);
      });

      it('returns description with a class which has description metadata', function () {
        class Obj { @D.Field({ description: 'this is a title' }) title: string; }
        const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
        const actual = fieldTypeFactory(Obj, metadata);
        assert(actual.description === 'this is a title');
      });

      it('returns resolve function with a class which has a function field', function () {
        class Obj { @D.Field() title(): string { return 'hello'; } }
        const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
        const actual = fieldTypeFactory(Obj, metadata);
        assert(!!actual.resolve);
      });

      it('should not return resolve function for input object type', function () {
        @D.InputObjectType()  class Obj { @D.Field() value: string }
        const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
        const actual = fieldTypeFactory(Obj, metadata);
        assert(!('resolve' in actual));
      });
    });

    describe('with explicit type', function () {
      it('returns any type which is set by explicitly', function () {
        class Obj { @D.Field({ type: graphql.GraphQLID }) id: string; }
        const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
        const actual = fieldTypeFactory(Obj, metadata);
        assert(actual.type instanceof graphql.GraphQLScalarType);
        assert(actual.type.name === 'ID');
      });

      it('returns GraphQLObjectType with a class which has a field of a class annotated @ObjectType', function () {
        @D.ObjectType() class ChildObj { @D.Field() title: string; }
        class ParentObj { @D.Field({ type: ChildObj }) child: any; }
        const metadata = getMetadataBuilder().buildFieldMetadata(ParentObj.prototype)[0];
        const actual = fieldTypeFactory(ParentObj, metadata);
        assert(actual.type instanceof graphql.GraphQLObjectType);
      });

      it('returns resolve function with a class which has a function field', function () {
        class Obj { @D.Field({ type: graphql.GraphQLString }) title() { return 'hello'; } }
        const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
        const actual = fieldTypeFactory(Obj, metadata);
        assert(actual.resolve() === 'hello');
      });
    });

    describe('with metadata options', function () {
      it('returns GraphQLNonNull with isNonNull option', function () {
        class Obj { @D.Field({ nonNull: true }) title: string; }
        const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
        const actual = fieldTypeFactory(Obj, metadata);
        assert(actual.type instanceof graphql.GraphQLNonNull);
      });

      it('returns GraphQLList with isList option', function () {
        class Obj { @D.Field({ isList: true, type: graphql.GraphQLString }) users: string[]; }
        const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
        const actual = fieldTypeFactory(Obj, metadata);
        assert(actual.type instanceof graphql.GraphQLList);
      });

      it('returns GraphQLNonNull with isList and isNonNull option', function () {
        class Obj { @D.Field({ isList: true, nonNull: true, type: graphql.GraphQLString }) users: string[]; }
        const metadata = getMetadataBuilder().buildFieldMetadata(Obj.prototype)[0];
        const actual = fieldTypeFactory(Obj, metadata);
        assert(actual.type instanceof graphql.GraphQLNonNull);
      });
    });
  });
});


text:
import textwrap

from django.contrib.postgres.indexes import BrinIndex
from django.core.validators import ValidationError
from django.db import connection, models
from django.forms.models import model_to_dict
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from model_utils.models import TimeStampedModel
from reversion import revisions as reversion

from pola.concurency import concurency

class IntegerRangeField(models.IntegerField):
    def __init__(self, min_value=None, max_value=None, *args, **kwargs):
        super(models.IntegerField, self).__init__(*args, **kwargs)
        self.min_value, self.max_value = min_value, max_value

    def formfield(self, **kwargs):
        defaults = {'min_value': self.min_value, 'max_value': self.max_value}
        defaults.update(kwargs)
        return super().formfield(**defaults)

class CompanyQuerySet(models.query.QuerySet):
    def get_or_create(self, commit_desc=None, commit_user=None, *args, **kwargs):
        if not commit_desc:
            return super().get_or_create(*args, **kwargs)

        with reversion.create_revision(manage_manually=True, atomic=True):
            obj, created = super().get_or_create(*args, **kwargs)
            if created:
                reversion.set_comment(commit_desc)
                reversion.set_user(commit_user)
                reversion.add_to_revision(obj)
            return obj, created

@reversion.register
class Company(TimeStampedModel):
    name = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        db_index=True,
        unique=False,
        verbose_name=_("Nazwa (pobrana z ILiM)"),
    )
    official_name = models.CharField(max_length=255, blank=True, null=True, verbose_name=_("Nazwa rejestrowa"))
    common_name = models.CharField(max_length=255, blank=True, verbose_name=_("Nazwa dla użytkownika"))

    plCapital = IntegerRangeField(
        verbose_name=_("Udział polskiego kapitału"), min_value=0, max_value=100, null=True, blank=True
    )
    plWorkers = IntegerRangeField(
        verbose_name=_("Miejsce produkcji"),
        min_value=0,
        max_value=100,
        null=True,
        blank=True,
        choices=((0, _("0 - Nie produkuje w Polsce")), (100, _("100 - Produkuje w Polsce"))),
    )
    plRnD = IntegerRangeField(
        verbose_name=_("Miejsca pracy w BiR w Polsce"),
        min_value=0,
        max_value=100,
        null=True,
        blank=True,
        choices=(
            (0, _("0 - Nie tworzy miejsc pracy w BiR Polsce")),
            (100, _("100 - Tworzy miejsca pracy w BiR w Polsce")),
        ),
    )
    plRegistered = IntegerRangeField(
        verbose_name=_("Miejsce rejestracji"),
        min_value=0,
        max_value=100,
        null=True,
        blank=True,
        choices=(
            (0, _("0 - Firma zarejestrowana za granicą")),
            (100, _("100 - Firma zarejestrowana w Polsce")),
        ),
    )
    plNotGlobEnt = IntegerRangeField(
        verbose_name=_("Struktura kapitałowa"),
        min_value=0,
        max_value=100,
        null=True,
        blank=True,
        choices=(
            (0, _("0 - Firma jest częścią zagranicznego koncernu")),
            (100, _("100 - Firma nie jest częścią zagranicznego koncernu")),
        ),
    )

    description = models.TextField(_("Opis producenta"), null=True, blank=True)
    sources = models.TextField(_("Źródła"), null=True, blank=True)

    verified = models.BooleanField(
        default=False, verbose_name=_("Dane zweryfikowane"), choices=((True, _("Tak")), (False, _("Nie")))
    )

    Editor_notes = models.TextField(_("Notatki redakcji (nie pokazujemy użytkownikom)"), null=True, blank=True)

    plCapital_notes = models.TextField(_("Więcej nt. udziału polskiego kapitału"), null=True, blank=True)
    plWorkers_notes = models.TextField(_("Więcej nt. miejsca produkcji"), null=True, blank=True)
    plRnD_notes = models.TextField(_("Więcej nt. miejsc pracy w BiR"), null=True, blank=True)
    plRegistered_notes = models.TextField(_("Więcej nt. miejsca rejestracji"), null=True, blank=True)
    plNotGlobEnt_notes = models.TextField(_("Więcej nt. struktury kapitałowej"), null=True, blank=True)

    nip = models.CharField(max_length=10, db_index=True, null=True, blank=True, verbose_name=_("NIP/Tax ID"))
    address = models.TextField(null=True, blank=True, verbose_name=_("Adres"))
    query_count = models.PositiveIntegerField(null=False, default=0, db_index=True)

    is_friend = models.BooleanField(
        default=False, verbose_name=_("Przyjaciel Poli"), choices=((True, _("Tak")), (False, _("Nie")))
    )
    display_brands_in_description = models.BooleanField(
        default=False,
        verbose_name=_("Wyświetlaj informacje o markach w opisie"),
        choices=((True, _("Tak")), (False, _("Nie"))),
    )

    objects = CompanyQuerySet.as_manager()

    def increment_query_count(self):
        with connection.cursor() as cursor:
            cursor.execute('update company_company set query_count = query_count +1 ' 'where id=%s', [self.id])

    @staticmethod
    def recalculate_query_count():
        with connection.cursor() as cursor:
            cursor.execute(
                textwrap.dedent(
                    """
                UPDATE company_company
                SET query_count =
                  (SELECT coalesce(sum(query_count), 0)
                   FROM product_product
                   WHERE company_company.id = product_product.company_id)
                """
                )
            )

    def to_dict(self):
        dict = model_to_dict(self)
        return dict

    def get_absolute_url(self):
        return reverse('company:detail', args=[self.pk])

    def locked_by(self):
        return concurency.locked_by(self)

    def __str__(self):
        return self.common_name or self.official_name or self.name

    def js_plCapital_notes(self):
        return '' if not self.plCapital_notes else self.plCapital_notes.replace('\n', '\\n').replace('\r', '\\r')

    def js_plWorkers_notes(self):
        return '' if not self.plWorkers_notes else self.plWorkers_notes.replace('\n', '\\n').replace('\r', '\\r')

    def js_plRnD_notes(self):
        return '' if not self.plRnD_notes else self.plRnD_notes.replace('\n', '\\n').replace('\r', '\\r')

    def js_plRegistered_notes(self):
        return '' if not self.plRegistered_notes else self.plRegistered_notes.replace('\n', '\\n').replace('\r', '\\r')

    def js_plNotGlobEnt_notes(self):
        return '' if not self.plNotGlobEnt_notes else self.plNotGlobEnt_notes.replace('\n', '\\n').replace('\r', '\\r')

    def get_sources(self, raise_exp=True):
        ret = {}
        if not self.sources:
            return ret

        lines = self.sources.splitlines()
        for line in lines:
            line = line.strip()
            if line == '':
                continue
            s = line.split('|')
            if s.__len__() != 2:
                if raise_exp:
                    raise ValidationError(
                        'Pole >Źródła< powinno składać się '
                        'linii zawierających tytuł odnośnika'
                        ' i odnośnik odzielone znakiem | (pipe)'
                    )
                else:
                    continue
            if s[0] in ret:
                if raise_exp:
                    raise ValidationError(f'Tytuł odnośnika >{s[0]}< występuje więcej niż raz')
                else:
                    continue
            ret[s[0]] = s[1]

        return ret

    def clean(self, *args, **kwargs):
        if self.verified:
            YOU_CANT_SET_VERIFIED = (
                'Nie możesz oznaczyć producenta jako ' 'zweryfikowany jeśli pole >{}< jest nieustalone'
            )
            if self.plCapital is None:
                raise ValidationError(YOU_CANT_SET_VERIFIED.format('udział kapitału polskiego'))
            if self.plWorkers is None:
                raise ValidationError(YOU_CANT_SET_VERIFIED.format('miejsce produkcji'))
            if self.plRnD is None:
                raise ValidationError(YOU_CANT_SET_VERIFIED.format('wysokopłatne miejsca pracy'))
            if self.plRegistered is None:
                raise ValidationError(YOU_CANT_SET_VERIFIED.format('miejsce rejestracji'))
            if self.plNotGlobEnt is None:
                raise ValidationError(YOU_CANT_SET_VERIFIED.format('struktura kapitałowa'))
            self.get_sources()

        super().clean(*args, **kwargs)

    def save(self, commit_desc=None, commit_user=None, *args, **kwargs):
        self.full_clean()
        if not commit_desc:
            super().save(*args, **kwargs)
            return

        with reversion.create_revision(manage_manually=True, atomic=True):
            super().save(*args, **kwargs)
            reversion.set_comment(commit_desc)
            reversion.set_user(commit_user)
            reversion.add_to_revision(self)

    class Meta:
        verbose_name = _("Producent")
        verbose_name_plural = _("Producenci")
        ordering = ['-created']
        permissions = (
            # ("view_company", "Can see all company"),
            # ("add_company", "Can add a new company"),
            # ("change_company", "Can edit the company"),
            # ("delete_company", "Can delete the company"),
        )
        indexes = [BrinIndex(fields=['created'], pages_per_range=16)]

class BrandQuerySet(models.query.QuerySet):
    def get_or_create(self, commit_desc=None, commit_user=None, *args, **kwargs):
        if not commit_desc:
            return super().get_or_create(*args, **kwargs)

        with reversion.create_revision(manage_manually=True, atomic=True):
            obj, created = super().get_or_create(*args, **kwargs)
            if created:
                reversion.set_comment(commit_desc)
                reversion.set_user(commit_user)
                reversion.add_to_revision(obj)
            return obj, created

@reversion.register
class Brand(TimeStampedModel):
    company = models.ForeignKey(Company, null=True, on_delete=models.CASCADE)
    name = models.CharField(
        max_length=128,
        null=True,
        blank=True,
        db_index=True,
        verbose_name=_("Nazwa marki (na podstawie ILiM)"),
    )
    common_name = models.CharField(max_length=128, null=True, blank=True, verbose_name=_("Nazwa dla użytkownika"))
    objects = BrandQuerySet.as_manager()

    def __str__(self):
        return self.common_name or self.name

    def get_absolute_url(self):
        return reverse('company:brand-detail', args=[self.pk])

    class Meta:
        verbose_name = _("Marka")
        verbose_name_plural = _("Marki")
        ordering = ['-name']
        permissions = (
            # ("view_brand", "Can see all brands"),
        )