text:
// ------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by TrackableData.CodeGenerator.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Serialization;
using System.Linq;
using System.Text;
using TrackableData;
using ProtoBuf;
using EntityNetwork;
using TypeAlias;

#region IUserData

namespace Domain
{
    [ProtoContract]
    public partial class TrackableUserData : IUserData
    {
        [IgnoreDataMember]
        public IPocoTracker<IUserData> Tracker { get; set; }

        public TrackableUserData Clone()
        {
            var o = new TrackableUserData();
            o._Name = _Name;
            o._RegisterTime = _RegisterTime;
            o._LastLoginTime = _LastLoginTime;
            o._LoginCount = _LoginCount;
            o._PlayCount = _PlayCount;
            o._WinCount = _WinCount;
            o._LoseCount = _LoseCount;
            o._DrawCount = _DrawCount;
            return o;
        }

        [IgnoreDataMember]
        public bool Changed { get { return Tracker != null && Tracker.HasChange; } }

        ITracker ITrackable.Tracker
        {
            get
            {
                return Tracker;
            }
            set
            {
                var t = (IPocoTracker<IUserData>)value;
                Tracker = t;
            }
        }

        ITracker<IUserData> ITrackable<IUserData>.Tracker
        {
            get
            {
                return Tracker;
            }
            set
            {
                var t = (IPocoTracker<IUserData>)value;
                Tracker = t;
            }
        }

        ITrackable ITrackable.Clone()
        {
            return Clone();
        }

        public ITrackable GetChildTrackable(object name)
        {
            switch ((string)name)
            {
                default:
                    return null;
            }
        }

        public IEnumerable<KeyValuePair<object, ITrackable>> GetChildTrackables(bool changedOnly = false)
        {
            yield break;
        }

        public static class PropertyTable
        {
            public static readonly PropertyInfo Name = typeof(IUserData).GetProperty("Name");
            public static readonly PropertyInfo RegisterTime = typeof(IUserData).GetProperty("RegisterTime");
            public static readonly PropertyInfo LastLoginTime = typeof(IUserData).GetProperty("LastLoginTime");
            public static readonly PropertyInfo LoginCount = typeof(IUserData).GetProperty("LoginCount");
            public static readonly PropertyInfo PlayCount = typeof(IUserData).GetProperty("PlayCount");
            public static readonly PropertyInfo WinCount = typeof(IUserData).GetProperty("WinCount");
            public static readonly PropertyInfo LoseCount = typeof(IUserData).GetProperty("LoseCount");
            public static readonly PropertyInfo DrawCount = typeof(IUserData).GetProperty("DrawCount");
        }

        private string _Name;

        [ProtoMember(1)]
        public string Name
        {
            get
            {
                return _Name;
            }
            set
            {
                if (Tracker != null && Name != value)
                    Tracker.TrackSet(PropertyTable.Name, _Name, value);
                _Name = value;
            }
        }

        private DateTime _RegisterTime;

        [ProtoMember(2)]
        public DateTime RegisterTime
        {
            get
            {
                return _RegisterTime;
            }
            set
            {
                if (Tracker != null && (RegisterTime != value || RegisterTime.Kind != value.Kind))
                    Tracker.TrackSet(PropertyTable.RegisterTime, _RegisterTime, value);
                _RegisterTime = value;
            }
        }

        private DateTime _LastLoginTime;

        [ProtoMember(3)]
        public DateTime LastLoginTime
        {
            get
            {
                return _LastLoginTime;
            }
            set
            {
                if (Tracker != null && (LastLoginTime != value || LastLoginTime.Kind != value.Kind))
                    Tracker.TrackSet(PropertyTable.LastLoginTime, _LastLoginTime, value);
                _LastLoginTime = value;
            }
        }

        private int _LoginCount;

        [ProtoMember(4)]
        public int LoginCount
        {
            get
            {
                return _LoginCount;
            }
            set
            {
                if (Tracker != null && LoginCount != value)
                    Tracker.TrackSet(PropertyTable.LoginCount, _LoginCount, value);
                _LoginCount = value;
            }
        }

        private int _PlayCount;

        [ProtoMember(5)]
        public int PlayCount
        {
            get
            {
                return _PlayCount;
            }
            set
            {
                if (Tracker != null && PlayCount != value)
                    Tracker.TrackSet(PropertyTable.PlayCount, _PlayCount, value);
                _PlayCount = value;
            }
        }

        private int _WinCount;

        [ProtoMember(6)]
        public int WinCount
        {
            get
            {
                return _WinCount;
            }
            set
            {
                if (Tracker != null && WinCount != value)
                    Tracker.TrackSet(PropertyTable.WinCount, _WinCount, value);
                _WinCount = value;
            }
        }

        private int _LoseCount;

        [ProtoMember(7)]
        public int LoseCount
        {
            get
            {
                return _LoseCount;
            }
            set
            {
                if (Tracker != null && LoseCount != value)
                    Tracker.TrackSet(PropertyTable.LoseCount, _LoseCount, value);
                _LoseCount = value;
            }
        }

        private int _DrawCount;

        [ProtoMember(8)]
        public int DrawCount
        {
            get
            {
                return _DrawCount;
            }
            set
            {
                if (Tracker != null && DrawCount != value)
                    Tracker.TrackSet(PropertyTable.DrawCount, _DrawCount, value);
                _DrawCount = value;
            }
        }
    }

    [ProtoContract]
    public class TrackableUserDataTrackerSurrogate
    {
        [ProtoMember(1)] public EnvelopedObject<string> Name;
        [ProtoMember(2)] public EnvelopedObject<DateTime> RegisterTime;
        [ProtoMember(3)] public EnvelopedObject<DateTime> LastLoginTime;
        [ProtoMember(4)] public EnvelopedObject<int> LoginCount;
        [ProtoMember(5)] public EnvelopedObject<int> PlayCount;
        [ProtoMember(6)] public EnvelopedObject<int> WinCount;
        [ProtoMember(7)] public EnvelopedObject<int> LoseCount;
        [ProtoMember(8)] public EnvelopedObject<int> DrawCount;

        [ProtoConverter]
        public static TrackableUserDataTrackerSurrogate Convert(TrackablePocoTracker<IUserData> tracker)
        {
            if (tracker == null)
                return null;

            var surrogate = new TrackableUserDataTrackerSurrogate();
            foreach(var changeItem in tracker.ChangeMap)
            {
                switch (changeItem.Key.Name)
                {
                    case "Name":
                        surrogate.Name = new EnvelopedObject<string> { Value = (string)changeItem.Value.NewValue };
                        break;
                    case "RegisterTime":
                        surrogate.RegisterTime = new EnvelopedObject<DateTime> { Value = (DateTime)changeItem.Value.NewValue };
                        break;
                    case "LastLoginTime":
                        surrogate.LastLoginTime = new EnvelopedObject<DateTime> { Value = (DateTime)changeItem.Value.NewValue };
                        break;
                    case "LoginCount":
                        surrogate.LoginCount = new EnvelopedObject<int> { Value = (int)changeItem.Value.NewValue };
                        break;
                    case "PlayCount":
                        surrogate.PlayCount = new EnvelopedObject<int> { Value = (int)changeItem.Value.NewValue };
                        break;
                    case "WinCount":
                        surrogate.WinCount = new EnvelopedObject<int> { Value = (int)changeItem.Value.NewValue };
                        break;
                    case "LoseCount":
                        surrogate.LoseCount = new EnvelopedObject<int> { Value = (int)changeItem.Value.NewValue };
                        break;
                    case "DrawCount":
                        surrogate.DrawCount = new EnvelopedObject<int> { Value = (int)changeItem.Value.NewValue };
                        break;
                }
            }

            return surrogate;
        }

        [ProtoConverter]
        public static TrackablePocoTracker<IUserData> Convert(TrackableUserDataTrackerSurrogate surrogate)
        {
            if (surrogate == null)
                return null;

            var tracker = new TrackablePocoTracker<IUserData>();
            if (surrogate.Name != null)
                tracker.ChangeMap.Add(TrackableUserData.PropertyTable.Name, new TrackablePocoTracker<IUserData>.Change { NewValue = surrogate.Name.Value });
            if (surrogate.RegisterTime != null)
                tracker.ChangeMap.Add(TrackableUserData.PropertyTable.RegisterTime, new TrackablePocoTracker<IUserData>.Change { NewValue = surrogate.RegisterTime.Value });
            if (surrogate.LastLoginTime != null)
                tracker.ChangeMap.Add(TrackableUserData.PropertyTable.LastLoginTime, new TrackablePocoTracker<IUserData>.Change { NewValue = surrogate.LastLoginTime.Value });
            if (surrogate.LoginCount != null)
                tracker.ChangeMap.Add(TrackableUserData.PropertyTable.LoginCount, new TrackablePocoTracker<IUserData>.Change { NewValue = surrogate.LoginCount.Value });
            if (surrogate.PlayCount != null)
                tracker.ChangeMap.Add(TrackableUserData.PropertyTable.PlayCount, new TrackablePocoTracker<IUserData>.Change { NewValue = surrogate.PlayCount.Value });
            if (surrogate.WinCount != null)
                tracker.ChangeMap.Add(TrackableUserData.PropertyTable.WinCount, new TrackablePocoTracker<IUserData>.Change { NewValue = surrogate.WinCount.Value });
            if (surrogate.LoseCount != null)
                tracker.ChangeMap.Add(TrackableUserData.PropertyTable.LoseCount, new TrackablePocoTracker<IUserData>.Change { NewValue = surrogate.LoseCount.Value });
            if (surrogate.DrawCount != null)
                tracker.ChangeMap.Add(TrackableUserData.PropertyTable.DrawCount, new TrackablePocoTracker<IUserData>.Change { NewValue = surrogate.DrawCount.Value });
            return tracker;
        }
    }
}

#endregion
#region ISnakeData

namespace Domain
{
    [ProtoContract]
    public partial class TrackableSnakeData : ISnakeData
    {
        [IgnoreDataMember]
        public IPocoTracker<ISnakeData> Tracker { get; set; }

        public TrackableSnakeData Clone()
        {
            var o = new TrackableSnakeData();
            o._State = _State;
            o._Score = _Score;
            return o;
        }

        [IgnoreDataMember]
        public bool Changed { get { return Tracker != null && Tracker.HasChange; } }

        ITracker ITrackable.Tracker
        {
            get
            {
                return Tracker;
            }
            set
            {
                var t = (IPocoTracker<ISnakeData>)value;
                Tracker = t;
            }
        }

        ITracker<ISnakeData> ITrackable<ISnakeData>.Tracker
        {
            get
            {
                return Tracker;
            }
            set
            {
                var t = (IPocoTracker<ISnakeData>)value;
                Tracker = t;
            }
        }

        ITrackable ITrackable.Clone()
        {
            return Clone();
        }

        public ITrackable GetChildTrackable(object name)
        {
            switch ((string)name)
            {
                default:
                    return null;
            }
        }

        public IEnumerable<KeyValuePair<object, ITrackable>> GetChildTrackables(bool changedOnly = false)
        {
            yield break;
        }

        public static class PropertyTable
        {
            public static readonly PropertyInfo State = typeof(ISnakeData).GetProperty("State");
            public static readonly PropertyInfo Score = typeof(ISnakeData).GetProperty("Score");
        }

        private SnakeState _State;

        [ProtoMember(1)]
        public SnakeState State
        {
            get
            {
                return _State;
            }
            set
            {
                if (Tracker != null && State != value)
                    Tracker.TrackSet(PropertyTable.State, _State, value);
                _State = value;
            }
        }

        private int _Score;

        [ProtoMember(2)]
        public int Score
        {
            get
            {
                return _Score;
            }
            set
            {
                if (Tracker != null && Score != value)
                    Tracker.TrackSet(PropertyTable.Score, _Score, value);
                _Score = value;
            }
        }
    }

    [ProtoContract]
    public class TrackableSnakeDataTrackerSurrogate
    {
        [ProtoMember(1)] public EnvelopedObject<SnakeState> State;
        [ProtoMember(2)] public EnvelopedObject<int> Score;

        [ProtoConverter]
        public static TrackableSnakeDataTrackerSurrogate Convert(TrackablePocoTracker<ISnakeData> tracker)
        {
            if (tracker == null)
                return null;

            var surrogate = new TrackableSnakeDataTrackerSurrogate();
            foreach(var changeItem in tracker.ChangeMap)
            {
                switch (changeItem.Key.Name)
                {
                    case "State":
                        surrogate.State = new EnvelopedObject<SnakeState> { Value = (SnakeState)changeItem.Value.NewValue };
                        break;
                    case "Score":
                        surrogate.Score = new EnvelopedObject<int> { Value = (int)changeItem.Value.NewValue };
                        break;
                }
            }

            return surrogate;
        }

        [ProtoConverter]
        public static TrackablePocoTracker<ISnakeData> Convert(TrackableSnakeDataTrackerSurrogate surrogate)
        {
            if (surrogate == null)
                return null;

            var tracker = new TrackablePocoTracker<ISnakeData>();
            if (surrogate.State != null)
                tracker.ChangeMap.Add(TrackableSnakeData.PropertyTable.State, new TrackablePocoTracker<ISnakeData>.Change { NewValue = surrogate.State.Value });
            if (surrogate.Score != null)
                tracker.ChangeMap.Add(TrackableSnakeData.PropertyTable.Score, new TrackablePocoTracker<ISnakeData>.Change { NewValue = surrogate.Score.Value });
            return tracker;
        }
    }
}

#endregion
#region IZoneControllerData

namespace Domain
{
    [ProtoContract]
    public partial class TrackableZoneControllerData : IZoneControllerData
    {
        [IgnoreDataMember]
        public IPocoTracker<IZoneControllerData> Tracker { get; set; }

        public TrackableZoneControllerData Clone()
        {
            var o = new TrackableZoneControllerData();
            o._State = _State;
            o._StartTime = _StartTime;
            o._WinnerId = _WinnerId;
            return o;
        }

        [IgnoreDataMember]
        public bool Changed { get { return Tracker != null && Tracker.HasChange; } }

        ITracker ITrackable.Tracker
        {
            get
            {
                return Tracker;
            }
            set
            {
                var t = (IPocoTracker<IZoneControllerData>)value;
                Tracker = t;
            }
        }

        ITracker<IZoneControllerData> ITrackable<IZoneControllerData>.Tracker
        {
            get
            {
                return Tracker;
            }
            set
            {
                var t = (IPocoTracker<IZoneControllerData>)value;
                Tracker = t;
            }
        }

        ITrackable ITrackable.Clone()
        {
            return Clone();
        }

        public ITrackable GetChildTrackable(object name)
        {
            switch ((string)name)
            {
                default:
                    return null;
            }
        }

        public IEnumerable<KeyValuePair<object, ITrackable>> GetChildTrackables(bool changedOnly = false)
        {
            yield break;
        }

        public static class PropertyTable
        {
            public static readonly PropertyInfo State = typeof(IZoneControllerData).GetProperty("State");
            public static readonly PropertyInfo StartTime = typeof(IZoneControllerData).GetProperty("StartTime");
            public static readonly PropertyInfo WinnerId = typeof(IZoneControllerData).GetProperty("WinnerId");
        }

        private ZoneState _State;

        [ProtoMember(1)]
        public ZoneState State
        {
            get
            {
                return _State;
            }
            set
            {
                if (Tracker != null && State != value)
                    Tracker.TrackSet(PropertyTable.State, _State, value);
                _State = value;
            }
        }

        private TimeSpan _StartTime;

        [ProtoMember(2)]
        public TimeSpan StartTime
        {
            get
            {
                return _StartTime;
            }
            set
            {
                if (Tracker != null && StartTime != value)
                    Tracker.TrackSet(PropertyTable.StartTime, _StartTime, value);
                _StartTime = value;
            }
        }

        private int _WinnerId;

        [ProtoMember(3)]
        public int WinnerId
        {
            get
            {
                return _WinnerId;
            }
            set
            {
                if (Tracker != null && WinnerId != value)
                    Tracker.TrackSet(PropertyTable.WinnerId, _WinnerId, value);
                _WinnerId = value;
            }
        }
    }

    [ProtoContract]
    public class TrackableZoneControllerDataTrackerSurrogate
    {
        [ProtoMember(1)] public EnvelopedObject<ZoneState> State;
        [ProtoMember(2)] public EnvelopedObject<TimeSpan> StartTime;
        [ProtoMember(3)] public EnvelopedObject<int> WinnerId;

        [ProtoConverter]
        public static TrackableZoneControllerDataTrackerSurrogate Convert(TrackablePocoTracker<IZoneControllerData> tracker)
        {
            if (tracker == null)
                return null;

            var surrogate = new TrackableZoneControllerDataTrackerSurrogate();
            foreach(var changeItem in tracker.ChangeMap)
            {
                switch (changeItem.Key.Name)
                {
                    case "State":
                        surrogate.State = new EnvelopedObject<ZoneState> { Value = (ZoneState)changeItem.Value.NewValue };
                        break;
                    case "StartTime":
                        surrogate.StartTime = new EnvelopedObject<TimeSpan> { Value = (TimeSpan)changeItem.Value.NewValue };
                        break;
                    case "WinnerId":
                        surrogate.WinnerId = new EnvelopedObject<int> { Value = (int)changeItem.Value.NewValue };
                        break;
                }
            }

            return surrogate;
        }

        [ProtoConverter]
        public static TrackablePocoTracker<IZoneControllerData> Convert(TrackableZoneControllerDataTrackerSurrogate surrogate)
        {
            if (surrogate == null)
                return null;

            var tracker = new TrackablePocoTracker<IZoneControllerData>();
            if (surrogate.State != null)
                tracker.ChangeMap.Add(TrackableZoneControllerData.PropertyTable.State, new TrackablePocoTracker<IZoneControllerData>.Change { NewValue = surrogate.State.Value });
            if (surrogate.StartTime != null)
                tracker.ChangeMap.Add(TrackableZoneControllerData.PropertyTable.StartTime, new TrackablePocoTracker<IZoneControllerData>.Change { NewValue = surrogate.StartTime.Value });
            if (surrogate.WinnerId != null)
                tracker.ChangeMap.Add(TrackableZoneControllerData.PropertyTable.WinnerId, new TrackablePocoTracker<IZoneControllerData>.Change { NewValue = surrogate.WinnerId.Value });
            return tracker;
        }
    }
}

#endregion
#region IUserContext

namespace Domain
{
    [ProtoContract]
    public partial class TrackableUserContext : IUserContext
    {
        [IgnoreDataMember]
        private TrackableUserContextTracker _tracker;

        [IgnoreDataMember]
        public TrackableUserContextTracker Tracker
        {
            get
            {
                return _tracker;
            }
            set
            {
                _tracker = value;
                Data.Tracker = value?.DataTracker;
            }
        }

        public TrackableUserContext Clone()
        {
            var o = new TrackableUserContext();
            o._Data = _Data?.Clone();
            return o;
        }

        public bool Changed { get { return Tracker != null && Tracker.HasChange; } }

        ITracker ITrackable.Tracker
        {
            get
            {
                return Tracker;
            }
            set
            {
                var t = (TrackableUserContextTracker)value;
                Tracker = t;
            }
        }

        ITracker<IUserContext> ITrackable<IUserContext>.Tracker
        {
            get
            {
                return Tracker;
            }
            set
            {
                var t = (TrackableUserContextTracker)value;
                Tracker = t;
            }
        }

        IContainerTracker<IUserContext> ITrackableContainer<IUserContext>.Tracker
        {
            get
            {
                return Tracker;
            }
            set
            {
                var t = (TrackableUserContextTracker)value;
                Tracker = t;
            }
        }

        ITrackable ITrackable.Clone()
        {
            return Clone();
        }

        public ITrackable GetChildTrackable(object name)
        {
            switch ((string)name)
            {
                case "Data":
                    return Data as ITrackable;
                default:
                    return null;
            }
        }

        public IEnumerable<KeyValuePair<object, ITrackable>> GetChildTrackables(bool changedOnly = false)
        {
            var trackableData = Data as ITrackable;
            if (trackableData != null && (changedOnly == false || trackableData.Changed))
                yield return new KeyValuePair<object, ITrackable>("Data", trackableData);
        }

        private TrackableUserData _Data = new TrackableUserData();

        [ProtoMember(1)]
        public TrackableUserData Data
        {
            get
            {
                return _Data;
            }
            set
            {
                if (_Data != null)
                    _Data.Tracker = null;
                if (value != null)
                    value.Tracker = Tracker?.DataTracker;
                _Data = value;
            }
        }

        TrackableUserData IUserContext.Data
        {
            get { return _Data; }
            set { _Data = (TrackableUserData)value; }
        }
    }

    [ProtoContract]
    public class TrackableUserContextTracker : IContainerTracker<IUserContext>
    {
        [ProtoMember(1)]
        public TrackablePocoTracker<IUserData> DataTracker { get; set; } = new TrackablePocoTracker<IUserData>();

        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append("{ ");
            var first = true;
            if (DataTracker != null && DataTracker.HasChange)
            {
                if (first)
                    first = false;
                else
                    sb.Append(", ");
                sb.Append("Data:");
                sb.Append(DataTracker);
            }

            sb.Append(" }");
            return sb.ToString();
        }

        public bool HasChange
        {
            get
            {
                return
                    (DataTracker != null && DataTracker.HasChange) ||
                    false;
            }
        }

        public event TrackerHasChangeSet HasChangeSet
        {
            add { throw new NotImplementedException(); }
            remove { throw new NotImplementedException(); }
        }

        public void Clear()
        {
            if (DataTracker != null)
                DataTracker.Clear();
        }

        public void ApplyTo(object trackable)
        {
            ApplyTo((IUserContext)trackable);
        }

        public void ApplyTo(IUserContext trackable)
        {
            if (DataTracker != null)
                DataTracker.ApplyTo(trackable.Data);
        }

        public void ApplyTo(ITracker tracker)
        {
            ApplyTo((TrackableUserContextTracker)tracker);
        }

        public void ApplyTo(ITracker<IUserContext> tracker)
        {
            ApplyTo((TrackableUserContextTracker)tracker);
        }

        public void ApplyTo(TrackableUserContextTracker tracker)
        {
            if (DataTracker != null)
                DataTracker.ApplyTo(tracker.DataTracker);
        }

        public void RollbackTo(object trackable)
        {
            RollbackTo((IUserContext)trackable);
        }

        public void RollbackTo(IUserContext trackable)
        {
            if (DataTracker != null)
                DataTracker.RollbackTo(trackable.Data);
        }

        public void RollbackTo(ITracker tracker)
        {
            RollbackTo((TrackableUserContextTracker)tracker);
        }

        public void RollbackTo(ITracker<IUserContext> tracker)
        {
            RollbackTo((TrackableUserContextTracker)tracker);
        }

        public void RollbackTo(TrackableUserContextTracker tracker)
        {
            if (DataTracker != null)
                DataTracker.RollbackTo(tracker.DataTracker);
        }
    }
}

#endregion


text:
from bar.person import build_person
from xyz.location import build_location

Person = build_person()
person = Person(name="Mozart", date_of_birth="27-JAN-1756")
print(str(person))

print("")

Location = build_location()
location = Location(country="Austria", city="Salzburg")
print(str(location))

print("Ready.")

redpajama_set_name: RedPajamaGithub


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

<TITLE>
Uses of Package net.nicholaswilliams.java.licensing.licensor.interfaces.text.abstraction (LicenseManager 1.0.0)
</TITLE>

<META NAME="date" CONTENT="2012-09-05">

<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 Package
net.nicholaswilliams.java.licensing.licensor.interfaces.text.abstraction

Packages that use net.nicholaswilliams.java.licensing.licensor.interfaces.text.abstraction

net.nicholaswilliams.java.licensing.licensor.interfaces.text

net.nicholaswilliams.java.licensing.licensor.interfaces.text.abstraction

Classes in net.nicholaswilliams.java.licensing.licensor.interfaces.text.abstraction used by net.nicholaswilliams.java.licensing.licensor.interfaces.text

TextInterfaceDevice

          Specifies an interface for interacting with text devices in order to abstract the details of interaction away from
 the application code.

Classes in net.nicholaswilliams.java.licensing.licensor.interfaces.text.abstraction used by net.nicholaswilliams.java.licensing.licensor.interfaces.text.abstraction

AbstractTextInterfaceDevice

          An abstract implementation of TextInterfaceDevice that implements any common utilities among all interface
 devices.

CliOptionsBuilder

          Class description here.

TextInterfaceDevice

          Specifies an interface for interacting with text devices in order to abstract the details of interaction away from
 the application code.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

				Copyright © 2010-2012 Nicholas Williams. All Rights Reserved. Licensed Under the
				Apache License version 2.0.


text:
layout: post
title: Your life is like a balloon
modified:
categories: blog
excerpt: Gotta unhook those anchors to rise high
comments: false
tags: [life, inspiration, stoicism]
image:
  feature:
date: 2017-02-20T20:28:16-07:00
---

Inspired by Steve Jobs' commencement speech at Stanford University - **You've got to find what you love**, I've been looking for that one thing since then. But there's no such step by step guide out there on how to find what you love to do. Its all in one man's words that I went out to seek passion. But where is it? Have I found it?

I've been trying out multiple things, connecting bunch of pieces to see if they form a logical structure or order. Its hard to say if I've found it or not but definitely discovered one thing, _**contentment**_.

#### What brought me this gratification?
_**Realization**_. Day in day out I learnt about myself, What I cannot do? What doesn't bring me happiness? Dejection is unavoidable, on the other hand accepting where I am right now and where I cannot be brings me incomparable pleasure. _**Glee**_, because I can let go this shackle and venture in some other direction. There is one less thing upholding me now.

#### The balloon
Now I see its all like a helium balloon anchored to the ground. All you got to do is let go off the strings one by one to let it rise high. It is very important to learn about yourself and accept who you are. Go out and challenge yourself everyday. Hear to your head. Fail; fail fast; learn; steer in some other direction; don't let yourself stagnate. Be on the lookout, constantly doing something. Spend time with yourself, answer is in your head. Embrace your lack of success.

{: .notice--success}
> **"Happy he who learns to bear what he cannot change."**  - Friedrich Schiller


text:
<?php
class Timelinereply_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }

    // 댓글 쓰기
    function timeline_reply_write($time_num, $content, $reply_user, $reply_date){

        $sql = "INSERT INTO timeline_reply(reply_num, time_num, user_id, reply_content, reply_date)
                VALUES ('', '$time_num', '$reply_user', '$content', '$reply_date');";

        return  $this->db->query($sql);
    }

    function getList($timelineList){

        for( $cnt = 0 ; $cnt < count($timelineList) ; $cnt++ ) {
            $time_num = $timelineList[$cnt] -> time_num;

            $sql = "SELECT t.*, m.*
                    FROM timeline_reply t, member m
                    WHERE t.user_id = m.user_id
                    AND time_num = '$time_num'
                    ORDER BY reply_date DESC;";
            $query = $this->db->query($sql);
            $data[$cnt] = $query -> result();
        }

        return @$data;

    }

}


text:
create class cl1 ( col1 int, col2 varchar(10));
create class cl2 ( col1 int, col2 varchar(10));
create trigger tr1
  after update on cl1
  if obj.col1 > 9
  execute insert into cl2 values (obj.col1 - 5, 'nhn');

insert into cl1 values(10,'nhnchina');
update cl1 set col1=11;
select * from cl1;
select * from cl2;

drop trigger tr1;
drop class cl1;
drop class cl2;


text:
'''
Created on Jun 8, 2010

Contains views for permissions tests

@author: jnaous
'''
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import create_update
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404
from expedient.common.permissions.utils import get_queryset_from_class
from expedient.common.permissions.utils import get_user_from_req, get_queryset
from expedient.common.permissions.shortcuts import give_permission_to
from expedient.common.permissions.decorators import require_objs_permissions_for_view
from models import PermissionTestClass

@require_objs_permissions_for_view(
    ["can_get_x2", "can_read_val"],
    get_user_from_req,
    get_queryset(PermissionTestClass, "obj_id"),
)
def test_view_x2(request, obj_id=None):
    obj = get_object_or_404(PermissionTestClass, pk=obj_id)
    return HttpResponse("%s" % obj.get_val_x2())

@require_objs_permissions_for_view(
    ["can_add"],
    get_user_from_req,
    get_queryset_from_class(PermissionTestClass),
    ["POST"],
)
def test_view_create(request):
    return create_update.create_object(
        request, PermissionTestClass,
        template_name="permissions/empty.html",
        post_save_redirect=reverse("test_view_crud"),
    )

def test_protected_url(request):
    return HttpResponse("Worked")

@require_objs_permissions_for_view(
    ["can_set_val"],
    get_user_from_req,
    get_queryset(PermissionTestClass, 'obj_id'),
    ["POST"],
)
@require_objs_permissions_for_view(
    ["can_read_val"],
    get_user_from_req,
    get_queryset(PermissionTestClass, 'obj_id'),
    ["GET"],
)
def test_view_update(request, obj_id=None):
    return create_update.update_object(
        request, PermissionTestClass,
        object_id=obj_id,
        template_name="permissions/empty.html",
        post_save_redirect=reverse("test_view_update",
                                   kwargs=dict(obj_id=obj_id)),
    )

def add_perms_view(request, permission, user, target, redirect_to=None):
    if request.method == "POST":
        give_permission_to(permission, target, user)
        redirect_to = redirect_to or reverse("test_view_crud")
        return HttpResponseRedirect(redirect_to)
    else:
        return HttpResponse(
"""
Do you want to get permissions to create PermissionTestClass instances?
<form action="" method="POST">
<input type="submit" value="Yes" />
<input type="button" value="No" onclick="document.location='%s'" />
</form>
""" % reverse("test_view_crud"))

def other_perms_view(request, permission, user, target, redirect_to=None):
    if request.method == "POST":
        give_permission_to(permission, target, user)
        redirect_to = redirect_to or reverse("test_view_crud")
        return HttpResponseRedirect(redirect_to)
    else:
        return HttpResponse(
"""
Do you want to get %s permission for obj %s?
<form action="" method="POST">
<input type="submit" value="Yes" />
<input type="button" value="No" onclick="document.location='%s'" />
</form>
""" % (permission.name, target, reverse("test_view_crud")))


text:
/*eslint-env worker*/
/*global sinon*/
"use strict";

// Abort if we are not running in a WebWorker
if (typeof importScripts !== "undefined") {
    importScripts("/pkg/sinon.js");

    var mySpy = sinon.spy(function(msg) {
        return "worker received:" + msg;
    });

    onmessage = function(e) {
        postMessage(mySpy(e.data));
    };
}


text:
package multibinder;

import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Processor;
import org.springframework.integration.annotation.ServiceActivator;

/**
 * @author Marius Bogoevici
 */
@EnableBinding(Processor.class)
public class BridgeTransformer {

	@ServiceActivator(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
	public Object transform(Object payload) {
		return payload;
	}
}


text:
module Nesta
  module Plugin
    module Sluggable
      VERSION = "0.0.1"
    end
  end
end


text:
using System.ComponentModel.DataAnnotations;
using Homebank.Web.Attributes;

namespace Homebank.Web.Models
{
	public class LoginModel
	{
		[Required(ErrorMessage = "Please enter your username.")]
		[UsernameValid(ErrorMessage = "Username not found.")]
		public string Name { get; set; }

		[Required(ErrorMessage = "Please enter your password.")]
		[PasswordValid(ErrorMessage = "Password is invalid.")]
		public string Password { get; set; }

        public string ReturnUrl { get; set; }
	}
}


text:
package com.github.andyshao.baker.packager;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.github.andyshao.lang.number.ByteSize;
import com.github.andyshao.lang.number.SimpleByteSize;
import com.github.andyshaox.baker.core.PackagerConfig;

@Component("packagerConfig")
public class ClouadPackagerConf implements PackagerConfig {
    @Value("${Baker.packager.type}")
    private String packagerType;
    @Value("${Baker.packager.valid}")
    private boolean valid;
    @Value("${Baker.packager.maxTaskNum}")
    private int maxTaskNum;
    @Value("${Baker.packager.maxDiskSize}")
    private String maxDiskSize;
    @Value("${Baker.packager.perTaskMaxDiskSize}")
    private String perTaskMaxDiskSize;

    @Override
    public String getPackagerType() {
        return this.packagerType;
    }

    @Override
    public boolean isValid() {
        return this.valid;
    }

    @Override
    public int getMaxTaskNum() {
        return this.maxTaskNum;
    }

    @Override
    public ByteSize getMaxDiskSize() {
        return SimpleByteSize.covertToString(this.maxDiskSize);
    }

    @Override
    public ByteSize getPerTaskMaxDiskSize() {
        return SimpleByteSize.covertToString(this.perTaskMaxDiskSize);
    }

}


text:
package com.mgaetan89.showsrage.view;

import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.view.menu.ActionMenuItemView;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.mgaetan89.showsrage.R;
import com.mgaetan89.showsrage.helper.Utils;

public class ColoredToolbar extends Toolbar {
	private PorterDuffColorFilter colorFilter = null;

	@ColorInt
	private int itemColor = 0;

	public ColoredToolbar(Context context) {
		super(context);

		this.init(context);
	}

	public ColoredToolbar(Context context, AttributeSet attrs) {
		super(context, attrs);

		this.init(context);
	}

	public ColoredToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);

		this.init(context);
	}

	@Override
	public void invalidate() {
		super.invalidate();

		this.setGroupColor(this);
	}

	public void setItemColor(@ColorInt int color) {
		this.colorFilter = new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN);
		this.itemColor = color;

		this.setGroupColor(this);
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		super.onLayout(changed, l, t, r, b);

		this.setGroupColor(this);
	}

	private void init(Context context) {
		this.setItemColor(Utils.getContrastColor(ContextCompat.getColor(context, R.color.primary)));
	}

	private void setChildColor(View child) {
		if (child instanceof ImageView) {
			((ImageView) child).setColorFilter(this.colorFilter);
			child.setAlpha(0.7f);
		} else if (child instanceof TextView) {
			((TextView) child).setTextColor(this.itemColor);
		} else if (child instanceof ActionMenuView) {
			ActionMenuView actionMenu = (ActionMenuView) child;
			final Drawable overflowIcon = actionMenu.getOverflowIcon();

			if (overflowIcon != null) {
				actionMenu.post(new Runnable() {
					@Override
					public void run() {
						overflowIcon.setColorFilter(ColoredToolbar.this.colorFilter);
						overflowIcon.setAlpha((int) (0.7f * 255));
					}
				});
			}

			for (int i = 0; i < actionMenu.getChildCount(); i++) {
				View actionMenuChild = actionMenu.getChildAt(i);

				if (actionMenuChild instanceof ActionMenuItemView) {
					ActionMenuItemView actionMenuItemChild = (ActionMenuItemView) actionMenuChild;

					for (int j = 0; j < actionMenuItemChild.getCompoundDrawables().length; j++) {
						final Drawable drawable = actionMenuItemChild.getCompoundDrawables()[j];

						if (drawable != null) {
							actionMenuChild.post(new Runnable() {
								@Override
								public void run() {
									drawable.setColorFilter(ColoredToolbar.this.colorFilter);
								}
							});
						}
					}
				}
			}
		} else if (child instanceof ViewGroup) {
			this.setGroupColor((ViewGroup) child);
		} else {
			Log.d("ColoredToolbar", child.getClass().getName() + " is not supported");
		}
	}

	private void setGroupColor(@Nullable ViewGroup group) {
		if (group != null) {
			for (int i = 0; i < group.getChildCount(); i++) {
				View child = group.getChildAt(i);

				this.setChildColor(child);
			}
		}
	}
}


text:
@interface BaseView : UIView

@property (nonatomic, strong) UIImageView *logoView;
@property (nonatomic, strong) UIImageView *logoLabelImage;
@property (nonatomic, strong) UIButton *navigationBarButton;
@property (nonatomic, strong) UIButton *searchButton;
@property (nonatomic, strong) UIView *titleBar;

- (void) showTitleBarWithBackViewType:(NSInteger)type;

@end


text:
/*
** LISA single subject statistical inference using 1st level GLM (general linear modeling).
** The prewhitening approach is adapted from Worsley et al (2002), Neuroimage 15(1).
**
** G.Lohmann, MPI-KYB, 2018
*/
#include <viaio/Vlib.h>
#include <viaio/VImage.h>
#include <viaio/mu.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>

extern gsl_matrix *PseudoInv(gsl_matrix *A,gsl_matrix *B);
extern void printmat(gsl_matrix *R,char *str);
extern void printvec(gsl_vector *x,char *str);

extern void prewhite(gsl_matrix_float** pinvX,gsl_matrix_float** invM,gsl_matrix_float* X,int);

extern void dfs(VFloat** Dfs,gsl_matrix_float* pinvX,gsl_matrix_float* X,gsl_matrix_float* con,int);

extern void whitecov(VImage rho_vol,gsl_matrix_float* Y,gsl_matrix_float* invM,
		     gsl_matrix_float* pinvX,gsl_matrix_float* X,int,int);

extern void whitecov2(VImage effect_image, VImage rho_vol,
		      gsl_matrix_float* Y, gsl_matrix_float* X, gsl_matrix_float* con,
		      VFloat* Dfs, int, int slice);

void CopySlice(gsl_matrix *Data,gsl_matrix_float *Y,VImage map,int slice)
{
  size_t nvox;
  size_t i=0,j=0;
  double u=0;
  int ncols = VPixel(map,0,3,2,VShort);

  gsl_matrix_float_set_zero(Y);

  for (nvox=0; nvox < Data->size1; nvox++) {
    int b = VPixel(map,0,0,nvox,VShort);
    if (b != slice) continue;
    int r = VPixel(map,0,1,nvox,VShort);
    int c = VPixel(map,0,2,nvox,VShort);
    i = c + ncols*r;
    if (i >= Y->size2) continue;

    for (j=0; j<Data->size2; j++) {
      u = gsl_matrix_get(Data,nvox,j);
      gsl_matrix_float_set(Y,j,i,(float)u);
    }
  }
}

gsl_matrix_float *GslFloatCpy(gsl_matrix *X)
{
  int i,j;
  double u;
  gsl_matrix_float *Z = gsl_matrix_float_calloc(X->size2,X->size1);
  for (i=0; i<X->size1; i++) {
    for (j=0; j<X->size2; j++) {
      u = gsl_matrix_get(X,i,j);
      gsl_matrix_float_set(Z,j,i,(float)u);
    }
  }
  return Z;
}

/*
** general linear model (GLM) using whitening
*/
void VWhiteGLM(gsl_matrix *Data,VImage map,gsl_matrix *X0,gsl_vector *con,int numlags,VImage zmap)
{
  int i,slice;
  int numcon=1;
  int nslices = VPixel(map,0,3,0,VShort);
  int nrows = VPixel(map,0,3,1,VShort);
  int ncols = VPixel(map,0,3,2,VShort);
  int npix = (nrows*ncols);
  int ntimesteps = Data->size2;

  gsl_set_error_handler_off();
  VFillImage(zmap,VAllBands,0);

  /* contrast vector */
  gsl_matrix_float *contrast = gsl_matrix_float_alloc(1,con->size);
  for (i=0; i<con->size; i++) gsl_matrix_float_set(contrast,0,i,(float)con->data[i]);

  /* copy design matrix */
  gsl_matrix_float *X = GslFloatCpy(X0);

  /* initialize rho_vol */
  VImage rho_vol = VCreateImage(npix,nslices,numlags,VFloatRepn);
  VFillImage(rho_vol,VAllBands,0);

  /* prewhitening */
  gsl_matrix_float *pinvX=NULL,*invM=NULL;
  prewhite(&pinvX,&invM,X,numlags);

  /* degrees of freedom */
  VFloat *dfs_gsl = (VFloat *)VMalloc(sizeof(VFloat)* (numcon+1));
  dfs(&dfs_gsl,pinvX,X,contrast,numlags);

  /* first pass */
  gsl_matrix_float *Y = gsl_matrix_float_calloc(ntimesteps,npix);
  for (slice=0; slice<nslices; slice++) {
    CopySlice(Data,Y,map,(int)slice);
    whitecov(rho_vol,Y,invM,pinvX,X,numlags,slice);
  }

  /* second pass */
  VImage dest = VCreateImage(nslices,nrows,ncols,VFloatRepn);
  VFillImage(dest,VAllBands,0);
  for (slice=0; slice<nslices; slice++) {
    CopySlice(Data,Y,map,(int)slice);
    whitecov2(dest,rho_vol,Y,X,contrast,dfs_gsl,numlags,slice);
  }

  /* output */
  zmap = VCopyImagePixels(dest,zmap,VAllBands);

  /* cleanup */
  gsl_matrix_float_free(contrast);
  gsl_matrix_float_free(X);
  gsl_matrix_float_free(Y);
  gsl_matrix_float_free(pinvX);
  gsl_matrix_float_free(invM);
  VFree(dfs_gsl);
  VDestroyImage(rho_vol);
  VDestroyImage(dest);
}


text:
package org.mifos.reports.admindocuments.persistence;

import java.util.List;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;
import org.mifos.framework.MifosIntegrationTestCase;
import org.mifos.framework.exceptions.PersistenceException;
import org.mifos.reports.admindocuments.business.AdminDocumentBO;

public class AdminDocumentPersistenceIntegrationTest extends MifosIntegrationTestCase {

    private AdminDocumentPersistence reportsPersistence;

    @Before
    public void setUp() throws Exception {
        reportsPersistence = new AdminDocumentPersistence();
    }

    @Test
    public void testGetAllAdminDocuments() throws PersistenceException {
        List<AdminDocumentBO> listadmindoc = reportsPersistence.getAllAdminDocuments();
       Assert.assertEquals(0, listadmindoc.size());
    }

    @Test
    public void testGetAdminDocumentById() throws NumberFormatException, PersistenceException {
        AdminDocumentBO admindoc = reportsPersistence.getAdminDocumentById(Short.valueOf("1"));
       Assert.assertEquals(null, admindoc);
    }

}


text:
"""Entry point for travis-bump-version.."""
import argparse

import atexit

import os

import subprocess

import sys

try:
    from subprocess import DEVNULL  # suppress(ungrouped-imports)
except ImportError:
    DEVNULL = open(os.devnull, "wb")
    atexit.register(DEVNULL.close)

def error(message):
    """Print message to stderr."""
    sys.stderr.write("{}\n".format(message))

def _last_commit_message_body():
    """Read body of last commit message from git."""
    return subprocess.check_output(["git",  # pragma: no cover
                                    "log",
                                    "--format=%b",
                                    "-n",
                                    "1"]).decode("utf-8").strip()

def _get_level():
    """Read the last commit message and get the version bump level."""
    level = "patch"
    last_msg = _last_commit_message_body()

    if len(last_msg):
        code = [w for w in last_msg.splitlines()[-1].split(" ") if len(w)]

        if len(code) > 1 and code[0] == "bumpversion:":
            valid = ("major", "minor", "patch")
            if code[1] not in valid:
                error("""bumpversion: Invalid code {} given, expected """
                      """major, minor or patch. """
                      """Assuming patch""".format(code[1]))
            else:
                level = code[1]

    return level

def _last_tag_from_git(repo=""):
    """Read known tag from git."""
    subprocess.check_call(["git", "checkout", "master"])  # pragma: no cover
    subprocess.check_call(["git",  # pragma: no cover
                           "fetch",
                           "--tags",
                           "git://github.com/{}".format(repo)])
    return subprocess.check_output(["git",  # pragma: no cover
                                    "describe",
                                    "--tags"]).decode("utf-8").strip()

def _call_bumpversion(level, files):
    """Call bumpversion to create commit and bump version."""
    subprocess.check_call(["git",  # pragma: no cover
                           "config",
                           "user.name",
                           "Travis-CI"])
    subprocess.check_call(["git",  # pragma: no cover
                           "config",
                           "user.email",
                           "travis@travis-ci.org"])
    subprocess.check_call([  # pragma: no cover
        "bumpversion",
        level
    ] + list(files) + [
        "--commit",
        "--message",
        "Bump version: {current_version} -> {new_version}\n\n[ci skip]",
        "--tag",
        "--verbose"
    ])

# pragma: no cover
def _push_commit_and_tags(api_token, repo):
    """Push most recent commit and tags to repo, using api_token."""
    url = "https://{0}:x-oauth-basic@github.com/{1}.git".format(api_token,
                                                                repo)
    process = subprocess.Popen(["git",
                                "push",
                                url,
                                "master",
                                "--tags"],
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)

    stdout, stderr = process.communicate()

    if process.returncode != 0:
        raise RuntimeError("""Failed with {returncode}, """
                           """{stdout} {stderr}"""
                           """""".format(returncode=process.returncode,
                                         stdout=stdout,
                                         stderr=stderr))

def version_bump(api_token=None,
                 repo=None,
                 files=None):
    """Check if possible to bump version and bump version."""
    if not files or not len(files):
        error("""Need to specify some files""")
        return 1

    last_tag = _last_tag_from_git(repo)

    if not last_tag.startswith("v"):
        error("""Release a tag that matches vx.x.x to get automatic """
              """version bumps""")
        return 1

    _call_bumpversion(_get_level(), files)

    try:
        _push_commit_and_tags(api_token, repo)
    except RuntimeError as exception:
        error("""bumpversion: Failed to push commit, assuming that another """
              """job was able to push it first. The reason given was:\n"""
              """{}""".format(str(exception).replace(api_token, "[redacted]")))

    return 0

def main(arguments=None):  # suppress(unused-function)
    """Run travis-bump-version, pass files to version_bump."""
    parser = argparse.ArgumentParser(description="""Automatically bump """
                                                 """version on successful """
                                                 """Travis-CI builds.""")
    parser.add_argument("--api-token",
                        required=True,
                        type=str,
                        help="""GitHub API token. Always make sure this """
                             """variable is encrypted first.""")
    parser.add_argument("--repo",
                        required=True,
                        type=str,
                        help="""Name of repo on GitHub, eg user/repo.""")
    parser.add_argument("files",
                        nargs="*",
                        metavar=("FILE"),
                        help="""bump version on FILE""")
    result = parser.parse_args(arguments or sys.argv[1:])

    sys.exit(version_bump(**vars(result)))  # suppress(E204)


text:
'use babel';

let Utils;
export default
(Utils = class Utils {
  static stringIsBlank(str) {
    return !str || /^\s*$/.test(str);
  }
});


text:
package com.mnubo.dbevolv.docker

import java.io.File

import com.mnubo.dbevolv.DatabaseDockerImage
import com.mnubo.dbevolv.util.Logging
import com.spotify.docker.client.DockerClient.{ExecCreateParam, LogsParam, RemoveContainerParam}
import com.spotify.docker.client.messages.{ContainerConfig, HostConfig}

import scala.annotation.tailrec

class Container(docker: Docker,
                imageName: String,
                isStarted: (String, Container) => Boolean,
                port: Int,
                envVars: Set[String] = Set.empty,
                forcePull: Boolean = true) extends Logging with AutoCloseable {
  import Container._

  def this (docker: Docker, descriptor: DatabaseDockerImage) = this(docker, descriptor.name, descriptor.isStarted, descriptor.exposedPort, descriptor.envVars, false)

  private var lastImageId: String = null

  if (forcePull || !docker.images.contains(imageName)) {
    log.info(s"Pulling image $imageName.")
    docker.client.pull(imageName, docker.authFor(imageName))
  }
  else
    log.info(s"The image $imageName already exists locally. Not pulling.")

  val volumes =
    if (existsAsFile(s"${docker.userHome}/.docker/config.json"))
      Seq(SocketVolume, s"${docker.userHome}/.docker:/root/.docker")
    else
      Seq(SocketVolume)

  private val creationInfo = docker.client.createContainer(
    ContainerConfig
      .builder
      .volumes(volumes: _*)
      .image(imageName)
      .hostConfig(HostConfig.builder.publishAllPorts(true).build)
      .env(envVars.toSeq: _*)
      .build
  )

  val containerId = creationInfo.id
  docker.client.startContainer(containerId)
  private val inspectionInfo = docker.client.inspectContainer(containerId)

  val exposedPort =
    if (docker.isInContainer)
      port
    else
      hostPort(port)
  val containerHost =
    if (docker.isInContainer)
      inspectionInfo.networkSettings.ipAddress
    else
      docker.dockerHost

  waitStarted(isStarted)

  def hostPort(port: Int) =
    inspectionInfo
      .networkSettings
      .ports
      .get(s"$port/tcp")
      .get(0)
      .hostPort
      .toInt

  def stop() =
    docker.client.stopContainer(containerId, 5)

  def start() = {
    val previousLog = logs

    def isStartedOnNewLogs(logs: String, container: Container) =
      isStarted(logs.replace(previousLog, ""), this)

    docker.client.startContainer(containerId)

    waitStarted(isStartedOnNewLogs)
  }

  def commit(repository: String, tag: String): String = {
    docker.client.pauseContainer(containerId)
    lastImageId = docker.client.commitContainer(containerId, repository, tag, ContainerConfig.builder.build, "", "dbevolv").id()
    docker.client.unpauseContainer(containerId)

    lastImageId
  }

  def exec(cmd: Seq[String]) = {
    val execId = docker.client.execCreate(containerId, cmd.toArray, ExecCreateParam.attachStdout, ExecCreateParam.attachStderr)
    docker.client.execStart(execId).readFully
  }

  def tag(tag: String) =
    docker.client.tag(lastImageId, tag)

  def remove() =
    docker.client.removeContainer(containerId, RemoveContainerParam.removeVolumes())

  def logs =
    docker.client.logs(containerId, LogsParam.stdout, LogsParam.stderr).readFully()

  @tailrec
  private def waitStarted(isStarted: (String, Container) => Boolean, startTS: Long = System.currentTimeMillis()): Unit = {
    val currentLogs = logs
    if (!isStarted(currentLogs, this) )
    {
      Thread.sleep(100)
      if (System.currentTimeMillis() - startTS > FiveMinMaxWaitTimeForStartInMS) {
        throw new Exception(s"Could not start $containerId within a reasonable time. Container logs were:\n$currentLogs\n")
      }
      waitStarted(isStarted, startTS)
    }
  }

  private def existsAsFile(path: String) = {
    val f = new File(path)
    f.exists && f.isFile
  }

  override def close =
    try stop()
    finally remove()
}

object Container extends Logging {
  private val FiveMinMaxWaitTimeForStartInMS = 5 * 60 * 1000L
  private val SocketVolume = "/var/run/docker.sock:/var/run/docker.sock"
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.Identity.Client;

namespace Azure.Identity.Tests
{
    internal static class StaticCachesUtilities
    {
        private static readonly Lazy<Action> s_clearStaticMetadataProvider = new Lazy<Action>(() =>
        {
            Type staticMetadataProviderType = typeof(PublicClientApplication).Assembly.GetType("Microsoft.Identity.Client.Instance.Discovery.NetworkCacheMetadataProvider", true);
            MethodInfo clearMethod = staticMetadataProviderType.GetMethod("Clear", BindingFlags.Public | BindingFlags.Instance);
            NewExpression callConstructor = Expression.New(staticMetadataProviderType);
            MethodCallExpression invokeClear = Expression.Call(callConstructor, clearMethod);
            return Expression.Lambda<Action>(invokeClear).Compile();
        });
        public static void ClearStaticMetadataProviderCache() => s_clearStaticMetadataProvider.Value();
    }
}


text:
var exports = exports || {};
var mustache = require ("mustache");

var SectionRequest = {
	handle: function (req, res) {

	},
	render: function (sections) {
		var promise = new Promise (function (resolve, reject) {
			var renderSections = [];
			sections.forEach (function (val, i, arr) {
			renderSections[i] = val;
			exports.Threads.find ({ parent: sections[i].id },
				function (result) {
					renderSections[i].threads = result;
					if (i + 1 === sections.length) {
						console.log (renderSections[0].threads);
						resolve (mustache.render (exports.cache["assets/templates/section.mst"], {
							sections: renderSections
						}));
					}
				});
			});
		});
		return promise;
	}
};

exports.SectionRequest = SectionRequest;


text:
package main

import (
	"bytes"
	"encoding/json"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/httptest"
	"testing"
)

func init() {
	log.SetOutput(ioutil.Discard)
}

type processedResponse struct {
	statusCode int
	header     http.Header
	body       []byte
}

func mustEncodeStub(t *testing.T, stub Stub) (buf *bytes.Buffer) {
	buf = new(bytes.Buffer)
	encoder := json.NewEncoder(buf)
	if err := encoder.Encode(stub); err != nil {
		t.Fatalf("Unable to JSON encode: %#v", stub)
	}
	return
}

func mustPost(t *testing.T, url string, body io.Reader) (pr *processedResponse) {
	resp, err := http.Post(url, "application/json", body)
	if err != nil {
		t.Fatalf("Unable to POST: %v", err)
	}

	pr = &processedResponse{statusCode: resp.StatusCode, header: resp.Header}
	pr.body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatal(err)
	}

	resp.Body.Close()

	return
}

func mustGet(t *testing.T, url string) (pr *processedResponse) {
	resp, err := http.Get(url)
	if err != nil {
		t.Fatal(err)
	}

	pr = &processedResponse{statusCode: resp.StatusCode, header: resp.Header}
	pr.body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatal(err)
	}

	resp.Body.Close()

	return
}

func TestStubEndpoint(t *testing.T) {
	handler := NewStubHandler()
	ts := httptest.NewServer(handler)

	stub := Stub{Method: "GET", Path: "/foo", Body: `{"foo":"bar"}`}
	postBody := mustEncodeStub(t, stub)
	mustPost(t, ts.URL+"/stubs", postBody)

	resp := mustGet(t, ts.URL+"/foo")
	if resp.statusCode != 200 {
		t.Errorf("Status was incorrect, expected 200, got: %v", resp.statusCode)
	}

	if string(resp.body) != `{"foo":"bar"}` {
		t.Errorf("Unexpected response body: %s", string(resp.body))
	}
}

func TestStubEndpointWithQuerystring(t *testing.T) {
	handler := NewStubHandler()
	ts := httptest.NewServer(handler)

	stub := Stub{Method: "GET", Path: "/foo", Body: `{"foo":"bar"}`}
	stubWithQuery := Stub{Method: "GET", Path: "/foo?bar=baz", Body: `{"baz":"bur"}`}

	postBody := mustEncodeStub(t, stub)
	mustPost(t, ts.URL+"/stubs", postBody)

	postBody = mustEncodeStub(t, stubWithQuery)
	mustPost(t, ts.URL+"/stubs", postBody)

	resp := mustGet(t, ts.URL+"/foo?bar=baz")
	if resp.statusCode != 200 {
		t.Errorf("Status was incorrect, expected 200, got: %v", resp.statusCode)
	}

	if string(resp.body) != `{"baz":"bur"}` {
		t.Errorf("Unexpected response body: %s", string(resp.body))
	}
}

func TestStubEndpointWithQuerystringOrdering(t *testing.T) {
	handler := NewStubHandler()
	ts := httptest.NewServer(handler)

	stub := Stub{Method: "GET", Path: "/foo?bar=baz&baz=bar", Body: `{"foo":"bar"}`}
	postBody := mustEncodeStub(t, stub)
	mustPost(t, ts.URL+"/stubs", postBody)

	resp := mustGet(t, ts.URL+"/foo?baz=bar&bar=baz")
	if resp.statusCode != 200 {
		t.Errorf("Status was incorrect, expected 200, got: %v", resp.statusCode)
	}

	if string(resp.body) != `{"foo":"bar"}` {
		t.Errorf("Unexpected response body: %s", string(resp.body))
	}
}

func TestStubEndpointWithMultipleMethods(t *testing.T) {
	handler := NewStubHandler()
	ts := httptest.NewServer(handler)

	stub := Stub{Method: "GET", Path: "/foo", Body: `get response`}
	postBody := mustEncodeStub(t, stub)
	mustPost(t, ts.URL+"/stubs", postBody)

	stub = Stub{Method: "POST", Path: "/foo", Body: `post response`}
	postBody = mustEncodeStub(t, stub)
	mustPost(t, ts.URL+"/stubs", postBody)

	resp := mustGet(t, ts.URL+"/foo")
	if resp.statusCode != 200 {
		t.Errorf("Status was incorrect, expected 200, got: %v", resp.statusCode)
	}

	if string(resp.body) != `get response` {
		t.Errorf("Unexpected response body: %s", string(resp.body))
	}

	resp = mustPost(t, ts.URL+"/foo", &bytes.Buffer{})
	if resp.statusCode != 200 {
		t.Errorf("Status was incorrect, expected 200, got: %v", resp.statusCode)
	}

	if string(resp.body) != `post response` {
		t.Errorf("Unexpected response body: %s", string(resp.body))
	}
}

func TestStubEndpointWithHeaders(t *testing.T) {
	handler := NewStubHandler()
	ts := httptest.NewServer(handler)

	stub := Stub{Method: "GET", Path: "/foo", Body: `get response`, Status: 404}
	postBody := mustEncodeStub(t, stub)
	mustPost(t, ts.URL+"/stubs", postBody)

	resp := mustGet(t, ts.URL+"/foo")
	if resp.statusCode != 404 {
		t.Errorf("Status was incorrect, expected 404, got: %v", resp.statusCode)
	}
}

func TestGetStubs(t *testing.T) {
	var stubs []Stub
	handler := NewStubHandler()
	ts := httptest.NewServer(handler)

	stub := Stub{Method: "GET", Path: "/foo", Body: `{"foo":"bar"}`}
	postBody := mustEncodeStub(t, stub)
	mustPost(t, ts.URL+"/stubs", postBody)
	resp := mustGet(t, ts.URL+"/stubs")
	decoder := json.NewDecoder(bytes.NewBuffer(resp.body))
	decoder.Decode(&stubs)
	if len(stubs) != 1 {
		t.Errorf("Expected one stub, got %d.", len(stubs))
	}
}

func TestClear(t *testing.T) {
	var stubs []Stub
	handler := NewStubHandler()
	ts := httptest.NewServer(handler)

	stub := Stub{Method: "GET", Path: "/foo", Body: `{"foo":"bar"}`}
	postBody := mustEncodeStub(t, stub)
	mustPost(t, ts.URL+"/stubs", postBody)
	resp := mustGet(t, ts.URL+"/stubs")
	decoder := json.NewDecoder(bytes.NewBuffer(resp.body))
	decoder.Decode(&stubs)
	if len(stubs) != 1 {
		t.Errorf("Expected one stub, got %d.", len(stubs))
	}

	client := http.Client{}
	req, err := http.NewRequest("DELETE", ts.URL+"/stubs", bytes.NewBuffer([]byte("")))
	client.Do(req)
	if err != nil {
		t.Error(err)
	}
	resp = mustGet(t, ts.URL+"/stubs")
	decoder = json.NewDecoder(bytes.NewBuffer(resp.body))
	decoder.Decode(&stubs)
	if len(stubs) != 0 {
		t.Errorf("Expected zero stubs, got %d.", len(stubs))
	}
}

func TestStubMalformedRequest(t *testing.T) {
	handler := NewStubHandler()
	ts := httptest.NewServer(handler)

	postBody := bytes.NewBuffer([]byte("not JSON"))
	resp, err := http.Post(ts.URL+"/stubs", "application/json", postBody)
	if err != nil {
		t.Fatal(err)
	}
	if resp.StatusCode != 400 {
		t.Fatalf("Status was incorrect, expected 400, got: %v", resp.StatusCode)
	}
}

func TestUnhandledStub(t *testing.T) {
	handler := NewStubHandler()
	ts := httptest.NewServer(handler)

	resp, err := http.Get(ts.URL + "/bar")
	if err != nil {
		t.Fatal(err)
	}

	if resp.StatusCode != 404 {
		t.Fatalf("Status was incorrect, expected 404, got: %v", resp.StatusCode)
	}
}

func TestStubFallback(t *testing.T) {
	handler := NewStubHandler()
	handler.fallbackHandler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		_, err := io.WriteString(w, "fallback")
		if err != nil {
			t.Fatal(err)
		}
	})

	ts := httptest.NewServer(handler)

	resp := mustGet(t, ts.URL+"/foo/bar")
	if resp.statusCode != 200 {
		t.Errorf("Status was incorrect, expected 200, got: %v", resp.statusCode)
	}

	if string(resp.body) != "fallback" {
		t.Errorf("Unexpected response body: %#v", string(resp.body))
	}
}

func TestLoad(t *testing.T) {
	handler := NewStubHandler()
	buff := new(bytes.Buffer)
	json := `
	[
		{ "method": "GET", "path": "/foo", "body": "bar"},
		{ "method": "GET", "path": "/baz", "body": "quz"}
	]
	`
	buff.WriteString(json)

	err := handler.load(buff)
	if err != nil {
		t.Fatalf("Unexpected error during load: %v", err)
	}

	ts := httptest.NewServer(handler)

	resp := mustGet(t, ts.URL+"/foo")
	if string(resp.body) != "bar" {
		t.Errorf("Unexpected response body: %#v", string(resp.body))
	}

	resp = mustGet(t, ts.URL+"/baz")
	if string(resp.body) != "quz" {
		t.Errorf("Unexpected response body: %#v", string(resp.body))
	}
}


text:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using InteropDotNet;

namespace Tesseract.Interop
{
	/// <summary>
	/// The exported leptonica api signatures.
	/// </summary>
	/// <remarks>
	/// Please note this is only public for technical reasons (you can't proxy a internal interface).
	/// It should be considered an internal interface and is NOT part of the public api and may have
	/// breaking changes between releases.
	/// </remarks>
    public interface ILeptonicaApiSignatures
    {
    	#region PixA

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixaReadMultipageTiff")]
        IntPtr pixaReadMultipageTiff( string filename );

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixaGetCount")]
        int pixaGetCount( HandleRef pixa );

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixaGetPix")]
        IntPtr pixaGetPix( HandleRef pixa, int index, PixArrayAccessType accesstype );

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixaDestroy")]
        void pixaDestroy(ref IntPtr pix);

		#endregion

        #region Pix

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixCreate")]
        unsafe IntPtr pixCreate(int width, int height, int depth);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixClone")]
        unsafe IntPtr pixClone(HandleRef pix);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixDestroy")]
        void pixDestroy(ref IntPtr pix);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixGetWidth")]
        int pixGetWidth(HandleRef pix);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixGetHeight")]
        int pixGetHeight(HandleRef pix);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixGetDepth")]
        int pixGetDepth(HandleRef pix);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixGetXRes")]
        int pixGetXRes(HandleRef pix);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixGetYRes")]
        int pixGetYRes(HandleRef pix);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixGetResolution")]
        int pixGetResolution(HandleRef pix, out int xres, out int yres);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixGetWpl")]
        int pixGetWpl(HandleRef pix);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixSetXRes")]
        int pixSetXRes(HandleRef pix, int xres);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixSetYRes")]
        int pixSetYRes(HandleRef pix, int yres);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixSetResolution")]
        int pixSetResolution(HandleRef pix, int xres, int yres);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixScaleResolution")]
        int pixScaleResolution(HandleRef pix, float xscale, float yscale);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixGetData")]
        IntPtr pixGetData(HandleRef pix);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixGetInputFormat")]
        ImageFormat pixGetInputFormat(HandleRef pix);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixSetInputFormat")]
        int pixSetInputFormat(HandleRef pix, ImageFormat inputFormat);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixEndianByteSwap")]
        int pixEndianByteSwap(HandleRef pix);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixRead")]
        IntPtr pixRead(string filename);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixReadMemTiff")]
        unsafe IntPtr pixReadMemTiff(byte* data, int length, int page);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixWrite")]
        int pixWrite(string filename, HandleRef handle, ImageFormat format);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixGetColormap")]
        IntPtr pixGetColormap(HandleRef pix);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixSetColormap")]
        int pixSetColormap(HandleRef pix, HandleRef pixCmap);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixDestroyColormap")]
        int pixDestroyColormap(HandleRef pix);

        // pixconv.h functions

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixConvertRGBToGray")]
        IntPtr pixConvertRGBToGray(HandleRef pix, float rwt, float gwt, float bwt);

        // image analysis and manipulation functions

        // skew

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixDeskewGeneral")]
        IntPtr pixDeskewGeneral(HandleRef pix, int redSweep, float sweepRange, float sweepDelta, int redSearch, int thresh, out float pAngle, out float pConf);

        // rotation

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixRotate")]
        IntPtr pixRotate(HandleRef pixs, float angle, RotationMethod type, RotationFill fillColor, int width, int heigh);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixRotateOrth")]
        IntPtr pixRotateOrth(HandleRef pixs, int quads);

        // Binarization - src/binarize.c

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixOtsuAdaptiveThreshold")]
        int pixOtsuAdaptiveThreshold(HandleRef pix, int sx, int sy, int smoothx, int smoothy, float scorefract, out IntPtr ppixth, out IntPtr ppixd);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixSauvolaBinarize")]
        int pixSauvolaBinarize(HandleRef pix, int whsize, float factor, int addborder, out IntPtr ppixm, out IntPtr ppixsd, out IntPtr ppixth, out IntPtr ppixd);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixSauvolaBinarizeTiled")]
        int pixSauvolaBinarizeTiled(HandleRef pix, int whsize, float factor, int nx, int ny, out IntPtr ppixth, out IntPtr ppixd);

        // Scaling - src/scale.c

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixScale")]
        IntPtr pixScale(HandleRef pixs, float scalex, float scaley);

        #endregion

        #region Color map

        // Color map creation and deletion

        /// <summary>
        /// Creates a new colormap with the specified <paramref name="depth"/>.
        /// </summary>
        /// <param name="depth">The depth of the pix in bpp, can be 2, 4, or 8</param>
        /// <returns>The pointer to the color map, or null on error.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapCreate")]
        IntPtr pixcmapCreate(int depth);

        /// <summary>
        /// Creates a new colormap of the specified <paramref name="depth"/> with random colors where the first color can optionally be set to black, and the last optionally set to white.
        /// </summary>
        /// <param name="depth">The depth of the pix in bpp, can be 2, 4, or 8</param>
        /// <param name="hasBlack">If set to 1 the first color will be black.</param>
        /// <param name="hasWhite">If set to 1 the last color will be white.</param>
        /// <returns>The pointer to the color map, or null on error.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapCreateRandom")]
        IntPtr pixcmapCreateRandom(int depth, int hasBlack, int hasWhite);

        /// <summary>
        /// Creates a new colormap of the specified <paramref name="depth"/> with equally spaced gray color values.
        /// </summary>
        /// <param name="depth">The depth of the pix in bpp, can be 2, 4, or 8</param>
        /// <param name="levels">The number of levels (must be between 2 and 2^<paramref name="depth"/></param>
        /// <returns>The pointer to the colormap, or null on error.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapCreateLinear")]
        IntPtr pixcmapCreateLinear(int depth, int levels);

        /// <summary>
        /// Performs a deep copy of the color map.
        /// </summary>
        /// <param name="cmaps">The pointer to the colormap instance.</param>
        /// <returns>The pointer to the colormap, or null on error.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapCopy")]
        IntPtr pixcmapCopy(HandleRef cmaps);

        /// <summary>
        /// Destorys and cleans up any memory used by the color map.
        /// </summary>
        /// <param name="cmap">The pointer to the colormap instance, set to null on success.</param>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapDestroy")]
        void pixcmapDestroy(ref IntPtr cmap);

        // colormap metadata (depth, count, etc)

        /// <summary>
        /// Gets the number of color entries in the color map.
        /// </summary>
        /// <param name="cmap">The pointer to the colormap instance.</param>
        /// <returns>Returns the number of color entries in the color map, or 0 on error.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapGetCount")]
        int pixcmapGetCount(HandleRef cmap);

        /// <summary>
        /// Gets the number of free color entries in the color map.
        /// </summary>
        /// <param name="cmap">The pointer to the colormap instance.</param>
        /// <returns>Returns the number of free color entries in the color map, or 0 on error.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapGetFreeCount")]
        int pixcmapGetFreeCount(HandleRef cmap);

        /// <returns>Returns color maps depth, or 0 on error.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapGetDepth")]
        int pixcmapGetDepth(HandleRef cmap);

        /// <summary>
        /// Gets the minimum pix depth required to support the color map.
        /// </summary>
        /// <param name="cmap">The pointer to the colormap instance.</param>
        /// <param name="minDepth">Returns the minimum depth to support the colormap</param>
        /// <returns>Returns 0 if OK, 1 on error.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapGetMinDepth")]
        int pixcmapGetMinDepth(HandleRef cmap, out int minDepth);

        // colormap - color addition\clearing

        /// <summary>
        /// Removes all colors from the color map by setting the count to zero.
        /// </summary>
        /// <param name="cmap">The pointer to the colormap instance.</param>
        /// <returns>Returns 0 if OK, 1 on error.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapClear")]
        int pixcmapClear(HandleRef cmap);

        /// <summary>
        /// Adds the color to the pix color map if their is room.
        /// </summary>
        /// <returns>Returns 0 if OK, 1 on error.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapAddColor")]
        int pixcmapAddColor(HandleRef cmap, int redValue, int greenValue, int blueValue);

        /// <summary>
        /// Adds the specified color if it doesn't already exist, returning the colors index in the data array.
        /// </summary>
        /// <param name="cmap">The pointer to the colormap instance.</param>
        /// <param name="redValue">The red value</param>
        /// <param name="greenValue">The green value</param>
        /// <param name="blueValue">The blue value</param>
        /// <param name="colorIndex">The index of the new color if it was added, or the existing color if it already existed.</param>
        /// <returns>Returns 0 for success, 1 for error, 2 for not enough space.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapAddNewColor")]
        int pixcmapAddNewColor(HandleRef cmap, int redValue, int greenValue, int blueValue, out int colorIndex);

        /// <summary>
        /// Adds the specified color if it doesn't already exist, returning the color's index in the data array.
        /// </summary>
        /// <remarks>
        /// If the color doesn't exist and there is not enough room to add a new color return the nearest color.
        /// </remarks>
        /// <param name="cmap">The pointer to the colormap instance.</param>
        /// <param name="redValue">The red value</param>
        /// <param name="greenValue">The green value</param>
        /// <param name="blueValue">The blue value</param>
        /// <param name="colorIndex">The index of the new color if it was added, or the existing color if it already existed.</param>
        /// <returns>Returns 0 for success, 1 for error, 2 for not enough space.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapAddNearestColor")]
        int pixcmapAddNearestColor(HandleRef cmap, int redValue, int greenValue, int blueValue, out int colorIndex);

        /// <summary>
        /// Checks if the color already exists or if their is enough room to add it.
        /// </summary>
        /// <param name="cmap">The pointer to the colormap instance.</param>
        /// <param name="redValue">The red value</param>
        /// <param name="greenValue">The green value</param>
        /// <param name="blueValue">The blue value</param>
        /// <param name="usable">Returns 1 if usable; 0 if not.</param>
        /// <returns>Returns 0 if OK, 1 on error.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapUsableColor")]
        int pixcmapUsableColor(HandleRef cmap, int redValue, int greenValue, int blueValue, out int usable);

        /// <summary>
        /// Adds a color (black\white) if not already there returning it's index through <paramref name="index"/>.
        /// </summary>
        /// <param name="cmap">The pointer to the colormap instance.</param>
        /// <param name="color">The color to add (0 for black; 1 for white)</param>
        /// <param name="index">The index of the color.</param>
        /// <returns>Returns 0 if OK; 1 on error.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapAddBlackOrWhite")]
        int pixcmapAddBlackOrWhite(HandleRef cmap, int color, out int index);

        /// <summary>
        /// Sets the darkest color in the colormap to black, if <paramref name="setBlack"/> is 1.
        /// Sets the lightest color in the colormap to white if <paramref name="setWhite"/> is 1.
        /// </summary>
        /// <param name="cmap">The pointer to the colormap instance.</param>
        /// <param name="setBlack">0 for no operation; 1 to set darket color to black</param>
        /// <param name="setWhite">0 for no operation; 1 to set lightest color to white</param>
        /// <returns>Returns 0 if OK; 1 on error.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapSetBlackAndWhite")]
        int pixcmapSetBlackAndWhite(HandleRef cmap, int setBlack, int setWhite);

        // color access - color entry access

        /// <summary>
        /// Gets the color at the specified index.
        /// </summary>
        /// <param name="cmap">The pointer to the colormap instance.</param>
        /// <param name="index">The index of the color entry.</param>
        /// <param name="redValue">The color entry's red value.</param>
        /// <param name="blueValue">The color entry's blue value.</param>
        /// <param name="greenValue">The color entry's green value.</param>
        /// <returns>Returns 0 if OK; 1 if not accessable (caller should check).</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapGetColor")]
        int pixcmapGetColor(HandleRef cmap, int index, out int redValue, out int blueValue, out int greenValue);

        /// <summary>
        /// Gets the color at the specified index.
        /// </summary>
        /// <remarks>
        /// The alpha channel will always be zero as it is not used in Leptonica color maps.
        /// </remarks>
        /// <param name="cmap">The pointer to the colormap instance.</param>
        /// <param name="index">The index of the color entry.</param>
        /// <param name="color">The color entry as 32 bit value</param>
        /// <returns>Returns 0 if OK; 1 if not accessable (caller should check).</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapGetColor32")]
        int pixcmapGetColor32(HandleRef cmap, int index, out int color);

        /// <summary>
        /// Sets a previously allocated color entry.
        /// </summary>
        /// <param name="cmap">The pointer to the colormap instance.</param>
        /// <param name="index">The index of the colormap entry</param>
        /// <param name="redValue"></param>
        /// <param name="blueValue"></param>
        /// <param name="greenValue"></param>
        /// <returns>Returns 0 if OK; 1 if not accessable (caller should check).</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapResetColor")]
        int pixcmapResetColor(HandleRef cmap, int index, int redValue, int blueValue, int greenValue);

        /// <summary>
        /// Gets the index of the color entry with the specified color, return 0 if found; 1 if not.
        /// </summary>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapGetIndex")]
        int pixcmapGetIndex(HandleRef cmap, int redValue, int blueValue, int greenValue, out int index);

        /// <summary>
        /// Returns 0 if the color exists in the color map; otherwise 1.
        /// </summary>
        /// <returns>Returns 0 if OK; 1 on error.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapHasColor")]
        int pixcmapHasColor(HandleRef cmap, int color);

        /// <summary>
        /// Returns the number of unique grey colors including black and white.
        /// </summary>
        /// <returns>Returns 0 if OK; 1 on error.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapCountGrayColors")]
        int pixcmapCountGrayColors(HandleRef cmap, out int ngray);

        /// <summary>
        /// Finds the index of the color entry with the rank intensity.
        /// </summary>
        /// <returns>Returns 0 if OK; 1 on error.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapCountGrayColors")]
        int pixcmapGetRankIntensity(HandleRef cmap, float rankVal, out int index);

        /// <summary>
        /// Finds the index of the color entry closest to the specified color.
        /// </summary>
        /// <returns>Returns 0 if OK; 1 on error.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapGetNearestIndex")]
        int pixcmapGetNearestIndex(HandleRef cmap, int rVal, int bVal, int gVal, out int index);

        /// <summary>
        /// Finds the index of the color entry closest to the specified color.
        /// </summary>
        /// <remarks>
        /// Should only be used on gray colormaps.
        /// </remarks>
        /// <returns>Returns 0 if OK; 1 on error.</returns>
        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapGetNearestGrayIndex")]
        int pixcmapGetNearestGrayIndex(HandleRef cmap, int val, out int index);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapGetComponentRange")]
        int pixcmapGetComponentRange(HandleRef cmap, int component, out int minVal, out int maxVal);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapGetExtremeValue")]
        int pixcmapGetExtremeValue(HandleRef cmap, int type, out int rVal, out int gVal, out int bVal);

        // color map conversion

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapGrayToColor")]
        IntPtr pixcmapGrayToColor(int color);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapColorToGray")]
        IntPtr pixcmapColorToGray(HandleRef cmaps, float redWeight, float greenWeight, float blueWeight);

        // colormap serialization

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapColorToGray")]
        int pixcmapToArrays(HandleRef cmap, out IntPtr redMap, out IntPtr blueMap, out IntPtr greenMap);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapToRGBTable")]
        int pixcmapToRGBTable(HandleRef cmap, out IntPtr colorTable, out int colorCount);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapSerializeToMemory")]
        int pixcmapSerializeToMemory(HandleRef cmap, out int components, out int colorCount, out IntPtr colorData, out int colorDataLength);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapDeserializeFromMemory")]
        IntPtr pixcmapDeserializeFromMemory(HandleRef colorData, int colorCount, int colorDataLength);

        // colormap transformations

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapGammaTRC")]
        int pixcmapGammaTRC(HandleRef cmap, float gamma, int minVal, int maxVal);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapContrastTRC")]
        int pixcmapContrastTRC(HandleRef cmap, float factor);

        [RuntimeDllImport(Constants.LeptonicaDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "pixcmapShiftIntensity")]
        int pixcmapShiftIntensity(HandleRef cmap, float fraction);

        #endregion
    }

    unsafe static class LeptonicaApi
    {
        private static ILeptonicaApiSignatures native;

        public static ILeptonicaApiSignatures Native
        {
            get
            {
                if (native == null)
                    Initialize();
                return native;
            }
        }

        public static void Initialize()
        {
            if (native == null)
            {
                native = InteropRuntimeImplementer.CreateInstance<ILeptonicaApiSignatures>();
            }
        }
    }
}


text:
require 'active_record'
require 'grass/key'
require 'grass/file_sync'
require 'grass/render'
require 'grass/cache'
require 'mime/types'

module Grass

  ##
  # Source is smallest data object

  class Source < ActiveRecord::Base

    MIMES = {
      'text'          => 'text/plain',
      'view'          => 'text/html',
      'layout'        => 'text/html',
      'page'          => 'text/html',
      'script'        => 'application/javascript',
      'stylesheet'    => 'text/css'
    }

    cattr_accessor :fallback

    self.fallback = true
    self.primary_key = :keyid
    self.table_name = :grass_sources

    attr_accessor :key

    after_initialize :convert_key

    def self.[](*keys)
      keys.flatten.map{|key|

        key = Key.new(id: key.dup)

        file = self.find_by(locale: key.locale, dir: key.dir, path: key.path)
        if file.nil? && self.fallback
           file = self.find_by(locale: I18n.default_locale, dir: key.dir, path: key.path)
        end
        file

      }.compact
    end

    scope :locale,    -> (locale) { unscoped.where(locale: locale.to_s) }
    default_scope     -> { where(hidden: false) }

    include FileSync
    include Render
    include Cache

    attr_reader :data

    serialize :pairs, Array

    after_initialize :set_mime_type
    before_save :set_mime_type

    def read
      self.binary || self.result || self.raw
    end

    def write value
      # self.file.write(value)
      self.update(raw: value)
    end

    def type
      @type ||= self.key.dir.split("/").last.singularize
    end

    def hide!
      self.update!(hidden: true)
    end

    def show!
      self.update!(hidden: false)
    end

    private

    def set_mime_type
      self.mime_type ||=  MIMES[self.type] || MIME::Types.type_for(self.binary.nil? ? self.format : self.filepath).first.to_s
    end

    def convert_key
      if self.key.nil?
        self.key = self.filepath ? Key.new(filepath: self.filepath) : Key.new(id: self.keyid)
      elsif self.key.is_a? String
        self.key = Key.new(id: self.key)
      end

      Key::ATTR_TYPES.each do |attr|
        unless attr == :id
          write_attribute(attr,self.key.public_send(attr))
        end
      end
      self.keyid = self.key.id
    end

  end

end


text:
// Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.

package org.rocksdb;

/**
 * Enum CompressionType
 *
 *
DB contents are stored in a set of blocks, each of which holds a
 * sequence of key,value pairs. Each block may be compressed before
 * being stored in a file. The following enum describes which
 * compression method (if any) is used to compress a block.

 */
public enum CompressionType {

  NO_COMPRESSION((byte) 0, null),
  SNAPPY_COMPRESSION((byte) 1, "snappy"),
  ZLIB_COMPRESSION((byte) 2, "z"),
  BZLIB2_COMPRESSION((byte) 3, "bzip2"),
  LZ4_COMPRESSION((byte) 4, "lz4"),
  LZ4HC_COMPRESSION((byte) 5, "lz4hc");

  /**
   *
Get the CompressionType enumeration value by
   * passing the library name to this method.

   *
   *
If library cannot be found the enumeration
   * value {@code NO_COMPRESSION} will be returned.

   *
   * @param libraryName compression library name.
   *
   * @return CompressionType instance.
   */
  public static CompressionType getCompressionType(String libraryName) {
    if (libraryName != null) {
      for (CompressionType compressionType : CompressionType.values()) {
        if (compressionType.getLibraryName() != null &&
            compressionType.getLibraryName().equals(libraryName)) {
          return compressionType;
        }
      }
    }
    return CompressionType.NO_COMPRESSION;
  }

  /**
   *
Get the CompressionType enumeration value by
   * passing the byte identifier to this method.

   *
   *
If library cannot be found the enumeration
   * value {@code NO_COMPRESSION} will be returned.

   *
   * @param byteIdentifier of CompressionType.
   *
   * @return CompressionType instance.
   */
  public static CompressionType getCompressionType(byte byteIdentifier) {
    for (CompressionType compressionType : CompressionType.values()) {
      if (compressionType.getValue() == byteIdentifier) {
        return compressionType;
      }
    }
    return CompressionType.NO_COMPRESSION;
  }

  /**
   *
Returns the byte value of the enumerations value.

   *
   * @return byte representation
   */
  public byte getValue() {
    return value_;
  }

  /**
   *
Returns the library name of the compression type
   * identified by the enumeration value.

   *
   * @return library name
   */
  public String getLibraryName() {
    return libraryName_;
  }

  private CompressionType(byte value, final String libraryName) {
        value_ = value;
        libraryName_ = libraryName;
  }

  private final byte value_;
  private final String libraryName_;
}


text:
package jsonnet

import "github.com/google/go-jsonnet/ast"

// RuntimeError is an error discovered during evaluation of the program
type RuntimeError struct {
	StackTrace []TraceFrame
	Msg        string
}

func makeRuntimeError(msg string, stackTrace []TraceFrame) RuntimeError {
	return RuntimeError{
		Msg:        msg,
		StackTrace: stackTrace,
	}
}

func (err RuntimeError) Error() string {
	return "RUNTIME ERROR: " + err.Msg
}

// The stack

// TraceFrame is tracing information about a single frame of the call stack.
// TODO(sbarzowski) the difference from TraceElement. Do we even need this?
type TraceFrame struct {
	Loc  ast.LocationRange
	Name string
}

func traceElementToTraceFrame(trace *TraceElement) TraceFrame {
	tf := TraceFrame{Loc: *trace.loc}
	if trace.context != nil {
		// TODO(sbarzowski) maybe it should never be nil
		tf.Name = *trace.context
	} else {
		tf.Name = ""
	}
	return tf
}

// TraceElement represents tracing information, including a location range and a
// surrounding context.
// TODO(sbarzowski) better name
type TraceElement struct {
	loc     *ast.LocationRange
	context ast.Context
}


text:
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Resize Multiple</title>
<meta name="description" content="A demonstration of the ResizeMultipleTool extension." />

<meta charset="UTF-8">

    This sample demonstrates a custom ResizingTool which allows the user to resize many selected objects at once.
    It is defined in its own file, as ResizeMultipleTool.js.

    Usage can also be seen in the Floor Plan Editor sample.


text:
'use strict';

module.exports = {
  parserOptions: { ecmaVersion: 2018 },
  rules: {
    'prefer-exponentiation-operator': 'error',
    'prefer-named-capture-group': 'error',
    'prefer-object-spread': 'error'
  }
};