public Integrator(double h, double maxTime, AWP awp = null) { _editPause = new ManualResetEvent (true); _h = h; _stepper = new RungeKuttaStepper (_h); //_stepper = new EulerStepper(_h); _calculating = false; _maxTime = maxTime; int capacity = (int)(maxTime / h) + 5; _list = new TimeList<Complex[]> (ChooseClosest.Distant, capacity); _triggerRange = 10; if (awp != null) { _awp = awp.Clone (); } else { Complex[] y0 = new Complex[100]; for (int i = 0; i < y0.Length; i++) { //y0 [i] = new Complex(1, rnd.NextDouble() * 2 - 1); //y0 [i] = new Complex (1, i < y0.Length / 2 ? -1 : 1); y0 [i] = Complex.FromPolarCoordinates(1, _rnd.NextDouble() * 2 * Math.PI); //y0 [i] = Complex.FromPolarCoordinates(1, i < y0.Length / 2 ? Math.PI / 2 : Math.PI * 3 / 2); } _awp = new AWP (100, 4, 1, 2, 14, 0, y0); } _awp.Changed+= delegate(object sender, EventArgs e) { _changed = true; Recalc (); }; _changed = true; Recalc (); }
public ThreadedSolver(Stepper stepper, int threadCount) { this._step = stepper; this._threadCount = threadCount; this._threadCount = System.Math.Max(1, threadCount); if(this._threadCount > 1) { _resets = new AutoResetEvent[this._threadCount]; for (int i = 0; i < this._threadCount; i++) { _resets [i] = new AutoResetEvent (false); } } }
public SwitchGallery () { var testLabel = new Label { Text = "Test Label" }; var normal = new Switch { IsToggled = true }; var disabled = new Switch (); var transparent = new Switch (); var stepper = new Stepper (); normal.Toggled += (sender, e) => { testLabel.Text = "Toggled normal switch"; }; disabled.Toggled += (sender, e) => { testLabel.Text = "Toggled disabled switch (magic)"; }; transparent.Toggled += (sender, e) => { testLabel.Text = "Toggled transparent switch"; }; stepper.ValueChanged += (sender, e) => { testLabel.Text = stepper.Value.ToString (); }; disabled.IsEnabled = false; transparent.Opacity = 0.5; Content = new StackLayout { Padding = new Thickness (20), Children = { testLabel, normal, disabled, transparent, stepper, } }; }
/// <summary> /// Главный цикл, в котором происходит запуск метода <see cref="StepperMotor.Run"/>. /// </summary> /// <param name="stopTimer">Флаг остановки</param> private void Loop(ref bool stopTimer) { Stepper.Enabled = true; OnStart(this, EventArgs.Empty); while (!stopTimer) { Stepper.Run(); if (Interval > 0 && Stepper.CurrentStepsCount % Interval == 0) { Elapsed(this, EventArgs.Empty); } stopTimer = !Stepper.IsRunning; } Stepper.Enabled = false; StopReason = StopReason == StepperStopReason.Stoped ? StopReason : StepperStopReason.WorkDone; OnStop(this, EventArgs.Empty); }
public void FinishedStep(Stepper stepper) { if (!_monsterSpawned) { SpawnMonster(); } if (stepper.acceptsInput) { // check if we've reached the edge of the screen Vector3 viewPos = playerCamera.WorldToViewportPoint(playerObject.transform.position); if (viewPos.x > 0.9f) { // end game in victory for player Debug.Log("Player has won the game!"); GameManager.Instance.GameEnding(Time.time);//, true, "You made it! Well done!"); // play animations playerStepper.Win(); AS_back.mute = true; AS_monster.mute = true; AS_win.Play(); if (GameManager.Instance.endTime - GameManager.Instance.startTime > UIManager.Instance.popPopHighScores[UIManager.Instance.currentDifficulty]) { newRecord = true; } if (newRecord) { //UIManager.Instance.popPopHighScores[UIManager.Instance.currentDifficulty] = GameManager.Instance.endTime - GameManager.Instance.startTime; //UIManager.Instance.UpdateTopResultTexts(); } } } }
public void Deadend_1() { var rng = new Mock <IRandomNumberGenerator>(); var evaluator = new Mock <INodeEvaluator>(); var bitAnalyser = new Mock <IBitAnalyser>(); var stepper = new Stepper(evaluator.Object, bitAnalyser.Object); var solution = new MatrixSolution { NoOfStates = 2, IsOptimized = true, Rows = new[] { new MatrixRowSolution { Branch = 0, Approach = SolutionType.DeadEnd, }, new MatrixRowSolution { Branch = 1, Approach = SolutionType.DeadEnd, }, } }; var machine = new Solver( rng.Object, stepper ); Assert.IsTrue(machine.Resolve(solution, 1, out int next)); Assert.AreEqual(1, next); Assert.IsTrue(machine.Resolve(solution, 1, out int next1)); Assert.AreEqual(1, next1); }
private void InitPhidget() { try { //Initialize the InterfaceKit object ifKit = new Stepper(); //Hook the basica event handlers ifKit.Error += new ErrorEventHandler(ifKit_Error); //Open the object for device connections ifKit.open(); //Wait for an InterfaceKit phidget to be attached ifKit.waitForAttachment(3000); //Hook the phidget spcific event handlers ifKit.InputChange += new InputChangeEventHandler(ifKit_InputChange); } catch (PhidgetException ex) { Console.WriteLine(ex.Description); } }
[TestMethod] public void Remove_Testing() { // removing a non-existing value should throw exceptions { IAvlTree <int> tree = new AvlTreeLinked <int>() { 1, 3, }; Assert.ThrowsException <ArgumentException>(() => tree.Remove(2)); } // normal remove checking { IAvlTree <int> tree = new AvlTreeLinked <int>() { 1, 2, 3, }; Assert.IsTrue(tree.Count == 3); tree.Remove(1); Assert.IsFalse(tree.Contains(1)); Assert.IsTrue(tree.Count == 2); tree.Remove(2); Assert.IsFalse(tree.Contains(2)); Assert.IsTrue(tree.Count == 1); tree.Remove(3); Assert.IsFalse(tree.Contains(3)); Assert.IsTrue(tree.Count == 0); } { IAvlTree <int> tree = new AvlTreeLinked <int>(); Stepper.Iterate(100, i => tree.Add(i)); Assert.IsTrue(tree.Count == 100); Stepper.Iterate(100, i => tree.Remove(i)); Assert.IsTrue(tree.Count == 0); } // large randomized data set { const int count = 1000; IAvlTree <int> tree = new AvlTreeLinked <int>(); for (int i = 0; i < count; i++) { Assert.IsTrue(tree.Count == i); tree.Add(i); Assert.IsTrue(tree.Count == i + 1); Assert.IsTrue(tree.Contains(i)); int stepperCount = 0; tree.Stepper(x => stepperCount++); Assert.IsTrue(stepperCount == tree.Count); } int[] values = new int[count]; for (int i = 0; i < count; i++) { values[i] = i; } Random random = new Random(7); random.Shuffle(values); for (int i = 0; i < count; i++) { Assert.IsTrue(tree.Count == count - i); tree.Remove(values[i]); Assert.IsTrue(tree.Count == count - i - 1); Assert.IsFalse(tree.Contains(values[i])); int stepperCount = 0; tree.Stepper(x => stepperCount++); Assert.IsTrue(stepperCount == tree.Count); } } }
/// <summary> /// Gets a list of StackLayout objects associated with properties in an object that have been /// decorated with a UiProperty attribute. /// </summary> /// <returns>The property stacks.</returns> /// <param name="o">Object to get StackLayouts for.</param> public static List <StackLayout> GetPropertyStacks(object o) { List <StackLayout> propertyStacks = new List <StackLayout>(); List <Tuple <PropertyInfo, UiProperty> > propertyUiElements = o.GetType() .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) .Select(p => new Tuple <PropertyInfo, UiProperty>(p, Attribute.GetCustomAttribute(p, typeof(UiProperty), true) as UiProperty)) .Where(pp => pp.Item2 != null) .OrderBy(pp => pp.Item2._order).ToList(); foreach (Tuple <PropertyInfo, UiProperty> propertyUiElement in propertyUiElements) { UiProperty uiElement = propertyUiElement.Item2; Label parameterNameLabel = new Label { Text = uiElement.LabelText ?? propertyUiElement.Item1.Name + ":", HorizontalOptions = LayoutOptions.Start, FontSize = 20 }; bool addParameterValueLabel = false; View view = null; BindableProperty bindingProperty = null; IValueConverter converter = null; if (uiElement is OnOffUiProperty) { view = new Switch(); bindingProperty = Switch.IsToggledProperty; } else if (uiElement is DisplayYesNoUiProperty) { view = new Label { FontSize = 20 }; bindingProperty = Label.TextProperty; converter = new DisplayYesNoUiProperty.ValueConverter(); uiElement.Editable = true; // just makes the label text non-dimmed. a label's text is never editable. } else if (uiElement is EditableListUiProperty) { view = new Editor { HorizontalOptions = LayoutOptions.FillAndExpand }; bindingProperty = Editor.TextProperty; converter = new EditableListUiProperty.ValueConverter(); } else if (uiElement is DisplayStringUiProperty) { view = new Label { FontSize = 20 }; bindingProperty = Label.TextProperty; converter = new DisplayStringUiProperty.ValueConverter(); uiElement.Editable = true; // just makes the label text non-dimmed. a label's text is never editable. } else if (uiElement is EntryIntegerUiProperty) { view = new Entry { Keyboard = Keyboard.Numeric, HorizontalOptions = LayoutOptions.FillAndExpand }; bindingProperty = Entry.TextProperty; converter = new EntryIntegerUiProperty.ValueConverter(); } else if (uiElement is EntryDoubleUiProperty) { view = new Entry { Keyboard = Keyboard.Numeric, HorizontalOptions = LayoutOptions.FillAndExpand }; bindingProperty = Entry.TextProperty; converter = new EntryDoubleUiProperty.ValueConverter(); } else if (uiElement is EntryFloatUiProperty) { view = new Entry { Keyboard = Keyboard.Numeric, HorizontalOptions = LayoutOptions.FillAndExpand }; bindingProperty = Entry.TextProperty; converter = new EntryFloatUiProperty.ValueConverter(); } else if (uiElement is EditorUiProperty) { view = new Editor { Keyboard = Keyboard.Default, HorizontalOptions = LayoutOptions.FillAndExpand }; bindingProperty = Editor.TextProperty; } else if (uiElement is IncrementalIntegerUiProperty) { IncrementalIntegerUiProperty p = uiElement as IncrementalIntegerUiProperty; view = new Stepper { Minimum = p.Minimum, Maximum = p.Maximum, Increment = p.Increment }; bindingProperty = Stepper.ValueProperty; addParameterValueLabel = true; } else if (uiElement is EntryStringUiProperty) { view = new Entry { Keyboard = Keyboard.Default, HorizontalOptions = LayoutOptions.FillAndExpand }; bindingProperty = Entry.TextProperty; } else if (uiElement is ListUiProperty) { Picker picker = new Picker { HorizontalOptions = LayoutOptions.FillAndExpand }; List <object> items = (uiElement as ListUiProperty).Items.ToList(); foreach (object item in items) { picker.Items.Add(item.ToString()); } picker.SelectedIndex = items.IndexOf(propertyUiElement.Item1.GetValue(o)); picker.SelectedIndexChanged += (oo, ee) => { if (picker.SelectedIndex >= 0) { propertyUiElement.Item1.SetValue(o, items[picker.SelectedIndex]); } }; view = picker; } if (view != null) { StackLayout stack = new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand }; stack.Children.Add(parameterNameLabel); if (addParameterValueLabel) { Label parameterValueLabel = new Label { HorizontalOptions = LayoutOptions.FillAndExpand, FontSize = 20 }; parameterValueLabel.BindingContext = o; parameterValueLabel.SetBinding(Label.TextProperty, propertyUiElement.Item1.Name); stack.Children.Add(parameterValueLabel); } view.IsEnabled = uiElement.Editable; if (bindingProperty != null) { view.BindingContext = o; view.SetBinding(bindingProperty, new Binding(propertyUiElement.Item1.Name, converter: converter)); } stack.Children.Add(view); propertyStacks.Add(stack); } } return(propertyStacks); }
/// <summary> /// This programmatically sets up the page's content. /// </summary> /// <param name="page">The content page that is to be set up.</param> /// <param name="index">The index of the page in the carousel page's page list.</param> private void SetupPage(ContentPage page, int index) { // Okay, so let me explain this mess... If I was better at Xamarin.Forms, I probably could have avoided doing the // page setup in this manner. However, I could not access each page's views and controls without doing all of this... // Most of this is grid setup that could have occurred in the XAML part of this page, but there were some changes // that needed to happen in certain circumstances so I elected to just do it all here instead. // I know it looks messy, but it works and I would probably avoid doing it this way now that I know how to use // XAML and Xamarin.Forms a bit better then when I initially did this page. Grid grid = page.FindByName("grdAll") as Grid; Grid volunteer = page.FindByName("grdVolunteer") as Grid; Image imgEvent = page.FindByName("imgEvent") as Image; Label lblSwipe = page.FindByName("lblSwipe") as Label; Label lblTitle = page.FindByName("lblTitle") as Label; Label lblDescription = page.FindByName("lblDescription") as Label; Label lblDate = page.FindByName("lblDate") as Label; Label lblStart = page.FindByName("lblStart") as Label; Label lblStartTime = page.FindByName("lblStartTime") as Label; lblStartTime.Text = string.Format("{0:g}", Convert.ToDateTime(lblStartTime.Text)); Label lblEnd = page.FindByName("lblEnd") as Label; Label lblEndTime = page.FindByName("lblEndTime") as Label; if (lblEndTime.Text == null || lblEnd.Text.Length < 1) // Some events do not have an 'End Time' so I { lblEndTime.Text = "Whenever it ends!"; // put a check here to avoid errors. } else { lblEndTime.Text = string.Format("{0:g}", Convert.ToDateTime(lblEndTime.Text)); } Label lblAddress = page.FindByName("lblAddress") as Label; Label lblAddressInfo = page.FindByName("lblAddressInfo") as Label; lblAddressInfo.Text = lblAddressInfo.Text.Replace("\n", "\n\n"); Button btnRegister = page.FindByName("btnRegister") as Button; btnRegister.HorizontalOptions = LayoutOptions.FillAndExpand; if (events[index].CurrentAttendees >= events[index].MaxAttendees) // If the event is full, don't allow people { // to register for it. btnRegister.IsEnabled = false; btnRegister.Text = "Event full!"; } Label lblGuests = page.FindByName("lblGuests") as Label; Stepper stpGuests = page.FindByName("stpGuests") as Stepper; if ((events[index].MaxAttendees ?? int.MaxValue) - events[index].CurrentAttendees < 11) // If there is a maximum amount { // of attendees and that number if ((events[index].MaxAttendees ?? int.MaxValue) - events[index].CurrentAttendees > 1) // is lower than 11, they can't { stpGuests.Maximum = (double)(events[index].MaxAttendees - events[index].CurrentAttendees - 1); // bring 10 guests, } else // which is the default max one { stpGuests.Minimum = -1; // can normally bring. If the } } // event only has one spot, set Label lblMaximum = page.FindByName("lblMaximum") as Label; // the minimum to -1. if (stpGuests.Minimum == -1) // If that minimum is -1, don't { // allow the user to bring guests, lblMaximum.Text = "Only one spot left!"; // as that would exceed the max lblGuests.Text = ""; // attendees for the event. } else { lblMaximum.Text = "Maximum is " + ((int)stpGuests.Maximum).ToString(); // Otherwise, set the maximum } Label txtStepper = page.FindByName("txtStepper") as Label; // to default (10), or the max txtStepper.Text = "Current value: " + ((int)stpGuests.Minimum).ToString(); // minus current plus one (to CheckBox chkVolunteer = page.FindByName("chkVolunteer") as CheckBox; // include themself). Label lblVolunteer = page.FindByName("lblVolunteer") as Label; (page.FindByName("imgLogo") as Image).HeightRequest = 75; imgEvent.HeightRequest = 75; // Inner grid definitions to make the checkbox look pretty. volunteer.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Auto) }); volunteer.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); // Add the checkbox and the label to the inner grid. volunteer.Children.Add(chkVolunteer, 0, 0); volunteer.Children.Add(lblVolunteer, 1, 0); // This part would have been unnecessary if it weren't for one row... grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) }); grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) }); grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) }); grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) }); grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) }); grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) }); grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) }); grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) }); grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) }); // This one... grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) }); grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) }); grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) }); grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) }); // Set up the grid programmatically. This was a load of fun to do. grid.Children.Clear(); grid.Children.Add(lblSwipe, 0, 0); Grid.SetColumnSpan(lblSwipe, 2); grid.Children.Add(imgEvent, 0, 1); Grid.SetColumnSpan(imgEvent, 2); grid.Children.Add(lblTitle, 0, 2); Grid.SetColumnSpan(lblTitle, 2); grid.Children.Add(lblDescription, 0, 3); Grid.SetColumnSpan(lblDescription, 2); grid.Children.Add(lblDate, 0, 4); grid.Children.Add(lblAddress, 1, 4); grid.Children.Add(lblStart, 0, 5); grid.Children.Add(lblStartTime, 0, 6); grid.Children.Add(lblEnd, 0, 7); grid.Children.Add(lblEndTime, 0, 8); grid.Children.Add(lblAddressInfo, 1, 5); Grid.SetRowSpan(lblAddressInfo, 4); grid.Children.Add(lblGuests, 0, 10); grid.Children.Add(txtStepper, 1, 10); grid.Children.Add(lblMaximum, 0, 11); grid.Children.Add(stpGuests, 1, 11); grid.Children.Add(volunteer, 0, 12); Grid.SetColumnSpan(volunteer, 2); grid.Children.Add(btnRegister, 0, 13); Grid.SetColumnSpan(btnRegister, 2); }
public iseseivtoo() { grid = new Grid { RowDefinitions = { new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }, new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }, new RowDefinition { Height = new GridLength(1, GridUnitType.Star) } }, ColumnDefinitions = { new ColumnDefinition { Width = new GridLength(165) }, new ColumnDefinition { Width = new GridLength(185) } } }; //----------------------------------------label 1----------------------------------------------------- lbl = new Label { Text = "Количество значений", FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)), HorizontalOptions = LayoutOptions.StartAndExpand }; //-----------------------------------------stepper---------------------------------------------------- Stepper stepper = new Stepper { Minimum = 0, Maximum = 50, Increment = 0.5, HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.StartAndExpand, }; stepper.ValueChanged += Stepper_ValueChanged;; this.Content = new StackLayout { Children = { lbl, stepper } }; grid.Children.Add(lbl, 0, 0); grid.Children.Add(stepper, 0, 1); //-----------------------------------------label 2--------------------------------------------------- lbl2 = new Label { Text = "Слайдер", FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)), HorizontalOptions = LayoutOptions.EndAndExpand }; //----------------------------------------slider----------------------------------------------------- Slider slider = new Slider { Minimum = 0, Maximum = 50, Value = 30 }; slider.ValueChanged += Slider_ValueChanged; this.Content = new StackLayout { Children = { lbl2, slider } }; grid.Children.Add(lbl2, 1, 0); grid.Children.Add(slider, 1, 0); Content = grid; grid.BackgroundColor = Color.BurlyWood; }
public MyViewsPage() { Title = "Views"; Image image = new Image { Source = "logo.png" }; Label label = new Label { Text = "Hello Xamarin", VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.CenterAndExpand, FontSize = 30, TextColor = Color.Red }; Entry usernameEntry = new Entry { Placeholder = "Username" }; Entry passwordEntry = new Entry { Placeholder = "Password", IsPassword = true }; Button button = new Button { Text = "Login" }; int numberOfClicks = 1; button.Clicked += (object sender, System.EventArgs e) => { DisplayAlert("Number of Clicks", "You clicked " + numberOfClicks.ToString() + " times", "OK"); numberOfClicks++; }; Editor editor = new Editor { Text = "This is Editor! You can write multiple lines into the Editor just like in this example :)" }; StackLayout boxViewLayout = new StackLayout { Orientation = StackOrientation.Vertical, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center, Children = { new StackLayout { Orientation = StackOrientation.Horizontal, Children = { new BoxView { Color = Color.Red, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center }, new BoxView { Color = Color.Green, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center } } }, new StackLayout { Orientation = StackOrientation.Horizontal, Children = { new BoxView { Color = Color.Blue, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center }, new BoxView { Color = Color.Yellow, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center } } } } }; Dictionary <string, Color> nameToColor = new Dictionary <string, Color> { { "Aqua", Color.Aqua }, { "Black", Color.Black }, { "Blue", Color.Blue }, { "Fuchsia", Color.Fuchsia }, { "Gray", Color.Gray }, { "Green", Color.Green }, { "Lime", Color.Lime }, { "Maroon", Color.Maroon }, { "Navy", Color.Navy }, { "Olive", Color.Olive }, { "Purple", Color.Purple }, { "Red", Color.Red }, { "Silver", Color.Silver }, { "Teal", Color.Teal }, { "White", Color.White }, { "Yellow", Color.Yellow } }; Picker picker = new Picker { Title = "Select Background Color" }; foreach (string colorName in nameToColor.Keys) { picker.Items.Add(colorName); } DatePicker datePicker = new DatePicker { Format = "D", MinimumDate = DateTime.Today.AddYears(-1), MaximumDate = DateTime.Today.AddYears(1) }; TimePicker timePicker = new TimePicker { TextColor = Color.Red }; Stepper stepper = new Stepper { Minimum = 0, Maximum = 10, Increment = 1, HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.Center }; Label stepperLabel = new Label { Text = stepper.Value.ToString(), HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, HorizontalTextAlignment = TextAlignment.End, VerticalTextAlignment = TextAlignment.Center, FontSize = 20 }; stepper.ValueChanged += (object sender, ValueChangedEventArgs e) => { stepperLabel.Text = stepper.Value.ToString(); }; StackLayout stepperLayout = new StackLayout { Orientation = StackOrientation.Horizontal, Children = { stepper, stepperLabel } }; Slider slider = new Slider { Minimum = 0, Maximum = 100, Value = 50, HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.Center, WidthRequest = 200 }; Label sliderLabel = new Label { Text = slider.Value.ToString(), HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, HorizontalTextAlignment = TextAlignment.End, VerticalTextAlignment = TextAlignment.Center, FontSize = 20 }; slider.ValueChanged += (object sender, ValueChangedEventArgs e) => { sliderLabel.Text = slider.Value.ToString(); }; StackLayout sliderLayout = new StackLayout { Orientation = StackOrientation.Horizontal, Children = { slider, sliderLabel } }; Switch switcher = new Switch { HorizontalOptions = LayoutOptions.CenterAndExpand, VerticalOptions = LayoutOptions.CenterAndExpand, }; Label switchLabel = new Label { Text = "False", HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, HorizontalTextAlignment = TextAlignment.End, VerticalTextAlignment = TextAlignment.Center, FontSize = 20 }; StackLayout switchLayout = new StackLayout { Orientation = StackOrientation.Horizontal, Children = { switcher, switchLabel } }; switcher.Toggled += (object sender, ToggledEventArgs e) => { switchLabel.Text = e.Value.ToString(); }; ActivityIndicator indicator = new ActivityIndicator(); ProgressBar progressBar = new ProgressBar(); ListView listView = new ListView(); StackLayout stackLayout = new StackLayout { HorizontalOptions = LayoutOptions.Fill, VerticalOptions = LayoutOptions.FillAndExpand, Children = { image, boxViewLayout, label, usernameEntry, passwordEntry, button, editor, picker, datePicker, timePicker, stepperLayout, sliderLayout, switchLayout } }; picker.SelectedIndexChanged += (object sender, System.EventArgs e) => { if (picker.SelectedIndex != -1) { this.BackgroundColor = nameToColor[picker.Items[picker.SelectedIndex]]; } else { this.BackgroundColor = Color.White; } }; Content = new ScrollView { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Content = stackLayout }; Padding = new Thickness(20, 20, 20, 20); }
public SliderStepperSwitchBindingsPage() { // Create a Slider. Slider slider = new Slider { VerticalOptions = LayoutOptions.EndAndExpand }; // Create a Label to display the Slider value. Label sliderValueLabel = new Label { Font = Font.SystemFontOfSize(NamedSize.Large), VerticalOptions = LayoutOptions.StartAndExpand, HorizontalOptions = LayoutOptions.Center }; // Create a Stepper. Stepper stepper = new Stepper { VerticalOptions = LayoutOptions.EndAndExpand, HorizontalOptions = LayoutOptions.Center }; // Create a Label to display the Stepper value. Label stepperValueLabel = new Label { Font = Font.SystemFontOfSize(NamedSize.Large), VerticalOptions = LayoutOptions.StartAndExpand, HorizontalOptions = LayoutOptions.Center, }; // Create a Switch. Switch switcher = new Switch { IsToggled = true, VerticalOptions = LayoutOptions.EndAndExpand, HorizontalOptions = LayoutOptions.Center }; // Create a Label to display the Switch value. Label switchToggledLabel = new Label { Font = Font.SystemFontOfSize(NamedSize.Large), VerticalOptions = LayoutOptions.StartAndExpand, HorizontalOptions = LayoutOptions.Center }; // Put them all in a StackLayout. this.Content = new StackLayout { Children = { slider, sliderValueLabel, stepper, stepperValueLabel, switcher, switchToggledLabel, } }; sliderValueLabel.BindingContext = slider; sliderValueLabel.SetBinding(Label.OpacityProperty, "Value"); slider.BindingContext = switcher; slider.SetBinding(Slider.IsEnabledProperty, "IsToggled"); stepper.BindingContext = switcher; stepper.SetBinding(Stepper.IsEnabledProperty, "IsToggled"); sliderValueLabel.SetBinding(Label.TextProperty, new Binding("Value", BindingMode.Default, null, null, "The Slider value is {0:F2}")); stepperValueLabel.BindingContext = stepper; stepperValueLabel.SetBinding(Label.TextProperty, new Binding("Value", BindingMode.Default, null, null, "The Stepper value is {0}")); switchToggledLabel.BindingContext = switcher; switchToggledLabel.SetBinding(Label.TextProperty, new Binding("IsToggled", BindingMode.Default, null, null, "The Switch is toggled {0}")); }
public MainPage() { InitializeComponent(); bool timer = true; double t = 0; Grid grid = new Grid { RowDefinitions = { new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }, new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }, new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }, new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }, new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }, new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }, new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }, new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }, }, ColumnDefinitions = { new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }, new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }, } }; Stepper stepper = new Stepper { Maximum = 6, Increment = 1, Margin = new Thickness(10, 0, 0, 0), HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center }; grid.Children.Add(stepper, 0, 1); Label p_amount = new Label { Text = "Amount", TextColor = Color.Black, FontSize = 18, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.CenterAndExpand }; grid.Children.Add(p_amount, 1, 1); Label name_label = new Label { Text = "Enter names", HorizontalTextAlignment = TextAlignment.Center, TextColor = Color.Black, Margin = new Thickness(0, 20, 0, 0), FontSize = 16 }; grid.Children.Add(name_label, 0, 2); var entry1 = new Entry { FontSize = 18 }; var entry2 = new Entry { FontSize = 18 }; var entry3 = new Entry { FontSize = 18 }; var entry4 = new Entry { FontSize = 18 }; var entry5 = new Entry { FontSize = 18 }; var entry6 = new Entry { FontSize = 18 }; Entry[] entries = { entry1, entry2, entry3, entry4, entry5, entry6 }; stepper.ValueChanged += (sender, e) => { p_amount.Text = stepper.Value.ToString(); if (stepper.Value > 0) { grid.Children.Add(entries[(int)stepper.Value - 1], 1, (int)stepper.Value + 1); } if (stepper.Value == 0) { for (int i = 0; i < entries.Length; i++) { grid.Children.Remove(entries[i]); } } if (e.NewValue < e.OldValue) { for (int i = 0; i < entries.Length; i++) { grid.Children.Remove(entries[(int)e.OldValue - 1]); } } }; Button reset = new Button { Text = "Reset", FontSize = 12.5, Margin = new Thickness(5, 5, 5, 5), VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.Center }; grid.Children.Add(reset, 0, 4); reset.Clicked += (sender, e) => { stepper.Value = 0; p_amount.Text = "Amount"; for (int k = 0; k < entries.Length; k++) { entries[k].Text = string.Empty; } }; Button rndm = new Button { Text = "Choose randomly", FontSize = 12, Margin = new Thickness(5, 5, 5, 5), VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.Center }; grid.Children.Add(rndm, 0, 5); /*var scroller = new ScrollView { Content = grid, VerticalOptions = LayoutOptions.FillAndExpand }; * var vScroller = new ScrollView() { Content = scroller }; * Content = vScroller;*/ Content = grid; rndm.Clicked += (sender, e) => { if (entry1.Text != null && stepper.Value != 0) { Device.StartTimer(TimeSpan.FromSeconds(1), () => { t++; if (t > 3) { timer = false; animationView.IsPlaying = false; Content = ShowRandom; t = 0; Random rnd1 = new Random(); int value1 = rnd1.Next(0, (int)stepper.Value); rndRes.Text = entries[value1].Text; } else { timer = true; Content = animationView; animationView.IsPlaying = true; } return(timer); }); } }; main.Clicked += (sender, e) => { Content = grid; }; }
static void Main(string[] args) { try { //Declare a Stepper object Stepper stepper = new Stepper(); //Hook the basic event handlers stepper.Attach += new AttachEventHandler(stepper_Attach); stepper.Detach += new DetachEventHandler(stepper_Detach); stepper.Error += new ErrorEventHandler(stepper_Error); //Hook the Stepper specific event handlers stepper.CurrentChange += new CurrentChangeEventHandler (stepper_CurrentChange); stepper.InputChange += new InputChangeEventHandler (stepper_InputChange); stepper.PositionChange += new StepperPositionChangeEventHandler (stepper_PositionChange); stepper.VelocityChange += new VelocityChangeEventHandler (stepper_VelocityChange); //Open the Stepper object for device connections stepper.open(); //get the program to wait for a Stepper device to be attached Console.WriteLine("Waiting for a Stepper to be attached...."); stepper.waitForAttachment(); Console.WriteLine("Now the velocity will be set"); Console.WriteLine("The motor will run until it reaches the set goal position"); Console.WriteLine("Press any key to continue..."); Console.ReadLine(); //Set the max velocity to start the stepper motor moving until it hits //the goal position stepper.steppers[0].VelocityLimit = 100.00; //Max velocity Console.WriteLine("Stepper motor velocity set to: {0}", stepper.steppers[0].VelocityLimit.ToString()); stepper.steppers[0].Acceleration = stepper.steppers[0].AccelerationMin; //ensure the value is between the AccelerationMin and AccelerationMax Console.WriteLine("Stepper motor acceleration set to: {0}", stepper.steppers[0].Acceleration.ToString()); stepper.steppers[0].TargetPosition = 0; stepper.steppers[0].Engaged = true; Console.WriteLine("Press any key to continue..."); Console.ReadLine(); Console.WriteLine("Will now move to position 2000."); Console.WriteLine("Please wait until the motor stops."); Console.WriteLine("Press any key to continue..."); Console.ReadLine(); //Set the goal position to 2000 stepper.steppers[0].TargetPosition = 2000; Console.WriteLine("Press any key to end...."); Console.ReadLine(); stepper.steppers[0].Engaged = false; //close the Stepper object stepper.close(); //set the object to null to get it out of memory stepper = null; //if no exceptions were thrown at this point it is safe to terminate Console.WriteLine("ok"); } catch (PhidgetException ex) { Console.WriteLine(ex.Description); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private ContentPage CreateTab1() { var tab1Layout = new StackLayout { VerticalOptions = LayoutOptions.Center, Children = { new Label { HorizontalTextAlignment = TextAlignment.Center, Text = "Xamarin Forms Tab Badge Sample", FontSize = 14, FontAttributes = FontAttributes.Bold }, } }; var stepper = new Stepper { Increment = 1, Maximum = 111, Minimum = 0, VerticalOptions = LayoutOptions.Center }; stepper.SetBinding(Stepper.ValueProperty, nameof(Tab1ViewModel.CountValue), BindingMode.TwoWay); var grid = new Grid(); grid.ColumnDefinitions.Add(new ColumnDefinition()); grid.ColumnDefinitions.Add(new ColumnDefinition()); grid.Children.Add(new Label { Text = "Increment / Decrement Value: ", HorizontalTextAlignment = TextAlignment.End, VerticalTextAlignment = TextAlignment.Center }, 0, 0); grid.Children.Add(stepper, 1, 0); tab1Layout.Children.Add(grid); var buttonChangeColor = new Button { Text = "Change Color" }; buttonChangeColor.SetBinding(Button.CommandProperty, nameof(Tab1ViewModel.ChangeColorCommand)); tab1Layout.Children.Add(buttonChangeColor); var buttonChangeTextColor = new Button { Text = "Change Text Color" }; buttonChangeTextColor.SetBinding(Button.CommandProperty, nameof(Tab1ViewModel.ChangeTextColorCommand)); tab1Layout.Children.Add(buttonChangeTextColor); var buttonChangeFontAttributes = new Button { Text = "Change Font Attributes" }; buttonChangeFontAttributes.SetBinding(Button.CommandProperty, nameof(Tab1ViewModel.ChangeFontAttributesCommand)); tab1Layout.Children.Add(buttonChangeFontAttributes); var buttonChangePosition = new Button { Text = "Change Position" }; buttonChangePosition.SetBinding(Button.CommandProperty, nameof(Tab1ViewModel.ChangePositionCommand)); tab1Layout.Children.Add(buttonChangePosition); var buttonAddTab = new Button() { Text = "Add tab" }; buttonAddTab.Clicked += ButtonAddTab_Clicked; var buttonRemoveTab = new Button() { Text = "Remove tab" }; buttonRemoveTab.Clicked += ButtonRemoveTab_Clicked; grid = new Grid(); grid.ColumnDefinitions.Add(new ColumnDefinition()); grid.ColumnDefinitions.Add(new ColumnDefinition()); grid.Children.Add(buttonAddTab, 0, 0); grid.Children.Add(buttonRemoveTab, 1, 0); tab1Layout.Children.Add(grid); grid = new Grid { RowSpacing = 0 }; grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto }); grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto }); grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto }); grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto }); grid.ColumnDefinitions.Add(new ColumnDefinition()); grid.ColumnDefinitions.Add(new ColumnDefinition()); var leftStepper = new Stepper { Increment = 1, Minimum = -50, Maximum = 50 }; leftStepper.SetBinding(Stepper.ValueProperty, nameof(Tab1ViewModel.MarginLeft), BindingMode.TwoWay); var leftMarginLabel = new Label(); leftMarginLabel.SetBinding(Label.TextProperty, nameof(Tab1ViewModel.MarginLeft), stringFormat: "Left: {0}"); grid.Children.Add(leftMarginLabel, 0, 0); grid.Children.Add(leftStepper, 0, 1); var topStepper = new Stepper { Increment = 1, Minimum = -50, Maximum = 50 }; topStepper.SetBinding(Stepper.ValueProperty, nameof(Tab1ViewModel.MarginTop), BindingMode.TwoWay); var topMarginLabel = new Label(); topMarginLabel.SetBinding(Label.TextProperty, nameof(Tab1ViewModel.MarginTop), stringFormat: "Top: {0}"); grid.Children.Add(topMarginLabel, 1, 0); grid.Children.Add(topStepper, 1, 1); var rightStepper = new Stepper { Increment = 1, Minimum = -50, Maximum = 50 }; rightStepper.SetBinding(Stepper.ValueProperty, nameof(Tab1ViewModel.MarginRight), BindingMode.TwoWay); var rightMarginLabel = new Label(); rightMarginLabel.SetBinding(Label.TextProperty, nameof(Tab1ViewModel.MarginRight), stringFormat: "Right: {0}"); grid.Children.Add(rightMarginLabel, 0, 2); grid.Children.Add(rightStepper, 0, 3); var bottomStepper = new Stepper { Increment = 1, Minimum = -50, Maximum = 50 }; bottomStepper.SetBinding(Stepper.ValueProperty, nameof(Tab1ViewModel.MarginBottom), BindingMode.TwoWay); var bottomMarginLabel = new Label(); bottomMarginLabel.SetBinding(Label.TextProperty, nameof(Tab1ViewModel.MarginBottom), stringFormat: "Bottom: {0}"); grid.Children.Add(bottomMarginLabel, 1, 2); grid.Children.Add(bottomStepper, 1, 3); tab1Layout.Children.Add(grid); var tab1 = new ContentPage { Title = "Tab1", Content = new ScrollView() { Content = tab1Layout } }; tab1.SetBinding(TabBadge.BadgeTextProperty, nameof(Tab1ViewModel.Count)); tab1.SetBinding(TabBadge.BadgeColorProperty, nameof(Tab1ViewModel.BadgeColor)); tab1.SetBinding(TabBadge.BadgeTextColorProperty, nameof(Tab1ViewModel.BadgeTextColor)); tab1.SetBinding(TabBadge.BadgeFontProperty, nameof(Tab1ViewModel.BadgeFont)); tab1.SetBinding(TabBadge.BadgePositionProperty, nameof(Tab1ViewModel.Position)); tab1.SetBinding(TabBadge.BadgeMarginProperty, nameof(Tab1ViewModel.Margin)); tab1.BindingContext = new Tab1ViewModel(); return(tab1); }
/// <summary> /// Solves the differential equation $y'=f(t,y)$ from $t=s_0$ to $t=s$ with initial value $y(s_0)=y_0$. Used by /// <see cref="SolveCashKarp" /> and <see cref="SolveVerner" />. /// </summary> public static Vector Solve(Func<double, Vector, Vector> f, Vector y0, double s0, double s, double[] t, Stepper stepper) { if (f == null || y0 == null || t == null || stepper == null) { throw new ArgumentNullException(); } int n = t.Length; Vector y = y0; if (n != 0 && t[0] != s0 || n == 0 && s0 != s) { throw new ArgumentException("Invalid first step."); } for (int i = 0; i < n; i++) { double u0 = t[i]; double u = i + 1 < n ? t[i + 1] : s; // Don't allow step direction to reverse or to overshoot (but allow steps of size 0). if (s > s0 && !(s >= u && u >= u0) || s < s0 && !(s <= u && u <= u0)) { throw new ArgumentException("Invalid step."); } if (u != u0) { y = stepper(f, y, u0, u); } } return y; }
static void Main(string[] args) { Console.WriteLine("You are runnning the Algorithms example."); Console.WriteLine("======================================================"); Console.WriteLine(); #region Sorting { // Note: these functions are not restricted to array types. You can use the // overloads with "Get" and "Assign" delegates to use them on any int-indexed // data structure. Console.WriteLine(" Sorting Algorithms----------------------"); Console.WriteLine(); int[] dataSet = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; Console.Write(" Data Set:" + string.Join(", ", dataSet.Select(x => x.ToString()))); Console.WriteLine(); // Shuffling (Randomizing) Sort.Shuffle(dataSet); Console.Write(" Shuffle (Randomizing): " + string.Join(", ", dataSet.Select(x => x.ToString()))); Console.WriteLine(); // Bubble Sort.Bubble(dataSet); Console.Write(" Bubble: " + string.Join(", ", dataSet.Select(x => x.ToString()))); Console.WriteLine(); Console.WriteLine(" shuffling dataSet..."); Sort.Shuffle(dataSet); // Selection Sort.Selection(dataSet); Console.Write(" Selection: " + string.Join(", ", dataSet.Select(x => x.ToString()))); Console.WriteLine(); Console.WriteLine(" shuffling dataSet..."); Sort.Shuffle(dataSet); // Insertion Sort.Insertion(dataSet); Console.Write(" Insertion: " + string.Join(", ", dataSet.Select(x => x.ToString()))); Console.WriteLine(); Console.WriteLine(" shuffling dataSet..."); Sort.Shuffle(dataSet); // Quick Sort.Quick(dataSet); Console.Write(" Quick: " + string.Join(", ", dataSet.Select(x => x.ToString()))); Console.WriteLine(); Console.WriteLine(" shuffling dataSet..."); Sort.Shuffle(dataSet); // Merge Sort.Merge(Compute.Compare, dataSet); Console.Write(" Merge: " + string.Join(", ", dataSet.Select(x => x.ToString()))); Console.WriteLine(); Console.WriteLine(" shuffling dataSet..."); Sort.Shuffle(dataSet); // Heap Sort.Heap(Compute.Compare, dataSet); Console.Write(" Heap: " + string.Join(", ", dataSet.Select(x => x.ToString()))); Console.WriteLine(); Console.WriteLine(" shuffling dataSet..."); Sort.Shuffle(dataSet); // OddEven Sort.OddEven(Compute.Compare, dataSet); Console.Write(" OddEven: " + string.Join(", ", dataSet.Select(x => x.ToString()))); Console.WriteLine(); //Console.WriteLine(" shuffling dataSet..."); //Sort<int>.Shuffle(dataSet); //// Slow //Sort<int>.Slow(Logic.compare, get, set, 0, dataSet.Length); //Console.Write("Slow: " + string.Join(", ", dataSet.Select(x => x.ToString()))); //Console.WriteLine(); //Console.WriteLine(" shuffling dataSet..."); //Sort<int>.Shuffle(dataSet); // Bogo //Sort<int>.Bogo(Logic.compare, get, set, 0, dataSet.Length); Console.Write(" Bogo: Disabled (takes forever)"); //+ string.Join(", ", dataSet.Select(x => x.ToString()))); //Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); } #endregion #region Graph Search (Using Graph Data Structure) { Console.WriteLine(" Graph Searching----------------------"); Console.WriteLine(); // make a graph IGraph <int> graph = new GraphSetOmnitree <int>() { // add nodes 0, 1, 2, 3, // add edges { 0, 1 }, { 0, 2 }, { 1, 3 }, { 2, 3 } }; // make a heuristic function int heuristic(int node) { switch (node) { case 0: return(3); case 1: return(6); case 2: return(1); case 3: return(0); default: throw new NotImplementedException(); } } // make a cost function int cost(int from, int to) { if (from == 0 && to == 1) { return(1); } if (from == 0 && to == 2) { return(2); } if (from == 1 && to == 3) { return(5); } if (from == 2 && to == 3) { return(1); } if (from == 0 && to == 3) { return(99); } throw new Exception("invalid path cost computation"); } // make a goal function bool goal(int node) { if (node == 3) { return(true); } else { return(false); } } // run A* the algorithm Stepper <int> aStar_path = Search.Graph <int, int>(0, graph, heuristic, cost, goal); Console.Write(" A* Path: "); if (aStar_path != null) { aStar_path(i => Console.Write(i + " ")); } else { Console.Write("none"); } Console.WriteLine(); // run the Greedy algorithm Stepper <int> greedy_path = Search.Graph <int, int>(0, graph, heuristic, goal); Console.Write(" Greedy Path: "); if (greedy_path != null) { greedy_path(i => Console.Write(i + " ")); } else { Console.Write("none"); } Console.WriteLine(); Console.WriteLine(); } #endregion #region Graph Search (Vector Game-Style Example) { Console.WriteLine(" Graph Searching (Vector Game-Style Example)-------------------"); Console.WriteLine(); Console.WriteLine(" Debug the code. The path is to large to write to the console."); Console.WriteLine(); // Lets say you are coding enemy AI and you want the AI to find a path towards the player // in order to attack them. Here are their starting positions: Vector <float> enemyLocation = new Vector <float>(-100f, 0f, -50f); Vector <float> playerLocation = new Vector <float>(200f, 0f, -50f); float enemyAttackRange = 3f; // enemy has a melee attack with 3 range // Lets say most of the terrain is open, but there is a big rock in between them that they // must go around. Vector <float> rockLocation = new Vector <float>(15f, 0f, -40f); float rockRadius = 20f; // Make sure we don't re-use locations (must be wiped after running the algorithm) ISet <Vector <float> > alreadyUsed = new SetHashLinked <Vector <float> >(); Vector <float> validationVectorStorage = null; // storage to prevent a ton of vectors from being allocated // So, we just need to validate movement locations (make sure the path finding algorithm // ignores locations inside the rock) bool validateMovementLocation(Vector <float> location) { // if the location is inside the rock, it is not a valid movement location.Subtract(rockLocation, ref validationVectorStorage); float magnitude = validationVectorStorage.Magnitude; if (magnitude <= rockRadius) { return(false); } // NOTE: If you are running a physics engine, you might be able to just call it to validate a location. // if the location was already used, then let's consider it invalid, because // another path (which is faster) has already reached that location if (alreadyUsed.Contains(location)) { return(false); } return(true); } // Now we need the neighbor function (getting the neighbors of the current location). void neighborFunction(Vector <float> currentLocation, Step <Vector <float> > neighbors) { // NOTES: // - This neighbor function has a 90 degree per-node resolution (360 / 4 [north/south/east/west] = 90). // - This neighbor function has a 1 unit per-node distance resolution, because we went 1 unit in each direction. // RECOMMENDATIONS: // - If the path finding is failing, you may need to increase the resolution. // - If the algorithm is running too slow, you may need to reduce the resolution. float distanceResolution = 1; float x = currentLocation.X; float y = currentLocation.Y; float z = currentLocation.Z; // Note: I'm using the X-axis and Z-axis here, but which axis you need to use // depends on your environment. Your "north" could be along the Y-axis for example. Vector <float> north = new Vector <float>(x + distanceResolution, y, z); if (validateMovementLocation(north)) { alreadyUsed.Add(north); // mark location as used neighbors(north); } Vector <float> east = new Vector <float>(x, y, z + distanceResolution); if (validateMovementLocation(east)) { alreadyUsed.Add(east); // mark location as used neighbors(east); } Vector <float> south = new Vector <float>(x - distanceResolution, y, z); if (validateMovementLocation(south)) { alreadyUsed.Add(south); // mark location as used neighbors(south); } Vector <float> west = new Vector <float>(x, y, z - distanceResolution); if (validateMovementLocation(west)) { alreadyUsed.Add(west); // mark location as used neighbors(west); } } Vector <float> heuristicVectorStorage = null; // storage to prevent a ton of vectors from being allocated // Heuristic function (how close are we to the goal) float heuristicFunction(Vector <float> currentLocation) { // The goal is the player's location, so we just need our distance from the player. currentLocation.Subtract(playerLocation, ref heuristicVectorStorage); return(heuristicVectorStorage.Magnitude); } // Lets say there is a lot of mud around the rock, and the mud makes our player move at half their normal speed. // Our path finding needs to find the fastest route to the player, whether it be through the mud or not. Vector <float> mudLocation = new Vector <float>(15f, 0f, -70f); float mudRadius = 30f; Vector <float> costVectorStorage = null; // storage to prevent a ton of vectors from being allocated // Cost function float costFunction(Vector <float> from, Vector <float> to) { // If the location we are moving to is in the mud, lets adjust the // cost because mud makes us move slower. to.Subtract(mudLocation, ref costVectorStorage); float magnitude = costVectorStorage.Magnitude; if (magnitude <= mudRadius) { return(2f); } // neither location is in the mud, it is just a standard movement at normal speed. return(1f); } Vector <float> goalVectorStorage = null; // storage to prevent a ton of vectors from being allocated // Goal function bool goalFunction(Vector <float> currentLocation) { // if the player is within the enemy's attack range WE FOUND A PATH! :) currentLocation.Subtract(playerLocation, ref goalVectorStorage); float magnitude = goalVectorStorage.Magnitude; if (magnitude <= enemyAttackRange) { return(true); } // the enemy is not yet within attack range return(false); } // We have all the necessary parameters. Run the pathfinding algorithms! Stepper <Vector <float> > aStarPath = Search.Graph( enemyLocation, neighborFunction, heuristicFunction, costFunction, goalFunction); // Flush the already used markers before running the Greedy algorithm. // Normally you won't run two algorithms for the same graph/location, but // we are running both algorithms in this example to demonstrate the // differences between them. alreadyUsed.Clear(); Stepper <Vector <float> > greedyPath = Search.Graph( enemyLocation, neighborFunction, heuristicFunction, goalFunction); // NOTE: If there is no valid path, then "Search.Graph" will return "null." // For this example, I know that there will be a valid path so I did not // include a null check. // Lets convert the paths into arrays so you can look at them in the debugger. :) Vector <float>[] aStarPathArray = aStarPath.ToArray(); Vector <float>[] greedyPathArray = greedyPath.ToArray(); // lets calculate the movement cost of each path to see how they compare float astartTotalCost = Compute.Add <float>(step => { for (int i = 0; i < aStarPathArray.Length - 1; i++) { step(costFunction(aStarPathArray[i], aStarPathArray[i + 1])); } }); float greedyTotalCost = Compute.Add <float>(step => { for (int i = 0; i < greedyPathArray.Length - 1; i++) { step(costFunction(greedyPathArray[i], greedyPathArray[i + 1])); } }); // Notice that that the A* algorithm produces a less costly path than the Greedy, // meaning that it is faster. The Greedy path went through the mud, but the A* path // took the longer route around the other side of the rock, which ended up being faster // than running through the mud. } #endregion #region Random Generation { Console.WriteLine(" Random Generation---------------------"); Console.WriteLine(); int iterationsperrandom = 3; void testrandom(Random random) { for (int i = 0; i < iterationsperrandom; i++) { Console.WriteLine(" " + i + ": " + random.Next()); } Console.WriteLine(); } Arbitrary mcg_2pow59_13pow13 = new Arbitrary.Algorithms.MultiplicativeCongruent_A(); Console.WriteLine(" mcg_2pow59_13pow13 randoms:"); testrandom(mcg_2pow59_13pow13); Arbitrary mcg_2pow31m1_1132489760 = new Arbitrary.Algorithms.MultiplicativeCongruent_B(); Console.WriteLine(" mcg_2pow31m1_1132489760 randoms:"); testrandom(mcg_2pow31m1_1132489760); Arbitrary mersenneTwister = new Arbitrary.Algorithms.MersenneTwister(); Console.WriteLine(" mersenneTwister randoms:"); testrandom(mersenneTwister); Arbitrary cmr32_c2_o3 = new Arbitrary.Algorithms.CombinedMultipleRecursive(); Console.WriteLine(" mersenneTwister randoms:"); testrandom(cmr32_c2_o3); Arbitrary wh1982cmcg = new Arbitrary.Algorithms.WichmannHills1982(); Console.WriteLine(" mersenneTwister randoms:"); testrandom(wh1982cmcg); Arbitrary wh2006cmcg = new Arbitrary.Algorithms.WichmannHills2006(); Console.WriteLine(" mersenneTwister randoms:"); testrandom(wh2006cmcg); Arbitrary mwcxorsg = new Arbitrary.Algorithms.MultiplyWithCarryXorshift(); Console.WriteLine(" mwcxorsg randoms:"); testrandom(mwcxorsg); } #endregion Console.WriteLine(); Console.WriteLine("============================================"); Console.WriteLine("Example Complete..."); Console.ReadLine(); }
//initialize the stepper object and hook the event handlers private void Form1_Load(object sender, EventArgs e) { timer1.Tick += new EventHandler(timer1_Tick); stepper = new Stepper(); stepper.Attach += new AttachEventHandler(stepper_Attach); stepper.Detach += new DetachEventHandler(stepper_Detach); stepper.Error += new ErrorEventHandler(stepper_Error); stepper.CurrentChange += new CurrentChangeEventHandler(stepper_CurrentChange); stepper.PositionChange += new StepperPositionChangeEventHandler(stepper_PositionChange); stepper.VelocityChange += new VelocityChangeEventHandler(stepper_VelocityChange); stepper.InputChange += new InputChangeEventHandler(stepper_InputChange); openCmdLine(stepper); }
static void Main(string[] args) { try { //Declare a Stepper object Stepper stepper = new Stepper(); //Hook the basic event handlers stepper.Attach += new AttachEventHandler(stepper_Attach); stepper.Detach += new DetachEventHandler(stepper_Detach); stepper.Error += new ErrorEventHandler(stepper_Error); //Hook the Stepper specific event handlers stepper.CurrentChange += new CurrentChangeEventHandler (stepper_CurrentChange); stepper.InputChange += new InputChangeEventHandler (stepper_InputChange); stepper.PositionChange += new StepperPositionChangeEventHandler (stepper_PositionChange); stepper.VelocityChange += new VelocityChangeEventHandler (stepper_VelocityChange); //Open the Stepper object for device connections stepper.open(); //get the program to wait for a Stepper device to be attached Console.WriteLine("Waiting for a Stepper to be attached...."); stepper.waitForAttachment(); Console.WriteLine("Now the velocity will be set"); Console.WriteLine("The motor will run until it reaches the set goal position"); Console.WriteLine("Press any key to continue..."); Console.ReadLine(); //Set the max velocity to start the stepper motor moving until it hits //the goal position stepper.steppers[0].VelocityLimit = 100.00; //Max velocity Console.WriteLine("Stepper motor velocity set to: {0}", stepper.steppers[0].VelocityLimit.ToString()); stepper.steppers[0].Acceleration = stepper.steppers[0].AccelerationMin; //ensure the value is between the AccelerationMin and AccelerationMax Console.WriteLine("Stepper motor acceleration set to: {0}", stepper.steppers[0].Acceleration.ToString()); stepper.steppers[0].TargetPosition = 0; stepper.steppers[0].Engaged = true; Console.WriteLine("Press any key to continue..."); Console.ReadLine(); Console.WriteLine("Will now move to position 2000."); Console.WriteLine("Please wait until the motor stops."); Console.WriteLine("Press any key to continue..."); Console.ReadLine(); //Set the goal position to 2000 stepper.steppers[0].TargetPosition = 2000; Console.WriteLine("Press any key to end...."); Console.ReadLine(); stepper.steppers[0].Engaged = false; //close the Stepper object stepper.close(); //set the object to null to get it out of memory stepper = null; //if no exceptions were thrown at this point it is safe to terminate Console.WriteLine("ok"); } catch (PhidgetException ex) { Console.WriteLine(ex.Description); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public StepperPosition(Stepper stepper) : this(stepper.X, stepper.Y) { }
static void Main() { Console.WriteLine("You are runnning the Mathematics example."); Console.WriteLine("=========================================="); Console.WriteLine(); #region Basic Operations Console.WriteLine(" Basics----------------------------------------------"); Console.WriteLine(); // Variables Fraction <short> clampA = new Fraction <short>(-123, 9); // -123 / 9 Fraction <short> clampB = new Fraction <short>(7, 12); // 7 / 12 Fraction <short> clampC = new Fraction <short>(14, 15); // 14 / 15 double[] values = new double[4]; Stepper <double> valueStepper = values.ToStepper(); values.Format(x => random.NextDouble()); // Examples double negation = Negation(7); Console.WriteLine(" Negate(7): " + negation); decimal addition = Addition(7m, 7m); Console.WriteLine(" Add(7, 7): " + addition); double summation = Σ(valueStepper); Console.WriteLine(" Σ (" + string.Join(", ", values.Select(x => Format(x))) + ") = " + summation); float subtraction = Subtraction(14f, 7f); Console.WriteLine(" Subtract(14, 7): " + subtraction); long multiplication = Multiplication(7L, 7L); Console.WriteLine(" Multiply(7, 7): " + multiplication); double product = Π(valueStepper); Console.WriteLine(" Π (" + string.Join(", ", values.Select(x => Format(x))) + ") = " + product); short division = Division((short)14, (short)7); Console.WriteLine(" Divide(14, 7): " + division); double absoluteValue = AbsoluteValue(-7d); Console.WriteLine(" AbsoluteValue(-7): " + absoluteValue); Fraction <short> clamp = Clamp(clampA, clampB, clampC); Console.WriteLine(" Clamp(" + clampA + ", " + clampB + ", " + clampC + "): " + clamp); int maximum = Maximum(1, 2, 3); Console.WriteLine(" Maximum(1, 2, 3): " + maximum); int minimum = Minimum(1, 2, 3); Console.WriteLine(" Minimum(1, 2, 3): " + minimum); bool lessThan = LessThan((Fraction <int>) 1, (Fraction <int>) 2); Console.WriteLine(" LessThan(1, 2): " + lessThan); bool greaterThan = GreaterThan((Fraction <int>) 1, (Fraction <int>) 2); Console.WriteLine(" GreaterThan(1, 2): " + greaterThan); CompareResult compare = Comparison((Fraction <short>) 7, (Fraction <short>) 7); Console.WriteLine(" Compare(7, 7): " + compare); bool equality = Equality(7, 6); Console.WriteLine(" Equate(7, 6): " + equality); bool equalsLeniency = EqualityLeniency(2, 1, 1); Console.WriteLine(" EqualsLeniency(2, 1, 1): " + equalsLeniency); Console.WriteLine(); #endregion #region More Numeric Mathematics Console.WriteLine(" More Numeric Mathematics----------------------------"); Console.WriteLine(); // some random ints for the examples int random1 = random.Next(1, 100000); int random2 = random.Next(1, 1000); int random3 = random.Next(1, 1000); int random4 = random.Next(1, 1000); int random5 = random.Next(1, 1000); int random6 = random.Next(1, 1000); int random7 = random.Next(6, 10); int random8 = random.Next(1, 100000); int[] randomInts1 = new int[3]; randomInts1.Format(x => random.Next(1, 500) * 2); Stepper <int> randomInts1Stepper = randomInts1.ToStepper(); int[] randomInts2 = new int[3]; randomInts2.Format(x => random.Next(1, 500) * 2); Stepper <int> randomInts2Stepper = randomInts2.ToStepper(); bool isPrime = IsPrime(random1); Console.WriteLine(" IsPrime(" + random1 + "): " + isPrime); bool isNegative = IsNegative(random2); Console.WriteLine(" IsNegative(" + random2 + "): " + isNegative); bool isNonNegative = IsNonNegative(random3); Console.WriteLine(" IsNonNegative(" + random3 + "): " + isNonNegative); bool isPositive = IsPositive(random4); Console.WriteLine(" IsPositive(" + random4 + "): " + isPositive); bool isOdd = IsOdd(random5); Console.WriteLine(" IsOdd(" + random5 + "): " + isOdd); bool isEven = IsEven(random6); Console.WriteLine(" IsEven(" + random6 + "): " + isEven); int greatestCommonFactor = GreatestCommonFactor(randomInts1Stepper); Console.WriteLine(" GCF(" + string.Join(", ", randomInts1) + "): " + greatestCommonFactor); int leastCommonMultiple = LeastCommonMultiple(randomInts2Stepper); Console.WriteLine(" LCM(" + string.Join(", ", randomInts2) + "): " + leastCommonMultiple); int factorial = Factorial(random7); Console.WriteLine(" " + random7 + "!: " + factorial); int combinations = Combinations(7, new int[] { 3, 4 }); Console.WriteLine(" 7! / (3! * 4!): " + combinations); int binomialCoefficient = BinomialCoefficient(7, 2); Console.WriteLine(" 7 choose 2: " + binomialCoefficient); Console.Write(" Prime Factors(" + random8 + "): "); FactorPrimes(random8, prime => Console.Write(prime + " ")); Console.WriteLine(); Console.WriteLine(); #endregion #region Trigonometry Console.WriteLine(" Trigonometry -----------------------------------------"); Console.WriteLine(); double randomDouble = random.NextDouble(); Angle <double> randomAngle = new Angle <double>(randomDouble, Angle.Units.Radians); double sineTaylorSeries = SineTaylorSeries(randomAngle); Console.WriteLine(" SinTaylorSeries(" + randomAngle + ") = " + Format(sineTaylorSeries)); double cosineTaylorSeries = CosineTaylorSeries(randomAngle); Console.WriteLine(" CosinTaylorSeries(" + randomAngle + ") = " + Format(cosineTaylorSeries)); Console.WriteLine(); #endregion #region Statistics Console.WriteLine(" Statistics-----------------------------------------"); Console.WriteLine(); // Data Generation double mode_temp = random.NextDouble() * 100; double[] dataArray = new double[random.Next(5, 7)]; dataArray.Format(x => random.NextDouble() * 100); // Lets copy a value in the array to ensure there is at least one // duplicate (so the "Mode" example will has something to show) dataArray[^ 1] = dataArray[0];
/// <summary> /// Initializes a new instance of the Evaluator class. /// This class is not instantiated itself, but only derived classes. /// </summary> /// <param name="initialPc">The initial pc value.</param> /// <param name="args">The expression to evaluate.</param> /// <param name="env">The evaluator environment.</param> /// <param name="caller">The caller evaluator.</param> protected internal Evaluator(Stepper initialPc, SchemeObject args, Environment env, Evaluator caller) { this.expr = args; this.env = env; this.caller = caller; this.pc = initialPc; this.lineNumber = 0; this.returnedExpr = Undefined.Instance; this.returnFlag = ReturnType.SynchronousReturn; this.finished = false; this.caught = 0; #if Diagnostics this.IncrementCounter(this.GetType().Name + ":ctor"); #endif }