/// <summary> /// ВЫвод минимума функции для делегата Function2 /// </summary> /// <param name="x1"></param> /// <param name="x2"></param> /// <param name="step"></param> /// <param name="func"></param> private static void minFunc2(double x1, double x2, double step, Function2 func) { string result = func(x1, x2, step); Console.WriteLine(); Console.WriteLine($"Минимум функции в точке: {result}"); }
public void Run() { // Arrange var toDo = new ToDo { Description = $"description-{Guid.NewGuid()}" }; // Act var actionResult = Function2.Run(toDo, _logger); // Assert Assert.IsType <OkObjectResult>(actionResult); var okObjectResult = (OkObjectResult)actionResult; Assert.IsType <ToDo>(okObjectResult.Value); toDo = (ToDo)okObjectResult.Value; var expectedDataStore = nameof(ToDoSample2DataStore); Assert.Equal(expectedDataStore, toDo.DataStore); }
public IRouteComponent Map(Function2 fn, float rhs) { switch (fn) { case Function2.Add: return(applyMath(Operation.Add, rhs)); case Function2.Multiply: return(applyMath(Operation.Multiply, rhs)); case Function2.Divide: return(applyMath(Operation.Divide, rhs)); case Function2.Modulus: return(applyMath(Operation.Modulus, rhs)); case Function2.Exponent: return(applyMath(Operation.Exponent, rhs)); case Function2.LeftShift: return(applyMath(Operation.LeftShift, rhs)); case Function2.RightShift: return(applyMath(Operation.RightShift, rhs)); case Function2.Subtract: return(applyMath(Operation.Subtract, rhs)); case Function2.Constant: return(applyMath(Operation.Constant, rhs)); } throw new Exception("Only here so the compiler won't get mad"); }
static void Main(string[] args) { //Вяльшина Вероника /*2. Модифицировать программу нахождения минимума функции так, чтобы можно было передавать функцию в виде делегата. * б) Используйте массив (или список) делегатов, в котором хранятся различные функции.*/ List <Function1> values1 = new List <Function1>(); values1.Add(functionA); values1.Add(functionB); List <Function2> values2 = new List <Function2>(); values2.Add(functionC); values2.Add(functionD); double x1, x2, step; int f = functionSelection(); switch (f) { case 1: Console.WriteLine("Вы выбрали функцию y = 2x^3 - 4x^2 + 6x"); Function1 func1 = new Function1(values1[0]); setSegment(out x1, out x2, out step); minFunc1(x1, x2, step, func1); break; case 2: Console.WriteLine("Вы выбрали функцию y = 6x^2 - 5x"); func1 = new Function1(values1[1]); setSegment(out x1, out x2, out step); minFunc1(x1, x2, step, func1); break; case 3: Console.WriteLine("Вы выбрали функцию y = 4x^2"); Function2 func2 = new Function2(values2[0]); setSegment(out x1, out x2, out step); minFunc2(x1, x2, step, func2); break; case 4: Console.WriteLine("Вы выбрали функцию y = 3x"); func2 = new Function2(values2[1]); setSegment(out x1, out x2, out step); minFunc2(x1, x2, step, func2); break; default: Console.WriteLine("Вы ничего не выбрали. Будет показана работа функции y=2x^3 - 4x^2 + 6x"); func1 = new Function1(values1[0]); setSegment(out x1, out x2, out step); minFunc1(x1, x2, step, func1); break; } Pause(); }
static double[] Apply(double[] a, Function2 f) { double[] result = new double[a.Length]; for (int i = 0; i < a.Length; i++) { result[i] = f(a[i]); } return(result); }
// Use this for initialization void Start() { IClient client = new Client1(); IFunction function = new Function2(); client.SetFunction(function); function.SetClient(client); client.mStr = "xxxx"; client.Call(); }
public IRouteComponent Map(Function2 fn, params string[] names) { RouteComponent next = Map(fn, 0) as RouteComponent; if (next != null) { foreach (string it in names) { state.feedback.Add(Tuple.Create(it, next.source, (byte)4, state.dataProcessors.Last.Value.Item2.config)); } } return(next); }
public async Task Run_BodyDoesNotContainSTARTED_Return400BadRequest(string body) { //arrange var mockHttpRequest = MockHttpRequestGenerator.CreateWithBodyString(body); //act var actionResult = await Function2.Run(mockHttpRequest.Object, new IntermediaryServiceDocument(), _mockLogger); //assert Assert.IsTrue(_mockLogger.GetLogs().Where(m => m.Contains(UserFriendlyMessages.UnexpectedBodyContent)).Count() == 1); Assert.IsInstanceOfType(actionResult, typeof(BadRequestObjectResult)); StringAssert.Contains(((BadRequestObjectResult)actionResult).Value.ToString(), UserFriendlyMessages.UnexpectedBodyContent); }
/// <summary> /// Očekává ze nenastane vyjimka, výsledek vypíše /// </summary> /// <param name="funkce">funkce vracejici double ktera bere dva double parametry</param> /// <param name="a">double</param> /// <param name="b">double</param> void ExpectNoThrow(Function2 funkce, double a, double b) { try { funkce(a, b); richTextBox1.AppendText("\r\nNoThrow zadane parametry:" + a + " " + b); } catch { chyby++; richTextBox1.AppendText("\r\nChybaNoThrow zadane parametry:" + a + " " + b); } }
public async Task Run_CosmosDbReturnsNoDocument_Return404NotFound() { //arrange var mockHttpRequest = MockHttpRequestGenerator.CreateWithBodyString("STARTED"); //act var actionResult = await Function2.Run(mockHttpRequest.Object, null, _mockLogger); //assert Assert.IsTrue(_mockLogger.GetLogs().Where(m => m.Contains(UserFriendlyMessages.DocumentNotFound)).Count() == 1); Assert.IsInstanceOfType(actionResult, typeof(NotFoundObjectResult)); StringAssert.Contains(((NotFoundObjectResult)actionResult).Value.ToString(), UserFriendlyMessages.DocumentNotFound); }
static void Main(string[] args) { Function1 instance1 = new Function1(); Function2 instance2 = new Function2(); Function3 instance3 = new Function3(); ParameterizedThreadStart function1 = new ParameterizedThreadStart(instance1.StartOfFunction); ParameterizedThreadStart function2 = new ParameterizedThreadStart(instance2.StartOfFunction); ParameterizedThreadStart function3 = new ParameterizedThreadStart(instance3.StartOfFunction); Thread thread1 = new Thread(function1); Thread thread2 = new Thread(function2); Thread thread3 = new Thread(function3); // Console.WriteLine("Dimension = " + methods.getSizeofArrays()); thread1.Start(4); thread2.Start(5); thread3.Start(6); }
private void LoadModuleButton_Click(object sender, EventArgs e) { StringBuilder errorMessage = new StringBuilder(); openFileDialog1.Filter = "test.py|test.py"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { pythonFile = openFileDialog1.FileName; pe = new PythonEngine(); pe.SetStandardOutput(myConsole); pe.SetStandardError(myConsole); try { pe.ExecuteFile(pythonFile); mainFunc = ((Function2)pe.Globals["main"]); } catch (InvalidCastException) { errorMessage.Append("Symbol 'main' found in Python script, but of wrong type!\n"); } catch (KeyNotFoundException) { errorMessage.Append("Symbol 'main' not found in Python script!\n"); } catch (Exception ex) { errorMessage.Append("Execution failed!\nException: "); errorMessage.Append(ex.Message); } if (errorMessage.Length > 0) { errorMessage.Append("\nScript must contain a 'main' function of the following signature:\n"); errorMessage.Append(" def main(engine, record)"); MessageBox.Show(errorMessage.ToString(), string.Format("Error Loading {0}", pythonFile), MessageBoxButtons.OK, MessageBoxIcon.Error); pythonFile = null; } } ToggleProcessButton(); }
private void InitializeService(MinFunGettingStarted gettingStarted) { #region Selection Init _randomSelection = new MinFuncRandomSelection(gettingStarted.EarlyPopulation); _randomSelfAdaptionSelection = new MinFuncSelfAdaptionRandomSelection(gettingStarted.EarlyPopulation); _rouletteWeelSelection = new MinFuncRouletteWeelSelection(); _susSelection = new MinFuncStochasticSampleSelection(); _tournamentSelection = new MinFuncTournamentSelection(gettingStarted.KIndividualTornomantInit); _selectionList.Add(_randomSelection); _selectionList.Add(_randomSelfAdaptionSelection); _selectionList.Add(_rouletteWeelSelection); _selectionList.Add(_susSelection); _selectionList.Add(_tournamentSelection); #endregion #region Recombination Init _singleRecombination = new MinFuncSingleRecombination(gettingStarted.ChoromosemeLenght, 0.5); _simpleRecombination = new MinFuncSimpleRecombination(gettingStarted.ChoromosemeLenght, 0.5); _wholeRecombination = new MinFuncWholeRecombination(gettingStarted.ChoromosemeLenght, 0.5); _reCombinationList.Add(_singleRecombination); _reCombinationList.Add(_simpleRecombination); _reCombinationList.Add(_wholeRecombination); #endregion #region Mutation Init _onePerFiveMutation = new MinFuncOnePerFiveMutation(gettingStarted.ChoromosemeLenght, gettingStarted.Sigma); _selfAdaptionMutation = new MinFuncSelfAdaptionMutation(gettingStarted.ChoromosemeLenght, gettingStarted.Sigma); _mutationList.Add(_onePerFiveMutation); _mutationList.Add(_selfAdaptionMutation); #endregion #region Functions _function1 = new Function1(10); _function2 = new Function2(gettingStarted.A, gettingStarted.B, gettingStarted.C); _function3 = new Function3(); _functionList.Add(_function1); _functionList.Add(_function2); _functionList.Add(_function3); #endregion }
private static void Assignment2() { Console.WriteLine("--------------ASSIGNMENT [2]--------------------"); Console.WriteLine("Starting vector 1:"); var x1 = new DenseVector(new[] { -1.9, 2.0 }); Console.WriteLine(x1); Console.WriteLine("Starting vector 2:"); Console.WriteLine(); var x2 = new DenseVector(new[] { 0.1, 0.3 }); Console.WriteLine(x2); Console.WriteLine(); var function1 = new Rosenbrock(); Console.WriteLine(function1); Console.WriteLine(); var function2 = new Function2(); Console.WriteLine(function2); Console.WriteLine("ROSENBROCK ALGORITHMS: optimal gradient descent & Newton Raphson"); var optimalDescentRosenbrock = Algorithms.GradientDescent(function1, x1); var newtonRaphsonRosenbrock = Algorithms.NewtonRaphson(function1, x1); Console.WriteLine(optimalDescentRosenbrock); Console.WriteLine(newtonRaphsonRosenbrock); Console.WriteLine(); Console.WriteLine("F2 ALGORITHMS: optimal gradient descent & Newton Raphson"); var optimalDescentF2 = Algorithms.GradientDescent(function2, x2); var newtonRaphsonF2 = Algorithms.NewtonRaphson(function2, x2); Console.WriteLine(optimalDescentF2); Console.WriteLine(newtonRaphsonF2); Console.WriteLine("--------------------END----------------------"); }
private static void Assignment3() { Console.WriteLine("--------------ASSIGNMENT [3]--------------------"); Console.WriteLine("Starting vector 1:"); var x1 = new DenseVector(new[] { -1.9, 2.0 }); Console.WriteLine(x1); Console.WriteLine("Starting vector 2:"); Console.WriteLine(); var x2 = new DenseVector(new[] { 0.1, 0.3 }); Console.WriteLine(x2); Console.WriteLine(); var function1 = new Rosenbrock(); Console.WriteLine(function1); Console.WriteLine(); var function2 = new Function2(); Console.WriteLine(function2);
private void DrawMomentum(Graphics graphics, DrawF draw) { ArrayList history = new ArrayList(); PointF2D point = new PointF2D(-4.0f, 2.0f); Function2 fun = new Function2(); Momentum optimizer = new Momentum(0.07f, 0.9f); for (int index = 0; index < 30; index++) { PointF2D xyPoint = draw.getBlockPoint(point.X, point.Y); history.Add(xyPoint); PointF2D diff = fun.DiffFormula(point.X, point.Y); optimizer.Update(point, diff); } PointF2D prePoint = ((PointF2D)history[0]); for (int index = 0; index < 30; index++) { draw.drawPoint(graphics, Brushes.Blue, ((PointF2D)history[index])); draw.drawLine(graphics, prePoint, ((PointF2D)history[index])); prePoint = ((PointF2D)history[index]); } }
private void DrawGradient(Graphics graphics, DrawF draw) { ArrayList xyPoints = new ArrayList(); ArrayList uvPoints = new ArrayList(); //float[] x = { -2, -1, 0, 1, -2, -1, 0, 1 }; //float[] y = { -2, -2, -2, -2, 1, 1, 1, 1 }; float[] x = { -2, -1, 0, 1, -2, -1, 0, 1 }; float[] y = { -2, -2, -2, -2, 1, 1, 1, 1 }; Function2 fun = new Function2(); for (int index = 0; index < 8; index++) { PointF2D xyPoint = draw.getBlockPoint(x[index], y[index]); PointF2D uvPoint = Fun(fun, -x[index], -y[index]); Console.Write(uvPoint.X + " " + uvPoint.Y); xyPoints.Add(xyPoint); uvPoints.Add(uvPoint); draw.drawPoint(graphics, Brushes.Blue, xyPoint); } draw.drawGradients(graphics, xyPoints, uvPoints); }
/// <summary> /// Draw the Curve. /// </summary> /// <param name="curve">The curve to draw.</param> void DrawCurve2(Function2 curve) { canvas2.Children.Clear(); #region Grafica 1 System.Windows.Point[] points = curve(); if (points.Length < 2) return; const double markerSize = 0.1; // Draw Curve points (Black) for (int i = 0; i < points.Length; ++i) { System.Windows.Shapes.Rectangle rect = new System.Windows.Shapes.Rectangle() { Stroke = System.Windows.Media.Brushes.Black, Fill = System.Windows.Media.Brushes.Black, Height = markerSize, Width = markerSize }; Canvas.SetLeft(rect, points[i].X - markerSize / 2); Canvas.SetTop(rect, points[i].Y - markerSize / 2); canvas2.Children.Add(rect); } // Get Bezier Spline Control Points. System.Windows.Point[] cp1, cp2; BezierSpline.GetCurveControlPoints(points, out cp1, out cp2); // Draw curve by Bezier. PathSegmentCollection lines = new PathSegmentCollection(); for (int i = 0; i < cp1.Length; ++i) { lines.Add(new BezierSegment(cp1[i], cp2[i], points[i + 1], true)); } PathFigure f = new PathFigure(points[0], lines, false); PathGeometry g = new PathGeometry(new PathFigure[] { f }); System.Windows.Shapes.Path path = new System.Windows.Shapes.Path() { Stroke = System.Windows.Media.Brushes.Blue, StrokeThickness = 1, Data = g }; canvas2.Children.Add(path); // Draw Bezier control points markers for (int i = 0; i < cp1.Length; ++i) { // First control point (Blue) System.Windows.Shapes.Ellipse marker = new System.Windows.Shapes.Ellipse() { Stroke = System.Windows.Media.Brushes.Blue, Fill = System.Windows.Media.Brushes.Blue, Height = markerSize / 2, Width = markerSize / 2 }; Canvas.SetLeft(marker, cp1[i].X - markerSize / 2); Canvas.SetTop(marker, cp1[i].Y - markerSize / 2); canvas2.Children.Add(marker); // Second control point (Green) marker = new System.Windows.Shapes.Ellipse() { Stroke = System.Windows.Media.Brushes.Green, Fill = System.Windows.Media.Brushes.Green, Height = markerSize / 2, Width = markerSize / 2 }; Canvas.SetLeft(marker, cp2[i].X - markerSize / 2); Canvas.SetTop(marker, cp2[i].Y - markerSize / 2); canvas2.Children.Add(marker); } // Print points //Trace.WriteLine(string.Format("Start=({0})", points[0])); //for (int i = 0; i < cp1.Length; ++i) //{ // Trace.WriteLine(string.Format("CP1=({0}) CP2=({1}) Stop=({2})" // , cp1[i], cp2[i], points[i + 1])); //} #endregion }
public static Task AddTask(Function2 func2, object data, int timeout) { return(AddTask(new Task(func2, data, timeout))); }
/// <summary> /// After a delay, Function f will be called with parameters p1, p2. /// </summary> /// <param name="owner">Mono object that will own the coroutine</param> /// <param name="f">Callback function</param> /// <param name="p1">Parameter 1</param> /// <param name="p2">Parameter 2</param> /// <param name="delay">A delay in seconds</param> public static void Start <P1, P2>(MonoBehaviour owner, Function2 <P1, P2> f, P1 p1, P2 p2, float delay) { owner.StartCoroutine(CallbackCoroutine(f, p1, p2, delay)); }
public double ExecuteFunction(IMessageCompassValue value1, IMessageCompassValue value2, Function2 op) { double value; if (value1 is MagneticMessageCompassValue) { value = True(value2).Value; } else if (value1 is TrueMessageCompassValue) { value = Magnetic(value2).Value; } else { throw new InvalidOperationException(); } return(op(value1.Value, value)); }
public void TestExceptions() { NPOI.SS.Formula.Functions.Function func = new Function2(); try { FunctionEval.RegisterFunction("SUM", func); Assert.Fail("expectecd exception"); } catch (ArgumentException e) { Assert.AreEqual("POI already implememts SUM" + ". You cannot override POI's implementations of Excel functions", e.Message); } try { FunctionEval.RegisterFunction("SUMXXX", func); Assert.Fail("expectecd exception"); } catch (ArgumentException e) { Assert.AreEqual("Unknown function: SUMXXX", e.Message); } try { FunctionEval.RegisterFunction("ISODD", func); Assert.Fail("expectecd exception"); } catch (ArgumentException e) { Assert.AreEqual("ISODD is a function from the Excel Analysis Toolpack. " + "Use AnalysisToolpack.RegisterFunction(String name, FreeRefFunction func) instead.", e.Message); } FreeRefFunction atpFunc = new FreeRefFunction2();/*FreeRefFunction() { * public ValueEval Evaluate(ValueEval[] args, OperationEvaluationContext ec) { * return ErrorEval.NUM_ERROR; * } * };*/ try { AnalysisToolPak.RegisterFunction("ISODD", atpFunc); Assert.Fail("expectecd exception"); } catch (ArgumentException e) { Assert.AreEqual("POI already implememts ISODD" + ". You cannot override POI's implementations of Excel functions", e.Message); } try { AnalysisToolPak.RegisterFunction("ISODDXXX", atpFunc); Assert.Fail("expectecd exception"); } catch (ArgumentException e) { Assert.AreEqual("ISODDXXX is not a function from the Excel Analysis Toolpack.", e.Message); } try { AnalysisToolPak.RegisterFunction("SUM", atpFunc); Assert.Fail("expectecd exception"); } catch (ArgumentException e) { Assert.AreEqual("SUM is a built-in Excel function. " + "Use FunctoinEval.RegisterFunction(String name, Function func) instead.", e.Message); } }
// 간편 기능2 버튼 private void Function2_Click(object sender, RoutedEventArgs e) { Function2 function2 = new Function2(); function2.Show(); }
public void TestExceptions() { NPOI.SS.Formula.Functions.Function func = new Function2(); try { FunctionEval.RegisterFunction("SUM", func); Assert.Fail("expectecd exception"); } catch (ArgumentException e) { Assert.AreEqual("POI already implememts SUM" + ". You cannot override POI's implementations of Excel functions", e.Message); } try { FunctionEval.RegisterFunction("SUMXXX", func); Assert.Fail("expectecd exception"); } catch (ArgumentException e) { Assert.AreEqual("Unknown function: SUMXXX", e.Message); } try { FunctionEval.RegisterFunction("ISODD", func); Assert.Fail("expectecd exception"); } catch (ArgumentException e) { Assert.AreEqual("ISODD is a function from the Excel Analysis Toolpack. " + "Use AnalysisToolpack.RegisterFunction(String name, FreeRefFunction func) instead.", e.Message); } FreeRefFunction atpFunc = new FreeRefFunction2();/*FreeRefFunction() { public ValueEval Evaluate(ValueEval[] args, OperationEvaluationContext ec) { return ErrorEval.NUM_ERROR; } };*/ try { AnalysisToolPak.RegisterFunction("ISODD", atpFunc); Assert.Fail("expectecd exception"); } catch (ArgumentException e) { Assert.AreEqual("POI already implememts ISODD" + ". You cannot override POI's implementations of Excel functions", e.Message); } try { AnalysisToolPak.RegisterFunction("ISODDXXX", atpFunc); Assert.Fail("expectecd exception"); } catch (ArgumentException e) { Assert.AreEqual("ISODDXXX is not a function from the Excel Analysis Toolpack.", e.Message); } try { AnalysisToolPak.RegisterFunction("SUM", atpFunc); Assert.Fail("expectecd exception"); } catch (ArgumentException e) { Assert.AreEqual("SUM is a built-in Excel function. " + "Use FunctoinEval.RegisterFunction(String name, Function func) instead.", e.Message); } }
public static Task AddTask(Function2 func2, object data, int timeout) { return AddTask(new Task(func2, data, timeout)); }
private static IEnumerator CallbackCoroutine <P1, P2>(Function2 <P1, P2> f, P1 p1, P2 p2, float delay) { yield return(new WaitForSeconds(delay)); f(p1, p2); }
public Task(Function2 f2, object dat, int time) { func2 = f2; data = dat; timeout = time; }
public R8Program(XElement xml) { XElement element = xml.Element("functionSnCount"); if (!Int32.TryParse(element.Value, out functionSnCount)) { functionSnCount = -1; } element = xml.Element("version"); version = element.Value.ToString(); element = xml.Element("start").Element("posX"); if (!Int32.TryParse(element.Value, out start.posX)) { start.posX = -1; } element = xml.Element("start").Element("posY"); if (!Int32.TryParse(element.Value, out start.posY)) { start.posY = -1; } //IEnumerable<XElement> functionElementst = xml.Element("function").Elements("function"); IEnumerable <XElement> functionElements = xml.Elements("function"); IEnumerable <XElement> function2Elements; Function2 function2; Function3 function3; int res; for (int i = 0; i < functionElements.Count(); i++) { function2Elements = functionElements.ElementAt(i).Elements("function"); function2 = new Function2(); element = functionElements.ElementAt(i); if (!Int32.TryParse(element.Element("sn").Value, out res)) { res = -1; } function2.sn = res; if (!Int32.TryParse(element.Element("functionSnCount").Value, out res)) { res = -1; } function2.functionSnCount = res; for (int j = 0; j < functionElements.Count(); j++) { element = functionElements.ElementAt(j); function3 = new Function3(); function3.name = element.Element("name").Value; if (!Int32.TryParse(element.Element("posX").Value, out res)) { res = -1; } function3.rectangle.X = res; if (!Int32.TryParse(element.Element("posY").Value, out res)) { res = -1; } function3.rectangle.Y = res; if (!Int32.TryParse(element.Element("sn").Value, out function3.sn)) { function3.sn = -1; } //Console.WriteLine("function.name = " + function.name); //Console.WriteLine("function.posX = " + function.posX); //Console.WriteLine("function.posY = " + function.posY); //Console.WriteLine("function.sn = " + function.sn); function2.functionList.Add(function3); } functionList.Add(function2); //Console.WriteLine("snCount = " + snCount); //Console.WriteLine("version = " + version); //Console.WriteLine("start.posX = " + start.posX); } }