コード例 #1
0
ファイル: HOGDescriptor.cs プロジェクト: samuto/UnityOpenCV
        /// <summary>
        /// Create a new HOGDescriptor using the specific parameters
        /// </summary>
        public HOGDescriptor(
            Size winSize,
            Size blockSize,
            Size blockStride,
            Size cellSize,
            int nbins,
            int derivAperture,
            double winSigma,
            double L2HysThreshold,
            bool gammaCorrection)
        {
            _ptr = CvHOGDescriptorCreate(
            ref winSize,
            ref blockSize,
            ref blockStride,
            ref cellSize,
            nbins,
            derivAperture,
            winSigma,
            0,
            L2HysThreshold,
            gammaCorrection);

             _rectStorage = new MemStorage();
             _rectSeq = new Seq<Rectangle>(_rectStorage);
        }
コード例 #2
0
ファイル: TraceCompiler.cs プロジェクト: modulexcite/IL2JS
 public void Emit()
 {
     if (Trace.Flavor == TraceFlavor.Remainder)
     {
         foreach (var kv in Trace.AssemblyMap)
         {
             var compiler = new AssemblyCompiler(this, kv.Value);
             compiler.Emit(null);
         }
     }
     else
     {
         var rootEnv = Env.Global.Environment();
         var body = new Seq<JST.Statement>();
         body.Add(JST.Statement.Var(RootId, new JST.Identifier(Env.Root).ToE()));
         foreach (var nm in rootEnv.AllLoadedAssembliesInLoadOrder().Where(Trace.AssemblyMap.ContainsKey))
         {
             var compiler = new AssemblyCompiler(this, Trace.AssemblyMap[nm]);
             compiler.Emit(body);
         }
         var program = new JST.Program
             (new JST.Statements
                  (new JST.ExpressionStatement
                       (new JST.StatementsPseudoExpression(new JST.Statements(body), null))));
         var fileName = Path.Combine(Env.OutputDirectory, Trace.Name + ".js");
         program.ToFile(fileName, Env.PrettyPrint);
         Env.Log(new GeneratedJavaScriptFile("trace '" + Trace.Name + "'", fileName));
     }
 }
コード例 #3
0
ファイル: TypeCompiler.cs プロジェクト: modulexcite/IL2JS
        // Complete a first-kinded type structure. If type definition is higher kinded, this will
        // complete an instance of the type at the type arguments. Otherwise, this will complete
        // the type definition itself.
        private void BuildTypeExpression(Seq<JST.Statement> body, JST.Expression lhs)
        {
            TypeCompEnv.BindUsage(body, CollectPhase1Usage(), TypePhase.Id);

            // TODO: Replace with prototype
            body.Add(JST.Statement.DotCall(RootId.ToE(), Constants.RootSetupTypeDefaults, TypeId.ToE()));

            EmitBaseAndSupertypes(body, lhs);
            EmitDefaultConstructor(body, lhs);
            EmitMemberwiseClone(body, lhs);
            EmitClone(body, lhs);
            EmitDefaultValue(body, lhs);
            EmitStaticMethods(body, lhs);
            EmitConstructObjectAndInstanceMethods(body, lhs);
            EmitVirtualAndInterfaceMethodRedirectors(body, lhs);
            EmitSetupType(body, lhs);
            EmitUnbox(body, lhs);
            EmitBox(body, lhs);
            EmitUnboxAny(body, lhs);
            EmitConditionalDeref(body, lhs);
            EmitIsValue(body, lhs);
            EmitEquals(body, lhs);
            EmitHash(body, lhs);
            EmitInterop(body, lhs);
        }
コード例 #4
0
ファイル: HOGDescriptor.cs プロジェクト: Rustemt/emgu_openCV
 /// <summary>
 /// Create a new HOGDescriptor
 /// </summary>
 public HOGDescriptor()
 {
    _ptr = CvHOGDescriptorCreateDefault();
    _rectStorage = new MemStorage();
    _rectSeq = new Seq<Rectangle>(_rectStorage);
    _vector = new VectorOfFloat();
 }
コード例 #5
0
        /// <summary>
        /// Create a new HOGDescriptor using the specific parameters
        /// </summary>
        /// <param name="blockSize">Block size in cells. Only (2,2) is supported for now.</param>
        /// <param name="cellSize">Cell size. Only (8, 8) is supported for now.</param>
        /// <param name="blockStride">Block stride. Must be a multiple of cell size.</param>
        /// <param name="gammaCorrection">Do gamma correction preprocessing or not.</param>
        /// <param name="L2HysThreshold">L2-Hys normalization method shrinkage.</param>
        /// <param name="nbins">Number of bins. Only 9 bins per cell is supported for now.</param>
        /// <param name="nLevels">Maximum number of detection window increases.</param>
        /// <param name="winSigma">Gaussian smoothing window parameter.</param>
        /// <param name="winSize">Detection window size. Must be aligned to block size and block stride.</param>
        public GpuHOGDescriptor(
         Size winSize,
         Size blockSize,
         Size blockStride,
         Size cellSize,
         int nbins,
         double winSigma,
         double L2HysThreshold,
         bool gammaCorrection,
         int nLevels)
        {
            _ptr = gpuHOGDescriptorCreate(
            ref winSize,
            ref blockSize,
            ref blockStride,
            ref cellSize,
            nbins,
            winSigma,
            L2HysThreshold,
            gammaCorrection,
            nLevels);

             _rectStorage = new MemStorage();
             _rectSeq = new Seq<Rectangle>(_rectStorage);
        }
コード例 #6
0
ファイル: StarDetector.cs プロジェクト: samuto/UnityOpenCV
 /// <summary>
 /// Detect STAR key points from the image
 /// </summary>
 /// <param name="image">The image to extract key points from</param>
 /// <returns>The STAR key points of the image</returns>
 public MKeyPoint[] DetectKeyPoints(Image<Gray, Byte> image)
 {
     using (MemStorage stor = new MemStorage())
      {
     Seq<MKeyPoint> seq = new Seq<MKeyPoint>(stor);
     CvStarDetectorDetectKeyPoints(ref this, image, seq.Ptr);
     return seq.ToArray();
      }
 }
コード例 #7
0
ファイル: HOGDescriptor.cs プロジェクト: samuto/UnityOpenCV
 /// <summary>
 /// Return the default people detector
 /// </summary>
 /// <returns>the default people detector</returns>
 public static float[] GetDefaultPeopleDetector()
 {
     using (MemStorage stor = new MemStorage())
      {
     Seq<float> desc = new Seq<float>(stor);
     CvHOGDescriptorPeopleDetectorCreate(desc);
     return desc.ToArray();
      }
 }
コード例 #8
0
ファイル: VisionToolkit.cs プロジェクト: rAum/auton_net
 /// <summary>
 /// Hough Line Transform, as in OpenCV (EmguCv does not wrap this function as it should be)
 /// </summary>
 /// <param name="img">Binary image</param>
 /// <param name="type">type of hough transform</param>
 /// <param name="threshold">how many votes is needed to accept line</param>
 /// <returns>Lines in theta/rho format</returns>
 public static PointF[] HoughLineTransform(Image<Gray, byte> img, Emgu.CV.CvEnum.HOUGH_TYPE type, int threshold)
 {
     using (MemStorage stor = new MemStorage())
     {
         IntPtr linePtr = CvInvoke.cvHoughLines2(img, stor.Ptr, type, 5, Math.PI / 180 * 15, threshold, 0, 0);
         Seq<PointF> seq = new Seq<PointF>(linePtr, stor);
         return seq.ToArray(); ;
     }
 }
コード例 #9
0
ファイル: FastDetector.cs プロジェクト: Rustemt/emgu_openCV
 /// <summary>
 /// Detect the Fast keypoints from the image
 /// </summary>
 /// <param name="image">The image to extract keypoints from</param>
 /// <returns>The array of fast keypoints</returns>
 public MKeyPoint[] DetectKeyPoints(Image<Gray, byte> image)
 {
    using (MemStorage stor = new MemStorage())
    {
       Seq<MKeyPoint> keypoints = new Seq<MKeyPoint>(stor);
       CvInvoke.CvFASTKeyPoints(image, keypoints, Threshold, NonmaxSupression);
       return keypoints.ToArray();
    }
 }
コード例 #10
0
 /// <summary>
 /// Detect planar object from the specific image
 /// </summary>
 /// <param name="image">The image where the planar object will be detected</param>
 /// <param name="h">The homography matrix which will be updated</param>
 /// <returns>The four corners of the detected region</returns>
 public PointF[] Detect(Image<Gray, Byte> image, HomographyMatrix h)
 {
     using (MemStorage stor = new MemStorage())
      {
     Seq<PointF> corners = new Seq<PointF>(stor);
     CvPlanarObjectDetectorDetect(_ptr, image, h, corners);
     return corners.ToArray();
      }
 }
コード例 #11
0
 /// <summary>
 /// Get the model points stored in this detector
 /// </summary>
 /// <returns>The model points stored in this detector</returns>
 public MKeyPoint[] GetModelPoints()
 {
     using (MemStorage stor = new MemStorage())
      {
     Seq<MKeyPoint> modelPoints = new Seq<MKeyPoint>(stor);
     CvPlanarObjectDetectorGetModelPoints(_ptr, modelPoints);
     return modelPoints.ToArray();
      }
 }
コード例 #12
0
ファイル: LDetector.cs プロジェクト: samuto/UnityOpenCV
 /// <summary>
 /// Detect the Lepetit keypoints from the image
 /// </summary>
 /// <param name="image">The image to extract Lepetit keypoints</param>
 /// <param name="maxCount">The maximum number of keypoints to be extracted</param>
 /// <param name="scaleCoords">Indicates if the coordinates should be scaled</param>
 /// <returns>The array of Lepetit keypoints</returns>
 public MKeyPoint[] DetectKeyPoints(Image<Gray, Byte> image, int maxCount, bool scaleCoords)
 {
     using (MemStorage stor = new MemStorage())
      {
     Seq<MKeyPoint> seq = new Seq<MKeyPoint>(stor);
     CvLDetectorDetectKeyPoints(ref this, image, seq.Ptr, maxCount, scaleCoords);
     return seq.ToArray();
      }
 }
コード例 #13
0
        /// <summary>
        /// Finds rectangular regions in the given image that are likely to contain objects the cascade has been trained for and returns those regions as a sequence of rectangles. 
        /// The function scans the image several times at different scales. Each time it considers overlapping regions in the image. 
        /// It may also apply some heuristics to reduce number of analyzed regions, such as Canny prunning. 
        /// After it has proceeded and collected the candidate rectangles (regions that passed the classifier cascade), it groups them and returns a sequence of average rectangles for each large enough group. 
        /// </summary>
        /// <param name="image">The image where the objects are to be detected from</param>
        /// <param name="scaleFactor">The factor by which the search window is scaled between the subsequent scans, for example, 1.1 means increasing window by 10%</param>
        /// <param name="minNeighbors">Minimum number (minus 1) of neighbor rectangles that makes up an object. All the groups of a smaller number of rectangles than min_neighbors-1 are rejected. If min_neighbors is 0, the function does not any grouping at all and returns all the detected candidate rectangles, which may be useful if the user wants to apply a customized grouping procedure</param>
        /// <param name="minSize">Minimum window size. Use Size.Empty for default, where it is set to the size of samples the classifier has been trained on (~20x20 for face detection)</param>
        /// <param name="maxSize">Maxumum window size. Use Size.Empty for default, where the parameter will be ignored.</param>
        /// <returns>The objects detected, one array per channel</returns>
        public Rectangle[] DetectMultiScale(Image<Gray, Byte> image, double scaleFactor, int minNeighbors, Size minSize, Size maxSize)
        {
            using (MemStorage stor = new MemStorage())
             {
            Seq<Rectangle> rectangles = new Seq<Rectangle>(stor);

            CvInvoke.CvCascadeClassifierDetectMultiScale(_ptr, image, rectangles, scaleFactor, minNeighbors, 0, minSize, maxSize);
            return rectangles.ToArray();
             }
        }
コード例 #14
0
 public SimplifierContext(bool inGlobalScope, bool keepFunctionNames, NameSupply nameSupply, Func<Expression, bool> isValue)
 {
     InGlobalScope = inGlobalScope;
     KeepFunctionNames = keepFunctionNames;
     NameSupply = nameSupply;
     subst = new Map<Identifier, Expression>();
     statements = null;
     contextEffects = Effects.Bottom;
     this.isValue = isValue;
 }
コード例 #15
0
 /// <summary>
 /// Find rectangular regions in the given image that are likely to contain objects and corresponding confidence levels
 /// </summary>
 /// <param name="image">The image to detect objects in</param>
 /// <param name="overlapThreshold">Threshold for the non-maximum suppression algorithm, Use default value of 0.5</param>
 /// <returns>Array of detected objects</returns>
 public MCvObjectDetection[] Detect(Image<Bgr, Byte> image, float overlapThreshold)
 {
     using (MemStorage stor = new MemStorage())
      {
     IntPtr seqPtr = CvInvoke.cvLatentSvmDetectObjects(image, Ptr, stor, overlapThreshold, -1);
     if (seqPtr == IntPtr.Zero)
        return new MCvObjectDetection[0];
     Seq<MCvObjectDetection> seq = new Seq<MCvObjectDetection>(seqPtr, stor);
     return seq.ToArray();
      }
 }
コード例 #16
0
 public SimplifierContext
     (CompilationEnvironment compEnv,
      JST.NameSupply nameSupply,
      ISimplifierDatabase database,
      CSTWriter trace)
 {
     CompEnv = compEnv;
     NameSupply = nameSupply;
     subst = new Map<JST.Identifier, Expression>();
     statements = null;
     contextEffects = JST.Effects.Bottom;
     Database = database;
     Trace = trace;
 }
コード例 #17
0
 protected SimplifierContext
     (bool inGlobalScope,
      bool keepFunctionNames,
      NameSupply nameSupply,
      Map<Identifier, Expression> subst,
      Seq<Statement> statements,
      Effects contextEffects,
      Func<Expression, bool> isValue)
 {
     InGlobalScope = inGlobalScope;
     KeepFunctionNames = keepFunctionNames;
     NameSupply = nameSupply;
     this.subst = subst;
     this.statements = statements;
     this.contextEffects = contextEffects;
     this.isValue = isValue;
 }
コード例 #18
0
 protected SimplifierContext
     (CompilationEnvironment compEnv,
      JST.NameSupply nameSupply,
      Map<JST.Identifier, Expression> subst,
      Seq<Statement> statements,
      JST.Effects contextEffects,
      ISimplifierDatabase database,
      CSTWriter trace)
 {
     CompEnv = compEnv;
     NameSupply = nameSupply;
     this.subst = subst;
     this.statements = statements;
     this.contextEffects = contextEffects;
     Database = database;
     Trace = trace;
 }
コード例 #19
0
        /// <summary>
        /// Finds rectangular regions in the given image that are likely to contain objects the cascade has been trained for and returns those regions as a sequence of rectangles. 
        /// The function scans the image several times at different scales (see cvSetImagesForHaarClassifierCascade). Each time it considers overlapping regions in the image and applies the classifiers to the regions using cvRunHaarClassifierCascade. 
        /// It may also apply some heuristics to reduce number of analyzed regions, such as Canny prunning. 
        /// After it has proceeded and collected the candidate rectangles (regions that passed the classifier cascade), it groups them and returns a sequence of average rectangles for each large enough group. 
        /// The default parameters (scale_factor=1.1, min_neighbors=3, flags=0) are tuned for accurate yet slow object detection. 
        /// For a faster operation on real video images the settings are: scale_factor=1.2, min_neighbors=2, flags=CV_HAAR_DO_CANNY_PRUNING, min_size=&lt;minimum possible face size&gt; 
        /// (for example, ~1/4 to 1/16 of the image area in case of video conferencing). 
        /// </summary>
        /// <param name="image">The image where the objects are to be detected from</param>
        /// <param name="scaleFactor">The factor by which the search window is scaled between the subsequent scans, for example, 1.1 means increasing window by 10%</param>
        /// <param name="minNeighbors">Minimum number (minus 1) of neighbor rectangles that makes up an object. All the groups of a smaller number of rectangles than min_neighbors-1 are rejected. If min_neighbors is 0, the function does not any grouping at all and returns all the detected candidate rectangles, which may be useful if the user wants to apply a customized grouping procedure</param>
        /// <param name="flag">Mode of operation. Currently the only flag that may be specified is CV_HAAR_DO_CANNY_PRUNING. If it is set, the function uses Canny edge detector to reject some image regions that contain too few or too much edges and thus can not contain the searched object. The particular threshold values are tuned for face detection and in this case the pruning speeds up the processing.</param>
        /// <param name="minSize">Minimum window size. By default, it is set to the size of samples the classifier has been trained on (~20x20 for face detection)</param>
        /// <returns>The objects detected, one array per channel</returns>
        public MCvAvgComp[] Detect(Image<Gray, Byte> image, double scaleFactor, int minNeighbors, CvEnum.HAAR_DETECTION_TYPE flag, Size minSize)
        {
            using (MemStorage stor = new MemStorage())
             {
            IntPtr objects = CvInvoke.cvHaarDetectObjects(
                image.Ptr,
                Ptr,
                stor.Ptr,
                scaleFactor,
                minNeighbors,
                flag,
                minSize);

            if (objects == IntPtr.Zero)
               return new MCvAvgComp[0];

            Seq<MCvAvgComp> rects = new Seq<MCvAvgComp>(objects, stor);
            return rects.ToArray();
             }
        }
コード例 #20
0
        /// <summary>
        /// Finds convex hull of 2D point set using Sklansky's algorithm
        /// </summary>
        /// <param name="points">The points to find convex hull from</param>
        /// <param name="storage">the storage used by the resulting sequence</param>
        /// <param name="orientation">The orientation of the convex hull</param>
        /// <returns>The convex hull of the points</returns>
        public static Seq<PointF> ConvexHull(PointF[] points, MemStorage storage, CvEnum.ORIENTATION orientation)
        {
            IntPtr seq = Marshal.AllocHGlobal(StructSize.MCvSeq);
             IntPtr block = Marshal.AllocHGlobal(StructSize.MCvSeqBlock);
             GCHandle handle = GCHandle.Alloc(points, GCHandleType.Pinned);
             CvInvoke.cvMakeSeqHeaderForArray(
            CvInvoke.CV_MAKETYPE((int)CvEnum.MAT_DEPTH.CV_32F, 2),
            StructSize.MCvSeq,
            StructSize.PointF,
            handle.AddrOfPinnedObject(),
            points.Length,
            seq,
            block);

             Seq<PointF> convexHull = new Seq<PointF>(CvInvoke.cvConvexHull2(seq, storage.Ptr, orientation, 1), storage);
             handle.Free();
             Marshal.FreeHGlobal(seq);
             Marshal.FreeHGlobal(block);
             return convexHull;
        }
コード例 #21
0
        /// <summary>
        /// Inserts numP points into the polygon
        /// </summary>
        /// <param name="poly">Eequence of points representing the polygon border</param>
        /// <param name="numP">Number of points to insert</param>
        void insertPoints(ref Seq<Point> poly, ref PolyFromTris triPoly, int numP, int iw, int ih)
        {
            ///////////////////////////////////////////// TODO: FIX !!!!!!
            Seq<PointF> testsek = new Seq<PointF>(new MemStorage());

            foreach (Point p in poly)
            {
                testsek.Insert(testsek.Total, new PointF((float)p.X, (float)p.Y));
            }

            Rectangle rect = testsek.BoundingRectangle;
            ////////////////////////////////////////


            //
            // Calculate BoundingBox to narrow random-inserting points area
          //  Rectangle rect = poly.BoundingRectangle;

            int maxIter = numP*500;

            while (numP > 0) // We want inside numP random points
            {
                if (maxIter-- <= 0) break;

                // Generate point inside BBox
                Point p = new Point(random.Next(rect.X, rect.X + rect.Width), random.Next(rect.Y, rect.Y+rect.Height));

                if (p.X > iw || p.Y > ih || p.Y < 0 || p.X<0) continue;

                if (poly.InContour(p) > 0) // If point is on the poly
                {

                    triPoly.addInnerPoint(new PointF((float)p.X, (float)p.Y));
                    poly.Insert(poly.Total, p); // Insert it to our list
                    numP--;
                }
 
            } 
        }
コード例 #22
0
        /// <summary>
        /// Function inserts points into poly (numInsert points) and triangulates while set of points. 
        /// Result is lsit of triangles representing the poly.
        /// </summary>
        /// <param name="poly">Seq. of points representing the poly</param>
        /// <param name="numInsert">Number of points to insert into poly</param>
        /// <returns>Triangle's list</returns>
        public /*Triangle2DF[]*/ PolyFromTris triangulatePoly(Seq<Point> poly, int numInsert, int iw, int ih)
        {
            //Triangle2DF[] trisList; // Triangles list
            PolyFromTris trisPoly = new PolyFromTris();

            if (poly.Total + numInsert <= 24)
            {

                insertPoints(ref poly, ref trisPoly, numInsert, iw, ih); // Insert random points into the poly
            }

            //Array.ConvertAll(convexHull.ToArray(), new Converter<Point, PointF>(PointToPointF));

            using (PlanarSubdivision subdiv = new PlanarSubdivision(Array.ConvertAll(poly.ToArray(), new Converter<Point, PointF>(PointToPointF))))   //(poly.ToArray()))
            {
                 Console.WriteLine(" ply size: " + poly.Total.ToString());
                 //trisList = subdiv.GetDelaunayTriangles(); // Do triangulation
                 trisPoly.setTris(subdiv.GetDelaunayTriangles());
            }
            
            
            return trisPoly;
        }
コード例 #23
0
ファイル: CallContext.cs プロジェクト: modulexcite/IL2JS
 public CallContext(IImSeq<Identifier> parameters, IImSeq<Expression> arguments, Func<Expression, bool> isValue)
 {
     var paramMap = new Map<Identifier, int>();
     for (var i = 0; i < parameters.Count; i++)
         paramMap.Add(parameters[i], i);
     Parameters = paramMap;
     var argumentEffects = new Seq<Effects>(parameters.Count);
     SeenParameters = new Seq<bool>(parameters.Count);
     var allReadOnly = true;
     AllArgumentEffects = Effects.Bottom;
     foreach (var e in arguments)
     {
         var fxCtxt = new EffectsContext(isValue);
         e.AccumEffects(fxCtxt, null, null);
         argumentEffects.Add(fxCtxt.AccumEffects);
         AllArgumentEffects = AllArgumentEffects.Lub(fxCtxt.AccumEffects);
         if (!fxCtxt.AccumEffects.IsReadOnly)
             allReadOnly = false;
         SeenParameters.Add(false);
     }
     ArgumentEffects = argumentEffects;
     AllReadOnly = allReadOnly;
     IsOk = true;
 }
コード例 #24
0
ファイル: CallContext.cs プロジェクト: modulexcite/IL2JS
 public CallContext(CompilationEnvironment outerCompEnv, CompilationEnvironment inlinedCompEnv, IImSeq<Expression> arguments)
 {
     var paramMap = new Map<JST.Identifier, int>();
     for (var i = 0; i < inlinedCompEnv.Method.Arity; i++)
         paramMap.Add(inlinedCompEnv.ValueParameterIds[i], i);
     Parameters = paramMap;
     var argumentEffects = new Seq<JST.Effects>(inlinedCompEnv.Method.Arity);
     SeenParameters = new Seq<bool?>(inlinedCompEnv.Method.Arity);
     AllArgumentEffects = JST.Effects.Bottom;
     var allReadOnly = true;
     foreach (var e in arguments)
     {
         var fxCtxt = new JST.EffectsContext(null);
         e.AccumEffects(fxCtxt, null, null);
         argumentEffects.Add(fxCtxt.AccumEffects);
         AllArgumentEffects = AllArgumentEffects.Lub(fxCtxt.AccumEffects);
         if (!fxCtxt.AccumEffects.IsReadOnly)
             allReadOnly = false;
         SeenParameters.Add(e.IsValue(outerCompEnv) ? default(bool?) : false);
     }
     ArgumentEffects = argumentEffects;
     AllReadOnly = allReadOnly;
     IsOk = true;
 }
コード例 #25
0
ファイル: MSeq.cs プロジェクト: Protiguous/language-ext
 public Task <bool> EqualsAsync(Seq <A> x, Seq <A> y) =>
 Equals(x, y).AsTask();
コード例 #26
0
 public Task <int> GetHashCodeAsync(Seq <A> x) =>
 GetHashCode(x).AsTask();
コード例 #27
0
ファイル: MSeq.cs プロジェクト: Protiguous/language-ext
 public Seq <A> BindReturn(Unit maOutput, Seq <A> mb) =>
 mb;
コード例 #28
0
 public static TestAggregate FromEvents <T1, T2, T3, T4, T5, T6, T7, T8>(IUtcTimeTimeSource timeSource, Guid?id = null)
 {
     return(FromEvents(timeSource, id, Seq.OfTypes <T1, T2, T3, T4, T5, T6, T7, T8>()));
 }
コード例 #29
0
 public static Seq <A> Succs <A>(this Seq <Fin <A> > xs) =>
 xs.Where(x => x.IsSucc).Select(x => x.Value);
コード例 #30
0
 private static Either <PowershellFailure, TypedPsObject <MinimizedVirtualMachineInfo> > SingleOrFailure(Seq <TypedPsObject <MinimizedVirtualMachineInfo> > sequence)
 {
     return(sequence.HeadOrNone().ToEither(new PowershellFailure()));
 }
コード例 #31
0
 public static TestAggregate FromEvents <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>(IUtcTimeTimeSource timeSource, Guid?id = null)
 {
     return(FromEvents(timeSource, id, Seq.OfTypes <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>()));
 }
コード例 #32
0
 public static void ForEach <T>(this IEnumerable <T> source, Action <T> action)
 {
     Seq.iter(action, source);
 }
コード例 #33
0
        // Collect and filter members for subsequent code gen
        private void CollectMembers()
        {
            var fields = new Seq<CST.FieldDef>();
            var events = new Seq<CST.EventDef>();
            var properties = new Seq<CST.PropertyDef>();
            var methods = new Seq<CST.MethodDef>();
            var exportedInstanceMethods = new Seq<CST.MethodDef>();
            StaticInitializer = null;
            DefaultConstructor = null;
            numRelevantMethods = 0;

            foreach (var fieldDef in TyconEnv.Type.Members.OfType<CST.FieldDef>().Where(d => d.Invalid == null))
            {
                if (fieldDef.IsUsed)
                    fields.Add(fieldDef);
                else if (TypeTrace == null || TypeTrace.IncludeType)
                    Env.Log
                        (new UnusedDefinitionMessage
                             (CST.MessageContextBuilders.Member
                                  (Env.Global, TyconEnv.Assembly, TyconEnv.Type, fieldDef)));
            }

            foreach (var eventDef in TyconEnv.Type.Members.OfType<CST.EventDef>().Where(d => d.Invalid == null))
            {
                if (eventDef.IsUsed)
                    events.Add(eventDef);
                else if (TypeTrace == null || TypeTrace.IncludeType)
                    Env.Log
                        (new UnusedDefinitionMessage
                             (CST.MessageContextBuilders.Member
                                  (Env.Global, TyconEnv.Assembly, TyconEnv.Type, eventDef)));
            }

            foreach (var propDef in TyconEnv.Type.Members.OfType<CST.PropertyDef>().Where(d => d.Invalid == null))
            {
                if (propDef.IsUsed)
                    properties.Add(propDef);
                else if (TypeTrace == null || TypeTrace.IncludeType)
                    Env.Log
                        (new UnusedDefinitionMessage
                             (CST.MessageContextBuilders.Member
                                  (Env.Global, TyconEnv.Assembly, TyconEnv.Type, propDef)));
            }

            var state = Env.InteropManager.GetTypeRepresentation(TyconEnv.Assembly, TyconEnv.Type).State;

            var s = TyconEnv.Type.Style;
            if (!(s is CST.InterfaceTypeStyle || s is CST.DelegateTypeStyle))
            {
                foreach (
                    var methodDef in
                        TyconEnv.Type.Members.OfType<CST.MethodDef>().Where(d => d.Invalid == null && !d.IsAbstract))
                {
                    if (!methodDef.IsUsed)
                    {
                        if (TypeTrace == null || TypeTrace.IncludeType)
                            Env.Log
                                (new UnusedDefinitionMessage
                                     (CST.MessageContextBuilders.Member
                                          (Env.Global, TyconEnv.Assembly, TyconEnv.Type, methodDef)));
                    }
                    else if (!Env.Validity.IsMustHaveADefinition(methodDef.QualifiedMemberName(Env.Global, TyconEnv.Assembly, TyconEnv.Type)) &&
                             (Env.InteropManager.IsInlinable(TyconEnv.Assembly, TyconEnv.Type, methodDef, state) ||
                              Env.InlinedMethods.IsInlinable(TyconEnv.Assembly, TyconEnv.Type, methodDef)))
                    {
                        if (TypeTrace == null || TypeTrace.IncludeType)
                            Env.Log
                                (new InlinedDefinitionMessage
                                     (CST.MessageContextBuilders.Member
                                          (Env.Global, TyconEnv.Assembly, TyconEnv.Type, methodDef)));
                    }
                    else if (state != InstanceState.JavaScriptOnly && state != InstanceState.ManagedAndJavaScript &&
                             !methodDef.IsStatic && methodDef.IsConstructor && methodDef.Arity > 1 &&
                             methodDef.ValueParameters[1].Equals(Env.JSContextRef))
                    {
                        // Silently ignore importing constructors unless they are needed.
                        // (Remember, the managed interop rewriter will interpert 'Merged' as
                        // 'JavaScriptOnly', and thus may need importing constructors.)
                    }
                    else
                    {
                        if (methodDef.IsStatic && methodDef.IsConstructor)
                        {
                            if (methodDef.TypeArity > 0)
                                throw new InvalidOperationException
                                    ("static constructors cannot be polymorphic");
                            StaticInitializer = new CST.MethodRef(TyconEnv.AddSelfTypeBoundArguments().TypeRef, methodDef.MethodSignature, null);
                        }
                        else if (!methodDef.IsStatic && methodDef.IsConstructor && methodDef.Arity == 1 &&
                                 !Env.InteropManager.IsFactory(TyconEnv.Assembly, TyconEnv.Type, methodDef))
                        {
                            if (methodDef.TypeArity > 0)
                                throw new InvalidOperationException
                                    ("instance constructors cannot be polymorphic");
                            DefaultConstructor = new CST.MethodRef(TyconEnv.AddSelfTypeBoundArguments().TypeRef, methodDef.MethodSignature, null);
                        }
                        if (Env.InteropManager.IsExported(TyconEnv.Assembly, TyconEnv.Type, methodDef))
                        {
                            if (Env.InteropManager.IsBindToInstance
                                (TyconEnv.Assembly, TyconEnv.Type, methodDef))
                                exportedInstanceMethods.Add(methodDef);
                            // else: will be exported by assembly's Initialize function
                        }

                        methods.Add(methodDef);

                        if (TypeTrace == null || TypeTrace.Methods.Contains(methodDef.MethodSignature))
                            numRelevantMethods++;
                    }
                }
            }
            // else: ignore members of interface and delegate types
            // TODO: Need to emit reflection data for methods of interface types, thus will need
            //       to collect interface methods

            Fields = fields;
            Events = events;
            Properties = properties;
            Methods = methods;
            ExportedInstanceMethods = exportedInstanceMethods;
        }
コード例 #34
0
 // Compile all methods not already compiled by above
 private void CompileMethods(Seq<JST.Statement> body, JST.NameSupply outerNameSupply)
 {
     switch (Env.CompilationMode)
     {
     case CompilationMode.Plain:
     case CompilationMode.Collecting:
         // Already compiled above
         return;
     case CompilationMode.Traced:
         foreach (var methodDef in
             Methods.Where(d => TypeTrace.Methods.Contains(d.MethodSignature)))
         {
             if (TypeTrace.Parent.Parent.Flavor == TraceFlavor.Remainder)
             {
                 // Compile method into stand-alone loader
                 var compiler = new MethodCompiler(this, outerNameSupply, methodDef, MethodCompilationMode.SelfContained);
                 compiler.Emit(body, null);
             }
             else
             {
                 // Bind method definition into method cache
                 var target = TypeDefinitionId.ToE();
                 if (TyconEnv.Type.Arity == 0 && !Env.InteropManager.IsStatic(TyconEnv.Assembly, TyconEnv.Type, methodDef))
                     target = JST.Expression.Dot
                         (target, Constants.TypeConstructObject, Constants.prototype);
                 target = JST.Expression.Dot(target, Constants.TypeMethodCache);
                 var compiler = new MethodCompiler(this, outerNameSupply, methodDef, MethodCompilationMode.DirectBind);
                 compiler.Emit(body, target);
             }
         }
         break;
     default:
         throw new ArgumentOutOfRangeException();
     }
 }
コード例 #35
0
        // ----------------------------------------------------------------------
        // Building type structures
        // ----------------------------------------------------------------------

        private void BuildTypeStructure(Seq<JST.Statement> body)
        {
            // Already bound: T, Id, Assembly, Name, Slot

            var compiler = new TypeCompiler(this);
            compiler.Emit(body);

            if (TyconEnv.Type.Arity > 0)
            {
                // Methods live on type definition itself if type is higher-kinded
                if (Env.DebugMode)
                    body.Add(new JST.CommentStatement("Method definitions (accepting type-bound type arguments)"));
                EmitMethods(body, TypeDefinitionId.ToE(), NameSupply, TypeDefinitionId.ToE(), false);
                EmitMethods(body, TypeDefinitionId.ToE(), NameSupply, TypeDefinitionId.ToE(), true);
            }

            // Shared strings
            if (Env.DebugMode)
                body.Add(new JST.CommentStatement("Shared strings"));
            foreach (var kv in Env.GlobalMapping.AllStringSlots(TyconEnv.Assembly, TyconEnv.Type))
            {
                body.Add
                    (JST.Statement.DotAssignment
                         (TypeDefinitionId.ToE(),
                          new JST.Identifier(Constants.TypeStringSlot(kv.Value)),
                          new JST.StringLiteral(kv.Key)));
            }
        }
コード例 #36
0
    void FrameGrabber()
    {
        CurrentFrame = grabber.QueryFrame();

        if (CurrentFrame != null)
        {
            if (!backgroundSaved)
            {
                background = CurrentFrame.Copy();
                background.Draw(new Rectangle(0, 0, CurrentFrame.Width / widthProp, CurrentFrame.Height), new Bgr(0, 0, 0), 0);
                background.Draw(new Rectangle(0, CurrentFrame.Height - CurrentFrame.Height / heightProp, CurrentFrame.Width, CurrentFrame.Height / heightProp), new Bgr(0, 0, 0), 0);
                backgroundSaved = true;
            }
            else
            {
                currentFrameCopy = CurrentFrame.Copy();
                currentFrameCopy.Draw(new Rectangle(0, 0, CurrentFrame.Width / widthProp, CurrentFrame.Height), new Bgr(0, 0, 0), 0);
                currentFrameCopy.Draw(new Rectangle(0, CurrentFrame.Height - CurrentFrame.Height / heightProp, CurrentFrame.Width, CurrentFrame.Height / heightProp), new Bgr(0, 0, 0), 0);
                Image <Gray, Byte> currentFrameGrey = currentFrameCopy.Convert <Gray, Byte>();

                Image <Gray, Byte> backgroundGrey           = background.Convert <Gray, Byte>();
                Image <Gray, Byte> currentFrameCopyGreyDiff = currentFrameCopy.CopyBlank().Convert <Gray, Byte>();

                CvInvoke.cvAbsDiff(backgroundGrey, currentFrameGrey, currentFrameCopyGreyDiff);
                Thresholded = currentFrameCopyGreyDiff.ThresholdBinary(new Gray(20), new Gray(255));

                CvInvoke.cvSmooth(Thresholded, Thresholded, Emgu.CV.CvEnum.SMOOTH_TYPE.CV_BLUR, 13, 13, 1.5, 0);
                CvInvoke.cvSmooth(Thresholded, Thresholded, Emgu.CV.CvEnum.SMOOTH_TYPE.CV_GAUSSIAN, 13, 13, 1.5, 0);

                #region draw and extract num
                using (MemStorage storage = new MemStorage())
                {
                    Contour <Point> contours = Thresholded.FindContours(Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE, Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_LIST, storage);

                    Double          Result1        = 0;
                    Double          Result2        = 0;
                    Contour <Point> biggestContour = null;
                    while (contours != null)
                    {
                        Result1 = contours.Area;
                        if (Result1 > Result2)
                        {
                            Result2        = Result1;
                            biggestContour = contours;
                        }
                        contours = contours.HNext;
                    }

                    // Drawing
                    if (biggestContour != null)
                    {
                        if (biggestContour.Area > minArea && biggestContour.Area < maxArea)
                        {
                            Contour <Point> contour = biggestContour.ApproxPoly(biggestContour.Perimeter * 0.0025, storage);
                            CurrentFrame.Draw(contour, new Bgr(System.Drawing.Color.LimeGreen), 2);

                            box = biggestContour.GetMinAreaRect();
                            currentFrame.Draw(new CircleF(new PointF(box.center.X, box.center.Y), 3), new Bgr(200, 125, 75), 2);
                            XHandPosition = (box.center.X - (float)CurrentFrame.Width / widthProp) / ((CurrentFrame.Width - (float)CurrentFrame.Width / widthProp) * xMarginMultiplier);
                            YHandPosition = 1 - (box.center.Y - (float)CurrentFrame.Height / heightProp) / ((CurrentFrame.Height - (float)CurrentFrame.Height / heightProp) * yMarginMultiplier);

                            defects     = biggestContour.GetConvexityDefacts(storage, Emgu.CV.CvEnum.ORIENTATION.CV_CLOCKWISE);
                            defectArray = defects.ToArray();

                            // DRAW & FINGER NUM
                            fingerNumCurrent = 0;

                            for (int i = 0; i < defects.Total; i++)
                            {
                                PointF startPoint = new PointF((float)defectArray[i].StartPoint.X,
                                                               (float)defectArray[i].StartPoint.Y);

                                PointF depthPoint = new PointF((float)defectArray[i].DepthPoint.X,
                                                               (float)defectArray[i].DepthPoint.Y);

                                LineSegment2D startDepthLine = new LineSegment2D(defectArray[i].StartPoint, defectArray[i].DepthPoint);

                                LineSegment2D depthEndLine = new LineSegment2D(defectArray[i].DepthPoint, defectArray[i].EndPoint);

                                CircleF startCircle = new CircleF(startPoint, 5f);

                                CircleF depthCircle = new CircleF(depthPoint, 5f);

                                //Custom heuristic based on some experiment, double check it before use
                                if ((startCircle.Center.Y < box.center.Y || depthCircle.Center.Y < box.center.Y) && (startCircle.Center.Y < depthCircle.Center.Y) && (Math.Sqrt(Math.Pow(startCircle.Center.X - depthCircle.Center.X, 2) + Math.Pow(startCircle.Center.Y - depthCircle.Center.Y, 2)) > box.size.Height / 6.5))
                                {
                                    fingerNumCurrent++;
                                    currentFrame.Draw(startDepthLine, new Bgr(System.Drawing.Color.Green), 2);
                                }
                                currentFrame.Draw(startCircle, new Bgr(System.Drawing.Color.Red), 2);
                                currentFrame.Draw(depthCircle, new Bgr(System.Drawing.Color.Yellow), 5);
                            }
                        }
                        else
                        {
                            fingerNumCurrent = 0;
                        }

                        if (fingerNumCurrent == fingerNumLast)
                        {
                            fingerCycleCount += 1;
                        }
                        else
                        {
                            fingerCycleCount = 0;
                        }

                        if (fingerCycleCount == numCyclesFingerChange)
                        {
                            FingerNumStable = fingerNumCurrent;
                        }

                        fingerNumLast = fingerNumCurrent;
                        MCvFont font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_DUPLEX, 5d, 5d);
                        currentFrame.Draw(fingerNumStable.ToString(), ref font, new Point(50, 150), new Bgr(System.Drawing.Color.White));
                    }
                }
                #endregion
            }
        }
    }
コード例 #37
0
ファイル: By_path.cs プロジェクト: zuohd/Composable
 public void SetupMappingsForEventsWithNoRenamingAttribute()
 {
     _nameMapper = new RenamingEventNameMapper(
         eventTypes: Seq.OfTypes <Event1, Event2>(),
         renamers: new RenameEventsBasedOnEventRenamedAttributes());
 }
コード例 #38
0
ファイル: MSeq.cs プロジェクト: Protiguous/language-ext
 public Seq <A> Apply(Func <A, A, A> f, Seq <A> fa, Seq <A> fb) =>
 from a in fa
 from b in fb
 select f(a, b);
コード例 #39
0
 private EitherAsync <TodoFailure, Unit> UpdateCache(Seq <TodoItem> items) =>
 items.Select(TodoItemDto.FromDomain)
 .Apply(xs => _cache.Set(_cacheKey, xs.ToList()))
 .MapLeft(TodoFailureCon.Cache);
コード例 #40
0
ファイル: MSeq.cs プロジェクト: Protiguous/language-ext
 public bool Equals(Seq <A> x, Seq <A> y) =>
 default(EqEnumerable <A>).Equals(x, y);
コード例 #41
0
 private static Either <PowershellFailure, TypedPsObject <MinimizedVMNetworkAdapter> > FindAdapter(Seq <TypedPsObject <MinimizedVMNetworkAdapter> > sequence, string adapterId)
 {
     adapterId = adapterId.Replace("Microsoft:GuestNetwork\\", "Microsoft:");
     return(sequence.Find(a => a.Value.Id == adapterId)
            .ToEither(new PowershellFailure {
         Message = $"could not find network adapter with Id '{adapterId}'"
     }));
 }
コード例 #42
0
ファイル: MSeq.cs プロジェクト: Protiguous/language-ext
 public Seq <A> Subtract(Seq <A> x, Seq <A> y) =>
 toSeq(Enumerable.Except(x, y));
コード例 #43
0
 public static Seq <Error> Fails <A>(this Seq <Fin <A> > xs) =>
 xs.Filter(x => x.IsFail).Map(x => x.Error);
コード例 #44
0
 public static IEnumerable <Tuple <T, T> > Pairwise <T>(this IEnumerable <T> source)
 {
     return(Seq.pairwise(source));
 }
コード例 #45
0
ファイル: SelectorsTests.cs プロジェクト: sharpyr/Veho
 public void IntoColumnsIterTest()
 {
     Matrix.SelectRowsIntoIter(Seq.From(2, 4, 6)).ToList().DecoMutableMatrix().Says("IntoColumnsIterTest");
 }
コード例 #46
0
ファイル: MSeq.cs プロジェクト: Protiguous/language-ext
 public int GetHashCode(Seq <A> x) =>
 hash(x);
コード例 #47
0
 : throw new AggregateException(Seq(completed[0].Exception, completed[1].Exception).Where(e => e != null)));
コード例 #48
0
ファイル: MSeq.cs プロジェクト: Protiguous/language-ext
 public Seq <A> Append(Seq <A> x, Seq <A> y) =>
 x.Concat(y);
コード例 #49
0
ファイル: MSeq.cs プロジェクト: Protiguous/language-ext
 public Func <Unit, int> Count(Seq <A> fa) => _ =>
 fa.Count;
コード例 #50
0
 public int GetHashCode(Seq <A> x) =>
 hash <HashA, A>(x);
コード例 #51
0
 public static void ForEach <T>(this IEnumerable <T> source, Action <T, int> action)
 {
     Seq.iteri((i, x) => action(x, i), source);
 }
コード例 #52
0
ファイル: MSeq.cs プロジェクト: Protiguous/language-ext
 public MB BindAsync <MONADB, MB, B>(Seq <A> ma, Func <A, MB> f) where MONADB : struct, MonadAsync <Unit, Unit, MB, B> =>
 traverseSyncAsync <MSeq <A>, MONADB, Seq <A>, MB, A, B>(ma, f);
コード例 #53
0
    public override int GetHashCode()
    {
        int hashcode = 157;

        unchecked {
            if (__isset.seq)
            {
                hashcode = (hashcode * 397) + Seq.GetHashCode();
            }
            if (__isset.type)
            {
                hashcode = (hashcode * 397) + Type.GetHashCode();
            }
            if (__isset.dialedNumber)
            {
                hashcode = (hashcode * 397) + DialedNumber.GetHashCode();
            }
            if (__isset.calledNumber)
            {
                hashcode = (hashcode * 397) + CalledNumber.GetHashCode();
            }
            if (__isset.toMid)
            {
                hashcode = (hashcode * 397) + ToMid.GetHashCode();
            }
            if (__isset.toName)
            {
                hashcode = (hashcode * 397) + ToName.GetHashCode();
            }
            if (__isset.setupTime)
            {
                hashcode = (hashcode * 397) + SetupTime.GetHashCode();
            }
            if (__isset.startTime)
            {
                hashcode = (hashcode * 397) + StartTime.GetHashCode();
            }
            if (__isset.endTime)
            {
                hashcode = (hashcode * 397) + EndTime.GetHashCode();
            }
            if (__isset.duration)
            {
                hashcode = (hashcode * 397) + Duration.GetHashCode();
            }
            if (__isset.terminate)
            {
                hashcode = (hashcode * 397) + Terminate.GetHashCode();
            }
            if (__isset.productType)
            {
                hashcode = (hashcode * 397) + ProductType.GetHashCode();
            }
            if (__isset.charge)
            {
                hashcode = (hashcode * 397) + Charge.GetHashCode();
            }
            if (__isset.unit)
            {
                hashcode = (hashcode * 397) + Unit.GetHashCode();
            }
            if (__isset.result)
            {
                hashcode = (hashcode * 397) + Result.GetHashCode();
            }
        }
        return(hashcode);
    }
コード例 #54
0
ファイル: MSeq.cs プロジェクト: Protiguous/language-ext
 public Func <Unit, S> FoldBack <S>(Seq <A> fa, S state, Func <S, A, S> f) => _ =>
 fa.FoldBack(state, f);
コード例 #55
0
        // ----------------------------------------------------------------------
        // Methods
        // ----------------------------------------------------------------------

        // Emit bindings for static or instance methods, but not for virtuals or interface methods
        //  - Invoked from TypeDefinitionCompiler for higher-kinded type definitions
        //  - Invoked from TypeCompiler for first-kinded type definitions
        public void EmitMethods(Seq<JST.Statement> body, JST.Expression lhs, JST.NameSupply outerNameSupply, JST.Expression target, bool isStatic)
        {
            switch (Env.CompilationMode)
            {
                case CompilationMode.Plain:
                {
                    // Method definitions are bound directly into target
                    foreach (var methodDef in Methods.Where(m => m.Invalid == null))
                    {
                        if (Env.InteropManager.IsStatic(TyconEnv.Assembly, TyconEnv.Type, methodDef) == isStatic)
                        {
                            var compiler = new MethodCompiler(this, outerNameSupply, methodDef, MethodCompilationMode.DirectBind);
                            compiler.Emit(body, target);
                        }
                    }
                    break;
                }
            case CompilationMode.Collecting:
                {
                    // Method definitions are bound into MethodCache, redirectors are bound into target
                    foreach (var methodDef in Methods.Where(m => m.Invalid == null))
                    {
                        if (Env.InteropManager.IsStatic(TyconEnv.Assembly, TyconEnv.Type, methodDef) == isStatic)
                        {
                            var slot = Env.GlobalMapping.ResolveMethodDefToSlot(TyconEnv.Assembly, TyconEnv.Type, methodDef);
                            var methodName = CST.CSTWriter.WithAppend
                                (Env.Global, CST.WriterStyle.Uniform, methodDef.MethodSignature.Append);
                            body.Add
                                (JST.Statement.DotCall
                                     (RootId.ToE(),
                                      Constants.RootCollectingBindMethodBuilder,
                                      lhs,
                                      new JST.BooleanLiteral(isStatic),
                                      new JST.StringLiteral(slot),
                                      new JST.StringLiteral(methodName)));
                            var compiler = new MethodCompiler(this, outerNameSupply, methodDef, MethodCompilationMode.DirectBind);
                            compiler.Emit(body, JST.Expression.Dot(target, Constants.TypeMethodCache));
                        }
                    }
                    break;
                }
            case CompilationMode.Traced:
                {
                    // Methods in the initial trace or this trace will be bound directly.
                    // Methods in a trace other than above are bound via builder which is given trace name.
                    // Remaining methods are built via builder with null trace name.
                    var traceToArgs = new Map<string, Seq<JST.Expression>>();
                    var remainingArgs = new Seq<JST.Expression>();
                    remainingArgs.Add(TypeDefinitionId.ToE());
                    remainingArgs.Add(new JST.BooleanLiteral(isStatic));
                    remainingArgs.Add(new JST.NullExpression());
                    foreach (var methodDef in Methods.Where(m => m.Invalid == null))
                    {
                        if (Env.InteropManager.IsStatic(TyconEnv.Assembly, TyconEnv.Type, methodDef) == isStatic)
                        {
                            var slot = Env.GlobalMapping.ResolveMethodDefToSlot(TyconEnv.Assembly, TyconEnv.Type, methodDef);
                            var defTrace = Env.Traces.MethodToTrace[methodDef.QualifiedMemberName(Env.Global, TyconEnv.Assembly, TyconEnv.Type)];
                            if (defTrace.Flavor == TraceFlavor.OnDemand && defTrace != TypeTrace.Parent.Parent)
                            {
                                // Method definition in in another trace, bind redirector for it.
                                var args = default(Seq<JST.Expression>);
                                if (!traceToArgs.TryGetValue(defTrace.Name, out args))
                                {
                                    args = new Seq<JST.Expression>();
                                    args.Add(lhs);
                                    args.Add(new JST.BooleanLiteral(isStatic));
                                    args.Add(new JST.StringLiteral(defTrace.Name));
                                    traceToArgs.Add(defTrace.Name, args);
                                }
                                args.Add(new JST.StringLiteral(slot));
                            }
                            else if (defTrace.Flavor == TraceFlavor.Remainder)
                                // Method definition is in a stand-alone loader, bind redirector for it.
                                remainingArgs.Add(new JST.StringLiteral(slot));
                            else
                            {
                                // Method definition is bound directly
                                var compiler = new MethodCompiler(this, outerNameSupply, methodDef, MethodCompilationMode.DirectBind);
                                compiler.Emit(body, target);
                            }
                        }
                    }
                    foreach (var kv in traceToArgs)
                        body.Add(JST.Statement.DotCall(RootId.ToE(), Constants.RootBindMethodBuilders, kv.Value));
                    if (remainingArgs.Count > 3)
                        body.Add(JST.Statement.DotCall(RootId.ToE(), Constants.RootBindMethodBuilders, remainingArgs));
                    break;
                }
            default:
                throw new ArgumentOutOfRangeException();
            }
        }
コード例 #56
0
ファイル: Prim.cs プロジェクト: mbernard/language-ext
 /// <summary>
 /// choice(ps) tries to apply the parsers in the list ps in order, until one
 /// of them succeeds.
 /// </summary>
 /// <returns>
 /// The value of the succeeding parser.
 /// </returns>
 public static Parser <T> choice <T>(Seq <Parser <T> > ps) =>
 choicei(ps);
コード例 #57
0
        // ----------------------------------------------------------------------
        // Entry point from AssemblyCompiler
        // ----------------------------------------------------------------------

        public void Emit(Seq<JST.Statement> body)
        {
            if (Env.BreakOnBreak &&
                Env.AttributeHelper.TypeHasAttribute(TyconEnv.Assembly, TyconEnv.Type, Env.AttributeHelper.BreakAttributeRef, false, false))
                System.Diagnostics.Debugger.Break();

            CollectMembers();

            var typeName = CST.CSTWriter.WithAppend
                (Env.Global, CST.WriterStyle.Uniform, TyconEnv.Type.EffectiveName(Env.Global).Append);
            var slotName = Env.GlobalMapping.ResolveTypeDefToSlot(TyconEnv.Assembly, TyconEnv.Type);

            if (TypeTrace != null && TypeTrace.IncludeType && TypeTrace.Parent.Parent.Flavor == TraceFlavor.Remainder)
            {
                // Self-loader fragment
                var assmName = CST.CSTWriter.WithAppend
                    (Env.Global, CST.WriterStyle.Uniform, TyconEnv.Assembly.Name.Append);
                var funcBody = new Seq<JST.Statement>();
                BuildTypeStructure(funcBody);
                var func = new JST.FunctionExpression
                    (new Seq<JST.Identifier> { RootId, AssemblyId, TypeDefinitionId }, new JST.Statements(funcBody));
                var loaderBody = new Seq<JST.Statement>();
                if (Env.DebugMode)
                    loaderBody.Add(new JST.CommentStatement(TyconEnv.ToString()));
                loaderBody.Add
                    (JST.Statement.DotCall
                         (new JST.Identifier(Env.Root).ToE(),
                          Constants.RootBindType,
                          new JST.StringLiteral(assmName),
                          new JST.StringLiteral(slotName),
                          new JST.StringLiteral(typeName),
                          func));
                var program = new JST.Program(new JST.Statements(loaderBody));
                var typePath = Path.Combine
                    (Path.Combine(Env.OutputDirectory, JST.Lexemes.StringToFileName(assmName)), slotName);
                var fileName = Path.Combine(typePath, Constants.TypeFileName);
                program.ToFile(fileName, Env.PrettyPrint);
                Env.Log(new GeneratedJavaScriptFile("type '" + TyconEnv.TypeConstructorRef + "'", fileName));

                CompileMethods(null, NameSupply);
            }
            else if (TypeTrace != null && !TypeTrace.IncludeType && TypeTrace.Parent.Parent.Flavor == TraceFlavor.Remainder)
            {
                // Just passisng through
                CompileMethods(body, NameSupply);
            }
            else if (TypeTrace != null && !TypeTrace.IncludeType)
            {
                // Type defined elsewhere, include some/all methods only
                body.Add
                    (JST.Statement.Var
                         (TypeDefinitionId,
                          JST.Expression.DotCall
                              (AssemblyId.ToE(),
                               new JST.Identifier(Constants.AssemblyTypeBuilderSlot(slotName)),
                               Env.JSTHelpers.PhaseExpression(TypePhase.Slots))));
                CompileMethods(body, NameSupply);
            }
            else
            {
                // Inline type definition and some/all methods
                if (Env.DebugMode)
                    body.Add(new JST.CommentStatement(TyconEnv.ToString()));
                // We must construct the type explicity to phase 1 rather than using type compiler environment
                // since it thinks the type is already at phase 2.
                body.Add
                    (JST.Statement.Var
                         (TypeDefinitionId,
                          JST.Expression.DotCall
                              (AssemblyId.ToE(),
                               new JST.Identifier(Constants.AssemblyTypeBuilderSlot(slotName)),
                               Env.JSTHelpers.PhaseExpression(TypePhase.Id))));
                BuildTypeStructure(body);
                CompileMethods(body, NameSupply);
            }
        }
コード例 #58
0
ファイル: Prim.cs プロジェクト: mbernard/language-ext
 /// <summary>
 /// Runs a sequence of parsers, if any fail then the failure state is
 /// returned immediately and subsequence parsers are not run.
 /// </summary>
 /// <returns>
 /// The result of each parser as an enumerable.
 /// </returns>
 public static Parser <Seq <T> > chain <T>(Seq <Parser <T> > ps) =>
 chaini(ps);
コード例 #59
0
			public override void Visit(Seq pred)
			{
				foreach (var p in pred.List)
					Visit(p);
			}
コード例 #60
0
 public static IEnumerable <T> Flatten <T>(this IEnumerable <IEnumerable <T> > sources)
 {
     return(Seq.flatten(sources));
 }