text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Msagl.Core.DataStructures;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Routing.Rectilinear;

namespace Microsoft.Msagl.Routing.Visibility {
    /// <summary>
    /// following "Visibility Algorithms in the Plane", Ghosh
    /// </summary>
    internal class PointVisibilityCalculator {
        [SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] //  VisibilityGraph graphOfHoleBoundaries;
            ActiveEdgeComparerWithRay activeEdgeComparer;

        RbTree<PolylinePoint> activeSidesTree;

        /// <summary>
        /// A mapping from sides to their RBNodes
        /// </summary>
        Dictionary<PolylinePoint, RBNode<PolylinePoint>> sideNodes = new Dictionary<PolylinePoint, RBNode<PolylinePoint>>();

        readonly BinaryHeapWithComparer<Stem> heapForSorting;

        readonly VisibilityGraph visibilityGraph;
        readonly VisibilityKind visibilityKind;

        /// <summary>
        /// These are parts of hole boundaries visible from q where each node is taken in isolation
        /// </summary>
        readonly Dictionary<Polyline, Stem> visibleBoundaries = new Dictionary<Polyline, Stem>();

        Point q;
        readonly PolylinePoint qPolylinePoint;

        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal VisibilityVertex QVertex { get; set; }

        readonly List<PolylinePoint> sortedListOfPolypoints = new List<PolylinePoint>();
                                     //the sorted list of possibly visible vertices

        readonly IEnumerable<Polyline> holes;

        /// <summary>
        /// We suppose that the holes are convex and oriented clockwis and are mutually disjoint
        /// </summary>
        /// <param name="listOfHoles"></param>
        /// <param name="visibilityGraph"></param>
        /// <param name="point">The point can belong to the boundary of one of the holes</param>
        /// <param name="visibilityKind">tangent or regural visibility</param>
        /// <param name="qVertex">the graph vertex corresponding to the pivot</param>
        /// <returns></returns>
        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal static void CalculatePointVisibilityGraph(IEnumerable<Polyline> listOfHoles,
                                                           VisibilityGraph visibilityGraph, Point point,
                                               VisibilityKind visibilityKind, out VisibilityVertex qVertex) {
            //maybe there is nothing to do
            var qv = visibilityGraph.FindVertex(point);
            if (qv != null){
                qVertex = qv;
                return;
            }

            var calculator = new PointVisibilityCalculator(listOfHoles, visibilityGraph, point, visibilityKind);
            calculator.FillGraph();
            qVertex = calculator.QVertex;
            Debug.Assert(qVertex != null);
        }

        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        void FillGraph() {
            ComputeHoleBoundariesPossiblyVisibleFromQ();
            if (visibleBoundaries.Count > 0) {
                SortSAndInitActiveSides();
                // CheckActiveSidesAreConsistent();
                Sweep();
            }
        }

        /// <summary>
        /// sorts the set of potentially visible vertices around point q
        /// </summary>
        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        void SortSAndInitActiveSides() {
            InitHeapAndInsertActiveSides();
            for (Stem stem = heapForSorting.GetMinimum();; stem = heapForSorting.GetMinimum()) {
                sortedListOfPolypoints.Add(stem.Start);
                if (stem.MoveStartClockwise())
                    heapForSorting.ChangeMinimum(stem);
                else
                    heapForSorting.Dequeue();
                if (heapForSorting.Count == 0)
                    break;
            }
        }

        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        void InitHeapAndInsertActiveSides() {
            foreach (Stem pp in GetInitialVisibleBoundaryStemsAndInsertActiveSides())
                heapForSorting.Enqueue(pp);
        }

        /// <summary>
        /// these are chuncks of the visible boundaries growing from the polyline  point just above its crossing with the horizontal ray or
        /// from the visible part start
        /// In the general case we have two stems from one polyline
        /// </summary>
        /// <returns></returns>
        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        IEnumerable<Stem> GetInitialVisibleBoundaryStemsAndInsertActiveSides() {
            foreach (var keyValuePair in visibleBoundaries) {
                Polyline hole = keyValuePair.Key;
                Stem stem = keyValuePair.Value;
                bool crosses = false;

                foreach (PolylinePoint side in stem.Sides) {
                    PolylinePoint source = side;
                    if (source.Point.Y < q.Y) {
                        if (side.NextOnPolyline.Point.Y >= q.Y) {
                            TriangleOrientation orientation = Point.GetTriangleOrientation(q, source.Point,
                                                                                side.NextOnPolyline.Point);
                            if (orientation == TriangleOrientation.Counterclockwise ||
                                orientation == TriangleOrientation.Collinear) {
                                crosses = true;
                                //we have two stems here
                                yield return new Stem(stem.Start, side);
                                yield return new Stem(side.NextOnPolyline, stem.End);

                                RegisterActiveSide(side);
                                break;
                            }
                        }
                    } else if (source.Point.Y > q.Y)
                        break;
                    else if (side.Point.X >= q.X) {
                        //we have pp.Y==q.Y
                        crosses = true;
                        //we need to add one or two stems here
                        yield return new Stem(side, stem.End);
                        if (side != stem.Start)
                            yield return new Stem(stem.Start, hole.Prev(source));

                        RegisterActiveSide(side);
                        break;
                    }
                }
                //there is no intersection with the ray
                if (!crosses)
                    yield return stem;
            }
        }

        void RegisterActiveSide(PolylinePoint side)
        {
            activeEdgeComparer.IntersectionOfTheRayAndInsertedEdge = activeEdgeComparer.IntersectEdgeWithRay(side, new Point(1, 0));
            sideNodes[side] = activeSidesTree.Insert(side);
        }

        //private Polyline GetPolylineBetweenPolyPointsTest(Polyline hole, PolylinePoint p0, PolylinePoint p1) {
        //    Polyline ret = new Polyline();
        //    while (p0 != p1) {
        //        ret.AddPoint(p0.Point);
        //        p0 = hole.Next(p0);
        //    }

        //    ret.AddPoint(p1.Point);
        //    return ret;
        //}

        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        PointVisibilityCalculator(IEnumerable<Polyline> holes, VisibilityGraph visibilityGraph, Point point,
                                  VisibilityKind visibilityKind) {
            this.holes = holes;
            //this.graphOfHoleBoundaries = holeBoundariesGraph;
            this.visibilityGraph = visibilityGraph;
            q = point;
            qPolylinePoint = new PolylinePoint(q);
            QVertex = this.visibilityGraph.AddVertex(qPolylinePoint);
            this.visibilityKind = visibilityKind;
            heapForSorting = new BinaryHeapWithComparer<Stem>(new StemStartPointComparer(q));
        }

        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        void Sweep() {
            foreach (PolylinePoint polylinePoint in sortedListOfPolypoints)
                SweepPolylinePoint(polylinePoint);
#if TEST_MSAGL
            //List<ICurve> l = new List<ICurve>();
            //foreach (PEdge pe in this.visibilityGraph.Edges) {
            //    if (!ApproximateComparer.Close(pe.SourcePoint, pe.TargetPoint && pe.Target.PolylinePoint.Polyline!=pe.Source.PolylinePoint.Polyline))
            //        l.Add(new LineSegment(pe.SourcePoint, pe.TargetPoint));
            //}

            ////foreach(PEdge pe in this.graphOfHoleBoundaries.Edges)
            ////    l.Add(new LineSegment(pe.SourcePoint, pe.TargetPoint));

            //SugiyamaLayoutSettings.Show(l.ToArray());
#endif
        }

        //this code will work for convex holes
        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        void SweepPolylinePoint(PolylinePoint v) {
            PolylinePoint inSide = GetIncomingSide(v);
            PolylinePoint outSide = GetOutgoingSide(v);

            //if (inEdge != null && outEdge != null)
            //    SugiyamaLayoutSettings.Show(new LineSegment(inEdge.Start.Point, inEdge.End.Point), new LineSegment(outEdge.Start.Point,
            //        outEdge.End.Point), new LineSegment(this.q, v.Point));
            //else if (inEdge != null)
            //    SugiyamaLayoutSettings.Show(new LineSegment(inEdge.Start.Point, inEdge.End.Point), new LineSegment(this.q, v.Point));
            //else if (outEdge != null)
            //    SugiyamaLayoutSettings.Show(new LineSegment(outEdge.Start.Point, outEdge.End.Point), new LineSegment(this.q, v.Point));

            activeEdgeComparer.IntersectionOfTheRayAndInsertedEdge = v.Point;
            RBNode<PolylinePoint> node;
            if (sideNodes.TryGetValue(inSide, out node) && node != null) {
//we have an active edge
                if (node == activeSidesTree.TreeMinimum())
                    AddEdge(v);

                if (outSide != null) {
                    node.Item = outSide; //just replace the edge since the order does not change
                    sideNodes[outSide] = node;
                } else {
                    RBNode<PolylinePoint> changedNode = activeSidesTree.DeleteSubtree(node);
                    if (changedNode != null)
                        if (changedNode.Item != null)
                            sideNodes[changedNode.Item] = changedNode;
                }
                sideNodes.Remove(inSide);
            } else //the incoming edge is not active
                if (outSide != null) {
                    RBNode<PolylinePoint> outsideNode;
                    if (!sideNodes.TryGetValue(outSide, out outsideNode) || outsideNode == null) {
                        outsideNode = activeSidesTree.Insert(outSide);
                        sideNodes[outSide] = outsideNode;
                        if (outsideNode == activeSidesTree.TreeMinimum())
                            AddEdge(v);
                    }
                } else
                    throw new InvalidOperationException();

            // CheckActiveSidesAreConsistent();
        }

        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        void AddEdge(PolylinePoint v) {
            if (visibilityKind == VisibilityKind.Regular ||
                (visibilityKind == VisibilityKind.Tangent && LineTouchesPolygon(QVertex.Point, v))) {
                visibilityGraph.AddEdge(QVertex.Point, v.Point, ((a,b)=>new TollFreeVisibilityEdge(a,b)));
            }
        }

        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        static bool LineTouchesPolygon(Point a, PolylinePoint p) {
            Point prev = p.Polyline.Prev(p).Point;
            Point next = p.Polyline.Next(p).Point;
            Point v = p.Point;
            return Point.SignedDoubledTriangleArea(a, v, prev)*Point.SignedDoubledTriangleArea(a, v, next) >= 0;
        }

#if TEST_MSAGL
        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
// ReSharper disable UnusedMember.Local
        void DrawActiveEdgesAndVisibleGraph() {
// ReSharper restore UnusedMember.Local
            var l = new List<ICurve>();
            foreach (VisibilityEdge pe in visibilityGraph.Edges)
                l.Add(new LineSegment(pe.SourcePoint, pe.TargetPoint));

            foreach (PolylinePoint pe in activeSidesTree)
                l.Add(new LineSegment(pe.Point, pe.NextOnPolyline.Point));
            l.Add(new Ellipse(0.1, 0.1, q));

            LayoutAlgorithmSettings.Show(l.ToArray());
        }
#endif

        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        PolylinePoint GetOutgoingSide(PolylinePoint v) {
            Stem visibleStem = visibleBoundaries[v.Polyline];

            if (v == visibleStem.End)
                return null;

            return v;
        }

        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        static PolylinePoint GetIncomingSide(PolylinePoint v) {
            return v.PrevOnPolyline;
        }

        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        void ComputeHoleBoundariesPossiblyVisibleFromQ() {
            InitActiveEdgesAndActiveEdgesComparer();

            foreach (Polyline hole in holes)
                ComputeVisiblePartOfTheHole(hole);
        }

        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        void InitActiveEdgesAndActiveEdgesComparer() {
            activeEdgeComparer = new ActiveEdgeComparerWithRay {Pivot = q};
            activeSidesTree = new RbTree<PolylinePoint>(activeEdgeComparer);
        }

        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        void ComputeVisiblePartOfTheHole(Polyline hole) {
            //find a separating edge
            PolylinePoint a;
            var needToGoCounterclockWise = true;

            for (a = hole.StartPoint; !HoleSideIsVisibleFromQ(hole, a); a = hole.Next(a)) {
                Debug.Assert(needToGoCounterclockWise || a != hole.StartPoint);
                    //check that we have not done the full circle
                needToGoCounterclockWise = false;
            }

            PolylinePoint b = hole.Next(a);

            //now the side a, a.Next - is separating
            if (needToGoCounterclockWise)
                while (HoleSideIsVisibleFromQ(hole, hole.Prev(a)))
                    a = hole.Prev(a);

            //go clockwise starting from b
            for (; HoleSideIsVisibleFromQ(hole, b); b = hole.Next(b)) {}

            visibleBoundaries[hole] = new Stem(a, b);
        }

        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        bool HoleSideIsVisibleFromQ(Polyline hole, PolylinePoint b) {
            return Point.SignedDoubledTriangleArea(q, b.Point, hole.Next(b).Point) >= -ApproximateComparer.SquareOfDistanceEpsilon;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php namespace Arcanedev\Stripe\Tests\Resources;

use Arcanedev\Stripe\Collection;
use Arcanedev\Stripe\Resources\Recipient;
use Arcanedev\Stripe\Tests\StripeTestCase;

/**
 * Class     RecipientTest
 *
 * @package  Arcanedev\Stripe\Tests\Resources
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 */
class RecipientTest extends StripeTestCase
{
    /* -----------------------------------------------------------------
     |  Properties
     | -----------------------------------------------------------------
     */

    /** @var \Arcanedev\Stripe\Resources\Recipient */
    private $recipient;

    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */

    public function setUp()
    {
        parent::setUp();

        $this->recipient = new Recipient;
    }

    public function tearDown()
    {
        unset($this->recipient);

        parent::tearDown();
    }

    /* -----------------------------------------------------------------
     |  Test Methods
     | -----------------------------------------------------------------
     */

    /** @test */
    public function it_can_be_instantiated()
    {
        $this->assertInstanceOf(Recipient::class, $this->recipient);
    }

    /** @test */
    public function it_can_get_all()
    {
        $recipients = Recipient::all();

        $this->assertInstanceOf(Collection::class, $recipients);
        $this->assertTrue($recipients->isList());
        $this->assertSame('/v1/recipients', $recipients->url);
    }

    /** @test */
    public function it_can_retrieve()
    {
        $this->recipient = self::createTestRecipient();
        $recipient       = Recipient::retrieve($this->recipient->id);

        $this->assertInstanceOf(Recipient::class, $recipient);

        $this->assertSame($this->recipient->id,   $recipient->id);
        $this->assertSame($this->recipient->name, $recipient->name);
    }

    /** @test */
    public function it_can_update()
    {
        $recipient = self::createTestRecipient();
        $recipient = Recipient::update($recipient->id, [
            'email' => 'gdb@stripe.com',
        ]);

        $this->assertSame('gdb@stripe.com', $recipient->email);

        $stripeRecipient = Recipient::retrieve($recipient->id);

        $this->assertSame($recipient->email, $stripeRecipient->email);
    }

    /** @test */
    public function it_can_save()
    {
        $recipient = self::createTestRecipient();

        $recipient->email = 'gdb@stripe.com';
        $recipient->save();

        $this->assertSame('gdb@stripe.com', $recipient->email);

        $stripeRecipient = Recipient::retrieve($recipient->id);

        $this->assertSame($recipient->email, $stripeRecipient->email);
    }

    /** @test */
    public function it_can_delete()
    {
        $recipient = self::createTestRecipient();
        $recipient->delete();

        $this->assertTrue($recipient->deleted);
    }

    /**
     * @test
     *
     * @expectedException \Arcanedev\Stripe\Exceptions\InvalidArgumentException
     */
    public function it_must_throw_invalid_argument_exception_on_bogus_attribute()
    {
        $recipient        = self::createTestRecipient();
        $recipient->bogus = 'bogus';
    }

    /** @test */
    public function it_can_update_all_metadata_recipient()
    {
        $recipient = self::createTestRecipient();

        $recipient->metadata = ['test' => 'foo bar'];
        $recipient->save();

        $updatedRecipient = Recipient::retrieve($recipient->id);

        $this->assertSame('foo bar', $updatedRecipient->metadata['test']);
    }

    /** @test */
    public function it_can_update_one_metadata_recipient()
    {
        $recipient = self::createTestRecipient();

        $recipient->metadata['test'] = 'foo bar';
        $recipient->save();

        $updatedRecipient = Recipient::retrieve($recipient->id);

        $this->assertSame('foo bar', $updatedRecipient->metadata['test']);
    }

    /* -----------------------------------------------------------------
     |  Cards Tests
     | -----------------------------------------------------------------
     */

    /** @test */
    public function it_can_add_card_to_recipient()
    {
        $recipient = $this->createTestRecipient();
        $recipient->cards->create(['card' => 'tok_visa_debit']);
        $recipient->save();

        $updatedRecipient   = Recipient::retrieve($recipient->id);
        $updatedCards       = $updatedRecipient->cards->all();

        $this->assertCount(1, $updatedCards['data']);

    }

    /** @test */
    public function it_can_update_recipient_card()
    {
        $recipient = $this->createTestRecipient();
        $recipient->cards->create(['card' => 'tok_visa_debit']);
        $recipient->save();

        $createdCards = $recipient->cards->all();

        $this->assertCount(1, $createdCards['data']);

        /** @var \Arcanedev\Stripe\Resources\Card $card */
        $card       = $createdCards['data'][0];
        $card->name = 'Jane Austen';
        $card->save();

        $updatedRecipient   = Recipient::retrieve($recipient->id);
        $updatedCards       = $updatedRecipient->cards->all();

        $this->assertSame('Jane Austen', $updatedCards['data'][0]->name);
    }

    /** @test */
    public function it_can_delete_recipient_card()
    {
        $recipient   = $this->createTestRecipient();
        $createdCard = $recipient->cards->create(['card' => 'tok_visa_debit']);

        $recipient->save();

        $updatedRecipient = Recipient::retrieve($recipient->id);
        $updatedCards     = $updatedRecipient->cards->all();

        $this->assertCount(1, $updatedCards['data']);

        $deleteStatus = $updatedRecipient->cards->retrieve($createdCard->id)->delete();

        $this->assertTrue($deleteStatus->deleted);

        $updatedRecipient->save();

        $postDeleteRecipient = Recipient::retrieve($recipient->id);
        $postDeleteCards     = $postDeleteRecipient->cards->all();

        $this->assertCount(0, $postDeleteCards['data']);
    }
}


text:
FROM ubuntu

MAINTAINER scott.miller171@gmail.com

RUN apt-get update
RUN apt-get dist-upgrade -yq
RUN apt-get install python python-dev python-pip libyaml-dev -yq
RUN pip install ansible
RUN apt-get clean
RUN rm -Rf ~/.pip/cache/


text:
package com.seasonfif.pluginhost.manager;

import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.view.ContextThemeWrapper;

/**
 * 创建时间:2017年01月22日14:49

 * 作者:zhangqiang

 * 描述:
 */

public class PluginContext extends ContextThemeWrapper{

  private final ClassLoader mPluginClassLoader;
  private final Resources mPluginResources;
  private final String mPluginName;
  private final Loader mLoader;

  public PluginContext(Context base, int themeres, ClassLoader cl, Resources r, String plugin, Loader loader) {
    super(base, themeres);

    mPluginClassLoader = cl;
    mPluginResources = r;
    mPluginName = plugin;
    mLoader = loader;
  }

  @Override public ClassLoader getClassLoader() {
    if (mPluginClassLoader != null){
      return mPluginClassLoader;
    }
    return super.getClassLoader();
  }

  @Override public Resources getResources() {
    if (mPluginResources != null){
      return mPluginResources;
    }
    return super.getResources();
  }

  @Override public AssetManager getAssets() {
    if (mPluginResources != null){
      return mPluginResources.getAssets();
    }
    return super.getAssets();
  }
}


text:
#pragma once

enum DirectoryFileProperty
{
  eFileProp_Directory = 0x1,
  eFileProp_Hidden = 0x2,
  eFileProp_Executable = 0x4,

  eFileProp_ErrorUnknown = 0x2000,
  eFileProp_ErrorAccessDenied = 0x4000,
  eFileProp_ErrorInvalidPath = 0x8000,
};

// replay_shader.h

enum VarType
{
  eVar_Float = 0,
  eVar_Int,
  eVar_UInt,
  eVar_Double,
};

enum FormatComponentType
{
  eCompType_None = 0,
  eCompType_Float,
  eCompType_UNorm,
  eCompType_SNorm,
  eCompType_UInt,
  eCompType_SInt,
  eCompType_UScaled,
  eCompType_SScaled,
  eCompType_Depth,
  eCompType_Double,
};

enum TextureSwizzle
{
  eSwizzle_Red,
  eSwizzle_Green,
  eSwizzle_Blue,
  eSwizzle_Alpha,
  eSwizzle_Zero,
  eSwizzle_One,
};

enum ShaderResourceType
{
  eResType_None,
  eResType_Buffer,
  eResType_Texture1D,
  eResType_Texture1DArray,
  eResType_Texture2D,
  eResType_TextureRect,
  eResType_Texture2DArray,
  eResType_Texture2DMS,
  eResType_Texture2DMSArray,
  eResType_Texture3D,
  eResType_TextureCube,
  eResType_TextureCubeArray,
  eResType_Count,
};

enum ShaderBindType
{
  eBindType_Unknown = 0,
  eBindType_ConstantBuffer,
  eBindType_Sampler,
  eBindType_ImageSampler,
  eBindType_ReadOnlyImage,
  eBindType_ReadWriteImage,
  eBindType_ReadOnlyTBuffer,
  eBindType_ReadWriteTBuffer,
  eBindType_ReadOnlyBuffer,
  eBindType_ReadWriteBuffer,
  eBindType_InputAttachment,
};

enum SystemAttribute
{
  eAttr_None = 0,
  eAttr_Position,
  eAttr_PointSize,
  eAttr_ClipDistance,
  eAttr_CullDistance,
  eAttr_RTIndex,
  eAttr_ViewportIndex,
  eAttr_VertexIndex,
  eAttr_PrimitiveIndex,
  eAttr_InstanceIndex,
  eAttr_InvocationIndex,
  eAttr_DispatchSize,
  eAttr_DispatchThreadIndex,
  eAttr_GroupIndex,
  eAttr_GroupFlatIndex,
  eAttr_GroupThreadIndex,
  eAttr_GSInstanceIndex,
  eAttr_OutputControlPointIndex,
  eAttr_DomainLocation,
  eAttr_IsFrontFace,
  eAttr_MSAACoverage,
  eAttr_MSAASamplePosition,
  eAttr_MSAASampleIndex,
  eAttr_PatchNumVertices,
  eAttr_OuterTessFactor,
  eAttr_InsideTessFactor,
  eAttr_ColourOutput,
  eAttr_DepthOutput,
  eAttr_DepthOutputGreaterEqual,
  eAttr_DepthOutputLessEqual,
};

// replay_render.h

enum OutputType
{
  eOutputType_None = 0,
  eOutputType_TexDisplay,
  eOutputType_MeshDisplay,
};

enum MeshDataStage
{
  eMeshDataStage_Unknown = 0,
  eMeshDataStage_VSIn,
  eMeshDataStage_VSOut,
  eMeshDataStage_GSOut,
};

enum TextureDisplayOverlay
{
  eTexOverlay_None = 0,
  eTexOverlay_Drawcall,
  eTexOverlay_Wireframe,
  eTexOverlay_Depth,
  eTexOverlay_Stencil,
  eTexOverlay_BackfaceCull,
  eTexOverlay_ViewportScissor,
  eTexOverlay_NaN,
  eTexOverlay_Clipping,
  eTexOverlay_ClearBeforePass,
  eTexOverlay_ClearBeforeDraw,
  eTexOverlay_QuadOverdrawPass,
  eTexOverlay_QuadOverdrawDraw,
};

enum FileType
{
  eFileType_DDS,
  eFileType_PNG,
  eFileType_JPG,
  eFileType_BMP,
  eFileType_TGA,
  eFileType_HDR,
  eFileType_EXR,
};

enum AlphaMapping
{
  eAlphaMap_Discard,
  eAlphaMap_BlendToColour,
  eAlphaMap_BlendToCheckerboard,
};

enum SpecialFormat
{
  eSpecial_Unknown = 0,
  eSpecial_BC1,
  eSpecial_BC2,
  eSpecial_BC3,
  eSpecial_BC4,
  eSpecial_BC5,
  eSpecial_BC6,
  eSpecial_BC7,
  eSpecial_ETC2,
  eSpecial_EAC,
  eSpecial_ASTC,
  eSpecial_R10G10B10A2,
  eSpecial_R11G11B10,
  eSpecial_R5G6B5,
  eSpecial_R5G5B5A1,
  eSpecial_R9G9B9E5,
  eSpecial_R4G4B4A4,
  eSpecial_R4G4,
  eSpecial_D16S8,
  eSpecial_D24S8,
  eSpecial_D32S8,
  eSpecial_S8,
  eSpecial_YUV,
};

enum QualityHint
{
  eQuality_DontCare,
  eQuality_Nicest,
  eQuality_Fastest,
};

enum GraphicsAPI
{
  eGraphicsAPI_D3D11,
  eGraphicsAPI_D3D12,
  eGraphicsAPI_OpenGL,
  eGraphicsAPI_Vulkan,
};

enum PrimitiveTopology
{
  eTopology_Unknown,
  eTopology_PointList,
  eTopology_LineList,
  eTopology_LineStrip,
  eTopology_LineLoop,
  eTopology_TriangleList,
  eTopology_TriangleStrip,
  eTopology_TriangleFan,
  eTopology_LineList_Adj,
  eTopology_LineStrip_Adj,
  eTopology_TriangleList_Adj,
  eTopology_TriangleStrip_Adj,
  eTopology_PatchList,
  eTopology_PatchList_1CPs = eTopology_PatchList,
  eTopology_PatchList_2CPs,
  eTopology_PatchList_3CPs,
  eTopology_PatchList_4CPs,
  eTopology_PatchList_5CPs,
  eTopology_PatchList_6CPs,
  eTopology_PatchList_7CPs,
  eTopology_PatchList_8CPs,
  eTopology_PatchList_9CPs,
  eTopology_PatchList_10CPs,
  eTopology_PatchList_11CPs,
  eTopology_PatchList_12CPs,
  eTopology_PatchList_13CPs,
  eTopology_PatchList_14CPs,
  eTopology_PatchList_15CPs,
  eTopology_PatchList_16CPs,
  eTopology_PatchList_17CPs,
  eTopology_PatchList_18CPs,
  eTopology_PatchList_19CPs,
  eTopology_PatchList_20CPs,
  eTopology_PatchList_21CPs,
  eTopology_PatchList_22CPs,
  eTopology_PatchList_23CPs,
  eTopology_PatchList_24CPs,
  eTopology_PatchList_25CPs,
  eTopology_PatchList_26CPs,
  eTopology_PatchList_27CPs,
  eTopology_PatchList_28CPs,
  eTopology_PatchList_29CPs,
  eTopology_PatchList_30CPs,
  eTopology_PatchList_31CPs,
  eTopology_PatchList_32CPs,
};

enum BufferCreationFlags
{
  eBufferCreate_VB = 0x1,
  eBufferCreate_IB = 0x2,
  eBufferCreate_CB = 0x4,
  eBufferCreate_UAV = 0x8,
  eBufferCreate_Indirect = 0x10,
};

enum TextureCreationFlags
{
  eTextureCreate_SRV = 0x1,
  eTextureCreate_RTV = 0x2,
  eTextureCreate_DSV = 0x4,
  eTextureCreate_UAV = 0x8,
  eTextureCreate_SwapBuffer = 0x10,
};

enum ShaderStageType
{
  eShaderStage_Vertex = 0,
  eShaderStage_First = eShaderStage_Vertex,

  eShaderStage_Hull,
  eShaderStage_Tess_Control = eShaderStage_Hull,

  eShaderStage_Domain,
  eShaderStage_Tess_Eval = eShaderStage_Domain,

  eShaderStage_Geometry,

  eShaderStage_Pixel,
  eShaderStage_Fragment = eShaderStage_Pixel,

  eShaderStage_Compute,

  eShaderStage_Count,
};

enum ShaderStageBits
{
  eStageBits_None = 0,
  eStageBits_Vertex = 1 << eShaderStage_Vertex,
  eStageBits_Hull = 1 << eShaderStage_Hull,
  eStageBits_Tess_Control = 1 << eShaderStage_Tess_Control,
  eStageBits_Domain = 1 << eShaderStage_Domain,
  eStageBits_Tess_Eval = 1 << eShaderStage_Tess_Eval,
  eStageBits_Geometry = 1 << eShaderStage_Geometry,
  eStageBits_Pixel = 1 << eShaderStage_Pixel,
  eStageBits_Fragment = 1 << eShaderStage_Fragment,
  eStageBits_Compute = 1 << eShaderStage_Compute,
  eStageBits_All = eStageBits_Vertex | eStageBits_Hull | eStageBits_Domain | eStageBits_Geometry |
                   eStageBits_Pixel |
                   eStageBits_Compute,
};

enum DebugMessageCategory
{
  eDbgCategory_Application_Defined = 0,
  eDbgCategory_Miscellaneous,
  eDbgCategory_Initialization,
  eDbgCategory_Cleanup,
  eDbgCategory_Compilation,
  eDbgCategory_State_Creation,
  eDbgCategory_State_Setting,
  eDbgCategory_State_Getting,
  eDbgCategory_Resource_Manipulation,
  eDbgCategory_Execution,
  eDbgCategory_Shaders,
  eDbgCategory_Deprecated,
  eDbgCategory_Undefined,
  eDbgCategory_Portability,
  eDbgCategory_Performance,
};

enum DebugMessageSeverity
{
  eDbgSeverity_High = 0,
  eDbgSeverity_Medium,
  eDbgSeverity_Low,
  eDbgSeverity_Info,
};

enum DebugMessageSource
{
  eDbgSource_API = 0,
  eDbgSource_RedundantAPIUse,
  eDbgSource_IncorrectAPIUse,
  eDbgSource_GeneralPerformance,
  eDbgSource_GCNPerformance,
  eDbgSource_RuntimeWarning,
  eDbgSoruce_UnsupportedConfiguration,
};

enum ResourceUsage
{
  eUsage_None,

  eUsage_VertexBuffer,
  eUsage_IndexBuffer,

  eUsage_VS_Constants,
  eUsage_HS_Constants,
  eUsage_DS_Constants,
  eUsage_GS_Constants,
  eUsage_PS_Constants,
  eUsage_CS_Constants,

  eUsage_SO,

  eUsage_VS_Resource,
  eUsage_HS_Resource,
  eUsage_DS_Resource,
  eUsage_GS_Resource,
  eUsage_PS_Resource,
  eUsage_CS_Resource,

  eUsage_VS_RWResource,
  eUsage_HS_RWResource,
  eUsage_DS_RWResource,
  eUsage_GS_RWResource,
  eUsage_PS_RWResource,
  eUsage_CS_RWResource,

  eUsage_InputTarget,
  eUsage_ColourTarget,
  eUsage_DepthStencilTarget,

  eUsage_Clear,

  eUsage_GenMips,
  eUsage_Resolve,
  eUsage_ResolveSrc,
  eUsage_ResolveDst,
  eUsage_Copy,
  eUsage_CopySrc,
  eUsage_CopyDst,

  eUsage_Barrier,
};

enum DrawcallFlags
{
  // types
  eDraw_Clear = 0x0001,
  eDraw_Drawcall = 0x0002,
  eDraw_Dispatch = 0x0004,
  eDraw_CmdList = 0x0008,
  eDraw_SetMarker = 0x0010,
  eDraw_PushMarker = 0x0020,
  eDraw_PopMarker = 0x0040,    // this is only for internal tracking use
  eDraw_Present = 0x0080,
  eDraw_MultiDraw = 0x0100,
  eDraw_Copy = 0x0200,
  eDraw_Resolve = 0x0400,
  eDraw_GenMips = 0x0800,
  eDraw_PassBoundary = 0x1000,

  // flags
  eDraw_UseIBuffer = 0x010000,
  eDraw_Instanced = 0x020000,
  eDraw_Auto = 0x040000,
  eDraw_Indirect = 0x080000,
  eDraw_ClearColour = 0x100000,
  eDraw_ClearDepthStencil = 0x200000,
  eDraw_BeginPass = 0x400000,
  eDraw_EndPass = 0x800000,
};

enum SolidShadeMode
{
  eShade_None = 0,
  eShade_Solid,
  eShade_Lit,
  eShade_Secondary,
  eShade_Count,
};

enum TriangleFillMode
{
  eFill_Solid = 0,
  eFill_Wireframe,
  eFill_Point,
};

enum TriangleCullMode
{
  eCull_None = 0,
  eCull_Front,
  eCull_Back,
  eCull_FrontAndBack,
};

enum GPUCounters
{
  eCounter_FirstGeneric = 1,
  eCounter_EventGPUDuration = eCounter_FirstGeneric,
  eCounter_InputVerticesRead,
  eCounter_VSInvocations,
  eCounter_PSInvocations,
  eCounter_RasterizedPrimitives,
  eCounter_SamplesWritten,

  // IHV specific counters can be set above this point
  // with ranges reserved for each IHV
  eCounter_FirstAMD = 1000000,

  eCounter_FirstIntel = 2000000,

  eCounter_FirstNvidia = 3000000,
};

enum CounterUnits
{
  eUnits_Absolute,
  eUnits_Seconds,
  eUnits_Percentage,
};

enum ReplaySupport
{
  eReplaySupport_Unsupported,
  eReplaySupport_Supported,
  eReplaySupport_SuggestRemote,
};

enum ReplayCreateStatus
{
  eReplayCreate_Success = 0,
  eReplayCreate_UnknownError,
  eReplayCreate_InternalError,
  eReplayCreate_FileNotFound,
  eReplayCreate_InjectionFailed,
  eReplayCreate_IncompatibleProcess,
  eReplayCreate_NetworkIOFailed,
  eReplayCreate_NetworkRemoteBusy,
  eReplayCreate_NetworkVersionMismatch,
  eReplayCreate_FileIOFailed,
  eReplayCreate_FileIncompatibleVersion,
  eReplayCreate_FileCorrupted,
  eReplayCreate_ImageUnsupported,
  eReplayCreate_APIUnsupported,
  eReplayCreate_APIInitFailed,
  eReplayCreate_APIIncompatibleVersion,
  eReplayCreate_APIHardwareUnsupported,
};

enum TargetControlMessageType
{
  eTargetControlMsg_Unknown = 0,
  eTargetControlMsg_Disconnected,
  eTargetControlMsg_Busy,
  eTargetControlMsg_Noop,
  eTargetControlMsg_NewCapture,
  eTargetControlMsg_CaptureCopied,
  eTargetControlMsg_RegisterAPI,
  eTargetControlMsg_NewChild,
};

enum EnvironmentModificationType
{
  eEnvMod_Set,
  eEnvMod_Append,
  eEnvMod_Prepend,
};

enum EnvironmentSeparator
{
  eEnvSep_Platform,
  eEnvSep_SemiColon,
  eEnvSep_Colon,
  eEnvSep_None,
};


text:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
    int *left;
    int *right;
    int leftSize;
    int rightSize;
    int i;
    int j;
    int *ret;

    if(root==NULL){
        *returnSize = 0;
        return NULL;
    }
    left = preorderTraversal(root->left, &leftSize);
    right = preorderTraversal(root->right, &rightSize);

    ret = (int *)malloc(sizeof(int)*(1+leftSize+rightSize));
    ret[0] = root->val;
    for(i=0,j=1; i<leftSize; i++,j++){
        ret[j] = left[i];
    }
    for(i=0; i<rightSize; i++,j++){
        ret[j] = right[i];
    }

    free(left);
    free(right);
    *returnSize = leftSize+rightSize+1;
    return ret;
}


text:
from django.utils.safestring import mark_safe
from django.utils.translation import gettext as _

from bootstrap4.utils import render_tag

from .text import text_value

def render_alert(content, alert_type=None, dismissible=True):
    """Render a Bootstrap alert."""
    button = ""
    if not alert_type:
        alert_type = "info"
    css_classes = ["alert", "alert-" + text_value(alert_type)]
    if dismissible:
        css_classes.append("alert-dismissible")
        close = _("close")
        button = (
            '<button type="button" class="close" data-dismiss="alert" aria-label="{close}">×</button>'
        ).format(close=close)
    button_placeholder = "__BUTTON__"
    return mark_safe(
        render_tag(
            "div",
            attrs={"class": " ".join(css_classes), "role": "alert"},
            content=mark_safe(button_placeholder) + text_value(content),
        ).replace(button_placeholder, button)
    )


text:
import time
import string
from unicodedata import east_asian_width

def get_real_width(str):
    """Gets real width of a string accounting for double width characters."""

    real_width = 0
    for char in str:
        real_width += 2 if east_asian_width(char) == 'W' else 1
    return real_width

def fit_string_split(str, width):
    """Fits a string into a width, truncates if it is over and pads if it is under.
    Returns a tuple with the first entry being the fitted part and the second
    the rest of the string.
    """

    real_width = 0
    index = 0
    while (index < len(str)):
        double_width = east_asian_width(str[index]) == 'W'
        real_width += 2 if double_width else 1
        if (real_width > width):
            padding = 0
            while (str[index] in string.ascii_letters + string.digits  and east_asian_width(str[index]) != 'W'):
                index -= 1
                padding += 1
            if (double_width and real_width - width == 1):
                return (str[0:index] + ' ' * (padding + 1), str[index + 1:])
            else:
                return (str[0:index] + ' ' * (padding) , str[index + 1:])
        index += 1
    return (str + ' ' * (width - real_width), '')

def fit_string(str, width):
    """Does the same thing as fit_string_split but does not return the second part."""

    return fit_string_split(str, width)[0]

def quick_fit_string(str, width, left_align = True, pad = ' '):
    """Fits a string into a width. Does not check for double width characters."""
    if (len(str) > width):
        return str[0:width]
    else:
        padding = pad * (width - len(str))
        if (left_align):
            return str + padding
        else:
            return padding + str

def trunc_int(num, len):
    """Truncates an int to a string of a certain length."""

    if (num < 10 ** len):
        return str(num)
    elif (num // 1000 < 10 ** (len - 1)):
        return str(num // 1000) + 'k'
    elif (num // 1000000 < 10 ** (len -1)):
        return str(num // 1000000) + 'm'
    else:
        return str(num // 1000000000) + 'b'

def format_int(num, len):
    """Formats an into into a string of a certain length."""

    return quick_fit_string(trunc_int(num, len), len)

def format_time(secs):
    """Format a length of a video."""

    hms = time.strftime('%H:%M:%S', time.gmtime(secs))
    i = 0
    while (hms[i] in '0:' and i < 4):
        i += 1
    return hms[i:]

def center(items, width):
    """Centers a list of items putting an equal amount of spacing between each item."""

    cur_width = 0
    for item in items:
        cur_width += len(item)
    spacing = (width - cur_width) // (len(items) - 1)
    line = ''
    for item in items:
        line += item + ' ' * spacing
    line = line[0:len(line) - spacing]
    line = ' ' * ((width - len(line)) // 2) + line
    return line


text:
package rfc

import (
	"encoding/asn1"

	"github.com/zmap/zcrypto/x509"
	"github.com/zmap/zlint/v3/lint"
	"github.com/zmap/zlint/v3/util"
)

type nameConstraintEmpty struct{}

/***********************************************************************
 Restrictions are defined in terms of permitted or excluded name
   subtrees.  Any name matching a restriction in the excludedSubtrees
   field is invalid regardless of information appearing in the
   permittedSubtrees.  Conforming CAs MUST mark this extension as
   critical and SHOULD NOT impose name constraints on the x400Address,
   ediPartyName, or registeredID name forms.  Conforming CAs MUST NOT
   issue certificates where name constraints is an empty sequence.  That
   is, either the permittedSubtrees field or the excludedSubtrees MUST
   be present.
************************************************************************/

func init() {
	lint.RegisterLint(&lint.Lint{
		Name:          "e_name_constraint_empty",
		Description:   "Conforming CAs MUST NOT issue certificates where name constraints is an empty sequence. That is, either the permittedSubtree or excludedSubtree fields must be present",
		Citation:      "RFC 5280: 4.2.1.10",
		Source:        lint.RFC5280,
		EffectiveDate: util.RFC5280Date,
		Lint:          &nameConstraintEmpty{},
	})
}

func (l *nameConstraintEmpty) Initialize() error {
	return nil
}

func (l *nameConstraintEmpty) CheckApplies(c *x509.Certificate) bool {
	if !(util.IsExtInCert(c, util.NameConstOID)) {
		return false
	}
	nc := util.GetExtFromCert(c, util.NameConstOID)
	var seq asn1.RawValue
	rest, err := asn1.Unmarshal(nc.Value, &seq) //only one sequence, so rest should be empty
	if err != nil || len(rest) != 0 || seq.Tag != 16 || seq.Class != 0 || !seq.IsCompound {
		return false
	}
	return true
}

func (l *nameConstraintEmpty) Execute(c *x509.Certificate) *lint.LintResult {
	nc := util.GetExtFromCert(c, util.NameConstOID)
	var seq asn1.RawValue
	_, err := asn1.Unmarshal(nc.Value, &seq) //only one sequence, so rest should be empty
	if err != nil {
		return &lint.LintResult{Status: lint.Fatal}
	}
	if len(seq.Bytes) == 0 {
		return &lint.LintResult{Status: lint.Error}
	}

	return &lint.LintResult{Status: lint.Pass}
}


text:
import { Directive, ElementRef, Input, NgZone, OnChanges, OnDestroy, OnInit, SimpleChange, SimpleChanges } from '@angular/core';
import { NwSafeAny } from 'ngx-weui/core';

declare const GM: NwSafeAny;

@Directive({ selector: 'canvas[weui-chart-g2]', exportAs: 'weuiChartG2' })
export class ChartG2Directive implements OnInit, OnDestroy, OnChanges {
  _chart: NwSafeAny;

  /**
   * 画布内部的边距,可以是数组 [top, right, bottom, left] 也可以是一个数字。
   */
  @Input() margin: number[] | number;

  private initFlag: boolean = false;

  /**
   * chart实例对象
   */
  get chart(): NwSafeAny {
    return this._chart;
  }

  /**
   * GM对象
   */
  get GM(): NwSafeAny {
    return GM;
  }
  constructor(private el: ElementRef, private zone: NgZone) {}

  ngOnInit(): void {
    this.initFlag = true;
    this.buildChart();
  }

  private buildChart(): void {
    const options: {
      el: HTMLElement;
      margin?: number | number[];
    } = {
      el: this.el.nativeElement,
    };
    if (this.margin) {
      options.margin = this.margin;
    }

    this.zone.runOutsideAngular(() => {
      this._chart = new GM.Chart(options);
    });
  }

  ngOnChanges(changes: { [P in keyof this]?: SimpleChange } & SimpleChanges): void {
    if (this.initFlag && changes.margin && !changes.margin.firstChange) {
      this.buildChart();
    }
  }

  ngOnDestroy(): void {
    if (this._chart) {
      this.zone.runOutsideAngular(() => {
        // fixed: TypeError: Cannot read property 'stop' of null
        try {
          this._chart.destroy();
        } catch (e) {
          console.warn(e);
        }
      });
    }
  }
}