private void AddPlotSeries(List<Tuple<List<Tuple<double, double>>, double>> ansv, double stepX, double stepY)
 {
     _stepX = stepX;
     _stepY = stepY;
     if (!_firstLoaded)
     {
         DrawGrid(ansv.Min(item => item.Item1.Min(it => it.Item1)), ansv.Max(item => item.Item1.Max(it => it.Item1)), stepX,
             ansv.Min(item => item.Item1.Min(it => it.Item2)), ansv.Max(item => item.Item1.Max(it => it.Item2)), stepY);
         PopulateSlider(ansv.Min(it => it.Item2), ansv.Max(it => it.Item2),
             (from a in ansv from b in ansv let d = Math.Abs(a.Item2 - b.Item2) where a.Item1 != b.Item1 select d).Min());
     }
     _XandYandParam.Add(ansv);
     Redraw();
 }
Пример #2
0
 private void btnAddBranch_Click(object sender, RoutedEventArgs e)
 {
     if (String.IsNullOrEmpty(txtStreet.Text)
         || String.IsNullOrEmpty(txtCity.Text)
         || String.IsNullOrEmpty(txtState.Text)
         || String.IsNullOrEmpty(txtZip.Text)
         || String.IsNullOrEmpty(cbManagerIds.Text))
     {
         MessageBox.Show("Must provide full address and select a manager Id", "Input Error",
             MessageBoxButton.OK, MessageBoxImage.Error);
     }
     else
     {
         using(var connection = DatabaseService.GetAccessConnection())
         {
             string commandString = String.Format(DatabaseService.Queries["InsertNewBranch"]
                 ,"'" + txtStreet.Text + "'"
                 , "'" + txtCity.Text + "'"
                 , "'" + txtState.Text + "'"
                 , "'" + txtZip.Text + "'"
                 , "'" + cbManagerIds.Text + "'");
             connection.Open();
             OleDbCommand cmd = new OleDbCommand(commandString, 
                 connection);
             cmd.ExecuteNonQuery();
             connection.Close();
     }
         List<int> currentBranchIds = new List<int>();
         DataTable branchNumberDT = DatabaseService.GetDataTable("GetBranchNumbers");
         foreach (DataRow row in branchNumberDT.Rows)
         {
             currentBranchIds.Add(int.Parse(row["BranchNumber"].ToString()));
         }
         int newestBranch = currentBranchIds.Max();
         if (!String.IsNullOrEmpty(txtPhone1.Text))
         {
             addPhoneNumber(txtPhone1.Text, newestBranch);
             txtPhone1.Text = "";
         }
         if (!String.IsNullOrEmpty(txtPhone2.Text))
         {
             addPhoneNumber(txtPhone2.Text, newestBranch);
             txtPhone2.Text = "";
         }
         if (!String.IsNullOrEmpty(txtPhone3.Text))
         {
             addPhoneNumber(txtPhone3.Text, newestBranch);
             txtPhone3.Text = "";
         }
         MessageBox.Show("Branch successfully added.", "Branch Added");
         txtStreet.Text = "";
         txtCity.Text = "";
         txtState.Text = "";
         txtZip.Text = "";
         cbManagerIds.SelectedIndex = -1;
     }
 }
 private int[,] CellsToArray(List<List<Cell>> cells)
 {
     var result = new int[cells.Count(), cells.Max(cellsRow => cellsRow.Count())];
     for (int x = 0; x < cells.Count(); ++x)
     {
         for (int y = 0; y < cells[x].Count(); ++y)
         {
             result[x, y] = cells[x][y].Value;
         }
     }
     return result;
 }
Пример #4
0
        public MainWindow()
        {
            InitializeComponent();

            int highestPrice = 65;
            List<int> vals = new List<int>() { 10, 20, 30, 40, 50 };
            int min = vals.Min();
            int max = vals.Max();
            max = highestPrice > max ? highestPrice : max;
            double range = max - min;

            // Draw max in red
            Color c = new Color() { ScA = 1, ScR = 1, ScG = 0, ScB = 0 };
            // y = 0 is at the top of the canvas
            var line = new Line() { X1 = 0, Y1 = 0, X2 = canvas.Width, Y2 = 0, Stroke = new SolidColorBrush(c), StrokeThickness = 2.0 };
            canvas.Children.Add(line);
            // Add txt so we can visualize better
            var txt = new TextBlock() { Text = max.ToString() };
            Canvas.SetLeft(txt, canvas.Width / 2);
            Canvas.SetTop(txt, 0 - 9);
            canvas.Children.Add(txt);

            foreach (int val in vals)
            {
                double percent = 1.0 - ((val - min) / range); // 0 is at the top, so invert it by doing 1.0 - xxx
                double y = percent * canvas.Height;
                // Draw line in a shade of blue/green
                c = new Color() { ScA = 1, ScR = 0, ScG = 0.5f, ScB = (float)percent };
                line = new Line() { X1 = 0, Y1 = y, X2 = canvas.Width, Y2 = y, Stroke = new SolidColorBrush(c), StrokeThickness = 2.0 };
                canvas.Children.Add(line);

                // Add txt so we can visualize better
                txt = new TextBlock() { Text = val.ToString() };
                Canvas.SetLeft(txt, canvas.Width / 2);
                Canvas.SetTop(txt, y - 9);
                canvas.Children.Add(txt);
            }
        }
Пример #5
0
        private void btn_simulate_Click(object sender, RoutedEventArgs e)
        {
            int nbrSim = Convert.ToInt32(txt_nbrsim.Text);
            double initWealth = Properties.Settings.Default.InitWealth;

            List<double> finalEarnings = new List<double>();
            List<int> counts = new List<int>();

            for (int i = 0; i < nbrSim; i++)
            {
                MartStrategy MStrat = new MartStrategy(5, 250, initWealth);
                double bid = MStrat.Bet();
                Number res;
                double payoff;
                int count = 0;
                while (bid <= MStrat.Wealth)
                {
                    MStrat.PlaceBet(bid);
                    res = _RGame.Play();
                    payoff = _RGame.GetPayoffColor(NumberColor.Red, bid, res);
                    MStrat.Setup(payoff);
                    bid = MStrat.Bet();
                    count++;
                }
                finalEarnings.Add(MStrat.Earnings-initWealth);
                counts.Add(count);
            }

            txt_earnings.Text = finalEarnings.Average().ToString();
            txt_plays.Text = counts.Average().ToString();
            txt_maxEarnings.Text = finalEarnings.Max().ToString();
            txt_maxLosses.Text = finalEarnings.Min().ToString();
            txt_totEarnings.Text = finalEarnings.Where(x => x > 0).Sum().ToString();
            txt_totLosses.Text = finalEarnings.Where(x => x < 0).Sum().ToString();
            txt_balance.Text = finalEarnings.Sum().ToString();
        }
Пример #6
0
        //初始化指数和、指数积、奖金的方法
        void Timer_Tick(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            string[] ZhuArr = null;
            string ButtonContext = string.Empty;
            int i = 0;

            double SumMinOdds = 0.00;//指数和 最小
            double SumMaxOdds = 0.00;//指数和 最大

            double ProductMinOdds = 1.00;//指数积 最小
            double ProductMaxOdds = 1.00;//指数积 最大

            List<double> DoubleList = new List<double>();

            var selfcols = this.DataGrid1.Columns[0];

            foreach (var item in DataGrid1.ItemsSource)
            {
                //--对象所在的单元格
                var cells = selfcols.GetCellContent(item);
                if (cells != null)
                {
                    //--单元格所包含的元素
                    Grid grid = cells as Grid;

                    StackPanel Sp = grid.Children[0] as StackPanel;

                    StackPanel Sp1 = Sp.Children[1] as StackPanel;

                    ZhuArr = GameNumber[i].Substring(GameNumber[i].IndexOf('(') + 1, GameNumber[i].LastIndexOf(')') - GameNumber[i].IndexOf('(') - 1).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (string s in ZhuArr)
                    {
                        Button b = ReturnShowNum(Sp1.Children[0] as StackPanel, s);

                        if (b == null)
                        {
                            b = ReturnShowNum(Sp1.Children[1] as StackPanel, s);
                            if (b == null)
                            {
                                b = ReturnShowNum(Sp1.Children[2] as StackPanel, s);
                            }
                        }

                        if (b != null)
                        {
                            b.Background = new SolidColorBrush(Colors.Red);//改变按钮颜色

                            DoubleList.Add(Netball.RetuntDouble(ToolTipService.GetToolTip(b).ToString()));
                        }
                    }

                    SumMinOdds += DoubleList.Min();
                    SumMaxOdds += DoubleList.Max();

                    ProductMinOdds *= DoubleList.Min();
                    ProductMaxOdds *= DoubleList.Max();
                }

                i++;
                DoubleList.Clear();

            }

            this.tbSum.Text = string.Format("{0:f2}", SumMinOdds) + "~" + string.Format("{0:f2}", SumMaxOdds);
            this.tbProduct.Text = string.Format("{0:f2}", ProductMinOdds) + "~" + string.Format("{0:f2}", ProductMaxOdds);
            this.tbPremium.Text = string.Format("{0:f2}", ProductMinOdds * 2) + "~" + string.Format("{0:f2}", ProductMaxOdds * 2);


            Timer.Stop();
        }
Пример #7
0
        private static int[] PruneAutosavesSprtGetDeletes(List<int>[] deletableSets, int numToDelete)
        {
            if (deletableSets.Sum(o => o.Count) == numToDelete)
            {
                // Everything in deletable sets needs to be deleted, so just return them all instead of taking the expense of load balancing
                return deletableSets.SelectMany(o => o).ToArray();
            }

            List<int> retVal = new List<int>();

            for (int cntr = 0; cntr < numToDelete; cntr++)
            {
                // Get the largest sets
                int maxSize = deletableSets.Max(o => o.Count);
                List<int>[] largest = deletableSets.Where(o => o.Count == maxSize).ToArray();

                // Pick a random set, and a random index within that set
                int setIndex = StaticRandom.Next(largest.Length);
                int innerIndex = StaticRandom.Next(largest[setIndex].Count);

                // Store the value pointed to
                retVal.Add(largest[setIndex][innerIndex]);

                // Now remove this from the set
                largest[setIndex].RemoveAt(innerIndex);
            }

            return retVal.ToArray();
        }
Пример #8
0
        private string GetMaxCompanyDocNum(List<V_CompanyDocNum> listnums)
        {
            string StrResult = "";
            string StrYear = "";
            List<int> list = new List<int>();
            listnums.ForEach(item =>
            {
                list.Add(GetCompanyNums(item.NUM));
            });
            StrResult = list.Max().ToString();
            StrYear = StrResult.Substring(0, 4);//获取年份
            StrResult = StrResult.Substring(4, StrResult.Length - 4);//取后面的数字
            var ents = from ent in listnums
                       where ent.NUM !=null && ent.NUM.Contains(StrResult)
                       select ent;
            if (ents.Count() > 0)
            {
                string StrMax = ents.FirstOrDefault().NUM;
                StrResult = StrMax.Replace(StrResult, (System.Convert.ToInt32(StrResult) + 1).ToString());


            }
            return StrResult;

        }
Пример #9
0
        void cardView_OnDragging(object sender, EventArgs e)
        {
            lock (cardArrangeLock)
            {
                // First, find the two stacks that the card is hovering above.
                var relevantStacks = new List<CardStack>();
                var yOverlap = new List<double>();
                CardStack resultDeckStack = null;
                double maxOverlap = 0;
                double resultOverlap = 0;

                foreach (var stack in _allCardStacks)
                {
                    Rect rect = stack.BoundingBox;
                    rect.Intersect(new Rect(InteractingCard.Position, new Size(InteractingCard.Width, InteractingCard.Height)));
                    if (rect.Size.Height > 0)
                    {
                        if (stack.Parent != _resultPanel)
                        {
                            relevantStacks.Add(stack);
                            yOverlap.Add(rect.Size.Height);
                        }
                        else if (rect.Size.Width > maxOverlap)
                        {
                            resultDeckStack = stack;
                            maxOverlap = rect.Size.Width;
                            resultOverlap = rect.Size.Height;
                        }
                    }
                }

                if (resultDeckStack != null)
                {
                    relevantStacks.Add(resultDeckStack);
                    yOverlap.Add(resultOverlap);
                }
                Trace.Assert(relevantStacks.Count <= 2 && yOverlap.Count == relevantStacks.Count);

                // Second, set the interacting card of all card stacks accordingly
                foreach (var stack in _allCardStacks)
                {
                    CardInteraction status;
                    if (relevantStacks.Contains(stack) || stack == _sourceDeck)
                    {
                        stack.InteractingCard = InteractingCard;
                        status = CardInteraction.Drag;
                    }
                    else
                    {
                        stack.InteractingCard = null;
                        status = CardInteraction.None;
                    }
                    if (status != stack.CardStatus || status == CardInteraction.Drag)
                    {
                        stack.CardStatus = status;
                        stack.RearrangeCards();
                    }
                }

                // Finally, in the stack with greatest overlapping y-distance, highlight the slot.
                _ResetHighlightSlot();

                if (relevantStacks.Count == 0)
                {
                    _highlightedStack = null;
                }
                else
                {
                    _highlightedStack = relevantStacks[yOverlap.IndexOf(yOverlap.Max())];
                    var highlightedSlot = _stackToSlot[_highlightedStack];
                    if (highlightedSlot.Cards.Count > 0)
                    {
                        int index = Math.Min(_highlightedStack.InteractingCardIndex, highlightedSlot.Cards.Count - 1);
                        _highlightedCardSlot = highlightedSlot.Cards[index];
                        _highlightedCardSlot.CardModel.IsFaded = true;
                    }
                }
            }
        }
Пример #10
0
		public static void ArrangeItems(IEnumerable<DesignItem> items, ArrangeDirection arrangeDirection)
		{
			var collection = items;

			var _context = collection.First().Context as XamlDesignContext;

			var container = collection.First().Parent;

			if (collection.Any(x => x.Parent != container))
				return;

			var placement = container.Extensions.OfType<IPlacementBehavior>().FirstOrDefault();
			if (placement == null)
				return;

			var operation = PlacementOperation.Start(items.ToList(), PlacementType.Move);
			
			//var changeGroup = container.OpenGroup("Arrange Elements");

			List<ItemPos> itemList = new List<ItemPos>();
			foreach (var item in collection)
			{
				itemList.Add(GetItemPos(operation, item));
			}

			var xmin = itemList.Min(x => x.Xmin);
			var xmax = itemList.Max(x => x.Xmax);
			var mpos = (xmax - xmin) / 2 + xmin;
			var ymin = itemList.Min(x => x.Ymin);
			var ymax = itemList.Max(x => x.Ymax);
			var ympos = (ymax - ymin) / 2 + ymin;

			foreach (var item in collection)
			{
				switch (arrangeDirection)
				{
					case ArrangeDirection.Left:
						{
							if (container.Component is Canvas)
							{
								if (!item.Properties.GetAttachedProperty(Canvas.RightProperty).IsSet)
								{
									item.Properties.GetAttachedProperty(Canvas.LeftProperty).SetValue(xmin);
								}
								else
								{
									var pos = (double)((Panel)item.Parent.Component).ActualWidth - (xmin + (double) ((FrameworkElement) item.Component).ActualWidth);
									item.Properties.GetAttachedProperty(Canvas.RightProperty).SetValue(pos);
								}
							}
							else if (container.Component is Grid)
							{
								if ((HorizontalAlignment)item.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).ValueOnInstance != HorizontalAlignment.Right)
								{
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Left = xmin;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
								else
								{
									var pos = (double)((Panel)item.Parent.Component).ActualWidth - (xmin + (double)((FrameworkElement)item.Component).ActualWidth);
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Right = pos;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
							}
						}
						break;
					case ArrangeDirection.HorizontalMiddle:
						{
							if (container.Component is Canvas)
							{
								if (!item.Properties.GetAttachedProperty(Canvas.RightProperty).IsSet)
								{
									if (!item.Properties.GetAttachedProperty(Canvas.RightProperty).IsSet)
									{
										item.Properties.GetAttachedProperty(Canvas.LeftProperty).SetValue(mpos - (((FrameworkElement)item.Component).ActualWidth) / 2);
									}
									else
									{
										var pp = mpos - (((FrameworkElement)item.Component).ActualWidth) / 2;
										var pos = (double)((Panel)item.Parent.Component).ActualWidth - pp - (((FrameworkElement)item.Component).ActualWidth);
										item.Properties.GetAttachedProperty(Canvas.RightProperty).SetValue(pos);
									}
								}
							}
							else if (container.Component is Grid)
							{
								if ((HorizontalAlignment)item.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).ValueOnInstance != HorizontalAlignment.Right)
								{
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Left = mpos - (((FrameworkElement)item.Component).ActualWidth) / 2;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
								else
								{
									var pp = mpos - (((FrameworkElement)item.Component).ActualWidth) / 2;
									var pos = (double)((Panel)item.Parent.Component).ActualWidth - pp - (((FrameworkElement)item.Component).ActualWidth);
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Right = pos;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
							}
						}
						break;
					case ArrangeDirection.Right:
						{
							if (container.Component is Canvas)
							{
								if (!item.Properties.GetAttachedProperty(Canvas.RightProperty).IsSet)
								{
									var pos = xmax - (double)((FrameworkElement)item.Component).ActualWidth;
									item.Properties.GetAttachedProperty(Canvas.LeftProperty).SetValue(pos);
								}
								else
								{
									var pos = (double)((Panel)item.Parent.Component).ActualWidth - xmax;
									item.Properties.GetAttachedProperty(Canvas.RightProperty).SetValue(pos);
								}
							}
							else if (container.Component is Grid)
							{
								if ((HorizontalAlignment)item.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).ValueOnInstance != HorizontalAlignment.Right)
								{
									var pos = xmax - (double)((FrameworkElement)item.Component).ActualWidth;
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Left = pos;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
								else
								{
									var pos = (double)((Panel)item.Parent.Component).ActualWidth - xmax;
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Right = pos;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
							}
						}
						break;
					case ArrangeDirection.Top:
						{
							if (container.Component is Canvas)
							{
								if (!item.Properties.GetAttachedProperty(Canvas.BottomProperty).IsSet)
								{
									item.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(ymin);
								}
								else
								{
									var pos = (double)((Panel)item.Parent.Component).ActualHeight - (ymin + (double)((FrameworkElement)item.Component).ActualHeight);
									item.Properties.GetAttachedProperty(Canvas.BottomProperty).SetValue(pos);
								}
							}
							else if (container.Component is Grid)
							{
								if ((VerticalAlignment)item.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).ValueOnInstance != VerticalAlignment.Bottom)
								{
									item.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(ymin);
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Top = ymin;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
								else
								{
									var pos = (double)((Panel)item.Parent.Component).ActualHeight - (ymin + (double)((FrameworkElement)item.Component).ActualHeight);
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Bottom = pos;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
							}
						}
						break;
					case ArrangeDirection.VerticalMiddle:
						{
							if (container.Component is Canvas)
							{
								if (!item.Properties.GetAttachedProperty(Canvas.BottomProperty).IsSet)
								{
									item.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(ympos - (((FrameworkElement)item.Component).ActualHeight) / 2);
								}
								else
								{
									var pp = mpos - (((FrameworkElement)item.Component).ActualHeight) / 2;
									var pos = (double)((Panel)item.Parent.Component).ActualHeight - pp - (((FrameworkElement)item.Component).ActualHeight);
									item.Properties.GetAttachedProperty(Canvas.BottomProperty).SetValue(pos);
								}
							}
							else if (container.Component is Grid)
							{
								if ((VerticalAlignment)item.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).ValueOnInstance != VerticalAlignment.Bottom)
								{
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Top = ympos - (((FrameworkElement)item.Component).ActualHeight) / 2;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
								else
								{
									var pp = mpos - (((FrameworkElement)item.Component).ActualHeight) / 2;
									var pos = (double)((Panel)item.Parent.Component).ActualHeight - pp - (((FrameworkElement)item.Component).ActualHeight);
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Bottom = pos;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
							}
						}
						break;
					case ArrangeDirection.Bottom:
						{
							if (container.Component is Canvas)
							{
								if (!item.Properties.GetAttachedProperty(Canvas.BottomProperty).IsSet)
								{
									var pos = ymax - (double)((FrameworkElement)item.Component).ActualHeight;
									item.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(pos);
								}
								else
								{
									var pos = (double)((Panel)item.Parent.Component).ActualHeight - ymax;
									item.Properties.GetAttachedProperty(Canvas.BottomProperty).SetValue(pos);
								}
							}
							else if (container.Component is Grid)
							{
								if ((VerticalAlignment)item.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).ValueOnInstance != VerticalAlignment.Bottom)
								{
									var pos = ymax - (double)((FrameworkElement)item.Component).ActualHeight;
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Top = pos;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
								else
								{
									var pos = (double)((Panel)item.Parent.Component).ActualHeight - ymax;
									var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
									margin.Bottom = pos;
									item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
								}
							}
						}
						break;
				}
			}

			operation.Commit();
		}
Пример #11
0
        void btnUploadOK_Click(object sender, RoutedEventArgs e)
        {
            listImages.Visibility = System.Windows.Visibility.Visible;
            btnSave.IsEnabled = true;

            List<ImageItem> list = new List<ImageItem>();
            foreach (object item in listImages.Items)
            {
                list.Add((ImageItem)item);
            }

            common.Image newImage = new common.Image();
            newImage.IsChanged = true;
            newImage.FileName = txtFileName.Text;
            newImage.ImageContent = _byteArray;
            newImage.ImageSmallContent = _byteArraySmall;
            newImage.CreatedBy = newImage.UpdatedBy = Globals.UserLogin.UserName;
            newImage.DisplayIndex = list != null && list.Count > 0 ? (list.Max(i => i.ImageDataItem.DisplayIndex) + 1) : 1;
            newImage.ImageTypeId = (int) this.ImageType;
            newImage.ItemId = this.ItemId;

            ImageItem imageItem = new ImageItem(newImage);
            imageItem.btnDelete.Click += new RoutedEventHandler(btnDelete_Click);
            imageItem.btnDelete.Visibility = this.IsReadOnly ? Visibility.Collapsed : Visibility.Visible;
            listImages.Items.Add(imageItem);

            uiPopupUpload.Close();
        }
Пример #12
0
		public static void WrapItemsNewContainer(IEnumerable<DesignItem> items, Type containerType)
		{
			var collection = items;
			
			var _context = collection.First().Context as XamlDesignContext;
			
			var oldContainer = collection.First().Parent;
			
			if (collection.Any(x => x.Parent != oldContainer))
				return;
			
			var newInstance = Activator.CreateInstance(containerType);
			DesignItem newPanel = _context.Services.Component.RegisterComponentForDesigner(newInstance);
			var changeGroup = newPanel.OpenGroup("Wrap in Container");
			
			List<ItemPos> itemList = new List<ItemPos>();
			
			foreach (var item in collection) {
				
				var itemPos = new ItemPos(){ DesignItem = item };
				itemList.Add(itemPos);
				
				if (oldContainer.Component is Canvas) {
					var canvas = oldContainer.View as Canvas;
					
					if (item.Properties.GetAttachedProperty(Canvas.RightProperty) != null && item.Properties.GetAttachedProperty(Canvas.RightProperty).IsSet) {
						itemPos.HorizontalAlignment = HorizontalAlignment.Right;
						itemPos.Xmax = canvas.ActualWidth - (double)item.Properties.GetAttachedProperty(Canvas.RightProperty).ValueOnInstance;
						itemPos.Xmin = itemPos.Xmax - ((FrameworkElement)item.View).ActualWidth;
					}
					else if (item.Properties.GetAttachedProperty(Canvas.LeftProperty) != null && item.Properties.GetAttachedProperty(Canvas.LeftProperty).IsSet) {
						itemPos.HorizontalAlignment = HorizontalAlignment.Left;
						itemPos.Xmin = (double)item.Properties.GetAttachedProperty(Canvas.LeftProperty).ValueOnInstance;
						itemPos.Xmax = itemPos.Xmin + ((FrameworkElement)item.View).ActualWidth;
					} else {
						itemPos.HorizontalAlignment = HorizontalAlignment.Left;
						itemPos.Xmax = itemPos.Xmin + ((FrameworkElement)item.View).ActualWidth;
					}
					
					if (item.Properties.GetAttachedProperty(Canvas.BottomProperty) != null && item.Properties.GetAttachedProperty(Canvas.BottomProperty).IsSet) {
						itemPos.VerticalAlignment = VerticalAlignment.Bottom;
						itemPos.Ymax = canvas.ActualHeight - (double)item.Properties.GetAttachedProperty(Canvas.BottomProperty).ValueOnInstance;
						itemPos.Ymin = itemPos.Ymax - ((FrameworkElement)item.View).ActualHeight;
					}
					else if (item.Properties.GetAttachedProperty(Canvas.TopProperty) != null && item.Properties.GetAttachedProperty(Canvas.TopProperty).IsSet) {
						itemPos.VerticalAlignment = VerticalAlignment.Top;
						itemPos.Ymin = (double)item.Properties.GetAttachedProperty(Canvas.TopProperty).ValueOnInstance;
						itemPos.Ymax = itemPos.Ymin + ((FrameworkElement)item.View).ActualHeight;
					} else {
						itemPos.VerticalAlignment = VerticalAlignment.Top;
						itemPos.Ymax = itemPos.Ymin + ((FrameworkElement)item.View).ActualHeight;
					}
					
					item.Properties.GetAttachedProperty(Canvas.RightProperty).Reset();
					item.Properties.GetAttachedProperty(Canvas.LeftProperty).Reset();
					item.Properties.GetAttachedProperty(Canvas.TopProperty).Reset();
					item.Properties.GetAttachedProperty(Canvas.BottomProperty).Reset();
				} else if (oldContainer.Component is Grid) {
					var grid = oldContainer.View as Grid;
					
					if ((HorizontalAlignment)item.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).ValueOnInstance == HorizontalAlignment.Right) {
						itemPos.HorizontalAlignment = HorizontalAlignment.Right;
						itemPos.Xmax = grid.ActualWidth - ((Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance).Right;
						itemPos.Xmin = itemPos.Xmax - ((FrameworkElement)item.View).ActualWidth;
					} else {
						itemPos.HorizontalAlignment = HorizontalAlignment.Left;
						itemPos.Xmin = ((Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance).Left;
						itemPos.Xmax = itemPos.Xmin + ((FrameworkElement)item.View).ActualWidth;
					}
					
					if ((VerticalAlignment)item.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).ValueOnInstance == VerticalAlignment.Bottom) {
						itemPos.VerticalAlignment = VerticalAlignment.Bottom;
						itemPos.Ymax = grid.ActualHeight - ((Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance).Bottom;
						itemPos.Ymin = itemPos.Ymax - ((FrameworkElement)item.View).ActualHeight;
					} else {
						itemPos.VerticalAlignment = VerticalAlignment.Top;
						itemPos.Ymin = ((Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance).Top;
						itemPos.Ymax = itemPos.Ymin + ((FrameworkElement)item.View).ActualHeight;
					}
					
					item.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).Reset();
					item.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).Reset();
					item.Properties.GetProperty(FrameworkElement.MarginProperty).Reset();
				}
				
				var parCol = item.ParentProperty.CollectionElements;
				parCol.Remove(item);
			}
			
			var xmin = itemList.Min(x => x.Xmin);
			var xmax = itemList.Max(x => x.Xmax);
			var ymin = itemList.Min(x => x.Ymin);
			var ymax = itemList.Max(x => x.Ymax);
			
			if (oldContainer.Component is Canvas) {
				newPanel.Properties.GetProperty(FrameworkElement.WidthProperty).SetValue(xmax - xmin);
				newPanel.Properties.GetProperty(FrameworkElement.HeightProperty).SetValue(ymax - ymin);
				newPanel.Properties.GetAttachedProperty(Canvas.LeftProperty).SetValue(xmin);
				newPanel.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(ymin);
			} else if (oldContainer.Component is Grid) {
				newPanel.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).SetValue(HorizontalAlignment.Left);
				newPanel.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).SetValue(VerticalAlignment.Top);
				newPanel.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(new Thickness(xmin, ymin, 0, 0));
				newPanel.Properties.GetProperty(FrameworkElement.WidthProperty).SetValue(xmax - xmin);
				newPanel.Properties.GetProperty(FrameworkElement.HeightProperty).SetValue(ymax - ymin);
			}
			
			foreach (var item in itemList) {
				newPanel.ContentProperty.CollectionElements.Add(item.DesignItem);
				
				if (newPanel.Component is Canvas) {
					if (item.HorizontalAlignment == HorizontalAlignment.Right) {
						item.DesignItem.Properties.GetAttachedProperty(Canvas.RightProperty).SetValue(xmax - item.Xmax);
					} else {
						item.DesignItem.Properties.GetAttachedProperty(Canvas.LeftProperty).SetValue(item.Xmin - xmin);
					}
					
					if (item.VerticalAlignment == VerticalAlignment.Bottom) {
						item.DesignItem.Properties.GetAttachedProperty(Canvas.BottomProperty).SetValue(ymax - item.Ymax);
					} else {
						item.DesignItem.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(item.Ymin - ymin);
					}
				} else if (newPanel.Component is Grid) {
					Thickness thickness = new Thickness(0);
					if (item.HorizontalAlignment == HorizontalAlignment.Right) {
						item.DesignItem.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).SetValue(HorizontalAlignment.Right);
						thickness.Right = xmax - item.Xmax;
					} else {
						item.DesignItem.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).SetValue(HorizontalAlignment.Left);
						thickness.Left = item.Xmin - xmin;
					}
					
					if (item.VerticalAlignment == VerticalAlignment.Bottom) {
						item.DesignItem.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).SetValue(VerticalAlignment.Bottom);
						thickness.Bottom = ymax - item.Ymax;
					} else {
						item.DesignItem.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).SetValue(VerticalAlignment.Top);
						thickness.Top = item.Ymin - ymin;
					}
					
					item.DesignItem.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(thickness);
				}
			}
			
			oldContainer.ContentProperty.CollectionElements.Add(newPanel);
			
			changeGroup.Commit();
			
			_context.Services.Selection.SetSelectedComponents(new []{ newPanel });
		}
        private void buttonScalingScore_Click(object sender, RoutedEventArgs e)
        {
            int cols, rows;
            double horizLength, vertLength;
            if (!parseChessboardParameters(out cols, out rows, out horizLength, out vertLength))
            {
                return;
            }

            // 以下改造
            MotionDataHandler handler;
            string path;
            if (openMotionData(out handler, out path))
            {
                CvMat displayMat1 = null;
                CvMat displayMat3 = null;
                CvMat displayMat4 = null;
                CvMat gray = null;

                int length = handler.FrameCount;
                if (length == 0) { return; }

                CvSize boardSize = new CvSize(cols, rows);
                CvSize imageSize = new CvSize();
                List<Tuple<double, double>> pairs = new List<Tuple<double, double>>();
                CvPoint2D32f[] lastCorners = null;

                IEnumerable<CvMat> colorImages, depthImages;
                Utility.LoadImages(handler.GetColorImagePaths(), out colorImages);
                Utility.LoadImages(handler.GetDepthImagePaths(), out depthImages);
                var images = colorImages.Zip(depthImages, (first, second) => Tuple.Create(first, second));

                foreach (Tuple<CvMat, CvMat> imagePair in images)
                {
                    CvMat imageMat = imagePair.Item1;
                    CvMat depthMat = imagePair.Item2;
                    
                    if (displayMat4 == null)
                    {
                        displayMat4 = CvEx.InitCvMat(imageMat);
                    }

                    imageSize = new CvSize(imageMat.Cols, imageMat.Rows);
                    CvPoint2D32f[] corners;
                    int count;
                    CvEx.InitCvMat(ref gray, imageMat, MatrixType.U8C1);
                    imageMat.CvtColor(gray, ColorConversion.RgbToGray);
                    if (gray.FindChessboardCorners(boardSize, out corners, out count, ChessboardFlag.AdaptiveThresh))
                    {
                        CvEx.CloneCvMat(ref displayMat1, imageMat);
                        CvTermCriteria criteria = new CvTermCriteria(50, 0.01);
                        gray.FindCornerSubPix(corners, count, new CvSize(3, 3), new CvSize(-1, -1), criteria);
                        CvPoint3D32f?[] cornerPoints = new CvPoint3D32f?[corners.Length];
                        for (int j = 0; j < corners.Length; j++)
                        {
                            CvPoint2D32f corner = corners[j];
                            double? value = CalcEx.BilateralFilterDepthMatSinglePixel(corner, depthMat, 100, 4, 9);
                            if (value.HasValue)
                            {
                                cornerPoints[j] = new CvPoint3D32f(corner.X, corner.Y, value.Value);
                            }
                        }
                        for (int x = 0; x < cols; x++)
                        {
                            for (int y = 0; y < rows; y++)
                            {
                                if (!cornerPoints[x + y * cols].HasValue)
                                    continue;
                                CvPoint3D32f point1 = cornerPoints[x + y * cols].Value;
                                CvPoint3D64f undistortPoint1 = this.UndistortionData.GetRealFromScreenPos(point1, imageSize);
                                foreach (var offset in new[] { new { X = 1, Y = 0, D = horizLength }, new { X = 0, Y = 1, D = vertLength } })
                                {
                                    int dx = x + offset.X;
                                    int dy = y + offset.Y;
                                    if (dx >= cols || dy >= rows)
                                        continue;
                                    if (!cornerPoints[dx + dy * cols].HasValue)
                                        continue;

                                    CvPoint3D32f point2 = cornerPoints[dx + dy * cols].Value;
                                    CvPoint3D64f undistortPoint2 = this.UndistortionData.GetRealFromScreenPos(point2, imageSize);
                                    double distance = Math.Sqrt(CvEx.GetDistanceSq(undistortPoint1, undistortPoint2));
                                    double scale = distance / offset.D;
                                    CvColor color = CalcEx.HSVtoRGB(Math.Max(0, Math.Min(300, scale * 600 - 450)), scale, 2 - scale);
                                    displayMat4.DrawLine((int)point1.X, (int)point1.Y, (int)point2.X, (int)point2.Y, new CvScalar(color.R, color.G, color.B), 1, LineType.AntiAlias);
                                    pairs.Add(new Tuple<double, double>(distance, offset.D));
                                }
                            }
                        }
                        CvEx.DrawChessboardCornerFrame(displayMat1, boardSize, corners, new CvScalar(64, 128, 64));
                        displayMat1.DrawChessboardCorners(boardSize, corners, true);
                        lastCorners = corners;
                        putImage(displayMat1, PixelFormats.Rgb24);
                    }
                    else
                    {
                        CvEx.CloneCvMat(ref displayMat3, imageMat);
                        putImage(displayMat3, PixelFormats.Rgb24);
                    }
                }

                CvMat displayMat2 = CvEx.InitCvMat(displayMat1);
                displayMat1.Undistort2(displayMat2, this.UndistortionData.CameraStruct.CreateCvMat(), this.UndistortionData.DistortStruct.CreateCvMat(true));
                if (lastCorners != null)
                {
                    drawUndistortedCornerFrame(displayMat2, lastCorners, boardSize);
                }
                displayMat2.PutText(string.Format("Min: {0}", pairs.Min(x => x.Item1 / x.Item2)), new CvPoint(20, 20), new CvFont(FontFace.HersheyPlain, 1, 1), new CvScalar(255, 255, 255));
                displayMat2.PutText(string.Format("Max: {0}", pairs.Max(x => x.Item1 / x.Item2)), new CvPoint(20, 40), new CvFont(FontFace.HersheyPlain, 1, 1), new CvScalar(255, 255, 255));
                displayMat2.PutText(string.Format("Avg: {0}", pairs.Average(x => x.Item1 / x.Item2)), new CvPoint(20, 60), new CvFont(FontFace.HersheyPlain, 1, 1), new CvScalar(255, 255, 255));
                displayMat2.PutText(string.Format("Med: {0}", CalcEx.GetMedian(pairs.Select(x => x.Item1 / x.Item2).ToList())), new CvPoint(20, 80), new CvFont(FontFace.HersheyPlain, 1, 1), new CvScalar(255, 255, 255));
                putImage(displayMat4, PixelFormats.Rgb24);
                displayLabels();
            }

        }
        private Path GenerateSeriesPath(List<Tuple<double, double>> ansv)
        {
            var myPath = new Path
            {
                Height = MyCanvas.Height,
                Width = MyCanvas.Width,
                Stroke = Brushes.Black,
                StrokeThickness = 3
            };

            myPath.MouseLeftButtonUp += (sender, args) =>
            {
                if (Equals((sender as Path).Stroke, Brushes.Black))
                {
                    (sender as Path).Stroke = Brushes.Red;
                    MyActiveLabel.Content = _seriesComments[MyCanvas.Children.IndexOf(sender as Path) - 5];
                }
                else
                {
                    (sender as Path).Stroke = Brushes.Black;
                    MyActiveLabel.Content = "Select plot for further info";
                }
            };

            if (ansv == null) return myPath;
            var segment = new PolyLineSegment();
            double scaleY = MyCanvas.Height / ansv.Max(item => item.Item2);
            double scaleX = MyCanvas.Width / ansv.Max(item => item.Item1);
            for (int i = ansv.Count - 1; i >= 0; i--)
            {
                segment.Points.Add(new Point(ansv[i].Item1 * scaleX, MyCanvas.Height - ansv[i].Item2 * scaleY));
            }
            var fig = new PathFigure();
            fig.Segments.Add(segment);
            fig.StartPoint = segment.Points.First();
            var geom = new PathGeometry();
            geom.Figures.Add(fig);
            myPath.Data = geom;
            return myPath;
        }
Пример #15
0
        private void SetSlider(RegionValueCollection regionValCol)
        {
            SliderGrd.Visibility = System.Windows.Visibility.Visible;
            ClearSlider();
            if (regionValCol == null || regionValCol.Count == 0)
                return;
            if (_isShare)
                PageSlider.IsEnabled = true;
            else
                PageSlider.IsEnabled = false;

            SetUnitLabel(regionValCol.Product, _isValue);
            SetCategoryNameLabel((regionValCol.Polygons == Polygons.Provinces) ? SanofiRegionTypes.Province : SanofiRegionTypes.Tehran);

            List<double> qtys = new List<double>();
            foreach (RegionData rv in regionValCol)
                qtys.Add(rv.Get(_isValue));
            double maximum = qtys.Max();

            double secondMaximum = 0;
            _totalRegionsValue = 0;
            foreach (double i in qtys)
            {
                _totalRegionsValue += i;
                if (i < maximum && i > secondMaximum)
                    secondMaximum = i;
            }
            PageSlider.Maximum = secondMaximum;
            PageSlider.Value = secondMaximum;
            _currentMaxRegionValue = secondMaximum;

            List<double> translateTransforms = new List<double>();
            foreach (RegionData rv in regionValCol)
            {
                if (rv.Get(_isValue) == maximum)
                {
                    SetMaximumText(rv);
                    continue;
                }
                translateTransforms = AddLabelToSlider(rv, translateTransforms);
            }
        }
Пример #16
0
        private static void CalculateMaxAndMinZValueFromAllSeries(ref List<DataSeries> seriesList, out Double minimumZVal, out Double maximumZVal)
        {
            List<Double> minValues = new List<double>();
            List<Double> maxValues = new List<double>();
            
            minimumZVal = 0;
            maximumZVal = 1;

            foreach (DataSeries series in seriesList)
            {
                if (series.Enabled == false)
                    continue;
                
                CalculateMaxAndMinZValue(series, out minimumZVal, out maximumZVal);
                minValues.Add(minimumZVal);
                maxValues.Add(maximumZVal);
            }

            if (minValues.Count > 0)
                minimumZVal = minValues.Min();

            if (maxValues.Count > 0)
                maximumZVal = maxValues.Max();
        }
        /// <summary>
        ///  Make a move on the board
        /// </summary>
        /// <param name="board"></param>
        /// <param name="player"></param>
        /// <returns></returns>
        private Tuple<int, int[]> mmMove(TTTBoard board, Player player)
        {
            if ((int)board.CheckWin() == 1)
            {
                return new Tuple<int, int[]>(Score(board.CheckWin()), new int[] { -1, -1 });
            }
            else if ((board.GetEmptySquares()).Count == (board.Dim * board.Dim))
            {
                return new Tuple<int, int[]>(0, new int[] { rnd.Next(board.Dim), rnd.Next(board.Dim) });
            }
            else if (board.GetEmptySquares().Count == 0)
            {
                return new Tuple<int, int[]>(Score(board.CheckWin()), new int[] { -1, -1 });
            }

            List<int> listScore = new List<int>();
            List<int[]> listMove = new List<int[]>();
            Player newPlayer = player == Player.PLAYERO ? Player.PLAYERX : Player.PLAYERO;

            List<int[]> moves = board.GetEmptySquares();
            foreach (int[] move in moves)
            {
                TTTBoard newBoard = board.Clone();
                newBoard.Move(move[0], move[1], player);

                int newScore = mmMove(newBoard, newPlayer).Item1;
                listScore.Add(newScore);
                listMove.Add(move);

                if (player == Player.PLAYERX && newScore == 1) break;
                else if (player == Player.PLAYERO && newScore == -1) break;
            }
            int[] moveNew;
            int newScoreNew;
            if (player == Player.PLAYERX)
            {
                newScoreNew = listScore.Max();
                moveNew = listMove[listScore.IndexOf(newScoreNew)];
            }
            else
            {
                newScoreNew = listScore.Min();
                moveNew = listMove[listScore.IndexOf(newScoreNew)];
            }
            return new Tuple<int, int[]>(newScoreNew, moveNew);
        }
Пример #18
0
        private PointCollection GetPointsFromY(List<double> positions, List<double> yList, double canvasHeight, double canvasWidth)
        {
            var points = new List<Point>(yList.Count);
            double heightScale = canvasHeight / yList.Max();
            double widthScale = canvasWidth / positions.Max();

            points.Add(new Point(0, canvasHeight));
            for (int i = 0; i < yList.Count; i++)
            {
                points.Add(new Point(positions[i] * widthScale, canvasHeight - yList[i] * heightScale));
            }
            return new PointCollection(points);
        }
Пример #19
0
        //(公共方法)计算指数积、指数和、奖金的方法
        private void CountOdds()
        {
            double SumMinOdds = 0.00;//指数和 最小
            double SumMaxOdds = 0.00;//指数和 最大

            double ProductMinOdds = 1.00;//指数积 最小
            double ProductMaxOdds = 1.00;//指数积 最大

            List<double> DoubleList = new List<double>();

            var selfcols = this.DataGrid1.Columns[3];

            foreach (var item in DataGrid1.ItemsSource)
            {
                //--对象所在的单元格
                var cells = selfcols.GetCellContent(item);
                if (cells != null)
                {
                    //--单元格所包含的元素
                    Grid grid = cells as Grid;
                    foreach (Button button1 in grid.Children)
                    {
                        SolidColorBrush b_Brush1 = (SolidColorBrush)(button1.Background);

                        if (b_Brush1.Color.ToString() == "#FFFF0000")
                        {
                            DoubleList.Add(Netball.RetuntDouble(ToolTipService.GetToolTip(button1).ToString()));
                        }
                    }

                    SumMinOdds += DoubleList.Min();
                    SumMaxOdds += DoubleList.Max();

                    ProductMinOdds *= DoubleList.Min();
                    ProductMaxOdds *= DoubleList.Max();
                }
                DoubleList.Clear();
            }

            this.tbSum.Text = string.Format("{0:f2}", SumMinOdds) + "~" + string.Format("{0:f2}", SumMaxOdds);
            this.tbProduct.Text = string.Format("{0:f2}", ProductMinOdds) + "~" + string.Format("{0:f2}", ProductMaxOdds);
            this.tbPremium.Text = string.Format("{0:f2}", ProductMinOdds * 2) + "~" + string.Format("{0:f2}", ProductMaxOdds * 2);
        }
Пример #20
0
        private void resultPainter(List<List<double>> paramList, List<List<double>> diffList)
        {
            if (paramList.Count < 3 || GetAxisItems == null)
            {
                return;
            }
            List<double> positions = paramList[0];
            List<double> rayleighYList = paramList[1];
            List<double> iterationYList = paramList[2];
            List<double> absoluteDiffList = diffList[0];
            List<double> relativeDiffList = diffList[1];

            resultCanvas.Children.Clear();
            Brush fillBlue = (Brush)FindResource("ResultLineGradientBlue");
            Brush fillRed = (Brush)FindResource("ResultLineGradientRed");
            double height = resultCanvas.ActualHeight;
            double width = resultCanvas.ActualWidth;
            double axisGap = 18;

            Polyline rayleighLine = polylineGenerator(positions, rayleighYList, new Size(width - axisGap, height - axisGap));
            rayleighLine.Stroke = fillBlue;
            Polyline iterationLine = polylineGenerator(positions, iterationYList, new Size(width - axisGap, height - axisGap));
            iterationLine.Stroke = fillRed;
            List<AxisItem> xAxisItems = new List<AxisItem>();
            List<AxisItem> yAxisItems = new List<AxisItem>();
            Polyline xAxis = new Polyline();
            Polyline yAxis = new Polyline();
            xAxis.Points.Add(new Point(0, height - axisGap));
            xAxis.Points.Add(new Point(width, height - axisGap));
            xAxis.Stroke = new SolidColorBrush(Colors.Black);
            yAxis.Points.Add(new Point(axisGap, 0));
            yAxis.Points.Add(new Point(axisGap, height));
            yAxis.Stroke = new SolidColorBrush(Colors.Black);
            TextBlock yHeader = new TextBlock();
            TextBlock xAxisHeader = new TextBlock();
            xAxisHeader.FontSize = 12;
            TextBlock yAxisHeader = new TextBlock();
            yAxisHeader.FontSize = 12;
            TextBlock rayleighLegendHeader = new TextBlock();
            Line rayleighLegend = new Line();
            rayleighLegend.Stroke = fillBlue;
            TextBlock iterationLegendHeader = new TextBlock();
            Line iterationLegend = new Line();
            iterationLegend.Stroke = fillRed;

            Canvas.SetLeft(yHeader, width * 0.382);
            Canvas.SetLeft(rayleighLine, axisGap);
            Canvas.SetLeft(iterationLine, axisGap);
            Canvas.SetBottom(xAxisHeader, axisGap + 3);
            Canvas.SetRight(xAxisHeader, 0);
            Canvas.SetTop(yAxisHeader, -axisGap);

            Canvas.SetLeft(rayleighLegendHeader, axisGap + 10);
            Canvas.SetTop(iterationLegendHeader, 20);
            Canvas.SetLeft(iterationLegendHeader, axisGap + 10);

            yHeader.Text = "雷利法与迭代法振型";
            xAxisHeader.Text = "Position(m)";
            yAxisHeader.Text = "Y(1)";
            rayleighLegendHeader.Text = "雷利法";
            iterationLegendHeader.Text = "振型迭代法";
            rayleighLegend.X1 = axisGap + 10;
            rayleighLegend.X2 = axisGap + 70;
            rayleighLegend.Y1 = 18;
            rayleighLegend.Y2 = 18;
            iterationLegend.X1 = axisGap + 10;
            iterationLegend.X2 = axisGap + 70;
            iterationLegend.Y1 = 38;
            iterationLegend.Y2 = 38;

            xAxisItems = GetAxisItems(positions, AxisType.X, new Point(axisGap, height - axisGap), width - axisGap, showMin:false);
            yAxisItems = GetAxisItems(iterationYList, AxisType.Y, new Point(axisGap, height - axisGap), height - axisGap);

            resultCanvas.Children.Add(xAxis);
            resultCanvas.Children.Add(yAxis);
            resultCanvas.Children.Add(xAxisHeader);
            resultCanvas.Children.Add(yAxisHeader);
            resultCanvas.Children.Add(yHeader);
            resultCanvas.Children.Add(rayleighLine);
            resultCanvas.Children.Add(iterationLine);
            resultCanvas.Children.Add(rayleighLegendHeader);
            resultCanvas.Children.Add(iterationLegendHeader);
            resultCanvas.Children.Add(rayleighLegend);
            resultCanvas.Children.Add(iterationLegend);
            foreach (var item in xAxisItems)
            {
                resultCanvas.Children.Add(item.Label);
                resultCanvas.Children.Add(item.Mark);
            }
            foreach (var item in yAxisItems)
            {
                resultCanvas.Children.Add(item.Label);
                resultCanvas.Children.Add(item.Mark);
            }

            //Compare Result
            resultCompareCanvas.Children.Clear();
            height = resultCompareCanvas.ActualHeight;
            width = resultCompareCanvas.ActualWidth;
            double absoluteMax = absoluteDiffList.Max(e => Math.Abs(e));
            double relativeMax = relativeDiffList.Max(e => Math.Abs(e));
            double absoluteRange = 0;
            double relativeRange = 0;
            List<double> yCompAxisList = new List<double>();

            if (absoluteMax > relativeMax)
            {
                absoluteRange = height - axisGap;
                relativeRange = (height - axisGap) * (relativeMax / absoluteMax);
                yCompAxisList = absoluteDiffList.Select(e => e * 100).ToList();
            }
            else
            {
                absoluteRange = (height - axisGap) * (absoluteMax / relativeMax);
                relativeRange = height - axisGap;
                yCompAxisList = relativeDiffList.Select(e => e * 100).ToList();
            }
            Polyline absoluteLine = polylineGenerator(
                positions,
                absoluteDiffList.Select(e => Math.Abs(e)).ToList(),
                new Size(width - axisGap, absoluteRange)
            );
            absoluteLine.Stroke = fillBlue;
            Polyline relativeLine = polylineGenerator(positions,
                relativeDiffList.Select(e => Math.Abs(e)).ToList(),
                new Size(width - axisGap, relativeRange)
            );
            relativeLine.Stroke = fillRed;
            List<AxisItem> xCompAxisItems = new List<AxisItem>();
            List<AxisItem> yCompAxisItems = new List<AxisItem>();

            Polyline xCompAxis = new Polyline();
            Polyline yCompAxis = new Polyline();
            xCompAxis.Points.Add(new Point(0, height - axisGap));
            xCompAxis.Points.Add(new Point(width, height - axisGap));
            xCompAxis.Stroke = new SolidColorBrush(Colors.Black);
            yCompAxis.Points.Add(new Point(axisGap, 0));
            yCompAxis.Points.Add(new Point(axisGap, height));
            yCompAxis.Stroke = new SolidColorBrush(Colors.Black);
            TextBlock yCompHeader = new TextBlock();
            TextBlock xCompAxisHeader = new TextBlock();
            xCompAxisHeader.FontSize = 12;
            TextBlock yCompAxisHeader = new TextBlock();
            yCompAxisHeader.FontSize = 12;
            TextBlock absoluteLegendHeader = new TextBlock();
            Line absoluteLegend = new Line();
            absoluteLegend.Stroke = fillBlue;
            TextBlock relativeLegendHeader = new TextBlock();
            Line relativeLegend = new Line();
            relativeLegend.Stroke = fillRed;

            Canvas.SetLeft(absoluteLine, axisGap);
            Canvas.SetBottom(absoluteLine, axisGap);
            Canvas.SetLeft(relativeLine, axisGap);
            Canvas.SetBottom(relativeLine, axisGap);
            Canvas.SetLeft(yCompHeader, width * 0.382);
            Canvas.SetBottom(xCompAxisHeader, axisGap + 3);
            Canvas.SetRight(xCompAxisHeader, 0);
            Canvas.SetTop(yCompAxisHeader, -axisGap);

            Canvas.SetLeft(absoluteLegendHeader, axisGap + 10);
            Canvas.SetTop(relativeLegendHeader, 20);
            Canvas.SetLeft(relativeLegendHeader, axisGap + 10);

            yCompHeader.Text = "振型绝对与相对差值";
            xCompAxisHeader.Text = "Position(m)";
            yCompAxisHeader.Text = "差值(%)";
            absoluteLegendHeader.Text = "绝对差值";
            relativeLegendHeader.Text = "相对差值";
            absoluteLegend.X1 = axisGap + 10;
            absoluteLegend.X2 = axisGap + 70;
            absoluteLegend.Y1 = 18;
            absoluteLegend.Y2 = 18;
            relativeLegend.X1 = axisGap + 10;
            relativeLegend.X2 = axisGap + 70;
            relativeLegend.Y1 = 38;
            relativeLegend.Y2 = 38;

            xCompAxisItems = GetAxisItems(positions, AxisType.X, new Point(axisGap, height - axisGap), width - axisGap, showMin:false);
            if (yCompAxisList.Max() != 0)
            {
                yCompAxisItems = GetAxisItems(yCompAxisList, AxisType.Y, new Point(axisGap, height - axisGap), height - axisGap, showMax: false);
            }
            resultCompareCanvas.Children.Add(xCompAxis);
            resultCompareCanvas.Children.Add(yCompAxis);
            resultCompareCanvas.Children.Add(xCompAxisHeader);
            resultCompareCanvas.Children.Add(yCompAxisHeader);
            resultCompareCanvas.Children.Add(yCompHeader);
            resultCompareCanvas.Children.Add(absoluteLine);
            resultCompareCanvas.Children.Add(relativeLine);
            resultCompareCanvas.Children.Add(absoluteLegendHeader);
            resultCompareCanvas.Children.Add(relativeLegendHeader);
            resultCompareCanvas.Children.Add(absoluteLegend);
            resultCompareCanvas.Children.Add(relativeLegend);
            foreach (var item in xCompAxisItems)
            {
                resultCompareCanvas.Children.Add(item.Label);
                resultCompareCanvas.Children.Add(item.Mark);
            }
            foreach (var item in yCompAxisItems)
            {
                resultCompareCanvas.Children.Add(item.Label);
                resultCompareCanvas.Children.Add(item.Mark);
            }
        }
Пример #21
0
		public static Tuple<DesignItem, Rect> WrapItemsNewContainer(IEnumerable<DesignItem> items, Type containerType, bool doInsert = true)
		{
			var collection = items;
			
			var _context = collection.First().Context as XamlDesignContext;
			
			var container = collection.First().Parent;
			
			if (collection.Any(x => x.Parent != container))
				return null;

			//Change Code to use the Placment Operation!
			var placement = container.Extensions.OfType<IPlacementBehavior>().FirstOrDefault();
			if (placement == null)
				return null;

			var operation = PlacementOperation.Start(items.ToList(), PlacementType.Move);

			var newInstance = _context.Services.ExtensionManager.CreateInstanceWithCustomInstanceFactory(containerType, null);
			DesignItem newPanel = _context.Services.Component.RegisterComponentForDesigner(newInstance);
			
			List<ItemPos> itemList = new List<ItemPos>();
			
			foreach (var item in collection) {
				itemList.Add(GetItemPos(operation, item));
				//var pos = placement.GetPosition(null, item);
				if (container.Component is Canvas) {
					item.Properties.GetAttachedProperty(Canvas.RightProperty).Reset();
					item.Properties.GetAttachedProperty(Canvas.LeftProperty).Reset();
					item.Properties.GetAttachedProperty(Canvas.TopProperty).Reset();
					item.Properties.GetAttachedProperty(Canvas.BottomProperty).Reset();
				} else if (container.Component is Grid) {
					item.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).Reset();
					item.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).Reset();
					item.Properties.GetProperty(FrameworkElement.MarginProperty).Reset();
				}
				
				var parCol = item.ParentProperty.CollectionElements;
				parCol.Remove(item);
			}
			
			var xmin = itemList.Min(x => x.Xmin);
			var xmax = itemList.Max(x => x.Xmax);
			var ymin = itemList.Min(x => x.Ymin);
			var ymax = itemList.Max(x => x.Ymax);

			foreach (var item in itemList) {
				if (newPanel.Component is Canvas) {
					if (item.HorizontalAlignment == HorizontalAlignment.Right) {
						item.DesignItem.Properties.GetAttachedProperty(Canvas.RightProperty).SetValue(xmax - item.Xmax);
					} else {
						item.DesignItem.Properties.GetAttachedProperty(Canvas.LeftProperty).SetValue(item.Xmin - xmin);
					}
					
					if (item.VerticalAlignment == VerticalAlignment.Bottom) {
						item.DesignItem.Properties.GetAttachedProperty(Canvas.BottomProperty).SetValue(ymax - item.Ymax);
					} else {
						item.DesignItem.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(item.Ymin - ymin);
					}

					newPanel.ContentProperty.CollectionElements.Add(item.DesignItem);

				} else if (newPanel.Component is Grid) {
					Thickness thickness = new Thickness(0);
					if (item.HorizontalAlignment == HorizontalAlignment.Right) {
						item.DesignItem.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).SetValue(HorizontalAlignment.Right);
						thickness.Right = xmax - item.Xmax;
					} else {
						item.DesignItem.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).SetValue(HorizontalAlignment.Left);
						thickness.Left = item.Xmin - xmin;
					}
					
					if (item.VerticalAlignment == VerticalAlignment.Bottom) {
						item.DesignItem.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).SetValue(VerticalAlignment.Bottom);
						thickness.Bottom = ymax - item.Ymax;
					} else {
						item.DesignItem.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).SetValue(VerticalAlignment.Top);
						thickness.Top = item.Ymin - ymin;
					}
					
					item.DesignItem.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(thickness);

					newPanel.ContentProperty.CollectionElements.Add(item.DesignItem);

				} else if (newPanel.Component is Viewbox) {
					newPanel.ContentProperty.SetValue(item.DesignItem);
				}
			}

			if (doInsert)
			{
				PlacementOperation operation2 = PlacementOperation.TryStartInsertNewComponents(
					container,
					new[] {newPanel},
					new[] {new Rect(xmin, ymin, xmax - xmin, ymax - ymin).Round()},
					PlacementType.AddItem
				);

				operation2.Commit();

				_context.Services.Selection.SetSelectedComponents(new[] {newPanel});
			}

			operation.Commit();

			return new Tuple<DesignItem, Rect>(newPanel, new Rect(xmin, ymin, xmax - xmin, ymax - ymin).Round());
		}
        private void CalculateBoundaries(List<SilverlightEdge> edges)
        {
            MaxX = edges.Max(x => x.Position.X);
            MinX = edges.Min(x => x.Position.X);
            LengthX = MaxX - MinX;
            MaxY = edges.Max(x => x.Position.Y);
            MinY = edges.Min(x => x.Position.Y);
            LengthY = MaxY-MinY;

            CenterPoint = new Point((MinX + MaxX) / 2, (MaxY + MinY) / 2);
        }
Пример #23
0
        private static string GetJsonPretty(string original)
        {
            #region -- Clear Break Line --
            original = original.Replace("\r\n", "");
            #endregion

            int index = 0;
            bool isContinue = true;

            #region -- Pair --
            Regex regex = new Regex("\"[a-zA-Z0-9]+\":");
            MatchCollection tmp = regex.Matches(original, 0);

            do
            {
                Match result = regex.Match(original, index);

                if (result.Success)
                {
                    int signIndex = original.IndexOf(':', result.Index);

                    // 冒號 & 換行
                    original = original.Insert(signIndex + 1, " ")
                                       .Insert(result.Index, Environment.NewLine);

                    index = result.Index + result.Index + result.Length;
                }
                else
                {
                    isContinue = false;
                }
            } while (isContinue);
            #endregion

            #region -- Break Line at { } ] --
            index = 1;
            isContinue = true;

            do
            {
                int result = original.IndexOfAny(new char[] { '{', '}', ']' }, index);

                if (result > 0)
                {
                    original = original.Insert(result, Environment.NewLine);

                    index += result + 3;
                }
                else
                {
                    isContinue = !isContinue;
                }
            } while (isContinue);
            #endregion

            #region -- Add Spaces --
            List<int> tabArr = new List<int>();

            string[] linesOriginal = original.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

            index = 0;
            int tabFlag = 0;
            bool inPhrase = false;
            bool endPhrase = false;
            int endIndex = linesOriginal.Length - 1;

            foreach (string line in linesOriginal)
            {
                if (line[0] == '{')
                {
                    tabFlag += 1;
                    inPhrase = true;
                }
                else if (line[0] == '}')
                {
                    tabFlag = 1;
                    inPhrase = false;
                    endPhrase = true;
                }

                tabArr.Add(tabFlag);

                if (inPhrase)
                {
                    tabFlag += 1;
                    inPhrase = false;
                }
                if (endPhrase)
                {
                    tabFlag -= 1;
                    endPhrase = false;
                }

                ++index;
            }

            if (linesOriginal[0][0] == '{')
            {
                tabArr = (from item in tabArr
                          select item - 1).ToList();
            }

            int tabMax = tabArr.Max() + 1;
            Dictionary<int, string> tabSpaceMap = new Dictionary<int, string>();
            for (int i = 0; i < tabMax; ++i)
            {
                tabSpaceMap.Add(i, GetTabSpace(i));
            }

            index = 0;
            foreach (string line in linesOriginal)
            {
                linesOriginal[index] = tabSpaceMap[tabArr[index]] + linesOriginal[index];

                ++index;
            }

            original = string.Join(Environment.NewLine, linesOriginal);
            #endregion

            return "";
        }
Пример #24
0
 void SetYAxisRange() {
   var points = new List<double>();
   StudyModels.ToList().ForEach( x => {
     points.AddRange( x.PointModels.Select( y => y.YAxisValue ) );
   } );
   YAxisMaxValue = points.Max();
   YAxisMinValue = points.Min();
 }
        private void FrmChild_PassDataBetweenForm(object sender, PassDataWinFormEventArgs e)
        {
            this.Dispatcher.Invoke(new Action(delegate {
                if (e.message == "文件读取成功")
                { Finished_File--; }

                win.FrontPage.Text += "\n" + e.Filename;
                win.FrontPage.Text += "文件状态:";
                win.FrontPage.Text += e.message;

                //结束读取数据后,将所有时间汇总,并统计到文件中^_^
                if (Finished_File == 0) {
                    win.Hide(); win.FrontPage.Text = "";
                    this.IsEnabled = true;
                    List<DateTime> All_File_Date = new List<DateTime>();
                    for (int i=0; i<Files.Count(); i++)
                    {
                        foreach(var date in Files[i].All_Date)
                        All_File_Date.Add(date);
                    }
                    start_time_calender.DisplayDateStart = All_File_Date.Min();
                    end_time_calender.DisplayDateStart = All_File_Date.Min();
                    start_time_calender.DisplayDateEnd = All_File_Date.Max();
                    end_time_calender.DisplayDateEnd = All_File_Date.Max();
                    start_time_calender.SelectedDate = All_File_Date.Min();
                    end_time_calender.SelectedDate = All_File_Date.Max();
                    output.IsEnabled = true;
                }
                win.scroll.ScrollToEnd();
            }));
        }
Пример #26
0
        private void GenerateButton_Click(object sender, RoutedEventArgs e)
        {
            var varList = varTextRichTextBox.Text.Split('\n');

            string cmd = templateTextRichTextBox.Text;
            string finalResult = string.Empty;
            List<string> properties = new List<string>();

            string text = inputRichTextBox1.Text;
            using (StringReader reader = new StringReader(text))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    properties.Add(line);
                }
            }

            var ls = new List<string[]>();
            ls.Add(inputRichTextBox1.Text.Split('\n'));
            ls.Add(inputRichTextBox2.Text.Split('\n'));
            ls.Add(inputRichTextBox3.Text.Split('\n'));
            ls.Add(inputRichTextBox4.Text.Split('\n'));
            ls.Add(inputRichTextBox5.Text.Split('\n'));

            var max = ls.Max(c => c.Length);
            ls = ProcessInput(ls, max);
            for (int i = 0; i < max; i++)
            {
                var result = cmd;
                for (int j = 0; j < ls.Count; j++)
                {
                    var input = ls[j];
                    var prop = input[i].Trim();
                    if (j == 0)
                    {
                        result = result.Replace("$A$", ProcessKey("$A$", prop));
                        result = result.Replace("$aA$", ProcessKey("$aA$", prop));
                        result = result.Replace("$_aA$", ProcessKey("$_aA$", prop));
                        result = result.Replace("$a_a$", ProcessKey("$a_a$", prop));
                        result = result.Replace("$A_A$", ProcessKey("$A_A$", prop));
                        result = result.Replace("$AA$", ProcessKey("$AA$", prop));
                        result = result.Replace("$aa$", ProcessKey("$aa$", prop));
                        result = result.Replace("$a$", ProcessKey("$a$", prop));
                        result = result.Replace("$as$", ProcessKey("$as$", prop));
                    }
                    if (j == 1)
                    {

                        result = result.Replace("$B$", ProcessKey("$B$", prop));
                        result = result.Replace("$bB$", ProcessKey("$bB$", prop));
                        result = result.Replace("$_bB$", ProcessKey("$_bB$", prop));
                        result = result.Replace("$b_b$", ProcessKey("$b_b$", prop));
                        result = result.Replace("$B_B$", ProcessKey("$B_B$", prop));
                        result = result.Replace("$BB$", ProcessKey("$BB$", prop));
                        result = result.Replace("$bb$", ProcessKey("$bb$", prop));
                        result = result.Replace("$b$", ProcessKey("$b$", prop));
                        result = result.Replace("$bs$", ProcessKey("$bs$", prop));
                    }
                    if (j == 2)
                    {
                        result = result.Replace("$C$", ProcessKey("$C$", prop));
                        result = result.Replace("$cC$", ProcessKey("$cC$", prop));
                        result = result.Replace("$_cC$", ProcessKey("$_cC$", prop));
                        result = result.Replace("$c_c$", ProcessKey("$c_c$", prop));
                        result = result.Replace("$C_C$", ProcessKey("$C_C$", prop));
                        result = result.Replace("$CC$", ProcessKey("$CC$", prop));
                        result = result.Replace("$cc$", ProcessKey("$cc$", prop));
                        result = result.Replace("$c$", ProcessKey("$c$", prop));
                        result = result.Replace("$cs$", ProcessKey("$cs$", prop));
                    }
                    if (j == 3)
                    {
                        result = result.Replace("$D$", ProcessKey("$D$", prop));
                        result = result.Replace("$dD$", ProcessKey("$dD$", prop));
                        result = result.Replace("$_dD$", ProcessKey("$_dD$", prop));
                        result = result.Replace("$d_d$", ProcessKey("$d_d$", prop));
                        result = result.Replace("$D_D$", ProcessKey("$D_D$", prop));
                        result = result.Replace("$DD$", ProcessKey("$DD$", prop));
                        result = result.Replace("$dd$", ProcessKey("$dd$", prop));
                        result = result.Replace("$d$", ProcessKey("$d$", prop));
                        result = result.Replace("$ds$", ProcessKey("$ds$", prop));
                    }
                    if (j == 4)
                    {
                        result = result.Replace("$E$", ProcessKey("$E$", prop));
                        result = result.Replace("$eE$", ProcessKey("$eE$", prop));
                        result = result.Replace("$_eE$", ProcessKey("$_eE$", prop));
                        result = result.Replace("$e_e$", ProcessKey("$e_e$", prop));
                        result = result.Replace("$E_E$", ProcessKey("$E_E$", prop));
                        result = result.Replace("$EE$", ProcessKey("$EE$", prop));
                        result = result.Replace("$ee$", ProcessKey("$ee$", prop));
                        result = result.Replace("$e$", ProcessKey("$e$", prop));
                        result = result.Replace("$es$", ProcessKey("$es$", prop));

                    }
                }

                for (int k = 0; k < varList.Length; k++)
                {
                    var v = varList[k].Trim();

                    result = result.Replace("$" + (k + 1), v);

                    int iv;
                    if (Int32.TryParse(v, out iv))
                    {
                        varList[k] = (iv + 1) + "";
                    }
                }

                finalResult += result + Environment.NewLine;
            }
            outputRichTextBox.Clear();
            outputRichTextBox.AppendText(finalResult);

            try
            {
                Clipboard.SetText(finalResult);
            }
            catch { }
        }
Пример #27
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //LUCAS
            try
            {
                Random rand = new Random(42);
                List<int> numbers = new List<int>();
                ListDisjointSet<int> disjointSet;
                disjointSet = new ListDisjointSet<int>();

                Stopwatch iterationTimer = new Stopwatch();
                List<long> ticksList = new List<long>();
                for (int i = 0; i < 10000; i++)
                {
                    int n = rand.Next();
                    numbers.Add(n);
                    iterationTimer.Start();
                    disjointSet.MakeSet(n);
                    iterationTimer.Stop();
                    ticksList.Add(iterationTimer.ElapsedTicks);
                    iterationTimer.Reset();
                }
                mksetOne.Text = String.Format("Avg : {0}, Max: {1}, Min: {2}", ticksList.Average(), ticksList.Max(), ticksList.Min());
                ticksList.Clear();

                for (int i = 0; i < numbers.Count * 3; i++)
                {
                    int lookup = numbers[rand.Next(numbers.Count)];
                    iterationTimer.Start();
                    disjointSet.Find(lookup);
                    iterationTimer.Stop();
                    ticksList.Add(iterationTimer.ElapsedTicks);
                    iterationTimer.Reset();
                }
                findOne.Text = String.Format("Avg : {0}, Max: {1}, Min: {2}", ticksList.Average(), ticksList.Max(), ticksList.Min());
                ticksList.Clear();

                for (int i = 0; i < numbers.Count * 3; i++)
                {
                    int lookupA = numbers[rand.Next(numbers.Count)];
                    int lookupB = numbers[rand.Next(numbers.Count)];
                    iterationTimer.Start();
                    disjointSet.Union(disjointSet.Find(lookupA), disjointSet.Find(lookupB));
                    iterationTimer.Stop();
                    ticksList.Add(iterationTimer.ElapsedTicks);
                    iterationTimer.Reset();
                }
                unionOne.Text = String.Format("Avg : {0}, Max: {1}, Min: {2}", ticksList.Average(), ticksList.Max(), ticksList.Min());
            }
            catch (Exception err)
            {
                Console.WriteLine(err.StackTrace);
            }

            //PAUL
            try
            {
                Random rand = new Random(42);
                List<int> numbers = new List<int>();
                DisjointDataSet<int> disjointSet;
                disjointSet = new DisjointDataSet<int>();

                Stopwatch iterationTimer = new Stopwatch();
                List<long> ticksList = new List<long>();
                for (int i = 0; i < 10000; i++)
                {
                    int n = rand.Next();
                    numbers.Add(n);
                    iterationTimer.Start();
                    disjointSet.MakeSet(n);
                    iterationTimer.Stop();
                    ticksList.Add(iterationTimer.ElapsedTicks);
                    iterationTimer.Reset();
                }
                mksetTwo.Text = String.Format("Avg : {0}, Max: {1}, Min: {2}", ticksList.Average(), ticksList.Max(), ticksList.Min());
                ticksList.Clear();

                for (int i = 0; i < numbers.Count * 3; i++)
                {
                    int lookup = numbers[rand.Next(numbers.Count)];
                    iterationTimer.Start();
                    disjointSet.Find(lookup);
                    iterationTimer.Stop();
                    ticksList.Add(iterationTimer.ElapsedTicks);
                    iterationTimer.Reset();
                }
                findTwo.Text = String.Format("Avg : {0}, Max: {1}, Min: {2}", ticksList.Average(), ticksList.Max(), ticksList.Min());
                ticksList.Clear();

                for (int i = 0; i < numbers.Count * 3; i++)
                {
                    int lookupA = numbers[rand.Next(numbers.Count)];
                    int lookupB = numbers[rand.Next(numbers.Count)];
                    iterationTimer.Start();
                    disjointSet.Union(lookupA, lookupB);
                    iterationTimer.Stop();
                    ticksList.Add(iterationTimer.ElapsedTicks);
                    iterationTimer.Reset();
                }
                unionTwo.Text = String.Format("Avg : {0}, Max: {1}, Min: {2}", ticksList.Average(), ticksList.Max(), ticksList.Min());
            }
            catch (Exception err)
            {
                Console.WriteLine(err.StackTrace);
            }
        }
Пример #28
0
        internal void ResetTable(List<DataRecords.RawDataRow> dt, bool _firstLineIsHeader)
        {
            dtTMP = dt;
            // get the number of columns to display
            //int maxCols = 0;
            firstLineIsHeader = _firstLineIsHeader;
            /*foreach (RawDataRow r in dt)
            {
                int ct = r.dataItems.Count;
                
                maxCols = Math.Max(ct, maxCols);
            }*/

            var counter = dt.Max(x => x.dataItems.Count());

            columnNames = new Dictionary<string, int>();

            RawDataRow rdr = dt[0];
            List<string> newBMFieldList = new List<string>();

            foreach (ColumnMetaInfo ss in bmRequiredFields)
            {
                newBMFieldList.Add(ss.columnName);
            }
            foreach (ColumnMetaInfo ss in bmOptionalFields)
            {
                newBMFieldList.Add(ss.columnName);
            }


            for (int i = 0; i < counter; i++)
            {
                bool errorinColumn = false;
                var col1 = new DataGridTextColumn();

                ComboBox dropDown = new ComboBox();
                dropDown.Width = 80;
                dropDown.HorizontalAlignment = HorizontalAlignment.Stretch;
                List<string> cli = new List<string>();
                cli.Add(rdr.dataItems[i]);
                cli.Add("");
                List<string> fields = new List<string>();
                fields = newBMFieldList;
                // add in the optional fields
                foreach (string req in fields)
                {
                    cli.Add("->" + req + " (" + rdr.dataItems[i] + ")");
                }

                try
                {
                    columnNames.Add(rdr.dataItems[i], i);
                }
                catch (Exception ex)
                {
                    if (ex is ArgumentException) //i.e. column names are probably not unique, drop out with a more useful error message
                    {
                        MessageBox.Show(String.Format("Column {0}, \"{1}\" in file: {2} is a duplicate, please ensure all column headings are unique, removing column for import", i, rdr.dataItems[i],
                            ((XODB.Import.Client.MainWindow)(((System.Delegate)(this.ColumnsMapped)).Target)).SelectedFile));
                        errorinColumn = true;
                    }
                }

                if (!errorinColumn)
                {
                    dropDown.SelectionChanged += new SelectionChangedEventHandler(dropDown_SelectionChanged);
                    dropDown.ItemsSource = cli;
                    dropDown.SelectedValue = "";

                    col1.Header = dropDown;

                    col1.Binding = new Binding("dataItems[" + i + "]");
                    PreviewGrid.Columns.Add(col1);
                }
            }

            PreviewGrid.ItemsSource = dt;
            isFileLoaded = true;
        }
Пример #29
0
        public void Plot(double a, double b, double step, string function)
        {
            this.Plotter.Children.Clear();
            this.Plotter.Children.Add(this.xAxis);
            this.Plotter.Children.Add(this.yAxis);

            int aInt = (int)a;
            int bInt = (int)b;
            int stepInt = (int)step;

            double min = 0;
            double max = 0;
            List<double> fxDouble = new List<double>();

            if (function.Equals(availablePlots.Plot_Sen.ToString()))
            {
                double xAmplifier = 250 * step;

                for (double i = a; i <= b; i += step)
                {
                    Ellipse e = new Ellipse();
                    e.Height = 5;
                    e.Width = 5;
                    e.Fill = Brushes.Red;

                    Canvas.SetBottom(e, 300 + 300 * Math.Sin(i));
                    Canvas.SetLeft(e, 300 + xAmplifier * i);

                    this.Plotter.Children.Add(e);
                }
            }
            else if (function.Equals(availablePlots.Plot_Cos.ToString()))
            {
                double xAmplifier = 250 * step;

                for (double i = a; i <= b; i += step)
                {
                    Ellipse e = new Ellipse();
                    e.Height = 5;
                    e.Width = 5;
                    e.Fill = Brushes.Red;

                    Canvas.SetBottom(e, 300 + 300 * Math.Cos(i));
                    Canvas.SetLeft(e, 300 + xAmplifier * i);

                    this.Plotter.Children.Add(e);
                }
            }
            else if (function.Equals(availablePlots.Plot_Factorial.ToString()))
            {
                fxDouble.Clear();

                for (int i = aInt; i <= bInt; i += stepInt)
                {
                    fxDouble.Add(Herramientas.ComputeFactorial(i));
                }

                min = fxDouble.Min();
                max = fxDouble.Max();

                double xAmplifier = 25 * step;
                double yAmplifier = (300 / Math.Abs(max - min));

                for (int i = aInt; i <= bInt; i += stepInt)
                {
                    Ellipse e = new Ellipse();
                    e.Height = 5;
                    e.Width = 5;
                    e.Fill = Brushes.Red;

                    Canvas.SetBottom(e, 300 + yAmplifier * Herramientas.ComputeFactorial(i));
                    Canvas.SetLeft(e, 300 + xAmplifier * i);

                    this.Plotter.Children.Add(e);
                }
            }
            else if (function.Equals(availablePlots.Plot_Fibonacci.ToString()))
            {
                fxDouble.Clear();

                for (int i = aInt; i <= bInt; i += stepInt)
                {
                    fxDouble.Add(Herramientas.ComputeFactorial(i));
                }

                min = fxDouble.Min();
                max = fxDouble.Max();

                double xAmplifier = 25 * step;
                double yAmplifier = (300 / Math.Abs(max - min));

                for (int i = aInt; i <= bInt; i += stepInt)
                {
                    Ellipse e = new Ellipse();
                    e.Height = 5;
                    e.Width = 5;
                    e.Fill = Brushes.Red;

                    Canvas.SetBottom(e, 300 + yAmplifier * Herramientas.ComputeFibonacci(i));
                    Canvas.SetLeft(e, 300 + xAmplifier * i);

                    this.Plotter.Children.Add(e);
                }
            }

            this.Show();
        }
Пример #30
0
        //比分的小按钮事件
        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // TODO: Add event handler implementation here.

            Button button = sender as Button;
            SolidColorBrush b_Brush = (SolidColorBrush)(button.Background);
            int ColorCount = 0;

            if (b_Brush.Color.ToString() == "#FFFF0000")
            {
                foreach (StackPanel Stack in ((button.Parent as StackPanel).Parent as StackPanel).Children)
                {
                    foreach (Button button2 in Stack.Children)
                    {
                        SolidColorBrush b_Brush2 = (SolidColorBrush)(button2.Background);
                        if (b_Brush2.Color.ToString() == "#FFFF0000")
                        {
                            ColorCount++;
                        }
                    }
                }

                if (ColorCount > 1)
                {
                    button.Background = new SolidColorBrush(Colors.White);
                }
            }
            else
            {
                button.Background = new SolidColorBrush(Colors.Red);
            }

            double SumMinOdds = 0.00;//指数和 最小
            double SumMaxOdds = 0.00;//指数和 最大

            double ProductMinOdds = 1.00;//指数积 最小
            double ProductMaxOdds = 1.00;//指数积 最大

            int ZhuCount = 1;
            List<double> DoubleList = new List<double>();

            var selfcols = this.DataGrid1.Columns[0];

            foreach (var item in DataGrid1.ItemsSource)
            {
                //--对象所在的单元格
                var cells = selfcols.GetCellContent(item);
                if (cells != null)
                {
                    //--单元格所包含的元素
                    Grid grid = cells as Grid;

                    StackPanel Sp = grid.Children[0] as StackPanel;

                    StackPanel Sp1 = Sp.Children[1] as StackPanel;

                    foreach (StackPanel StackPanel in Sp1.Children)
                    {
                        foreach (Button button1 in StackPanel.Children)
                        {
                            SolidColorBrush b_Brush1 = (SolidColorBrush)(button1.Background);

                            if (b_Brush1.Color.ToString() == "#FFFF0000")
                            {
                                DoubleList.Add(Netball.RetuntDouble(ToolTipService.GetToolTip(button1).ToString()));
                            }
                        }
                    }

                    ZhuCount *= DoubleList.Count;

                    SumMinOdds += DoubleList.Min();
                    SumMaxOdds += DoubleList.Max();

                    ProductMinOdds *= DoubleList.Min();
                    ProductMaxOdds *= DoubleList.Max();
                }
                DoubleList.Clear();
            }

            this.tbSum.Text = string.Format("{0:f2}", SumMinOdds) + "~" + string.Format("{0:f2}", SumMaxOdds);
            this.tbProduct.Text = string.Format("{0:f2}", ProductMinOdds) + "~" + string.Format("{0:f2}", ProductMaxOdds);
            this.tbPremium.Text = string.Format("{0:f2}", ProductMinOdds * 2) + "~" + string.Format("{0:f2}", ProductMaxOdds * 2);
        }