Ejemplo n.º 1
0
        //public int GPA(Method() x)
        public static int Marks(FunctionDelegate paramDel)
        {
            int Mid   = 15;
            int Final = 40;

            return(paramDel(Mid, Final));
        }
Ejemplo n.º 2
0
    // Update is called once per frame
    void Update()
    {
        CreatePoints();

        FunctionDelegate _f = functionDelegates[(int)function];

        for (int i = 0; i < resolution; i++)
        {
            Vector3 _p = points[i].position;
            if (i % 2 == 0)
            {
                _p.y = _f(_p.x); // y offsite based on music spectrum value;
            }
            else
            {
                _p.y = -_f(_p.x); // y offsite based on music spectrum value;
            }
            points[i].position = _p;
        }

        currentRadius = radius;
        currentA      = a;
        currentB      = b;

        graphParticle.SetParticles(points, points.Length);
    }
Ejemplo n.º 3
0
 internal TransitionGate(FunctionDelegate _condition, PDAState _rejectState,
                         PDAStackOperation _rejectStackOperation)
 {
     condition            = _condition;
     rejectState          = _rejectState;
     rejectStackOperation = _rejectStackOperation;
 }
Ejemplo n.º 4
0
        public void DrawFunction(FunctionDelegate function, Brush color)
        {
            for (int i = -1 * DiagramParts; i < DiagramParts; i++)
            {
                double diagramElementX1 = i * (DiagramDistanseX / (2 * DiagramParts)) + DiagramCenterX;
                double diagramElementX2 = (i + 1) * (DiagramDistanseX / (2 * DiagramParts)) + DiagramCenterX;

                double diagramElementY1 = function(diagramElementX1);
                double diagramElementY2 = function(diagramElementX2);

                if (double.IsNaN(diagramElementY1) || double.IsNaN(diagramElementY2) || ConvertorY(diagramElementY1) < 0 || DrawingCanvas.Height < ConvertorY(diagramElementY1))
                {
                    continue;
                }

                Line line = new Line();
                line.Stroke          = color;
                line.StrokeThickness = 2;

                line.X1 = ConvertorX(diagramElementX1);
                line.X2 = ConvertorX(diagramElementX2);

                line.Y1 = ConvertorY(diagramElementY1);
                line.Y2 = ConvertorY(diagramElementY2);

                DrawingCanvas.Children.Add(line);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates a new instance of the BuiltInFunction class.
        /// </summary>
        /// <param name="name">Name of this function.</param>
        /// <param name="paramCount">Parameter count.</param>
        /// <param name="isVariadic">Does this function accept a variable number of arguments?</param>
        /// <param name="func">C# Function to invoke.</param>
        public BuiltInFunction(string name, int paramCount, bool isVariadic, FunctionDelegate func)
        {
            if (name is null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("Function name is empty.");
            }

            if (func is null)
            {
                throw new ArgumentNullException(nameof(func));
            }

            if (paramCount < 0)
            {
                paramCount = 0;
            }

            _func          = func;
            Name           = name;
            ParameterCount = paramCount;
            IsVariadic     = isVariadic;
        }
Ejemplo n.º 6
0
    void Update()
    {
        if ((int)function != prevFunction)
        {
            FunctionDelegate f = functionDelegates[(int)function];
            f(colorPicker);             //HeatedBody BlueYellow Gray
            flipColorMap(colorPickerFlip);
            displayPicker = colorPicker;

            prevFunction = (int)function;
        }

        //colorPicker.
        if (dispMapWidth != textureWidth || dispMapHeight != textureHeight)
        {
            colorPicker.Resize(dispMapWidth, dispMapHeight);

            textureWidth  = dispMapWidth;
            textureHeight = dispMapHeight;
            FunctionDelegate f = functionDelegates[(int)function];
            f(colorPicker);

            displayPicker = colorPicker;
        }

        if (flip)
        {
            displayPicker = colorPickerFlip;
        }
        else
        {
            displayPicker = colorPicker;
        }
    }
Ejemplo n.º 7
0
    /**
     * Representa o domínio e o cliente App
     */

    static void Main()
    {
        FunctionDelegate f1 = line => Student.Parse(line);
        FunctionDelegate f2 = Student.Parse;
        // FunctionDelegate f3 = new FunctionDelegate(Student.Parse);

        object res1 = f1("46100;David Monteiro Lopes;TLI42D");
        object res2 = f2("46100;David Monteiro Lopes;TLI42D");

        IEnumerable names =
            Distinct(
                Convert(                        // Seq<String>
                    Filter(                     // Seq<Student>
                        Filter(                 // Seq<Student>
                            Convert(            // Seq<Student>
                                Lines("isel-AVE-2021.txt"),
                                Student.Parse), // Seq<String>
                            std => ((Student)std).Number > 47000),
                        std => ((Student)std).Name.StartsWith("D")),
                    std => ((Student)std).Name.Split(" ")[0]));

        foreach (object l in names)
        {
            Console.WriteLine(l);
        }
    }
Ejemplo n.º 8
0
 static IEnumerable Convert(IEnumerable src, FunctionDelegate mapper)
 {
     foreach (object item in src)
     {
         yield return(mapper(item));
     }
 }
Ejemplo n.º 9
0
    void Update()
    {
        if (currentResolution != resolution || optimizationPoints == null)
        {
            CreateOptimizationPoints();
        }
        FunctionDelegate f = functionDelegates[(int)function];
        float            t = Time.timeSinceLevelLoad;

        //optimization steps

        Matrix a = QuadraticFormMatrix(t);

        Matrix currentPoint = new Matrix(new double[][] {
            new double[] { xStart },
            new double[] { zStart }
        });
        Matrix currentGradient;
        Matrix currentHessianInv;
        Matrix lastPoint = currentPoint.Clone();

        double[] ts = new double[iterationCount + 1];
        double[] xs = new double[iterationCount + 1];
        double[] zs = new double[iterationCount + 1];
        xs[0] = currentPoint.GetArray()[0][0];
        zs[0] = currentPoint.GetArray()[1][0];

        for (int i = 0; i < iterationCount; i++)
        {
            ts[i]           = i;
            currentGradient = a * lastPoint;
            //currentHessianInv = a.Inverse();
            //currentPoint = lastPoint - ((double) learningRate) * currentHessianInv * currentGradient;
            currentPoint = lastPoint - ((double)learningRate) * currentGradient;
            xs[i + 1]    = currentPoint.GetArray()[0][0];
            zs[i + 1]    = currentPoint.GetArray()[1][0];
            lastPoint    = currentPoint.Clone();
        }
        ts[iterationCount] = iterationCount;

        IInterpolationMethod xInterp = Interpolation.Create(ts, xs);
        IInterpolationMethod zInterp = Interpolation.Create(ts, zs);

        float increment = ((float)iterationCount) / ((float)(resolution - 1));

        for (int i = 0; i < resolution; i++)
        {
            float   curInc = increment * i;
            Vector3 p      = new Vector3((float)xInterp.Interpolate(curInc), 0.0f, (float)zInterp.Interpolate(curInc));
            p.y = f(p, t);
            optimizationPoints[i].position = p;
            Color c = optimizationPoints [i].color;
            c.g = ((float)i) / ((float)resolution);
            c.b = ((float)curInc) / ((float)iterationCount);
            //c.g = 1.0f / Mathf.Exp((float) i / 15.0f);
            optimizationPoints[i].color = c;
        }

        particleSystem.SetParticles(optimizationPoints, optimizationPoints.Length);
    }
Ejemplo n.º 10
0
 /// <summary>Adds a parameterized function to the context</summary>
 /// <typeparam name="T1">The type of the first argument</typeparam>
 /// <typeparam name="T2">The type of the second argument</typeparam>
 /// <param name="name">The function name</param>
 /// <param name="fn">The function delegate</param>
 protected void AddFunc <T1, T2>(string name, FunctionDelegate <T1, T2> fn)
 {
     ValFuncs.Add(new Pair <string, int>(name, 2), new ValFunc <T1, T2>(fn)); if (!ValFuncRef.Contains(name))
     {
         ValFuncRef.Add(name);
     }
 }
Ejemplo n.º 11
0
 public static void Apply <T>(IEnumerable <T> coll, FunctionDelegate <T> func)
 {
     foreach (var obj in coll)
     {
         func(obj);
     }
 }
Ejemplo n.º 12
0
    // Update is called once per frame
    void Update()
    {
        if (curRes != resolution || curScale != scale || curSize != size)
        {
            CreatePoints();
        }


        FunctionDelegate f = functionDelegates[(int)function];

        for (int i = 0; i < resolution; i++)
        {
            Vector3 p = points[i].position;
            p.y = f(verticalStrech_a, horizontalStrech_b, verticalShift_c, phase, p.x);
            //p.y = Exponential(p.x);
            Color c = points[i].color;
            c.g                = p.y;
            points[i].color    = c;
            points[i].position = p;
        }

        //transform.position.x = horizontalShift_d;
        transform.position = new Vector3(horizontalShift_d, transform.position.y, transform.position.z);



        particleSystem.SetParticles(points, points.Length);
    }
Ejemplo n.º 13
0
        /// <summary>
        /// Get Rmain for left rectangles method
        /// </summary>
        /// <param name="interval">Interval of points</param>
        /// <param name="n">Number of segments after interval partition</param>
        /// <param name="f">Function delegate of under integral sign function</param>
        /// <returns>Calculated main error</returns>
        public static double GetMainErrorForLeftRectangles(Interval interval, int n, FunctionDelegate f)
        {
            var Sn  = CalculateLeftRectanglesIntegral(interval, n, f);
            var S2n = CalculateLeftRectanglesIntegral(interval, 2 * n, f);

            return(GetMainErrorForLeftRectangles(S2n, Sn));
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Calculates the integral by Simpsons method
        /// </summary>
        /// <param name="interval">Interval of points for function arguments</param>
        /// <param name="n">Number of segments the interval is partitioned</param>
        /// <param name="f">Function delegate of under integral function</param>
        /// <returns>The calculated value of the integral</returns>
        public static double CalculateSimpsonsIntergral(Interval interval, int n, FunctionDelegate f)
        {
            n *= 2;
            double h   = GetStep(interval, n);
            double sum = 0;
            double x;

            for (int i = 1; i < n; i++)
            {
                x = interval.Left + i * h;
                if (i % 2 == 0)
                {
                    sum += 2 * f(x);
                }
                else
                {
                    sum += 4 * f(x);
                }
            }

            sum += f(interval.Left) + f(interval.Right);
            double coeff = (interval.Right - interval.Left) / 3 / n;

            return(coeff * sum);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Parse the specified tokenList and curIndex.
        /// overloaded by child types to do there own specific parsing.
        /// </summary>
        /// <param name="tokenList">Token list.</param>
        /// <param name="curIndex">Current index.</param>
        /// <param name="owner">the equation that this node is part of.  required to pull function delegates out of the dictionary</param>
        protected override void ParseToken(List <Token> tokenList, ref int curIndex, Equation owner)
        {
            //check arguments
            if (null == tokenList)
            {
                throw new ArgumentNullException("tokenList");
            }
            if (null == owner)
            {
                throw new ArgumentNullException("owner");
            }
            Debug.Assert(curIndex < tokenList.Count); //TODO: throw exceptions

            //get the function name
            FunctionName = tokenList[curIndex].TokenText;

            //check if the function is in the equation dictionary
            if (!owner.FunctionDictionary.ContainsKey(FunctionName))
            {
                throw new FormatException("Unknown function call: " + FunctionName);
            }

            //set the function delegate
            MyFunction = owner.FunctionDictionary[FunctionName];

            //increment the current index since we consumed the function name token
            curIndex++;
        }
Ejemplo n.º 16
0
    void Awake()
    {
        Lvalstat = Lval;

        if (!useDefinedPosition)
        {
            positionLeft = (Screen.width / 2) - (textureWidth / 2);
            positionTop  = (Screen.height / 2) - (textureHeight / 2);
        }

        dispMapWidth  = textureWidth;
        dispMapHeight = textureHeight;

        // if a default color picker texture hasn't been assigned, make one dynamically
        if (!colorPicker)
        {
            colorPicker     = new Texture2D(dispMapWidth, dispMapHeight, TextureFormat.ARGB32, false);
            colorPickerFlip = new Texture2D(dispMapWidth, dispMapHeight, TextureFormat.ARGB32, false);
        }

        FunctionDelegate f = functionDelegates[(int)function];

        prevFunction = (int)function;

        f(colorPicker);   //HeatedBody BlueYellow Gray
        flipColorMap(colorPickerFlip);

        displayPicker = colorPicker;

        // small color picker box texture
        //styleTexture = new Texture2D(1, 1);
        //styleTexture.SetPixel(0, 0, setColor);
    }
Ejemplo n.º 17
0
        /// <summary>
        /// Creates an empty function.
        /// </summary>
        /// <param name="prototype"> The next object in the prototype chain. </param>
        private UserDefinedFunction(ObjectInstance prototype)
            : base(prototype)
        {
            var body = new FunctionDelegate((engine, scope, functionObject, thisObject, argumentValues) => Undefined.Value);

            Init("Empty", new string[0], this.Engine.CreateGlobalScope(), "return undefined", new GeneratedMethod(body, null), true, false);
        }
Ejemplo n.º 18
0
 /// <summary>Adds a parameterized function to the context</summary>
 /// <typeparam name="T1">The type of the first argument</typeparam>
 /// <typeparam name="T2">The type of the second argument</typeparam>
 /// <typeparam name="T3">The type of the third argument</typeparam>
 /// <typeparam name="T4">The type of the fourth argument</typeparam>
 /// <typeparam name="T5">The type of the fifth argument</typeparam>
 /// <typeparam name="T6">The type of the sixth argument</typeparam>
 /// <typeparam name="T7">The type of the seventh argument</typeparam>
 /// <typeparam name="T8">The type of the eighth argument</typeparam>
 /// <typeparam name="T9">The type of the ninth argument</typeparam>
 /// <param name="name">The function name</param>
 /// <param name="fn">The function delegate</param>
 protected void AddFunc <T1, T2, T3, T4, T5, T6, T7, T8, T9>(string name, FunctionDelegate <T1, T2, T3, T4, T5, T6, T7, T8, T9> fn)
 {
     ValFuncs.Add(new Pair <string, int>(name, 9), new ValFunc <T1, T2, T3, T4, T5, T6, T7, T8, T9>(fn)); if (!ValFuncRef.Contains(name))
     {
         ValFuncRef.Add(name);
     }
 }
Ejemplo n.º 19
0
    void Update()
    {
        if (currentResolution != resolution || points == null)
        {
            createPoints();
        }
        FunctionDelegate f = functionDelegates [(int)function];
        float            t = Time.timeSinceLevelLoad;

        if (absolute)
        {
            for (int i = 0; i < points.Length; i++)
            {
                Color c = points [i].startColor;
                c.a = f(points [i].position, t) >= threshold ? 1f : 0f;
                points [i].startColor = c;
            }
        }
        else
        {
            for (int i = 0; i < points.Length; i++)
            {
                Color c = points [i].color;
                c.a = f(points [i].position, t);
                points [i].color = c;
            }
        }

        GetComponent <ParticleSystem> ().SetParticles(points, points.Length);
    }
Ejemplo n.º 20
0
    // Update is called once per frame
    void Update()
    {
        if (Center)
        {
            origin.x = origin.y = .5f;
            Center   = false;
        }
        if (currentResolution != resolution)
        {
            CreatePoints();
        }
        FunctionDelegate f = functionDelegates[(int)function];
        float            t = Time.timeSinceLevelLoad;

        for (int i = 0; i < points.Length; ++i)
        {
            Vector3 p = points[i].position;
            p.y = f(new InputData(p, origin, t * timestep));
            points[i].position = p;
            Color c = points[i].color;
            c.g             = p.y;
            points[i].color = c;
        }
        particleSystem.SetParticles(points, points.Length);
    }
Ejemplo n.º 21
0
        public static void drawStepResponse(FunctionDelegate W, object chart, object table, int time)
        {
            var plot     = chart as System.Windows.Forms.DataVisualization.Charting.Chart;
            var dataView = table as System.Windows.Forms.DataGridView;

            plot.ChartAreas[0].AxisY.Minimum = Double.NaN;
            plot.ChartAreas[0].AxisY.Maximum = Double.NaN;
            foreach (var series in plot.Series)
            {
                series.Points.Clear();
                series.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.None;
                series.BorderWidth = 3;
            }
            plot.ChartAreas[0].AxisX.Title   = "t, сек.";
            plot.ChartAreas[0].AxisY.Title   = "h(t)";
            plot.ChartAreas[0].AxisX.Minimum = 0;
            dataView.Rows.Clear();
            int _time = (int)time;

            for (double i = 0.00001; i < _time; i += 0.1)
            {
                double invCalc = Laplace.InverseTransform(W, i);
                plot.Series[0].Points.AddXY(i, invCalc);
                if (i.ToString("N2") == Math.Truncate(i).ToString("N2"))
                {
                    dataView.Rows.Add(i.ToString("N2"), invCalc.ToString("N4"));
                }
            }
        }
Ejemplo n.º 22
0
        //     INITIALIZATION
        //_________________________________________________________________________________________

        /// <summary>
        /// Creates a new instance of a user-defined function.
        /// </summary>
        /// <param name="prototype"> The next object in the prototype chain. </param>
        /// <param name="name"> The name of the function. </param>
        /// <param name="argumentsText"> A comma-separated list of arguments. </param>
        /// <param name="bodyText"> The source code for the body of the function. </param>
        /// <remarks> This is used by <c>new Function()</c>. </remarks>
        internal UserDefinedFunction(ObjectInstance prototype, string name, string argumentsText, string bodyText)
            : base(prototype)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if (argumentsText == null)
            {
                throw new ArgumentNullException("argumentsText");
            }
            if (bodyText == null)
            {
                throw new ArgumentNullException("bodyText");
            }

            // Set up a new function scope.
            var scope = DeclarativeScope.CreateFunctionScope(this.Engine.CreateGlobalScope(), name, null);

            // Compile the code.
            var context = new FunctionMethodGenerator(this.Engine, scope, name, argumentsText, bodyText, new CompilerOptions());

            context.GenerateCode();

            this.ArgumentsText   = argumentsText;
            this.ArgumentNames   = context.Arguments.Select(a => a.Name).ToList();
            this.BodyText        = bodyText;
            this.generatedMethod = context.GeneratedMethod;
            this.body            = (FunctionDelegate)this.generatedMethod.GeneratedDelegate;
            this.ParentScope     = this.Engine.CreateGlobalScope();
            this.StrictMode      = context.StrictMode;
            InitProperties(name, context.Arguments.Count);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Вычисление значений функции в интерполяционных узлах
        /// </summary>
        /// <param name="function">Интерполируемая функция f: R -> R</param>
        /// <param name="points">Список узлов - параметров функции</param>
        /// <param name="precision">Точность вычисления</param>
        /// <returns>Список значений функции в узлах</returns>
        public static List <double> GetValues(FunctionDelegate function, List <double> points, double precision)
        {
            var values = new List <double>();

            points.ForEach(p => values.Add((Truncate(precision, function(p)))));
            return(values);
        }
Ejemplo n.º 24
0
 public static void Apply(System.Collections.ICollection coll, FunctionDelegate <object> func)
 {
     foreach (object obj in coll)
     {
         func(obj);
     }
 }
Ejemplo n.º 25
0
 public static List <Tuple <double, int> > GetRootsByNewton2(List <Tuple <double, double> > intervals,
                                                             double precision,
                                                             FunctionDelegate function,
                                                             FunctionDelegate functionDerivate,
                                                             int KMax)
 {
     return(intervals.Select(interval => GetRootByNewton2(interval.Item1 + (interval.Item2 - interval.Item1) / 2, precision, function, functionDerivate, KMax)).ToList());
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Executes a function on each item in a <see cref="ICollection" />
 /// and returns the results in a new <see cref="IList" />.
 /// </summary>
 /// <param name="coll"></param>
 /// <param name="func"></param>
 /// <returns></returns>
 public static IList Transform(ICollection coll, FunctionDelegate<object> func)
 {
     IList result = new ArrayList();
     IEnumerator i = coll.GetEnumerator(); 
     foreach(object obj in coll)           
         result.Add(func(obj));
     return result;
 }
Ejemplo n.º 27
0
 /// <summary>
 /// Executes a function on each item in a <see cref="ICollection" />
 /// and collects all the entries for which the result
 /// of the function is equal to <c>true</c>.
 /// </summary>
 /// <param name="coll"></param>
 /// <param name="func"></param>
 /// <returns></returns>
 public static IList Select(ICollection coll, FunctionDelegate<object> func)
 {
     IList result = new ArrayList();            
     foreach (object obj in coll)
         if (true.Equals(func(obj)))
             result.Add(obj);                            
     return result;
 }
Ejemplo n.º 28
0
 public void AddDelegate(params FunctionDelegate[] delegatedFunctions) //method to add one or more delegate of the same type
 {
     this.DelegatedFunction = delegatedFunctions.First();
     foreach (FunctionDelegate delegateFunction in delegatedFunctions.Skip(1))
     {
         this.DelegatedFunction += delegateFunction;
     }
 }
 public void AddButtonPressCallback(Buttons button, PlayerIndex playerIndex, FunctionDelegate callback)
 {
     InputCallback c = new InputCallback();
       c.button = button;
       c.index = playerIndex;
       c.callback = callback;
       callbacks.Add(c);
 }
Ejemplo n.º 30
0
 public StaticFunction(string name, FunctionDelegate function, int minParameters, int maxParameters)
 {
     Name             = name;
     FunctionDelegate = function;
     MinParameters    = minParameters;
     MaxParameters    = maxParameters;
     Arguments        = new Variables();
 }
Ejemplo n.º 31
0
 public Function(int n, int m, double[] min, double[] max, FunctionDelegate f)
 {
     this.N   = n;
     this.M   = m;
     this.Min = min;
     this.Max = max;
     this.f   = f;
 }
Ejemplo n.º 32
0
		public ProgressController(FunctionDelegate function, object user_parameter)
		{
			m_worker.WorkerReportsProgress = true;
			m_worker.DoWork += new DoWorkEventHandler(DoWork);
			m_worker.ProgressChanged += new ProgressChangedEventHandler(ProgressChanged);
			m_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunWorkerCompleted);
			m_function_delegate = function;
		}
Ejemplo n.º 33
0
        double Error(double[] x, FunctionDelegate functionDelegate)
        {
            // 0.42888194248035300000 when x0 = -sqrt(2), x1 = 0
            //double trueMin = -0.42888194; // true min for z = x * exp(-(x^2 + y^2))
            double z = functionDelegate(x, dim);

            return((z - trueMin) * (z - trueMin)); // squared diff
        }
 public ProgressController(FunctionDelegate function, object user_parameter)
 {
     m_worker.WorkerReportsProgress = true;
     m_worker.DoWork             += new DoWorkEventHandler(DoWork);
     m_worker.ProgressChanged    += new ProgressChangedEventHandler(ProgressChanged);
     m_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunWorkerCompleted);
     m_function_delegate          = function;
 }
Ejemplo n.º 35
0
 public override int GenerateFunction(functionExpressionNode node, string name, StatementNode r, out FunctionDelegate _delegate)
 {
     DynamicMethod method = new DynamicMethod(name, MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, typeof(JSValue), new Type[] { typeof(JSContext) }, typeof(JSContext), false);
     ILGenerator tmp = method.GetILGenerator();
     base.GenerateFunctionBody(r, tmp);
     _delegate = (FunctionDelegate) method.CreateDelegate(typeof(FunctionDelegate));
     base.Source.FunctionList.Add(node);
     return (base.Source.FunctionList.Count - 1);
 }
Ejemplo n.º 36
0
        //     SERIALIZATION
        //_________________________________________________________________________________________

#if !SILVERLIGHT

        /// <summary>
        /// Runs when the entire object graph has been deserialized.
        /// </summary>
        /// <remarks> Derived classes must call the base class implementation. </remarks>
        protected override void OnDeserializationCallback()
        {
            // Call the base class.
            base.OnDeserializationCallback();

            this.body = new FunctionDelegate((engine, scope, thisObject, functionObject, argumentValues) =>
            {
                throw new JavaScriptException(this.Engine, "TypeError", "It is illegal to access the 'callee' or 'caller' property in strict mode");
            });
        }
Ejemplo n.º 37
0
        //     INITIALIZATION
        //_________________________________________________________________________________________

        /// <summary>
        /// Creates a new ThrowTypeErrorFunction instance.
        /// </summary>
        /// <param name="prototype"> The next object in the prototype chain. </param>
        internal ThrowTypeErrorFunction(ObjectInstance prototype)
            : base(prototype)
        {
            this.FastSetProperty("length", 0);
            this.IsExtensible = false;
            this.body = new FunctionDelegate((engine, scope, thisObject, functionObject, argumentValues) =>
                {
                    throw new JavaScriptException(this.Engine, "TypeError", "It is illegal to access the 'callee' or 'caller' property in strict mode");
                });
        }
Ejemplo n.º 38
0
        internal Function(LibraryMethodList container, Functor functor, FunctionDelegate functionDelegate)
            : base(container, functor, true)
        {
            if (functionDelegate == null)
            {
                throw new ArgumentNullException("functionDelegate");
            }

            m_functionDelegate = functionDelegate;
        }
Ejemplo n.º 39
0
 public override int GenerateFunction(functionExpressionNode node, string name, StatementNode r, out FunctionDelegate _delegate)
 {
     int n = this.FunctionList.Count;
     MethodBuilder method = this.tb.DefineMethod(name + "_" + n, MethodAttributes.Static | MethodAttributes.Public, typeof(JSValue), new Type[] { typeof(JSContext) });
     method.DefineParameter(1, ParameterAttributes.None, "context");
     base.GenerateFunctionBody(r, method.GetILGenerator());
     this.FunctionList.Add(new _FncInfo() { args=node.ParameterList.Names, mb = method});
     _delegate = null;
     return n;
 }
Ejemplo n.º 40
0
        /// <summary>
        /// Adds a function to the grammar dictionaary so that it can be used in equations.
        /// </summary>
        /// <param name="FunctionText">Function text. Must be 4 characters, no numerals</param>
        /// <param name="callbackMethod">Callback method that will be called when $XXXX is encountered in an equation</param>
        /// <exception cref="FormatException">thrown when the fucntionText is incorrect format</exception>
        public void AddFunction(string functionText, FunctionDelegate callbackMethod)
        {
            if (4 != functionText.Length)
            {
                //string length of a function text must be 4 cahracters, no numbers
                //This makes it easy to parse when we find $xxxx (that means it's a function)
                throw new FormatException("The functionText parameter must be exactly four characters in length.");
            }

            //Store the thing in the dictionary
            FunctionDictionary.Add(functionText, callbackMethod);
        }
        /// <summary>
        /// Calculates the integral of a 1d function over the interval [min..max]
        /// </summary>
        public static float Integrate( float min, float max, FunctionDelegate function )
        {
            float radius = 0.5f * ( max - min );
            float centre = 0.5f * ( max + min );

            float result = 0;
            for ( int degree = 0; degree < kDegrees; ++degree )
            {
                result += Coeefficients[ degree ] * function( radius * Roots[ degree ] + centre );
            }
            result *= radius;

            return result;
        }
Ejemplo n.º 42
0
 public MethodResult Execute(FunctionDelegate F, GradientDelegate Gradient, OptimizationMethod OptimizationMethod, Vector StartVector, int MaxIterations)
 {
     stopwatch.Start();
     currentVector = StartVector;
     for (int i = 0; i < MaxIterations; i++)
     {
         oldVector = currentVector;
         deltaGradient = Gradient(currentVector);
         var lambda = OptimizationMethod((x) => { return F(currentVector - x * deltaGradient); }, -10, 10, 1E-9, MaxIterations);
         currentVector = currentVector - lambda * deltaGradient;
         if (deltaGradient.LengthSquared < epsilon)
         {
             stopwatch.Stop();
             return new MethodResult() { Result = new Vector[] { currentVector }, IterationEnd = false, Iterations = i, MethodName = "Метод градиентного спуска", stopwatch = stopwatch, StartPoint = new Vector[] { StartVector }, FunctionValue = F(currentVector) };
         }
     }
     stopwatch.Stop();
     return new MethodResult() { Result = new Vector[] { currentVector }, IterationEnd = true, MethodName = "Метод градиентного спуска", Iterations = MaxIterations, stopwatch = stopwatch, StartPoint = new Vector[] { StartVector }, FunctionValue = F(currentVector) };
 }
Ejemplo n.º 43
0
        /// <summary>
        /// Parse the specified tokenList and curIndex.
        /// overloaded by child types to do there own specific parsing.
        /// </summary>
        /// <param name="tokenList">Token list.</param>
        /// <param name="curIndex">Current index.</param>
        /// <param name="owner">the equation that this node is part of.  required to pull function delegates out of the dictionary</param>
        protected override void ParseToken(List<Token> tokenList, ref int curIndex, Equation owner)
        {
            Debug.Assert(null != tokenList);
            Debug.Assert(null != owner);
            Debug.Assert(curIndex < tokenList.Count);

            //get the function name
            FunctionName = tokenList[curIndex].TokenText;

            //check if the function is in the equation dictionary
            if (!owner.FunctionDictionary.ContainsKey(FunctionName))
            {
                throw new FormatException("Unknown function call: " + FunctionName);
            }

            //set the function delegate
            MyFunction = owner.FunctionDictionary[FunctionName];

            //increment the current index since we consumed the function name token
            curIndex++;
        }
Ejemplo n.º 44
0
 public MethodResult Execute(FunctionDelegate F, GradientDelegate Gradient, OptimizationMethod OptimizationMethod, int MaxIterations)
 {
     stopwatch.Start();
     for (int i = 0; i < MaxIterations; i++)
     {
         var oldGradientValue = Gradient(currentValue);
         Vector newDirection = -(hessianMatrix * oldGradientValue);
         var lambda = OptimizationMethod((alpha) => { return F(currentValue + alpha * newDirection); }, -10, 10, 1E-9, MaxIterations);
         var vector = lambda * newDirection;
         currentValue = vector + currentValue;
         //var functionValue = F(currentValue);
         var gradientValue = Gradient(currentValue);
         if (gradientValue.LengthSquared < epsilon || vector.LengthSquared < epsilon)
         {
             stopwatch.Stop();
             return new MethodResult() { Result = new Vector[] { currentValue }, IterationEnd = false, MethodName = "Квазиньютоновский метод", Iterations = i, stopwatch = stopwatch, StartPoint = new Vector[] { StartVector }, FunctionValue = F(currentValue) };
         }
         var matrixU = gradientValue - oldGradientValue;
         var matrixA = (vector * vector.GetTranspose()) / (vector.ToMatrix().GetTranspose() * matrixU)[0, 0];
         var matrixB = -(hessianMatrix * matrixU * matrixU.GetTranspose() * hessianMatrix) / (matrixU.GetTranspose() * hessianMatrix * matrixU)[0, 0];
         hessianMatrix = hessianMatrix + matrixA + matrixB;
     }
     return new MethodResult() { Result = new Vector[] { currentValue }, IterationEnd = true, MethodName = "Квазиньютоновский метод", Iterations = MaxIterations, stopwatch = stopwatch, StartPoint = new Vector[] { StartVector }, FunctionValue = F(currentValue) };
 }
Ejemplo n.º 45
0
 public MethodResult Execute(FunctionDelegate F, GradientDelegate Gradient, OptimizationMethod OptimizationMethod, int MaxIterations)
 {
     stopwatch.Start();
     var antiGradient = -Gradient(x);
     var gradientSquare = antiGradient.LengthSquared;
     for (int i = 0; i < MaxIterations; i++)
     {
         var lambda = OptimizationMethod((alpha) => { return F(x + alpha * antiGradient); }, -10, 10, 1E-9, MaxIterations);
         x = x + lambda * antiGradient;
         var newAntiGradient = -Gradient(x);
         var newGradientSquare = newAntiGradient.LengthSquared;
         var beta = newGradientSquare / gradientSquare;
         if (i % (500) == 0 && i != 0) beta = 0;
         antiGradient = newAntiGradient + beta * antiGradient;
         gradientSquare = newGradientSquare;
         if (gradientSquare < epsilon)
         {
             stopwatch.Stop();
             return new MethodResult() { Result = new Vector[] { x }, IterationEnd = false, Iterations = i, MethodName = "Метод сопряженных градиентов", stopwatch = stopwatch , StartPoint = new Vector[] { StartVector}, FunctionValue = F(x)};
         }
     }
     stopwatch.Stop();
     return new MethodResult() { Result = new Vector[] { x }, IterationEnd = true, MethodName = "Метод сопряженных градиентов", Iterations = MaxIterations, stopwatch = stopwatch, StartPoint = new Vector[] { StartVector }, FunctionValue = F(x) };
 }
Ejemplo n.º 46
0
 // Select the appropriate function and redraw.
 private void equationComboBox_SelectedIndexChanged(object sender, EventArgs e)
 {
     switch (equationComboBox.SelectedIndex)
     {
         case 0:
             TheFunction = Function1;
             break;
         case 1:
             TheFunction = Function2;
             break;
         case 2:
             TheFunction = Function3;
             break;
     }
     graphPictureBox.Refresh();
 }
 public override void Reset()
 {
     this._delegate = null;
     this.FunctionID = -1;
     base.Reset();
 }
Ejemplo n.º 48
0
 public ContainerFunction(String name, FunctionDelegate execution)
 {
     _name = name;
     _execution = execution;
 }
Ejemplo n.º 49
0
        public Function Add(Functor functor, FunctionDelegate functionDelegate)
        {
            if (functor == null)
            {
                throw new ArgumentNullException("functor");
            }
            if (functionDelegate == null)
            {
                throw new ArgumentNullException("functionDelegate");
            }

            Function function = Methods.Add(functor, functionDelegate);

            return function;
        }
Ejemplo n.º 50
0
 public void Add(string name, string op, int arity, FunctionDelegate functionDelegate)
 {
     Add(new Functor(name, arity), functionDelegate);
     Add(new Functor(op, arity), functionDelegate);
 }
Ejemplo n.º 51
0
 /// <summary>
 /// Executes a function on each item in a <see cref="ICollection" /> 
 /// but does not accumulate the result.
 /// </summary>
 /// <param name="coll"></param>
 /// <param name="func"></param>
 public static void Apply(ICollection coll, FunctionDelegate<object> func)
 {
     foreach(object obj in coll)
         func(obj);
 }
        /// <summary>
        /// Initializes a user-defined function.
        /// </summary>
        /// <param name="name"> The name of the function. </param>
        /// <param name="argumentNames"> The names of the arguments. </param>
        /// <param name="parentScope"> The scope at the point the function is declared. </param>
        /// <param name="bodyText"> The source code for the function body. </param>
        /// <param name="generatedMethod"> A delegate which represents the body of the function, plus any dependencies. </param>
        /// <param name="strictMode"> <c>true</c> if the function body is strict mode; <c>false</c> otherwise. </param>
        /// <param name="hasInstancePrototype"> <c>true</c> if the function should have a valid
        /// "prototype" property; <c>false</c> if the "prototype" property should be <c>null</c>. </param>
        private void Init(string name, IList<string> argumentNames, Scope parentScope, string bodyText, GeneratedMethod generatedMethod, bool strictMode, bool hasInstancePrototype)
        {
            if (name == null)
                throw new ArgumentNullException("name");
            if (argumentNames == null)
                throw new ArgumentNullException("argumentNames");
            if (bodyText == null)
                throw new ArgumentNullException("bodyText");
            if (generatedMethod == null)
                throw new ArgumentNullException("generatedMethod");
            if (parentScope == null)
                throw new ArgumentNullException("parentScope");
            this.ArgumentNames = new System.Collections.ObjectModel.ReadOnlyCollection<string>(argumentNames);
            this.BodyText = bodyText;
            this.generatedMethod = generatedMethod;
            this.body = (FunctionDelegate)this.generatedMethod.GeneratedDelegate;
            this.ParentScope = parentScope;
            this.StrictMode = strictMode;

            // Add function properties.
            this.FastSetProperty("name", name);
            this.FastSetProperty("length", argumentNames.Count);

            // The empty function doesn't have an instance prototype.
            if (hasInstancePrototype == true)
            {
                this.FastSetProperty("prototype", this.Engine.Object.Construct(), PropertyAttributes.Writable);
                this.InstancePrototype.FastSetProperty("constructor", this, PropertyAttributes.NonEnumerable);
            }
        }
Ejemplo n.º 53
0
 public SafeMethodState(FunctionDelegate method, object[] nullArguments)
 {
     this.method = method;
     this.nullArguments = nullArguments;
 }
 /// <summary>
 ///		Initializes a new instance of this class.
 /// </summary>
 /// <param name="identifier">Identifier used to call this function from a script.</param>
 /// <param name="nativeFunctionDelegate">Delegate of function you wish to be called when function is called from the script.</param>
 /// <param name="returnType">Data type that this function returns.</param>
 /// <param name="parameterTypes">Array of parameter data types this function uses.</param>
 public NativeFunction(string identifier, FunctionDelegate nativeFunctionDelegate, DataTypeValue returnType, DataTypeValue[] parameterTypes)
 {
     _identifier = identifier;
     _delegate = nativeFunctionDelegate;
     _returnType = returnType;
     _parameterTypes = parameterTypes;
 }
        /// <summary>
        ///		Registers a native function that can be imported and used by script processes.
        /// </summary>
        public void RegisterNativeFunction(string identifier, FunctionDelegate functionDelegate, DataTypeValue returnType, params DataTypeValue[] parameterTypeList)
        {
            string fullName = identifier + "(";
            for (int i = 0; i < parameterTypeList.Length; i++)
                fullName += parameterTypeList[i] + (i < parameterTypeList.Length - 1 ? "," : "");
            fullName += ")";

            _nativeFunctions.Add(fullName, new NativeFunction(identifier, functionDelegate, returnType, parameterTypeList));
        }
 /// <summary>
 /// Creates an empty function.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain. </param>
 private UserDefinedFunction(ObjectInstance prototype)
     : base(prototype)
 {
     var body = new FunctionDelegate((engine, scope, functionObject, thisObject, argumentValues) => Undefined.Value);
     Init("Empty", new string[0], this.Engine.CreateGlobalScope(), "return undefined", new GeneratedMethod(body, null), true, false);
 }
 /// <summary>
 /// Creates a new instance of a user-defined function.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain. </param>
 /// <param name="name"> The name of the function. </param>
 /// <param name="argumentNames"> The names of the arguments. </param>
 /// <param name="parentScope"> The scope at the point the function is declared. </param>
 /// <param name="bodyText"> The source code for the function body. </param>
 /// <param name="body"> A delegate which represents the body of the function. </param>
 /// <param name="strictMode"> <c>true</c> if the function body is strict mode; <c>false</c> otherwise. </param>
 internal UserDefinedFunction(ObjectInstance prototype, string name, IList<string> argumentNames, Scope parentScope, string bodyText, FunctionDelegate body, bool strictMode)
     : base(prototype)
 {
     Init(name, argumentNames, parentScope, bodyText, new GeneratedMethod(body, null), strictMode, true);
 }
 /// <summary>
 /// Compiles the function (if it hasn't already been compiled) and returns a delegate
 /// representing the compiled function.
 /// </summary>
 private FunctionDelegate Compile()
 {
     if (this.body == null)
     {
         // Compile the function.
         var scope = DeclarativeScope.CreateFunctionScope(this.Engine.CreateGlobalScope(), this.Name, this.ArgumentNames);
         var functionGenerator = new FunctionMethodGenerator(this.Engine, scope, this.Name, this.ArgumentNames, this.BodyText, new CompilerOptions());
         functionGenerator.GenerateCode();
         this.generatedMethod = functionGenerator.GeneratedMethod;
         this.body = (FunctionDelegate)this.generatedMethod.GeneratedDelegate;
     }
     return this.body;
 }
Ejemplo n.º 59
0
 public abstract int GenerateFunction(functionExpressionNode node, string name, StatementNode r, out FunctionDelegate _delegate);
Ejemplo n.º 60
0
 public InternalFunction(FunctionDelegate target)
 {
     this.target = target;
 }