text:
namespace NInternal {
    using namespace NMBus;

    using TReceivers = std::list<TReceiverPtr>;

    TReceivers::iterator find(TReceivers& receivers, TReceiverPtr& receiver) {
        return find(receivers.begin(), receivers.end(), receiver);
    }

    class TGlobalMessenger : public IMessenger {
    public:
        virtual bool Register(TReceiverPtr);
        virtual bool Unregister(TReceiverPtr);
        virtual bool Has(TReceiverPtr);
        virtual void Send(TMessagePtr);
    private:
        TReceivers Receivers;
    };

    bool TGlobalMessenger::Register(TReceiverPtr receiver) {
        if (Has(receiver)) {
            return false;
        }
        Receivers.push_back(receiver);
        return true;
    }

    bool TGlobalMessenger::Unregister(TReceiverPtr receiver) {
        auto iter = find(Receivers, receiver);
        if (iter == Receivers.end()) {
            return false;
        }
        Receivers.erase(iter);
        return true;
    }

    bool TGlobalMessenger::Has(TReceiverPtr receiver) {
        return Receivers.end() != find(Receivers, receiver);
    }

    void TGlobalMessenger::Send(TMessagePtr message) {
        for(auto& receiver : Receivers) {
            receiver->Send(message);
        }
    }

}

namespace NMBus {
    TMessengerPtr GlobalMessenger() {
        return TSingleton<NInternal::TGlobalMessenger>();
    }
}

redpajama_set_name: RedPajamaGithub


text: I dunno, some game


text:
package com.emitrom.ti4j.mobile.client.core.handlers.ui;

import com.emitrom.ti4j.mobile.client.core.events.ui.slider.SliderEvent;
import com.google.gwt.event.shared.EventHandler;

public interface SliderChangeHandler extends EventHandler {
    public void onChange(SliderEvent event);
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using sadx_model_view.Ninja;
using SharpDX;

namespace sadx_model_view.SA1
{
	[Flags]
	public enum ColFlags : uint
	{
		Solid          = 0x1,
		Water          = 0x2,
		NoFriction     = 0x4,
		NoAccel        = 0x8,
		Unknown2       = 0x10,
		UseSkyDrawDist = 0x20,
		NoLandingA     = 0x40,
		IncAccel       = 0x80,
		Dig            = 0x100,
		Unknown5       = 0x200,
		Unknown6       = 0x400,
		Unknown7       = 0x800,
		NoClimb        = 0x1000,
		Unknown8       = 0x2000,
		Stairs         = 0x4000,
		Unknown10      = 0x8000,
		Hurt           = 0x10000,
		Unknown11      = 0x20000,
		Unknown12      = 0x40000,
		Unknown13      = 0x80000,
		Footprints     = 0x100000,
		NoLandingB     = 0x200000,
		WaterNoAlpha   = 0x400000,
		Unknown16      = 0x800000,
		NoAlphaSortPls = 0x1000000,
		AlphaSortThing = 0x2000000,
		UvManipulation = 0x4000000,
		Unknown20      = 0x8000000,
		UseRotation    = 0x10000000,
		Unknown22      = 0x20000000,
		Unknown23      = 0x40000000,
		Visible        = 0x80000000
	}

	/// <summary>
	/// A class defining a model in a <see cref="LandTable"/>.
	/// </summary>
	public class Col : IDisposable
	{
		public static int SizeInBytes => 0x24;

		public Vector3 Center;
		public float   Radius;

		// ReSharper disable once NotAccessedField.Local
		private int pad_a;
		// ReSharper disable once NotAccessedField.Local
		private int pad_b;

		public NJS_OBJECT? Object;
		// ReSharper disable once NotAccessedField.Local
		private int      anonymous_6;
		public  ColFlags Flags;

		/// <summary>
		/// Constructs a Col object from a stream.
		/// </summary>
		/// <param name="stream">The stream containing the Col data.</param>
		public Col(Stream stream)
		{
			byte[] buffer = new byte[SizeInBytes];
			stream.Read(buffer, 0, buffer.Length);
			long position = stream.Position;

			Center = Util.VectorFromStream(in buffer, 0x00);
			Radius = BitConverter.ToSingle(buffer, 0x04);
			pad_a  = BitConverter.ToInt32(buffer, 0x10);
			pad_b  = BitConverter.ToInt32(buffer, 0x14);

			uint object_ptr = BitConverter.ToUInt32(buffer, 0x18);

			if (object_ptr > 0)
			{
				Object = ObjectCache.FromStream(stream, object_ptr);
			}

			anonymous_6 = BitConverter.ToInt32(buffer, 0x1C);
			Flags       = (ColFlags)BitConverter.ToUInt32(buffer, 0x20);

			stream.Position = position;
		}

		public Col()
		{
			Center      = Vector3.Zero;
			Radius      = 0.0f;
			pad_a       = 0;
			pad_b       = 0;
			Object      = null;
			anonymous_6 = 0;
			Flags       = 0;
		}

		public void Dispose()
		{
			Object?.Dispose();
		}

		public void CommitVertexBuffer(Renderer device)
		{
			Object?.CommitVertexBuffer(device);
		}

		public IEnumerable<ObjectTriangles> GetTriangles()
		{
			if (Object == null)
			{
				yield break;
			}

			foreach (NJS_OBJECT o in Object)
			{
				yield return o.GetTriangles();
			}
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<TextView
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:layout_weight="1.0"
	    android:layout_marginTop="100dip"
	    android:gravity="center_horizontal"
	    android:text="@string/hello"
	    android:textSize="16sp"
	    android:textStyle="bold"
	    />
	<Button
		android:id="@+id/btn_settings"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_gravity="center_horizontal"
		android:text="@string/settings"
		/>
	<EditText
		android:id="@+id/massage"
		android:layout_width="200dp"
		android:layout_height="wrap_content"
		android:layout_gravity="center_horizontal"
		android:text=""
		android:hint="来吧"
		/>
	<Button
		android:id="@+id/send"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_gravity="center_horizontal"
		android:text="发送"
		/>
</LinearLayout>


text:
#if !defined(lint) && !defined(DOS)
static char rcsid[] = "$Id: chnge_pw.c 673 2007-08-16 22:25:10Z hubert@u.washington.edu $";
#endif

#include <system.h>		/* os-dep defs/includes */
#include <general.h>		/* generally useful definitions */

#include "../../c-client/mail.h"	/* for MAILSTREAM and friends */
#include "../../c-client/osdep.h"
#include "../../c-client/rfc822.h"	/* for soutr_t and such */
#include "../../c-client/misc.h"	/* for cpystr proto */
#include "../../c-client/utf8.h"	/* for CHARSET and such*/
#include "../../c-client/imap4r1.h"

#include "../../pith/osdep/color.h"
#include "../../pith/state.h"

#include "termin.gen.h"
#include "termout.gen.h"
#include "chnge_pw.h"

/*----------------------------------------------------------------------
       Call the system to change the passwd

It would be nice to talk to the passwd program via a pipe or ptty so the
user interface could be consistent, but we can't count on the the prompts
and responses from the passwd program to be regular so we just let the user
type at the passwd program with some screen space, hope he doesn't scroll
off the top and repaint when he's done.
 ----*/
void
change_passwd(void)
{
#ifdef	PASSWD_PROG
    char cmd_buf[100];

    ClearLines(1, ps_global->ttyo->screen_rows - 1);

    MoveCursor(5, 0);
    fflush(stdout);

    PineRaw(0);
    strncpy(cmd_buf, PASSWD_PROG, sizeof(cmd_buf));
    cmd_buf[sizeof(cmd_buf)-1] = '\0';
    system(cmd_buf);
    sleep(3);
    PineRaw(1);
#endif /* PASSWD_PROG */
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WooCode.Slack.WebHooks
{
    public static class MessageExtensions
    {
        public static void AttachException<T>(this Message @this, T exception) where T : Exception
        {
            var attachment = new Attachment
            {
                Color = AttachmentColor.Danger
            };
            attachment.Fields.Add(new AttachmentField() { Title = "Type", Value = exception.GetType().FullName, Short = true });
            attachment.Fields.Add(new AttachmentField() { Title = "Message", Value = exception.Message, Short = true });

            if (exception.StackTrace != null)
                attachment.Fields.Add(new AttachmentField() { Title = "StackTrace", Value = exception.StackTrace, Short = false });

            if (exception.InnerException != null)
            {
                attachment.Fields.Add(new AttachmentField() { Title = "InnerException Type", Value = exception.InnerException.GetType().FullName, Short = true });
                attachment.Fields.Add(new AttachmentField() { Title = "InnerException Message", Value = exception.InnerException.Message, Short = true });
                if (exception.InnerException.StackTrace != null)
                    attachment.Fields.Add(new AttachmentField() { Title = "InnerException StackTrace", Value = exception.InnerException.StackTrace, Short = false });
            }

            @this.Attachments.Add(attachment);
        }

    }
}


text:
Template.shoppingCart.helpers({
  item: function() {
  	var cart=ShoppingCarts.findOne({ active:true , userId:Meteor.userId()});
  	var items= cart.items;
  	for (i = 0; i < items.length; i++) {
      var dbItem=Products.findOne({code:parseInt(items[i].productCode)});
      items[i].name=dbItem.name;
      items[i].cost=dbItem.cost;
      items[i].image=dbItem.image;
      items[i].total=parseFloat(items[i].amount*items[i].cost).toFixed(2);;
    }
    return items;
  },
  shoppingCart: function() {
    return ShoppingCarts.findOne({ active:true , userId:Meteor.userId()});
  },
  userPressedSig: function(){
    return Session.get('recommendation');

  },
  sessionfalse: function(){
    Session.set('recommendation', false)
  }

});

Template.recommenderCarousel.helpers({
  isItem1: function(){
    res = false
    if (Session.get('recommendationsShopping').length>0){
      res = true
    }
    return res
  },
  isItem2: function(){
    res = false
    if (Session.get('recommendationsShopping').length>4){
      res = true
    }
    return res
  },
  isItem3: function(){
    res = false
    if (Session.get('recommendationsShopping').length>8){
      res = true
    }
    return res
  },
  isItem4: function(){
    res = false
    if (Session.get('recommendationsShopping').length>12){
      res = true
    }
    return res
  },
  recomendations1: function(){
    var response = Session.get('recommendationsShopping');
    var items = []
    if (response.length >= 4){
      for (i = 0; i < 4; i++) {
        var dbItem=Products.findOne({code:parseInt(response[i])});
        items.push(dbItem);
      }
    }else{
      for (i = 0; i < response.length; i++) {
        var dbItem=Products.findOne({code:parseInt(response[i])});
        items.push(dbItem);
      }
    }

    return items
  },
  recomendations2: function(){
    var response = Session.get('recommendationsShopping');
    var items = []

    if (response.length >= 8){
      for (i = 4; i < 8; i++) {
        var dbItem=Products.findOne({code:parseInt(response[i])});
        items.push(dbItem);
      }
    }else{
      for (i = 4; i < response.length; i++) {
        var dbItem=Products.findOne({code:parseInt(response[i])});
        items.push(dbItem);
      }
    }

    return items
  },
  recomendations3: function(){
    var response = Session.get('recommendationsShopping');
    var items = []

    if (response.length >= 12){
      for (i = 8; i < 12; i++) {
        var dbItem=Products.findOne({code:parseInt(response[i])});
        items.push(dbItem);
      }
    }else{
      for (i = 8; i < response.length; i++) {
        var dbItem=Products.findOne({code:parseInt(response[i])});
        items.push(dbItem);
      }
    }
    return items
  },
  recomendations4: function(){
    var response = Session.get('recommendationsShopping');
    var items = []

    if (response.length >= 16){
      for (i = 12; i < 16; i++) {
        var dbItem=Products.findOne({code:parseInt(response[i])});
        items.push(dbItem);
      }
    }else{
      for (i = 12; i < response.length; i++) {
        var dbItem=Products.findOne({code:parseInt(response[i])});
        items.push(dbItem);
      }
    }
    return items
  }
});

Template.shoppingCart.events({
  'click .idConfirmCart': function(){
    if(Meteor.userId()){
          // var t=TAPi18n.__("toastr_addCart", lang_tag=null);
          // Meteor.call('confirmCart');

      Meteor.call('checkUser', Meteor.userId(), function(error, response) {
        if(response){
          var cart=ShoppingCarts.findOne({ active:true , userId:Meteor.userId()});
          var items= cart.items;
          if(items.length>0){
            var totalCost=0.0;
            for (i = 0; i < items.length; i++) {
              var dbItem=Products.findOne({code:parseInt(items[i].productCode)});
              totalCost=totalCost+(items[i].amount*dbItem.cost);
            }
            totalCost=parseFloat(totalCost).toFixed(2);
            bootbox.confirm(TAPi18n.__("confirmOrder", lang_tag=null)
              +totalCost+TAPi18n.__("confirmOrder2", lang_tag=null)+"
"+
              Meteor.user().name+" "+Meteor.user().surname+"
"+
              Meteor.user().address.postalCode+"
"+
              Meteor.user().address.name+"  n: "+
              Meteor.user().address.number, function(result) {
              if(result){
                bootbox.prompt({
                  title: "Confirm credit card number",
                  value: Meteor.user().creditCard.number,
                  callback: function(result) {
                    if (result === null) {
                    } else {
                      Meteor.call('verifyCCNumber', result, function(error, res) {
                        if(!error){
                          Meteor.call('confirmCart');
                          Router.go('home');
                        }
                        else{
                          bootbox.alert(TAPi18n.__("error_CCverification", lang_tag=null));
                        }
                      });
                    }
                  }
                });
              }
            });
          }
          else {
            bootbox.alert(TAPi18n.__("emptyCart", lang_tag=null));
          }
        }
        else{
          bootbox.alert(TAPi18n.__("error_profileDate", lang_tag=null), function() {
            Router.go('/updateProfile');
            $('.modal-backdrop').remove();
          });
        }

      });
    }else{
      var t=TAPi18n.__("toastr_anon", lang_tag=null);
      toastr.error(t);
    }
  },
  'click .recommender': function(){
    Session.set('recommendation', true);
    Session.get('recommendation');

    var cart=ShoppingCarts.findOne({ active:true , userId:Meteor.userId()});
    var codes = [];

    for (i = 0; i < cart.items.length; i++) {
      codes.push(cart.items[i].productCode);
    }

    //var test = [2,3,4,5,6,7,8,9,10,11,12];
    Meteor.call('shoppingRecommender', function(err, data) {
      if (err){
        console.log(err);
      }
      Session.set('recommendationsShopping', data);
    });
    //Session.set('recommendationsShopping', test);
  }

});

Template.recommenderProduct.events({
  'click .idAddCart': function(){
        if(Meteor.userId()){
          var t=TAPi18n.__("toastr_addCart", lang_tag=null);
          Meteor.call('addToCart',this.code);
          toastr.success(t);
        }else{
          var t=TAPi18n.__("toastr_anon", lang_tag=null);
          toastr.error(t);
        }
    }
});

Template.shoppingCartItem.events({
  'click .idDeleteItem': function(){
    Meteor.call('deleteFromCart',this.productCode);
  },
  'click .minusAmount': function(){
    Meteor.call('minusAmount',this.productCode);
  },
  'click .addAmount': function(){
    Meteor.call('addAmount',this.productCode);
  }
});

Template.recommenderProduct.rendered = function () {
  this.$('.rateit').rateit();
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<phpunit>
    <testsuite name='MoySklad'>
        <directory suffix='.php'>./Cases</directory>
    </testsuite>
</phpunit>


text:
using Azure;
using Azure.Core;
using Azure.ResourceManager.Models;

namespace Azure.ResourceManager.Automanage.Models
{
    /// <summary> Details about the resource processed by the configuration profile assignment. </summary>
    public partial class ReportResource : ResourceData
    {
        /// <summary> Initializes a new instance of ReportResource. </summary>
        internal ReportResource()
        {
        }

        /// <summary> Initializes a new instance of ReportResource. </summary>
        /// <param name="id"> The id. </param>
        /// <param name="name"> The name. </param>
        /// <param name="resourceType"> The resourceType. </param>
        /// <param name="systemData"> The systemData. </param>
        /// <param name="status"> Status of the resource. </param>
        /// <param name="error"> Error message, if any, returned when deploying the resource. </param>
        internal ReportResource(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, string status, ResponseError error) : base(id, name, resourceType, systemData)
        {
            Status = status;
            Error = error;
        }

        /// <summary> Status of the resource. </summary>
        public string Status { get; }
        /// <summary> Error message, if any, returned when deploying the resource. </summary>
        public ResponseError Error { get; }
    }
}


text:
#include "config.h"

#if ENABLE(VIDEO_TRACK)
#include "VTTCue.h"

#include "CSSPropertyNames.h"
#include "CSSValueKeywords.h"
#include "DocumentFragment.h"
#include "Event.h"
#include "HTMLDivElement.h"
#include "HTMLSpanElement.h"
#include "Logging.h"
#include "NodeTraversal.h"
#include "RenderVTTCue.h"
#include "Text.h"
#include "TextTrack.h"
#include "TextTrackCueList.h"
#include "VTTScanner.h"
#include "WebVTTElement.h"
#include "WebVTTParser.h"
#include <wtf/MathExtras.h>
#include <wtf/text/StringBuilder.h>

#if ENABLE(WEBVTT_REGIONS)
#include "VTTRegionList.h"
#endif

namespace WebCore {

// This constant should correspond with the percentage returned by CaptionUserPreferences::captionFontSizeScaleAndImportance.
const static double DEFAULTCAPTIONFONTSIZEPERCENTAGE = 5;

static const int undefinedPosition = -1;

static const CSSValueID displayWritingModeMap[] = {
    CSSValueHorizontalTb, CSSValueVerticalRl, CSSValueVerticalLr
};
COMPILE_ASSERT(WTF_ARRAY_LENGTH(displayWritingModeMap) == VTTCue::NumberOfWritingDirections, displayWritingModeMap_has_wrong_size);

static const CSSValueID displayAlignmentMap[] = {
    CSSValueStart, CSSValueCenter, CSSValueEnd, CSSValueLeft, CSSValueRight
};
COMPILE_ASSERT(WTF_ARRAY_LENGTH(displayAlignmentMap) == VTTCue::NumberOfAlignments, displayAlignmentMap_has_wrong_size);

static const String& startKeyword()
{
    DEPRECATED_DEFINE_STATIC_LOCAL(const String, start, (ASCIILiteral("start")));
    return start;
}

static const String& middleKeyword()
{
    DEPRECATED_DEFINE_STATIC_LOCAL(const String, middle, (ASCIILiteral("middle")));
    return middle;
}

static const String& endKeyword()
{
    DEPRECATED_DEFINE_STATIC_LOCAL(const String, end, (ASCIILiteral("end")));
    return end;
}

static const String& leftKeyword()
{
    DEPRECATED_DEFINE_STATIC_LOCAL(const String, left, ("left"));
    return left;
}

static const String& rightKeyword()
{
    DEPRECATED_DEFINE_STATIC_LOCAL(const String, right, ("right"));
    return right;
}

static const String& horizontalKeyword()
{
    return emptyString();
}

static const String& verticalGrowingLeftKeyword()
{
    DEPRECATED_DEFINE_STATIC_LOCAL(const String, verticalrl, (ASCIILiteral("rl")));
    return verticalrl;
}

static const String& verticalGrowingRightKeyword()
{
    DEPRECATED_DEFINE_STATIC_LOCAL(const String, verticallr, (ASCIILiteral("lr")));
    return verticallr;
}

// ----------------------------

PassRefPtr<VTTCueBox> VTTCueBox::create(Document& document, VTTCue& cue)
{
    VTTCueBox* cueBox = new VTTCueBox(document, cue);
    cueBox->setPseudo(VTTCueBox::vttCueBoxShadowPseudoId());
    return adoptRef(cueBox);
}

VTTCueBox::VTTCueBox(Document& document, VTTCue& cue)
    : HTMLElement(divTag, document)
    , m_cue(cue)
{
    setPseudo(vttCueBoxShadowPseudoId());
}

VTTCue* VTTCueBox::getCue() const
{
    return &m_cue;
}

void VTTCueBox::applyCSSProperties(const IntSize& videoSize)
{
    // FIXME: Apply all the initial CSS positioning properties. http://wkb.ug/79916
#if ENABLE(WEBVTT_REGIONS)
    if (!m_cue.regionId().isEmpty()) {
        setInlineStyleProperty(CSSPropertyPosition, CSSValueRelative);
        return;
    }
#endif

    // 3.5.1 On the (root) List of WebVTT Node Objects:

    // the 'position' property must be set to 'absolute'
    setInlineStyleProperty(CSSPropertyPosition, CSSValueAbsolute);

    //  the 'unicode-bidi' property must be set to 'plaintext'
    setInlineStyleProperty(CSSPropertyUnicodeBidi, CSSValueWebkitPlaintext);

    // the 'direction' property must be set to direction
    setInlineStyleProperty(CSSPropertyDirection, m_cue.getCSSWritingDirection());

    // the 'writing-mode' property must be set to writing-mode
    setInlineStyleProperty(CSSPropertyWebkitWritingMode, m_cue.getCSSWritingMode(), false);

    std::pair<float, float> position = m_cue.getCSSPosition();

    // the 'top' property must be set to top,
    setInlineStyleProperty(CSSPropertyTop, static_cast<double>(position.second), CSSPrimitiveValue::CSS_PERCENTAGE);

    // the 'left' property must be set to left
    setInlineStyleProperty(CSSPropertyLeft, static_cast<double>(position.first), CSSPrimitiveValue::CSS_PERCENTAGE);

    double authorFontSize = std::min(videoSize.width(), videoSize.height()) * DEFAULTCAPTIONFONTSIZEPERCENTAGE / 100.0;
    double multiplier = 1.0;
    if (authorFontSize)
        multiplier = m_fontSizeFromCaptionUserPrefs / authorFontSize;

    double textPosition = m_cue.position();
    double maxSize = 100.0;
    CSSValueID alignment = m_cue.getCSSAlignment();
    if (alignment == CSSValueEnd || alignment == CSSValueRight)
        maxSize = textPosition;
    else if (alignment == CSSValueStart || alignment == CSSValueLeft)
        maxSize = 100.0 - textPosition;

    double newCueSize = std::min(m_cue.getCSSSize() * multiplier, 100.0);
    // the 'width' property must be set to width, and the 'height' property  must be set to height
    if (m_cue.vertical() == horizontalKeyword()) {
        setInlineStyleProperty(CSSPropertyWidth, newCueSize, CSSPrimitiveValue::CSS_PERCENTAGE);
        setInlineStyleProperty(CSSPropertyHeight, CSSValueAuto);
        setInlineStyleProperty(CSSPropertyMinWidth, "-webkit-min-content");
        setInlineStyleProperty(CSSPropertyMaxWidth, maxSize, CSSPrimitiveValue::CSS_PERCENTAGE);
        if ((alignment == CSSValueMiddle || alignment == CSSValueCenter) && multiplier != 1.0)
            setInlineStyleProperty(CSSPropertyLeft, static_cast<double>(position.first - (newCueSize - m_cue.getCSSSize()) / 2), CSSPrimitiveValue::CSS_PERCENTAGE);
    } else {
        setInlineStyleProperty(CSSPropertyWidth, CSSValueAuto);
        setInlineStyleProperty(CSSPropertyHeight, newCueSize, CSSPrimitiveValue::CSS_PERCENTAGE);
        setInlineStyleProperty(CSSPropertyMinHeight, "-webkit-min-content");
        setInlineStyleProperty(CSSPropertyMaxHeight, maxSize, CSSPrimitiveValue::CSS_PERCENTAGE);
        if ((alignment == CSSValueMiddle || alignment == CSSValueCenter) && multiplier != 1.0)
            setInlineStyleProperty(CSSPropertyTop, static_cast<double>(position.second - (newCueSize - m_cue.getCSSSize()) / 2), CSSPrimitiveValue::CSS_PERCENTAGE);
    }

    // The 'text-align' property on the (root) List of WebVTT Node Objects must
    // be set to the value in the second cell of the row of the table below
    // whose first cell is the value of the corresponding cue's text track cue
    // alignment:
    setInlineStyleProperty(CSSPropertyTextAlign, m_cue.getCSSAlignment());

    if (!m_cue.snapToLines()) {
        // 10.13.1 Set up x and y:
        // Note: x and y are set through the CSS left and top above.

        // 10.13.2 Position the boxes in boxes such that the point x% along the
        // width of the bounding box of the boxes in boxes is x% of the way
        // across the width of the video's rendering area, and the point y%
        // along the height of the bounding box of the boxes in boxes is y%
        // of the way across the height of the video's rendering area, while
        // maintaining the relative positions of the boxes in boxes to each
        // other.
        setInlineStyleProperty(CSSPropertyWebkitTransform,
            String::format("translate(-%.2f%%, -%.2f%%)", position.first, position.second));

        setInlineStyleProperty(CSSPropertyWhiteSpace, CSSValuePre);
    }
}

const AtomicString& VTTCueBox::vttCueBoxShadowPseudoId()
{
    DEPRECATED_DEFINE_STATIC_LOCAL(const AtomicString, trackDisplayBoxShadowPseudoId, ("-webkit-media-text-track-display", AtomicString::ConstructFromLiteral));
    return trackDisplayBoxShadowPseudoId;
}

RenderPtr<RenderElement> VTTCueBox::createElementRenderer(PassRef<RenderStyle> style)
{
    return createRenderer<RenderVTTCue>(*this, WTF::move(style));
}

// ----------------------------

const AtomicString& VTTCue::cueBackdropShadowPseudoId()
{
    DEPRECATED_DEFINE_STATIC_LOCAL(const AtomicString, cueBackdropShadowPseudoId, ("-webkit-media-text-track-display-backdrop", AtomicString::ConstructFromLiteral));
    return cueBackdropShadowPseudoId;
}

PassRefPtr<VTTCue> VTTCue::create(ScriptExecutionContext& context, double start, double end, const String& content)
{
    return adoptRef(new VTTCue(context, start, end, content));
}

PassRefPtr<VTTCue> VTTCue::create(ScriptExecutionContext& context, const WebVTTCueData& data)
{
    return adoptRef(new VTTCue(context, data));
}

VTTCue::VTTCue(ScriptExecutionContext& context, double start, double end, const String& content)
    : TextTrackCue(context, start, end)
    , m_content(content)
{
    initialize(context);
}

VTTCue::VTTCue(ScriptExecutionContext& context, const WebVTTCueData& cueData)
    : TextTrackCue(context, 0, 0)
{
    initialize(context);
    setText(cueData.content());
    setStartTime(cueData.startTime(), IGNORE_EXCEPTION);
    setEndTime(cueData.endTime(), IGNORE_EXCEPTION);
    setId(cueData.id());
    setCueSettings(cueData.settings());
    m_originalStartTime = cueData.originalStartTime();
}

VTTCue::~VTTCue()
{
    if (!hasDisplayTree())
        return;

    displayTreeInternal()->remove(ASSERT_NO_EXCEPTION);
}

void VTTCue::initialize(ScriptExecutionContext& context)
{
    m_linePosition = undefinedPosition;
    m_computedLinePosition = undefinedPosition;
    m_textPosition = 50;
    m_cueSize = 100;
    m_writingDirection = Horizontal;
    m_cueAlignment = Middle;
    m_webVTTNodeTree = nullptr;
    m_cueBackdropBox = HTMLDivElement::create(toDocument(context));
    m_cueHighlightBox = HTMLSpanElement::create(spanTag, toDocument(context));
    m_displayDirection = CSSValueLtr;
    m_displaySize = 0;
    m_snapToLines = true;
    m_displayTreeShouldChange = true;
    m_notifyRegion = true;
    m_originalStartTime = 0;
}

PassRefPtr<VTTCueBox> VTTCue::createDisplayTree()
{
    return VTTCueBox::create(ownerDocument(), *this);
}

VTTCueBox* VTTCue::displayTreeInternal()
{
    if (!m_displayTree)
        m_displayTree = createDisplayTree();
    return m_displayTree.get();
}

void VTTCue::didChange()
{
    TextTrackCue::didChange();
    m_displayTreeShouldChange = true;
}

const String& VTTCue::vertical() const
{
    switch (m_writingDirection) {
    case Horizontal:
        return horizontalKeyword();
    case VerticalGrowingLeft:
        return verticalGrowingLeftKeyword();
    case VerticalGrowingRight:
        return verticalGrowingRightKeyword();
    default:
        ASSERT_NOT_REACHED();
        return emptyString();
    }
}

void VTTCue::setVertical(const String& value, ExceptionCode& ec)
{
    // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-vertical
    // On setting, the text track cue writing direction must be set to the value given
    // in the first cell of the row in the table above whose second cell is a
    // case-sensitive match for the new value, if any. If none of the values match, then
    // the user agent must instead throw a SyntaxError exception.

    WritingDirection direction = m_writingDirection;
    if (value == horizontalKeyword())
        direction = Horizontal;
    else if (value == verticalGrowingLeftKeyword())
        direction = VerticalGrowingLeft;
    else if (value == verticalGrowingRightKeyword())
        direction = VerticalGrowingRight;
    else
        ec = SYNTAX_ERR;

    if (direction == m_writingDirection)
        return;

    willChange();
    m_writingDirection = direction;
    didChange();
}

void VTTCue::setSnapToLines(bool value)
{
    if (m_snapToLines == value)
        return;

    willChange();
    m_snapToLines = value;
    didChange();
}

void VTTCue::setLine(double position, ExceptionCode& ec)
{
    // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-line
    // On setting, if the text track cue snap-to-lines flag is not set, and the new
    // value is negative or greater than 100, then throw an IndexSizeError exception.
    if (!m_snapToLines && (position < 0 || position > 100)) {
        ec = INDEX_SIZE_ERR;
        return;
    }

    // Otherwise, set the text track cue line position to the new value.
    if (m_linePosition == position)
        return;

    willChange();
    m_linePosition = position;
    m_computedLinePosition = calculateComputedLinePosition();
    didChange();
}

void VTTCue::setPosition(double position, ExceptionCode& ec)
{
    // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-position
    // On setting, if the new value is negative or greater than 100, then throw an IndexSizeError exception.
    // Otherwise, set the text track cue text position to the new value.
    if (position < 0 || position > 100) {
        ec = INDEX_SIZE_ERR;
        return;
    }

    // Otherwise, set the text track cue line position to the new value.
    if (m_textPosition == position)
        return;

    willChange();
    m_textPosition = position;
    didChange();
}

void VTTCue::setSize(int size, ExceptionCode& ec)
{
    // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-size
    // On setting, if the new value is negative or greater than 100, then throw an IndexSizeError
    // exception. Otherwise, set the text track cue size to the new value.
    if (size < 0 || size > 100) {
        ec = INDEX_SIZE_ERR;
        return;
    }

    // Otherwise, set the text track cue line position to the new value.
    if (m_cueSize == size)
        return;

    willChange();
    m_cueSize = size;
    didChange();
}

const String& VTTCue::align() const
{
    switch (m_cueAlignment) {
    case Start:
        return startKeyword();
    case Middle:
        return middleKeyword();
    case End:
        return endKeyword();
    case Left:
        return leftKeyword();
    case Right:
        return rightKeyword();
    default:
        ASSERT_NOT_REACHED();
        return emptyString();
    }
}

void VTTCue::setAlign(const String& value, ExceptionCode& ec)
{
    // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-align
    // On setting, the text track cue alignment must be set to the value given in the
    // first cell of the row in the table above whose second cell is a case-sensitive
    // match for the new value, if any. If none of the values match, then the user
    // agent must instead throw a SyntaxError exception.

    CueAlignment alignment = m_cueAlignment;
    if (value == startKeyword())
        alignment = Start;
    else if (value == middleKeyword())
        alignment = Middle;
    else if (value == endKeyword())
        alignment = End;
    else if (value == leftKeyword())
        alignment = Left;
    else if (value == rightKeyword())
        alignment = Right;
    else
        ec = SYNTAX_ERR;

    if (alignment == m_cueAlignment)
        return;

    willChange();
    m_cueAlignment = alignment;
    didChange();
}

void VTTCue::setText(const String& text)
{
    if (m_content == text)
        return;

    willChange();
    // Clear the document fragment but don't bother to create it again just yet as we can do that
    // when it is requested.
    m_webVTTNodeTree = 0;
    m_content = text;
    didChange();
}

void VTTCue::createWebVTTNodeTree()
{
    if (!m_webVTTNodeTree)
        m_webVTTNodeTree = WebVTTParser::createDocumentFragmentFromCueText(ownerDocument(), m_content);
}

void VTTCue::copyWebVTTNodeToDOMTree(ContainerNode* webVTTNode, ContainerNode* parent)
{
    for (Node* node = webVTTNode->firstChild(); node; node = node->nextSibling()) {
        RefPtr<Node> clonedNode;
        if (node->isWebVTTElement())
            clonedNode = toWebVTTElement(node)->createEquivalentHTMLElement(ownerDocument());
        else
            clonedNode = node->cloneNode(false);
        parent->appendChild(clonedNode, ASSERT_NO_EXCEPTION);
        if (node->isContainerNode())
            copyWebVTTNodeToDOMTree(toContainerNode(node), toContainerNode(clonedNode.get()));
    }
}

PassRefPtr<DocumentFragment> VTTCue::getCueAsHTML()
{
    createWebVTTNodeTree();
    if (!m_webVTTNodeTree)
        return 0;

    RefPtr<DocumentFragment> clonedFragment = DocumentFragment::create(ownerDocument());
    copyWebVTTNodeToDOMTree(m_webVTTNodeTree.get(), clonedFragment.get());
    return clonedFragment.release();
}

PassRefPtr<DocumentFragment> VTTCue::createCueRenderingTree()
{
    RefPtr<DocumentFragment> clonedFragment;
    createWebVTTNodeTree();
    if (!m_webVTTNodeTree)
        return 0;

    clonedFragment = DocumentFragment::create(ownerDocument());
    m_webVTTNodeTree->cloneChildNodes(clonedFragment.get());
    return clonedFragment.release();
}

#if ENABLE(WEBVTT_REGIONS)
void VTTCue::setRegionId(const String& regionId)
{
    if (m_regionId == regionId)
        return;

    willChange();
    m_regionId = regionId;
    didChange();
}

void VTTCue::notifyRegionWhenRemovingDisplayTree(bool notifyRegion)
{
    m_notifyRegion = notifyRegion;
}
#endif

void VTTCue::setIsActive(bool active)
{
    TextTrackCue::setIsActive(active);

    if (!active) {
        if (!hasDisplayTree())
            return;

        // Remove the display tree as soon as the cue becomes inactive.
        removeDisplayTree();
    }
}

int VTTCue::calculateComputedLinePosition()
{
    // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-computed-line-position

    // If the text track cue line position is numeric, then that is the text
    // track cue computed line position.
    if (m_linePosition != undefinedPosition)
        return m_linePosition;

    // If the text track cue snap-to-lines flag of the text track cue is not
    // set, the text track cue computed line position is the value 100;
    if (!m_snapToLines)
        return 100;

    // Otherwise, it is the value returned by the following algorithm:

    // If cue is not associated with a text track, return -1 and abort these
    // steps.
    if (!track())
        return -1;

    // Let n be the number of text tracks whose text track mode is showing or
    // showing by default and that are in the media element's list of text
    // tracks before track.
    int n = track()->trackIndexRelativeToRenderedTracks();

    // Increment n by one.
    n++;

    // Negate n.
    n = -n;

    return n;
}

static bool isCueParagraphSeparator(UChar character)
{
    // Within a cue, paragraph boundaries are only denoted by Type B characters,
    // such as U+000A LINE FEED (LF), U+0085 NEXT LINE (NEL), and U+2029 PARAGRAPH SEPARATOR.
    return u_charType(character) == U_PARAGRAPH_SEPARATOR;
}

void VTTCue::determineTextDirection()
{
    DEPRECATED_DEFINE_STATIC_LOCAL(const String, rtTag, (ASCIILiteral("rt")));
    createWebVTTNodeTree();
    if (!m_webVTTNodeTree)
        return;

    // Apply the Unicode Bidirectional Algorithm's Paragraph Level steps to the
    // concatenation of the values of each WebVTT Text Object in nodes, in a
    // pre-order, depth-first traversal, excluding WebVTT Ruby Text Objects and
    // their descendants.
    StringBuilder paragraphBuilder;
    for (Node* node = m_webVTTNodeTree->firstChild(); node; node = NodeTraversal::next(node, m_webVTTNodeTree.get())) {
        // FIXME: The code does not match the comment above. This does not actually exclude Ruby Text Object descendant.
        if (!node->isTextNode() || node->localName() == rtTag)
            continue;

        paragraphBuilder.append(node->nodeValue());
    }

    String paragraph = paragraphBuilder.toString();
    if (!paragraph.length())
        return;

    for (size_t i = 0; i < paragraph.length(); ++i) {
        UChar current = paragraph[i];
        if (!current || isCueParagraphSeparator(current))
            return;

        if (UChar current = paragraph[i]) {
            UCharDirection charDirection = u_charDirection(current);
            if (charDirection == U_LEFT_TO_RIGHT) {
                m_displayDirection = CSSValueLtr;
                return;
            }
            if (charDirection == U_RIGHT_TO_LEFT || charDirection == U_RIGHT_TO_LEFT_ARABIC) {
                m_displayDirection = CSSValueRtl;
                return;
            }
        }
    }
}

void VTTCue::calculateDisplayParameters()
{
    // Steps 10.2, 10.3
    determineTextDirection();

    // 10.4 If the text track cue writing direction is horizontal, then let
    // block-flow be 'tb'. Otherwise, if the text track cue writing direction is
    // vertical growing left, then let block-flow be 'lr'. Otherwise, the text
    // track cue writing direction is vertical growing right; let block-flow be
    // 'rl'.

    // The above step is done through the writing direction static map.

    // 10.5 Determine the value of maximum size for cue as per the appropriate
    // rules from the following list:
    int maximumSize = m_textPosition;
    if ((m_writingDirection == Horizontal && m_cueAlignment == Start && m_displayDirection == CSSValueLtr)
        || (m_writingDirection == Horizontal && m_cueAlignment == End && m_displayDirection == CSSValueRtl)
        || (m_writingDirection == Horizontal && m_cueAlignment == Left)
        || (m_writingDirection == VerticalGrowingLeft && (m_cueAlignment == Start || m_cueAlignment == Left))
        || (m_writingDirection == VerticalGrowingRight && (m_cueAlignment == Start || m_cueAlignment == Left))) {
        maximumSize = 100 - m_textPosition;
    } else if ((m_writingDirection == Horizontal && m_cueAlignment == End && m_displayDirection == CSSValueLtr)
        || (m_writingDirection == Horizontal && m_cueAlignment == Start && m_displayDirection == CSSValueRtl)
        || (m_writingDirection == Horizontal && m_cueAlignment == Right)
        || (m_writingDirection == VerticalGrowingLeft && (m_cueAlignment == End || m_cueAlignment == Right))
        || (m_writingDirection == VerticalGrowingRight && (m_cueAlignment == End || m_cueAlignment == Right))) {
        maximumSize = m_textPosition;
    } else if (m_cueAlignment == Middle) {
        maximumSize = m_textPosition <= 50 ? m_textPosition : (100 - m_textPosition);
        maximumSize = maximumSize * 2;
    } else
        ASSERT_NOT_REACHED();

    // 10.6 If the text track cue size is less than maximum size, then let size
    // be text track cue size. Otherwise, let size be maximum size.
    m_displaySize = std::min(m_cueSize, maximumSize);

    // FIXME: Understand why step 10.7 is missing (just a copy/paste error?)
    // Could be done within a spec implementation check - http://crbug.com/301580

    // 10.8 Determine the value of x-position or y-position for cue as per the
    // appropriate rules from the following list:
    if (m_writingDirection == Horizontal) {
        switch (m_cueAlignment) {
        case Start:
            if (m_displayDirection == CSSValueLtr)
                m_displayPosition.first = m_textPosition;
            else
                m_displayPosition.first = 100 - m_textPosition - m_displaySize;
            break;
        case End:
            if (m_displayDirection == CSSValueRtl)
                m_displayPosition.first = 100 - m_textPosition;
            else
                m_displayPosition.first = m_textPosition - m_displaySize;
            break;
        case Left:
            if (m_displayDirection == CSSValueLtr)
                m_displayPosition.first = m_textPosition;
            else
                m_displayPosition.first = 100 - m_textPosition;
            break;
        case Right:
            if (m_displayDirection == CSSValueLtr)
                m_displayPosition.first = m_textPosition - m_displaySize;
            else
                m_displayPosition.first = 100 - m_textPosition - m_displaySize;
            break;
        case Middle:
            if (m_displayDirection == CSSValueLtr)
                m_displayPosition.first = m_textPosition - m_displaySize / 2;
            else
                m_displayPosition.first = 100 - m_textPosition - m_displaySize / 2;
            break;
        case NumberOfAlignments:
            ASSERT_NOT_REACHED();
        }
    }

    // A text track cue has a text track cue computed line position whose value
    // is defined in terms of the other aspects of the cue.
    m_computedLinePosition = calculateComputedLinePosition();

    // 10.9 Determine the value of whichever of x-position or y-position is not
    // yet calculated for cue as per the appropriate rules from the following
    // list:
    if (m_snapToLines && m_displayPosition.second == undefinedPosition && m_writingDirection == Horizontal)
        m_displayPosition.second = 0;

    if (!m_snapToLines && m_displayPosition.second == undefinedPosition && m_writingDirection == Horizontal)
        m_displayPosition.second = m_computedLinePosition;

    if (m_snapToLines && m_displayPosition.first == undefinedPosition
        && (m_writingDirection == VerticalGrowingLeft || m_writingDirection == VerticalGrowingRight))
        m_displayPosition.first = 0;

    if (!m_snapToLines && (m_writingDirection == VerticalGrowingLeft || m_writingDirection == VerticalGrowingRight))
        m_displayPosition.first = m_computedLinePosition;
}

void VTTCue::markFutureAndPastNodes(ContainerNode* root, double previousTimestamp, double movieTime)
{
    DEPRECATED_DEFINE_STATIC_LOCAL(const String, timestampTag, (ASCIILiteral("timestamp")));

    bool isPastNode = true;
    double currentTimestamp = previousTimestamp;
    if (currentTimestamp > movieTime)
        isPastNode = false;

    for (Node* child = root->firstChild(); child; child = NodeTraversal::next(child, root)) {
        if (child->nodeName() == timestampTag) {
            double currentTimestamp;
            bool check = WebVTTParser::collectTimeStamp(child->nodeValue(), currentTimestamp);
            ASSERT_UNUSED(check, check);

            currentTimestamp += m_originalStartTime;
            if (currentTimestamp > movieTime)
                isPastNode = false;
        }

        if (child->isWebVTTElement()) {
            toWebVTTElement(child)->setIsPastNode(isPastNode);
            // Make an elemenet id match a cue id for style matching purposes.
            if (!id().isEmpty())
                toElement(child)->setIdAttribute(id());
        }
    }
}

void VTTCue::updateDisplayTree(double movieTime)
{
    // The display tree may contain WebVTT timestamp objects representing
    // timestamps (processing instructions), along with displayable nodes.

    if (!track()->isRendered())
        return;

    // Clear the contents of the set.
    m_cueHighlightBox->removeChildren();

    // Update the two sets containing past and future WebVTT objects.
    RefPtr<DocumentFragment> referenceTree = createCueRenderingTree();
    if (!referenceTree)
        return;

    markFutureAndPastNodes(referenceTree.get(), startTime(), movieTime);
    m_cueHighlightBox->appendChild(referenceTree);
}

VTTCueBox* VTTCue::getDisplayTree(const IntSize& videoSize, int fontSize)
{
    RefPtr<VTTCueBox> displayTree = displayTreeInternal();
    if (!m_displayTreeShouldChange || !track()->isRendered())
        return displayTree.get();

    // 10.1 - 10.10
    calculateDisplayParameters();

    // 10.11. Apply the terms of the CSS specifications to nodes within the
    // following constraints, thus obtaining a set of CSS boxes positioned
    // relative to an initial containing block:
    displayTree->removeChildren();

    // The document tree is the tree of WebVTT Node Objects rooted at nodes.

    // The children of the nodes must be wrapped in an anonymous box whose
    // 'display' property has the value 'inline'. This is the WebVTT cue
    // background box.

    // Note: This is contained by default in m_cueHighlightBox.
    m_cueHighlightBox->setPseudo(cueShadowPseudoId());

    m_cueBackdropBox->setPseudo(cueBackdropShadowPseudoId());
    m_cueBackdropBox->appendChild(m_cueHighlightBox, ASSERT_NO_EXCEPTION);
    displayTree->appendChild(m_cueBackdropBox, ASSERT_NO_EXCEPTION);

    // FIXME(BUG 79916): Runs of children of WebVTT Ruby Objects that are not
    // WebVTT Ruby Text Objects must be wrapped in anonymous boxes whose
    // 'display' property has the value 'ruby-base'.

    displayTree->setFontSizeFromCaptionUserPrefs(fontSize);
    displayTree->applyCSSProperties(videoSize);

    m_displayTreeShouldChange = false;

    // 10.15. Let cue's text track cue display state have the CSS boxes in
    // boxes.
    return displayTree.get();
}

void VTTCue::removeDisplayTree()
{
#if ENABLE(WEBVTT_REGIONS)
    // The region needs to be informed about the cue removal.
    if (m_notifyRegion && track()) {
        if (VTTRegionList* regions = track()->regions()) {
            if (VTTRegion* region = regions->getRegionById(m_regionId))
                region->willRemoveTextTrackCueBox(m_displayTree.get());
        }
    }
#endif

    if (!hasDisplayTree())
        return;
    displayTreeInternal()->remove(ASSERT_NO_EXCEPTION);
}

std::pair<double, double> VTTCue::getPositionCoordinates() const
{
    // This method is used for setting x and y when snap to lines is not set.
    std::pair<double, double> coordinates;

    if (m_writingDirection == Horizontal && m_displayDirection == CSSValueLtr) {
        coordinates.first = m_textPosition;
        coordinates.second = m_computedLinePosition;

        return coordinates;
    }

    if (m_writingDirection == Horizontal && m_displayDirection == CSSValueRtl) {
        coordinates.first = 100 - m_textPosition;
        coordinates.second = m_computedLinePosition;

        return coordinates;
    }

    if (m_writingDirection == VerticalGrowingLeft) {
        coordinates.first = 100 - m_computedLinePosition;
        coordinates.second = m_textPosition;

        return coordinates;
    }

    if (m_writingDirection == VerticalGrowingRight) {
        coordinates.first = m_computedLinePosition;
        coordinates.second = m_textPosition;

        return coordinates;
    }

    ASSERT_NOT_REACHED();

    return coordinates;
}

VTTCue::CueSetting VTTCue::settingName(VTTScanner& input)
{
    CueSetting parsedSetting = None;
    if (input.scan("vertical"))
        parsedSetting = Vertical;
    else if (input.scan("line"))
        parsedSetting = Line;
    else if (input.scan("position"))
        parsedSetting = Position;
    else if (input.scan("size"))
        parsedSetting = Size;
    else if (input.scan("align"))
        parsedSetting = Align;
#if ENABLE(WEBVTT_REGIONS)
    else if (input.scan("region"))
        parsedSetting = RegionId;
#endif
    // Verify that a ':' follows.
    if (parsedSetting != None && input.scan(':'))
        return parsedSetting;

    return None;
}

void VTTCue::setCueSettings(const String& inputString)
{
    if (inputString.isEmpty())
        return;

    VTTScanner input(inputString);

    while (!input.isAtEnd()) {

        // The WebVTT cue settings part of a WebVTT cue consists of zero or more of the following components, in any order,
        // separated from each other by one or more U+0020 SPACE characters or U+0009 CHARACTER TABULATION (tab) characters.
        input.skipWhile<WebVTTParser::isValidSettingDelimiter>();
        if (input.isAtEnd())
            break;

        // When the user agent is to parse the WebVTT settings given by a string input for a text track cue cue,
        // the user agent must run the following steps:
        // 1. Let settings be the result of splitting input on spaces.
        // 2. For each token setting in the list settings, run the following substeps:
        //    1. If setting does not contain a U+003A COLON character (:), or if the first U+003A COLON character (:)
        //       in setting is either the first or last character of setting, then jump to the step labeled next setting.
        //    2. Let name be the leading substring of setting up to and excluding the first U+003A COLON character (:) in that string.
        CueSetting name = settingName(input);

        // 3. Let value be the trailing substring of setting starting from the character immediately after the first U+003A COLON character (:) in that string.
        VTTScanner::Run valueRun = input.collectUntil<WebVTTParser::isValidSettingDelimiter>();

        // 4. Run the appropriate substeps that apply for the value of name, as follows:
        switch (name) {
        case Vertical: {
            // If name is a case-sensitive match for "vertical"
            // 1. If value is a case-sensitive match for the string "rl", then let cue's text track cue writing direction
            //    be vertical growing left.
            if (input.scanRun(valueRun, verticalGrowingLeftKeyword()))
                m_writingDirection = VerticalGrowingLeft;

            // 2. Otherwise, if value is a case-sensitive match for the string "lr", then let cue's text track cue writing
            //    direction be vertical growing right.
            else if (input.scanRun(valueRun, verticalGrowingRightKeyword()))
                m_writingDirection = VerticalGrowingRight;

            else
                LOG(Media, "VTTCue::setCueSettings, invalid Vertical");
            break;
        }
        case Line: {
            bool isValid = false;
            do {
                // 1-2 - Collect chars that are either '-', '%', or a digit.
                // 1. If value contains any characters other than U+002D HYPHEN-MINUS characters (-), U+0025 PERCENT SIGN
                //    characters (%), and characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump
                //    to the step labeled next setting.
                float linePosition;
                bool isNegative;
                if (!input.scanFloat(linePosition, &isNegative))
                    break;

                bool isPercentage = input.scan('%');
                if (!input.isAt(valueRun.end()))
                    break;

                // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT
                //    NINE (9), then jump to the step labeled next setting.
                // 3. If any character in value other than the first character is a U+002D HYPHEN-MINUS character (-), then
                //    jump to the step labeled next setting.
                // 4. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%), then
                //    jump to the step labeled next setting.
                // 5. If the first character in value is a U+002D HYPHEN-MINUS character (-) and the last character in value is a
                //    U+0025 PERCENT SIGN character (%), then jump to the step labeled next setting.
                if (isPercentage && isNegative)
                    break;

                // 6. Ignoring the trailing percent sign, if any, interpret value as a (potentially signed) integer, and
                //    let number be that number.
                // 7. If the last character in value is a U+0025 PERCENT SIGN character (%), but number is not in the range
                //    0 ≤ number ≤ 100, then jump to the step labeled next setting.
                // 8. Let cue's text track cue line position be number.
                // 9. If the last character in value is a U+0025 PERCENT SIGN character (%), then let cue's text track cue
                //    snap-to-lines flag be false. Otherwise, let it be true.
                if (isPercentage) {
                    if (linePosition < 0 || linePosition > 100)
                        break;

                    // 10 - If '%' then set snap-to-lines flag to false.
                    m_snapToLines = false;
                } else {
                    if (linePosition - static_cast<int>(linePosition))
                        break;

                    m_snapToLines = true;
                }

                m_linePosition = linePosition;
                isValid = true;
            } while (0);

            if (!isValid)
                LOG(Media, "VTTCue::setCueSettings, invalid Line");

            break;
        }
        case Position: {
            float position;
            if (WebVTTParser::parseFloatPercentageValue(input, position) && input.isAt(valueRun.end()))
                m_textPosition = position;
            else
                LOG(Media, "VTTCue::setCueSettings, invalid Position");
            break;
        }
        case Size: {
            float cueSize;
            if (WebVTTParser::parseFloatPercentageValue(input, cueSize) && input.isAt(valueRun.end()))
                m_cueSize = cueSize;
            else
                LOG(Media, "VTTCue::setCueSettings, invalid Size");
            break;
        }
        case Align: {
            // 1. If value is a case-sensitive match for the string "start", then let cue's text track cue alignment be start alignment.
            if (input.scanRun(valueRun, startKeyword()))
                m_cueAlignment = Start;

            // 2. If value is a case-sensitive match for the string "middle", then let cue's text track cue alignment be middle alignment.
            else if (input.scanRun(valueRun, middleKeyword()))
                m_cueAlignment = Middle;

            // 3. If value is a case-sensitive match for the string "end", then let cue's text track cue alignment be end alignment.
            else if (input.scanRun(valueRun, endKeyword()))
                m_cueAlignment = End;

            // 4. If value is a case-sensitive match for the string "left", then let cue's text track cue alignment be left alignment.
            else if (input.scanRun(valueRun, leftKeyword()))
                m_cueAlignment = Left;

            // 5. If value is a case-sensitive match for the string "right", then let cue's text track cue alignment be right alignment.
            else if (input.scanRun(valueRun, rightKeyword()))
                m_cueAlignment = Right;

            else
                LOG(Media, "VTTCue::setCueSettings, invalid Align");

            break;
        }
#if ENABLE(WEBVTT_REGIONS)
        case RegionId:
            m_regionId = input.extractString(valueRun);
            break;
#endif
        case None:
            break;
        }

        // Make sure the entire run is consumed.
        input.skipRun(valueRun);
    }
#if ENABLE(WEBVTT_REGIONS)
    // If cue's line position is not auto or cue's size is not 100 or cue's
    // writing direction is not horizontal, but cue's region identifier is not
    // the empty string, let cue's region identifier be the empty string.
    if (m_regionId.isEmpty())
        return;

    if (m_linePosition != undefinedPosition || m_cueSize != 100 || m_writingDirection != Horizontal)
        m_regionId = emptyString();
#endif
}

CSSValueID VTTCue::getCSSAlignment() const
{
    return displayAlignmentMap[m_cueAlignment];
}

CSSValueID VTTCue::getCSSWritingDirection() const
{
    return m_displayDirection;
}

CSSValueID VTTCue::getCSSWritingMode() const
{
    return displayWritingModeMap[m_writingDirection];
}

int VTTCue::getCSSSize() const
{
    return m_displaySize;
}

std::pair<double, double> VTTCue::getCSSPosition() const
{
    if (!m_snapToLines)
        return getPositionCoordinates();

    return m_displayPosition;
}

bool VTTCue::cueContentsMatch(const TextTrackCue& cue) const
{
    const VTTCue* vttCue = toVTTCue(&cue);
    if (text() != vttCue->text())
        return false;
    if (cueSettings() != vttCue->cueSettings())
        return false;
    if (position() != vttCue->position())
        return false;
    if (line() != vttCue->line())
        return false;
    if (size() != vttCue->size())
        return false;
    if (align() != vttCue->align())
        return false;

    return true;
}

bool VTTCue::isEqual(const TextTrackCue& cue, TextTrackCue::CueMatchRules match) const
{
    if (!TextTrackCue::isEqual(cue, match))
        return false;

    if (cue.cueType() != WebVTT)
        return false;

    return cueContentsMatch(cue);
}

bool VTTCue::doesExtendCue(const TextTrackCue& cue) const
{
    if (!cueContentsMatch(cue))
        return false;

    return TextTrackCue::doesExtendCue(cue);
}

void VTTCue::setFontSize(int fontSize, const IntSize&, bool important)
{
    if (!hasDisplayTree() || !fontSize)
        return;

    LOG(Media, "TextTrackCue::setFontSize - setting cue font size to %i", fontSize);

    m_displayTreeShouldChange = true;
    displayTreeInternal()->setInlineStyleProperty(CSSPropertyFontSize, fontSize, CSSPrimitiveValue::CSS_PX, important);
}

VTTCue* toVTTCue(TextTrackCue* cue)
{
    return const_cast<VTTCue*>(toVTTCue(const_cast<const TextTrackCue*>(cue)));
}

const VTTCue* toVTTCue(const TextTrackCue* cue)
{
    ASSERT_WITH_SECURITY_IMPLICATION(cue->isRenderable());
    return static_cast<const VTTCue*>(cue);
}

} // namespace WebCore

#endif


text:
namespace cpr {

class Body {
  public:
    template <typename TextType>
    Body(TextType&& p_text)
            : text{CPR_FWD(p_text)} {}

    std::string text;
};

} // namespace cpr

#endif


text:
package com.anysoftkeyboard.remote;

import androidx.annotation.NonNull;

public interface RemoteInsertion {
    void startMediaRequest(
            @NonNull String[] mimeTypes, int requestId, @NonNull InsertionRequestCallback callback);

    void destroy();
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
      <module fileurl="file://$PROJECT_DIR$/contextplayer.iml" filepath="$PROJECT_DIR$/contextplayer.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/contextplayer-app.iml" filepath="$PROJECT_DIR$/app/contextplayer-app.iml" />
      <module fileurl="file://$PROJECT_DIR$/logger/logger.iml" filepath="$PROJECT_DIR$/logger/logger.iml" />
    </modules>
  </component>
</project>


text:
/* eslint-env jest */
import { execSync as orgExecSync } from 'child_process'

describe('tasksfile', () => {
  const scriptPath = '../../bin/task.js'
  function execSync(cmd: string) {
    return orgExecSync(cmd, {
      cwd: './test/sandbox',
      env: {
        ...process.env,
        FORCE_COLOR: '0'
      },
      stdio: 'pipe'
    }).toString()
  }

  it('executes simple task', () => {
    expect(execSync(`${scriptPath} echo 1 2 3 --foo --bar`)).toEqual(
      "echo [ { foo: true, bar: true }, '1', '2', '3' ]\n"
    )
  })

  it('executes shell commands in a task', () => {
    const output = execSync(`${scriptPath} shell`)
    expect(output).toContain(
      'echo "sync terminal"\nsync terminal\necho "sync silent"\noutput sync silent'
    )
    expect(output).toContain('\nasync terminal\n')
    expect(output).toContain('\noutput async silent\n')
  })

  it('executes task from a namespace', () => {
    expect(execSync(`${scriptPath} nested:echo 1 2 3 --foo --bar`)).toEqual(
      "nested echo [ { foo: true, bar: true }, '1', '2', '3' ]\n"
    )
  })

  it('executes default task from a namespace', () => {
    expect(execSync(`${scriptPath} nested 1 2 3 --foo --bar`)).toEqual(
      "nested default [ { foo: true, bar: true }, '1', '2', '3' ]\n"
    )
  })

  it('includes ./node_modules/.bin to PATH when executing bin scripts', () => {
    execSync('cp -p ./scripts/hello.js ./node_modules/.bin/hello')
    expect(execSync(`${scriptPath} npmBin`)).toEqual('hello\nHello!\n')
  })

  it('executes async/await task', () => {
    expect(execSync(`${scriptPath} asyncAwait`)).toContain(
      'echo "async and await"\noutput async and await\n\nafter await\n'
    )
  })

  it('displays help for a task', () => {
    expect(execSync(`${scriptPath} echo --help`)).toEqual(
      'Usage: echo  \n\nSimple echo task\n\n'
    )
  })

  it('displays detailed help', () => {
    expect(execSync(`${scriptPath} nested:echo --help`)).toEqual(
      'Usage: nested:echo [options] [p1 p2]\n\nDescription of nested task\n\n' +
        'Options:\n\n  --foo       foo option description\n' +
        '  --bar       bar option description\n'
    )
  })

  it('displays error from executed task', () => {
    expect(() => execSync(`${scriptPath} error`)).toThrow(
      `Command failed: ${scriptPath} error`
    )
  })

  it('displays error from executed async task', () => {
    expect(() => execSync(`${scriptPath} errorAsyncAwait`)).toThrow(
      `Command failed: ${scriptPath} errorAsyncAwait`
    )
  })

  it('displays commands list if only --help option provided and no task name', () => {
    expect(execSync(`${scriptPath} --help`)).toMatchSnapshot()
  })
})


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace ZKWebStandard.Collections {
	///
	/// Dictionary use to search hierarchy key(such as path)

	/// Not thread safe

	/// 用于搜索有层级关系的键(例如路径)的词典

	/// 非线程安全

	///
	/// <typeparam name="TKeyElement"></typeparam>
	/// <typeparam name="TValue"></typeparam>
	public class HierarchyDictionary<TKeyElement, TValue> : IDictionary<IEnumerable<TKeyElement>, TValue> {
		///
		/// Key of this node, default value if this is the root

		/// 这个节点对应的键, 如果是根节点则为默认值

		///
		public TKeyElement KeyElement { get; protected set; }
		///
		/// Parent node, null if this is the root

		/// 上级节点, 如果是根节点则为null

		///
		public HierarchyDictionary<TKeyElement, TValue> Parent { get; protected set; }
		///
		/// Is this node has value?

		/// 当前节点是否有值

		///
		public bool HasValue { get; protected set; }
		///
		/// Value of this node

		/// 当前节点的值

		///
		public TValue Value { get; protected set; }
		///
		/// Child nodes

		/// 子节点

		///
		public IDictionary<TKeyElement, HierarchyDictionary<TKeyElement, TValue>> Childs { get; protected set; }

		///
		/// Initialize

		/// 初始化

		///
		public HierarchyDictionary() {
		}

		///
		/// Initialize with parent node

		/// 指定上级节点的初始化

		///
		public HierarchyDictionary(TKeyElement keyElement, HierarchyDictionary<TKeyElement, TValue> parent) {
			KeyElement = keyElement;
			Parent = parent;
		}

		///
		/// Get key of this node

		/// 获取这个节点对应的键

		///
		/// <returns></returns>
		public IEnumerable<TKeyElement> GetKey() {
			var key = new List<TKeyElement>();
			var node = this;
			while (node.Parent != null) {
				key.Add(node.KeyElement);
				node = node.Parent;
			}
			key.Reverse();
			return key;
		}

		///
		/// Travel nodes by the key elements

		/// 根据键里的元素探索节点

		///
		/// <param name="key">Key elements</param>
		/// <param name="createChildsIfNotExist">Create child node if not exist</param>
		/// <returns></returns>
		public IEnumerable<HierarchyDictionary<TKeyElement, TValue>> Travel(
			IEnumerable<TKeyElement> key, bool createChildsIfNotExist) {
			var node = this;
			yield return node;
			foreach (var element in key) {
				if (node.Childs == null || !node.Childs.TryGetValue(element, out var childNode)) {
					if (createChildsIfNotExist) {
						if (node.Childs == null) {
							node.Childs = new Dictionary<TKeyElement, HierarchyDictionary<TKeyElement, TValue>>();
						}
						childNode = new HierarchyDictionary<TKeyElement, TValue>(element, node);
						node.Childs[element] = childNode;
					} else {
						break;
					}
				}
				node = childNode;
				yield return node;
			}
		}

		///
		/// Travel nodes by the key elements, return the last node if found or created

		/// 根据键里的元素探索节点, 返回找到或者创建的最后一个节点

		///
		/// <param name="key">Key elements</param>
		/// <param name="createChildsIfNotExist">Create child node if not exist</param>
		/// <returns></returns>
		public HierarchyDictionary<TKeyElement, TValue> TravelLast(
			IEnumerable<TKeyElement> key, bool createChildsIfNotExist) {
			var node = this;
			foreach (var element in key) {
				if (node.Childs == null || !node.Childs.TryGetValue(element, out var childNode)) {
					if (createChildsIfNotExist) {
						if (node.Childs == null) {
							node.Childs = new Dictionary<TKeyElement, HierarchyDictionary<TKeyElement, TValue>>();
						}
						childNode = new HierarchyDictionary<TKeyElement, TValue>(element, node);
						node.Childs[element] = childNode;
					} else {
#pragma warning disable S1168
						return null;
#pragma warning restore S1168
					}
				}
				node = childNode;
			}
			return node;
		}

#pragma warning disable CS1591
		public TValue this[IEnumerable<TKeyElement> key] {
			get {
				var node = TravelLast(key, false);
				if (node == null || !node.HasValue) {
					throw new KeyNotFoundException($"key [{string.Join(", ", key)}] not found");
				}
				return node.Value;
			}
			set {
				var node = TravelLast(key, true);
				node.Value = value;
				node.HasValue = true;
			}
		}

		public ICollection<IEnumerable<TKeyElement>> Keys {
			get {
				return new List<IEnumerable<TKeyElement>>(this.Select(pair => pair.Key));
			}
		}

		public ICollection<TValue> Values {
			get {
				return new List<TValue>(this.Select(pair => pair.Value));
			}
		}

		public int Count {
			get {
				return this.Select(pair => pair).Count();
			}
		}

		public bool IsReadOnly { get { return false; } }

		public void Add(IEnumerable<TKeyElement> key, TValue value) {
			var node = TravelLast(key, true);
			if (node.HasValue) {
				throw new ArgumentException($"key [{string.Join(", ", key)}] already exists");
			}
			node.Value = value;
			node.HasValue = true;
		}

		public void Add(KeyValuePair<IEnumerable<TKeyElement>, TValue> item) {
			Add(item.Key, item.Value);
		}

		public void Clear() {
			HasValue = false;
			Value = default(TValue);
			Childs = null;
		}

		public bool Contains(KeyValuePair<IEnumerable<TKeyElement>, TValue> item) {
			return ContainsKey(item.Key);
		}

		public bool ContainsKey(IEnumerable<TKeyElement> key) {
			var node = TravelLast(key, false);
			return node != null && node.HasValue;
		}

		public void CopyTo(KeyValuePair<IEnumerable<TKeyElement>, TValue>[] array, int arrayIndex) {
			foreach (var pair in this.Select(pair => pair)) {
				array[arrayIndex++] = pair;
			}
		}

		public IEnumerator<KeyValuePair<IEnumerable<TKeyElement>, TValue>> GetEnumerator() {
			var nodes = new[] { this }.AsEnumerable();
			var childs = nodes;
			while (true) {
				childs = childs.Where(a => a.Childs != null).SelectMany(a => a.Childs.Values);
				if (childs.Any()) {
					nodes = nodes.Concat(childs);
				} else {
					break;
				}
			}
			nodes = nodes.Where(a => a.HasValue);
			return nodes
				.Select(a => new KeyValuePair<IEnumerable<TKeyElement>, TValue>(a.GetKey(), a.Value))
				.GetEnumerator();
		}

		public bool Remove(IEnumerable<TKeyElement> key) {
			var node = this;
			foreach (var element in key) {
				if (node.Childs == null || !node.Childs.TryGetValue(element, out node)) {
					break;
				}
			}
			if (node != null) {
				node.HasValue = false;
				node.Value = default(TValue);
				// Clean up orphans
				while (!node.HasValue && (node.Childs == null || node.Childs.Count == 0)) {
					var parent = node.Parent;
					parent.Childs.Remove(node.KeyElement);
					node = parent;
				}
				return true;
			}
			return false;
		}

		public bool Remove(KeyValuePair<IEnumerable<TKeyElement>, TValue> item) {
			return Remove(item.Key);
		}

		public bool TryGetValue(IEnumerable<TKeyElement> key, out TValue value) {
			var node = TravelLast(key, false);
			if (node != null && node.HasValue) {
				value = node.Value;
				return true;
			} else {
				value = default(TValue);
				return false;
			}
		}

		IEnumerator IEnumerable.GetEnumerator() {
			var nodes = new[] { this }.AsEnumerable();
			nodes = nodes.Concat(nodes.Where(a => a.Childs != null).SelectMany(a => a.Childs.Values));
			return nodes.Where(a => a.HasValue).Select(a => a.Value).GetEnumerator();
		}
#pragma warning restore CS1591
	}
}


text:
/* */
"format cjs";
/**
 * @license
 * Copyright Google Inc. All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */
import * as testing from './dom_test_component_renderer';
export var __platform_browser_dynamic_private__ = {
    DOMTestComponentRenderer: testing.DOMTestComponentRenderer
};
//# sourceMappingURL=private_export_testing.js.map


text:
// <copyright file="Assists.cs" company="Primas">
//     Company copyright tag.
// </copyright>
namespace FPL.Data.Models.FullStats
{
    using System.Collections.Generic;

    using Newtonsoft.Json;

    /// <summary>
    /// The Player Assists class
    /// </summary>
    public class Assists : ModelBase
    {
        /// <summary>
        /// Gets or sets the away assists.
        /// </summary>
        /// <value>
        /// The away.
        /// </value>
        [JsonProperty("away")]
        public virtual IList<object> Away { get; set; }

        /// <summary>
        /// Gets or sets the home assists.
        /// </summary>
        /// <value>
        /// The home.
        /// </value>
        [JsonProperty("home")]
        public virtual IList<Home> Home { get; set; }
    }
}


text:
package com.twitter.meil_mitu.twitter4holo.api.account;

import com.twitter.meil_mitu.twitter4holo.AbsOauth;
import com.twitter.meil_mitu.twitter4holo.AbsPost;
import com.twitter.meil_mitu.twitter4holo.ITwitterJsonConverter;
import com.twitter.meil_mitu.twitter4holo.OauthType;
import com.twitter.meil_mitu.twitter4holo.data.User;
import com.twitter.meil_mitu.twitter4holo.exception.Twitter4HoloException;

import java.io.File;

public class UpdateProfileBackgroundImage extends AbsPost<ITwitterJsonConverter>{

    public UpdateProfileBackgroundImage(AbsOauth oauth, ITwitterJsonConverter json){
        super(oauth, json);
    }

    public UpdateProfileBackgroundImage image(File image){
        addFileParam("image", image);
        return this;
    }

    public UpdateProfileBackgroundImage tile(boolean tile){
        addParam("tile", tile);
        return this;
    }

    public UpdateProfileBackgroundImage includeEntities(boolean includeEntities){
        addParam("include_entities", includeEntities);
        return this;
    }

    public UpdateProfileBackgroundImage skipStatus(boolean skipStatus){
        addParam("skip_status", skipStatus);
        return this;
    }

    public UpdateProfileBackgroundImage use(boolean use){
        addParam("use", use);
        return this;
    }

    @Override
    public String url(){
        return "https://api.twitter.com/1.1/account/update_profile_background_image.json";
    }

    @Override
    public int allowOauthType(){
        return OauthType.Oauth1;
    }

    @Override
    public boolean isAuthorization(){
        return true;
    }

    @Override
    public User call() throws Twitter4HoloException{
        return Json.toUser(Oauth.post(this));
    }
}


text:
module Gifts::Grit

  class Config
    def initialize(repo)
      @repo = repo
    end

    def []=(key, value)
      @repo.git.config({}, key, value)
      @data = nil
    end

    def [](key)
      data[key]
    end

    def fetch(key, default = nil)
      data[key] || default || raise(IndexError.new("key not found"))
    end

    def keys
      data.keys
    end

    protected
      def data
        @data ||= load_config
      end

      def load_config
        hash = {}
        config_lines.map do |line|
          key, value = line.split(/=/, 2)
          hash[key] = value
        end
        hash
      end

      def config_lines
        @repo.git.config(:list => true).split(/\n/)
      end
  end # Config

end # Gifts::Grit


text:
<?php

namespace frontend\controllers;

use Yii;
use app\models\AkkSijilCpr;
use frontend\models\AkkSijilCprSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;

use app\models\general\Upload;
use app\models\general\GeneralVariable;
use common\models\general\GeneralFunction;

/**
 * AkkSijilCprController implements the CRUD actions for AkkSijilCpr model.
 */
class AkkSijilCprController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all AkkSijilCpr models.
     * @return mixed
     */
    public function actionIndex()
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        $searchModel = new AkkSijilCprSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single AkkSijilCpr model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        $model = $this->findModel($id);

        $model->tarikh_tamat = GeneralFunction::convert($model->tarikh_tamat);

        return $this->renderAjax('view', [
            'model' => $model,
            'readonly' => true,
        ]);
    }

    /**
     * Creates a new AkkSijilCpr model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($akademi_akk_id)
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        $model = new AkkSijilCpr();

        Yii::$app->session->open();

        if($akademi_akk_id != ''){
            $model->akademi_akk_id = $akademi_akk_id;
        } else {
            if(isset(Yii::$app->session->id)){
                $model->session_id = Yii::$app->session->id;
            }
        }

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $file = UploadedFile::getInstance($model, 'sijil');
            if($file){
                $model->sijil = Upload::uploadFile($file, Upload::akademiAkkFolder, $model->akk_sijil_cpr_id, Upload::akademiAkkSijilCprFolder);
            }

            if($model->save()){
                return '1';
            }
        }

        return $this->renderAjax('create', [
            'model' => $model,
            'readonly' => false,
        ]);
    }

    /**
     * Updates an existing AkkSijilCpr model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        $model = $this->findModel($id);

        $existingSijil= $model->sijil;

        if($model->load(Yii::$app->request->post())){
            $file = UploadedFile::getInstance($model, 'sijil');

            if($file){
                //valid file to upload
                //upload file to server

                // delete upload file
                /*if($existingSijil != ""){
                    self::actionDeleteupload($id, 'sijil');
                }

                $model->sijil = Upload::uploadFile($file, Upload::akademiAkkFolder, $model->akk_sijil_cpr_id, Upload::akademiAkkSijilCprFolder);*/
            } else {
                //invalid file to upload
                //remain existing file
                $model->sijil = $existingSijil;
            }
        }

        if (Yii::$app->request->post() && $model->save()) {
            $file = UploadedFile::getInstance($model, 'sijil');
            if($file){
                $model->sijil = Upload::uploadFile($file, Upload::akademiAkkFolder, $model->akk_sijil_cpr_id, Upload::akademiAkkSijilCprFolder);
            }

            if($model->save()){
                return '1';
            }
        }

        return $this->renderAjax('update', [
                'model' => $model,
                'readonly' => false,
            ]);
    }

    /**
     * Deletes an existing AkkSijilCpr model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        self::actionDeleteupload($id, 'sijil');

        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the AkkSijilCpr model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return AkkSijilCpr the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = AkkSijilCpr::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    // Add function for delete image or file
    public function actionDeleteupload($id, $field)
    {
            $img = $this->findModel($id)->$field;

            if($img){
                if (!unlink($img)) {
                    return false;
                }
            }

            $img = $this->findModel($id);
            $img->$field = NULL;
            $img->update();

            //return $this->redirect(['update', 'id' => $id]);
    }
}


text:
#ifndef _CLINK_MEDIA_GATEWAYITEMNODE_H_
#define _CLINK_MEDIA_GATEWAYITEMNODE_H_

#include <cybergarage/io/File.h>
#include <cybergarage/io/FileInputStream.h>
#include <cybergarage/upnp/media/server/object/item/ItemNode.h>

namespace CyberLink {

class GatewayItemNode : public ItemNode
{
	CyberIO::File *itemFile;

	////////////////////////////////////////////////
	// Constroctor
	////////////////////////////////////////////////

public:

	GatewayItemNode();

	////////////////////////////////////////////////
	// File/TimeStamp
	////////////////////////////////////////////////

public:

	void setFile(CyberIO::File *file)
	{
		itemFile = file;
	}

	CyberIO::File *getFile()
	{
		return itemFile;
	}

	long getFileTimeStamp()
	{
		return itemFile->lastModified();
	}

	bool equals(CyberIO::File *file)
	{
		if (itemFile == NULL)
			return false;
		return itemFile->equals(file);
	}

	////////////////////////////////////////////////
	// Abstract methods
	////////////////////////////////////////////////

public:

	const char *getContent(std::string &buf);

	long getContentLength()
	{
		return itemFile->length();
	}

	CyberIO::InputStream *getContentInputStream();

	const char *getMimeType();
};

}

#endif


text:
from django.contrib import admin
from mptt.admin import MPTTModelAdmin
from T.tings.models.models_tings import TTing

class TTingAdminAdmin(MPTTModelAdmin):
    mptt_level_indent = 20

admin.site.register(TTing, TTingAdminAdmin)


text:
package org.apache.cassandra.utils.logging;

import java.util.Map;

/**
 * Common abstraction of functionality which can be implemented for different logging backend implementations (slf4j bindings).
 * Concrete implementations are dynamically loaded and instantiated by {@link LoggingSupportFactory#getLoggingSupport()}.
 */
public interface LoggingSupport
{
    /**
     * Hook used to execute logging implementation specific customization at Cassandra startup time.
     */
    default void onStartup() {}

    /**
     * Hook used to execute logging implementation specific customization at Cassandra shutdown time.
     */
    default void onShutdown() {}

    /**
     * Changes the given logger to the given log level.
     *
     * @param classQualifier the class qualifier or logger name
     * @param rawLevel the string representation of a log level
     * @throws Exception an exception which may occur while changing the given logger to the given log level.
     */
    void setLoggingLevel(String classQualifier, String rawLevel) throws Exception;

    /**
     * @return a map of logger names and their associated log level as string representations.
     */
    Map<String, String> getLoggingLevels();
}


text:
/*
 * HibernateUtil.java
 *
 * Created on March 27, 2007, 10:39 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package test;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;
    //public static final String DIALECT;
    static {
        try {
            // Create the SessionFactory
            sessionFactory = new Configuration().configure("qbt-hibernate.cfg.xml").buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static final ThreadLocal session = new ThreadLocal();

    public static Session getSession() throws HibernateException {
        Session s = (Session) session.get();
        // Open a new Session, if this Thread has none yet
        if (s == null) {
            s = sessionFactory.openSession();
            session.set(s);
        }
        return s;
    }

    public static void closeSession() throws HibernateException {
        Session s = (Session) session.get();
        session.set(null);
        if (s != null)
            s.close();
    }
}


text:
package cc.catalysts.boot.report.pdf.elements;

import cc.catalysts.boot.report.pdf.config.PdfTextStyle;
import cc.catalysts.boot.report.pdf.utils.ReportAlignType;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.springframework.util.StringUtils;

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

/**
 *
IMPORTANT: Although this class is publicly visible, it is subject to change and may not be implemented by clients!

 *
 * @author Klaus Lehner
 */
public class ReportTextBox implements ReportElement {

    private static final String LINE_SEPARATOR = System.getProperty("line.separator");

    protected PdfTextStyle textConfig;
    protected String text;
    protected final float lineDistance;
    protected ReportAlignType align = ReportAlignType.LEFT;
    protected Map<CacheKey, String[]> cache = new HashMap<CacheKey, String[]>();

    public ReportTextBox(PdfTextStyle textConfig, float lineDistance, String text) {
        this.textConfig = textConfig;
        this.text = text == null ? "" : text;
        this.lineDistance = lineDistance;
    }

    /**
     * copy constructor with new text
     *
     * @param object reportTextBox object for configurations
     * @param text   text of text box
     */
    public ReportTextBox(ReportTextBox object, String text) {
        this.text = text == null ? "" : text;
        this.textConfig = object.textConfig;
        this.lineDistance = object.lineDistance;
        this.align = object.align;
    }

    public ReportTextBox clone(String newString) {
        return new ReportTextBox(this, newString);
    }

    @Override
    public float print(PDDocument document, PDPageContentStream stream, int pageNumber, float textX, float textY, float allowedWidth) {
        return PdfBoxHelper.addTextWithLineBreaks(stream, textConfig, textX, textY, allowedWidth, lineDistance, align, text);
    }

    @Override
    public float getHeight(float allowedWidth) {
        int height = 0;
        String currText = text;
        while (currText != null) {
            if  (height > 0 && "".equals(currText)) {
                // a trailing empty string does not add any height
                break;
            }
            String[] split = split(allowedWidth, currText);
            height += getFirstSegmentHeight(allowedWidth) + lineDistance;
            if (split[1] != null && split[1].equals(currText)) {
                // see PdfBoxHelper:441, it could be that text is not reduced, but just put in a second row,
                // in that case we would run in an endless loop
                // that needs to be fixed in PdfBoxHelper, this is just the attempt to ensure that we do not
                // run into an endless loop here

                height += getFirstSegmentHeight(allowedWidth) + lineDistance;
                break;
            }
            currText = split[1];

        }
        return height;
    }

    @Override
    public boolean isSplitable() {
        return true;
    }

    @Override
    public float getFirstSegmentHeight(float allowedWidth) {
        return textConfig.getFontSize();
    }

    @Override
    public ReportElement[] split(float allowedWidth) {
        String[] split = split(allowedWidth, text);
        ReportElement firstLine = new ReportTextBox(this, split[0]);
        ReportElement nextLines = new ReportTextBox(this, split[1]);
        return new ReportElement[]{firstLine, nextLines};
    }

    @Override
    public ReportElement[] split(float allowedWidth, float allowedHeight) {
        StringBuilder sb = new StringBuilder();
        float currHeight = 0;
        String currText = text;
        while (!StringUtils.isEmpty(currText) && currHeight <= allowedHeight) {
            if (currHeight + getFirstSegmentHeight(allowedWidth) <= allowedHeight) {
                String[] split = split(allowedWidth, currText);
                sb.append(split[0].trim());
                sb.append(LINE_SEPARATOR);
                currText = split[1];
                currHeight += getFirstSegmentHeight(allowedWidth) + lineDistance;
            } else {
                break;
            }
        }

        ReportElement firstPart = new ReportTextBox(this, sb.toString());
        ReportElement nextLines = StringUtils.isEmpty(currText) ? null : new ReportTextBox(this, currText);
        return new ReportElement[]{firstPart, nextLines};
    }

    @Override
    public float getHeightOfElementToSplit(float allowedWidth, float allowedHeight) {
        return getHeight(allowedWidth);
    }

    @Override
    public Collection<ReportImage.ImagePrintIntent> getImageIntents() {
        return Collections.emptyList();
    }

    protected String[] split(float allowedWidth, String text) {
        if (text == null) {
            return new String[]{null, null};
        }
        CacheKey key = new CacheKey(textConfig.getCurrentFontStyle(), textConfig.getFontSize(), allowedWidth, text);
        if (cache.containsKey(key)) {
            return cache.get(key);
        } else {
            String[] split = PdfBoxHelper.splitText(textConfig.getCurrentFontStyle(), textConfig.getFontSize(), allowedWidth, text);
            cache.put(key, split);
            return split;
        }
    }

    public ReportAlignType getAlign() {
        return align;
    }

    public void setAlign(ReportAlignType align) {
        this.align = align;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    private static final class CacheKey {
        private PDFont font;
        private float fontSize;
        private float width;
        private String text;

        private CacheKey(PDFont font, float fontSize, float width, String text) {
            this.font = font;
            this.fontSize = fontSize;
            this.width = width;
            this.text = text;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            CacheKey cacheKey = (CacheKey) o;

            if (!text.equals(cacheKey.text)) return false;
            if (fontSize != cacheKey.fontSize) return false;
            if (Float.compare(cacheKey.width, width) != 0) return false;
            return font.equals(cacheKey.font);

        }

        @Override
        public int hashCode() {
            int result = font.hashCode();
            result = 31 * result + (int) fontSize;
            result = 31 * result + text.hashCode();
            result = 31 * result + (width != +0.0f ? Float.floatToIntBits(width) : 0);
            return result;
        }
    }
}


text:
package demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;

@Configuration
@EnableResourceServer
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class SecurityConfig implements ResourceServerConfigurer {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("ui-implicit");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .httpBasic().disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .anonymous()
                .and()
                .authorizeRequests()
                .anyRequest().permitAll()
                .and()
                .csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
                .and()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/");
    }

}


text:
include_recipe "bcpc::packages-mysql"

ruby_block "initialize-mysql-config" do
    block do
        make_config('mysql-root-user', "root")
        make_config('mysql-root-password', secure_password)
        make_config('mysql-galera-user', "sst")
        make_config('mysql-galera-password', secure_password)
        make_config('mysql-check-user', "check")
        make_config('mysql-check-password', secure_password)
    end
end

ruby_block "initial-mysql-config" do
    block do
        %x[ mysql -u root -e "DELETE FROM mysql.user WHERE user='';"
            mysql -u root -e "UPDATE mysql.user SET password=PASSWORD('#{get_config('mysql-root-password')}') WHERE user='root'; FLUSH PRIVILEGES;"
            export MYSQL_PWD=#{get_config('mysql-root-password')};
            mysql -u root -e "UPDATE mysql.user SET host='%' WHERE user='root' and host='localhost'; FLUSH PRIVILEGES;"
            mysql -u root -e "GRANT USAGE ON *.* to #{get_config('mysql-galera-user')}@'%' IDENTIFIED BY '#{get_config('mysql-galera-password')}';"
            mysql -u root -e "GRANT ALL PRIVILEGES on *.* TO #{get_config('mysql-galera-user')}@'%' IDENTIFIED BY '#{get_config('mysql-galera-password')}';"
            mysql -u root -e "GRANT PROCESS ON *.* to '#{get_config('mysql-check-user')}'@'localhost' IDENTIFIED BY '#{get_config('mysql-check-password')}';"
            mysql -u root -e "FLUSH PRIVILEGES;"
        ]
    end
    not_if { system "MYSQL_PWD=#{get_config('mysql-root-password')} mysql -uroot -e 'SELECT user from mysql.user where User=\"haproxy\"' >/dev/null" }
end

include_recipe "bcpc::mysql-common"

template "/etc/mysql/debian.cnf" do
    source "my-debian.cnf.erb"
    mode 00644
    variables(
        :root_user_key => "mysql-root-user",
        :root_pass_key => "mysql-root-password"
    )
    notifies :reload, "service[mysql]", :immediately
end

if node['bcpc']['mysql-head']['max_connections'] == 0 then
    node.default['bcpc']['mysql-head']['max_connections'] = [get_head_nodes.length*150+get_all_nodes.length*10, 450].max
end

template "/etc/mysql/conf.d/wsrep.cnf" do
    source "wsrep.cnf.erb"
    mode 00644
    variables(
        :max_connections => node['bcpc']['mysql-head']['max_connections'],
        :servers => get_head_nodes,
        :wsrep_cluster_name => node['bcpc']['region_name'],
        :wsrep_port => 4567,
        :galera_user_key => "mysql-galera-user",
        :galera_pass_key => "mysql-galera-password",
        :innodb_buffer_pool_size => node['bcpc']['mysql-head']['innodb_buffer_pool_size'],
        :innodb_buffer_pool_instances => node['bcpc']['mysql-head']['innodb_buffer_pool_instances'],
        :thread_cache_size => node['bcpc']['mysql-head']['thread_cache_size'],
        :innodb_io_capacity => node['bcpc']['mysql-head']['innodb_io_capacity'],
        :innodb_log_buffer_size => node['bcpc']['mysql-head']['innodb_log_buffer_size'],
        :innodb_flush_method => node['bcpc']['mysql-head']['innodb_flush_method'],
        :wsrep_slave_threads => node['bcpc']['mysql-head']['wsrep_slave_threads'],
        :slow_query_log => node['bcpc']['mysql-head']['slow_query_log'],
        :slow_query_log_file => node['bcpc']['mysql-head']['slow_query_log_file'],
        :long_query_time => node['bcpc']['mysql-head']['long_query_time'],
        :log_queries_not_using_indexes => node['bcpc']['mysql-head']['log_queries_not_using_indexes']
    )
    notifies :restart, "service[mysql]", :immediately
end

# logrotate_app resource is not used because it does not support lazy {}
template '/etc/logrotate.d/mysql_slow_query' do
  source 'logrotate_mysql_slow_query.erb'
  mode   '00400'
  variables(
    lazy {
      {
        :slow_query_log_file => node['bcpc']['mysql-head']['slow_query_log_file'],
        :mysql_root_password => get_config('mysql-root-password'),
        :mysql_root_user     => get_config('mysql-root-user')
      }
    }
  )
end

template '/usr/local/bin/mysql_slow_query_check.sh' do
  source 'mysql_slow_query_check.sh.erb'
  mode  '00755'
  owner 'root'
  group 'root'
  variables(
    slow_query_log_file: node['bcpc']['mysql-head']['slow_query_log_file']
  )
end