public IEnumerable<Earthquake> ParseJsonToQuakes(string json)
 {
     try
     {
         JObject o = JObject.Parse(json);
         List<Earthquake> quakes = new List<Earthquake>(30);
         foreach (var q in o["features"].Children())
         {
             Earthquake quake = new Earthquake
             {
                 Location = new GeoCoordinate(q["geometry"]["coordinates"].Values<double>().ElementAt(1),
                     q["geometry"]["coordinates"].Values<double>().ElementAt(0)),
                 Depth = (double)q["properties"]["depth"],
                 Magnitude = (double)q["properties"]["magnitude"],
                 Reference = (string)q["properties"]["publicid"],
                 /* origintime=2012-08-13 05:25:24.727000  (that's in UTC) */
                 Date = DateTime.Parse((string)q["properties"]["origintime"] + "Z"),
                 Agency = (string)q["properties"]["agency"],
                 Status = (string)q["properties"]["status"]
             };
             quakes.Add(quake);
         }
         return quakes.OrderByDescending(q => q.Date);
     }
     catch (Exception e)
     {
         throw new JsonException("Problem with JSON data", e);
     }
 }
Beispiel #2
0
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            string[] inputStrings = textBox1.Text.Split(new char[] { '\n', ',', '.'}, StringSplitOptions.RemoveEmptyEntries);
            textBox3.Text = string.Empty;
            string output = string.Empty;
            List<SimilirityAndString> unSortedOutput = new List<SimilirityAndString>();
            string lookupString = textBox2.Text.ToLower();
            foreach (var item in inputStrings)
            {
                string candidate = item.Trim().ToLower();
                double sIndex = FuzzyString.FuzzyString.GetSimilarIndex(lookupString, candidate);
                if (sIndex > 30)
                unSortedOutput.Add(
                    new SimilirityAndString()
                    {
                        simIndex = sIndex,
                        inputString = item
                    });
            }

            var sortedOutput = unSortedOutput.OrderByDescending(item => item.simIndex);
            foreach (var item in sortedOutput)
            {
                output += string.Format("Similarity:{0:0.00} ---- {1}\r\n", item.simIndex, item.inputString);
            }
            textBox3.Text = output;
        }
Beispiel #3
0
        public static void WriteAll(List<HistoryItem> items)
        {
            IsolatedStorageSettings.ApplicationSettings["HistoryItems"] = items.OrderByDescending(a => a.Date).Take(MAX_TO_KEEP).ToList();
            IsolatedStorageSettings.ApplicationSettings.Save();

            //App.HistoryViewModel.IsValid = false;
        }
Beispiel #4
0
        public Highscore()
        {
            InitializeComponent();

            try
            {
                int length = (int)DataManager.userSettings["taille"];
                this.scores = new List<HighscoreElement>();
                for(int i=1; i <= length; i++)
                    this.scores.Add(new HighscoreElement((int)DataManager.userSettings["highscore"+i]));

                listeDesScores.ItemsSource = scores.OrderByDescending(e => e.Score).Select(e => new HighscoreElement(e.Score,ObtientImage(e.Score)));
            }
            catch (System.Collections.Generic.KeyNotFoundException)
            {
                MessageBox.Show("No Key");
            }
        }
            /// <summary>
            /// Test2 takes an original point, and chooses the nearest X items from the new positions.
            /// 
            /// Say two of those original points had a link.  Now you could have several new points that correspond to one
            /// of the originals, linked to several that correspond to the second original
            /// 
            /// This method creates links from one set to the other
            /// </summary>
            public static LinkResult3[] Test4(LinkResult2[] from, LinkResult2[] to, int maxReturn)
            {
                // Find the combinations that have the highest percentage
                List<Tuple<int, int, double>> products = new List<Tuple<int, int, double>>();
                for (int fromCntr = 0; fromCntr < from.Length; fromCntr++)
                {
                    for (int toCntr = 0; toCntr < to.Length; toCntr++)
                    {
                        products.Add(new Tuple<int, int, double>(fromCntr, toCntr, from[fromCntr].Percent * to[toCntr].Percent));
                    }
                }

                // Don't return too many
                IEnumerable<Tuple<int, int, double>> topProducts = null;
                if (products.Count <= maxReturn)
                {
                    topProducts = products;		// no need to sort or limit
                }
                else
                {
                    topProducts = products.
                        OrderByDescending(o => o.Item3).
                        Take(maxReturn).
                        ToArray();
                }

                // Normalize
                double totalPercent = topProducts.Sum(o => o.Item3);

                LinkResult3[] retVal = topProducts.
                    Select(o => new LinkResult3(from[o.Item1], to[o.Item2], o.Item3 / totalPercent)).
                    ToArray();

                return retVal;
            }
Beispiel #6
0
        /// <summary>
        /// Füllt das DataGrid
        /// </summary>
        private void refreshDataGrid(List<BookingDataGridModel> bookingModels)
        {
            // Sortiere absteigend
            bookingModels = bookingModels.OrderByDescending(t => t.bookingID).ToList();

            this.dataGridPaging = new DataGridPaging<BookingDataGridModel>(bookingModels);
            AccountingRecordDataGrid.ItemsSource = this.dataGridPaging.FirstSide();
            AccountingRecordDataGrid.Items.Refresh();
            this.ChangePagingBar();
        }
        // Showing ranking
        private List<int> readRanking()
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            //List<int> listaPontos = new List<int>();
            List<int> resultList = new List<int>();

            if (settings.Contains("pointing"))
            {
                pointList = (List<int>)settings["pointing"];
                var result = pointList.OrderByDescending(n => n).Take(3);

                foreach (var i in result)
                {
                    resultList.Add(i);
                }
            }
            else {
                MessageBox.Show("Nenhum dado cadastrado!");
                pivotGame.SelectedIndex = 0;
            }

            return resultList;
        }
Beispiel #8
0
		public static void Sort(this DataGrid dg, Type cTypeOfElement, string sFieldName, bool bBackward)
		{
			System.Reflection.PropertyInfo cHeader = (System.Reflection.PropertyInfo)cTypeOfElement.GetMember(sFieldName)[0];

			List<ObjectForSort> aOFS = new List<ObjectForSort>();
			foreach (object oOFS in dg.ItemsSource)
					aOFS.Add(new ObjectForSort() { o = oOFS, oValue = cHeader.GetValue(oOFS, null) });
			if (bBackward)
				dg.ItemsSource = aOFS.OrderByDescending(o => o.oValue).Select(o => o.o).ToList();
			else
				dg.ItemsSource = aOFS.OrderBy(o => o.oValue).Select(o => o.o).ToList();
		}
        public void CategorySort(ClusteringResult baseResult)
        {
            List<Category> list = new List<Category>();
            List<Category> list2 = new List<Category>(this.Categories);
            foreach (var item in baseResult.Categories)
            {
                if (list2.Count > 0)
                {
                    var idList = item.GetComuity().Select(n => n.Id);
                    var c = list2.OrderByDescending(n => n.GetComuity().Select(m => m.Id).Intersect(idList).Count()).First();
                    list2.Remove(c);
                    list.Add(c);
                }
                else
                {
                    list.Add(new Category());
                }
            }
            this.Categories.Clear();
            foreach (var item in list)
            {
                this.Categories.Add(item);
            }

            var layerNames = this.LayerGroup.Select(n => n.Key).Distinct().ToArray();
            LayerGroup.Clear();
            foreach (var item in layerNames)
            {
                LayerGroup lg = new LayerGroup() { Name = item, Items = new System.Collections.ObjectModel.ObservableCollection<Layer>() };
                LayerGroup.Add(item, lg);
                foreach (var item2 in Categories)
                {
                    lg.Items.Add(item2.GetLayer(item));
                }
            }
        }
        private void parse_ConsumerList(object sender, HtmlDocumentLoadCompleted e)
        {
            IList < ProductViewModel >  tmpItems = new List<ProductViewModel>();
            IList<HtmlNode> hnc = e.Document.DocumentNode.DescendantNodes().ToList();
            String currentCategory = "Consumer Product Recalls";
            foreach (HtmlNode node in hnc)
            {
                if (node.Name.ToLower() == "table")
                {
                    foreach (HtmlAttribute att in node.Attributes)
                    {
                        if (att.Name.ToLower() == "summary" && att.Value == "Search results")
                        {
                            foreach (HtmlNode table in node.DescendantNodes().ToList())
                            {
                                if (table.Name.ToLower() == "tr")
                                {
                                    ProductViewModel po = new ProductViewModel();
                                    po.Category = currentCategory;

                                    foreach (HtmlNode tr in table.DescendantNodes().ToList())
                                    {
                                        if (tr.Name.ToLower() == "th")
                                        {
                                            break;
                                        }
                                        else if(tr.Name.ToLower() == "td")
                                        {
                                            String datetest = tr.InnerText;    
                                            DateTime test;
                                            datetest = datetest.Replace(",", "");
                                            datetest = datetest.Replace("Sept", "Sep");
                                            datetest = datetest.Replace("y 008", "2008");
                                            if (DateTime.TryParse(datetest, out test))
                                            {
                                                po.RecallDateString = datetest;
                                            }
                                            else
                                            {
                                                po.ShortDescription = ConvertWhitespacesToSingleSpaces( this.getTitleFromURLNode(tr) ).Trim();
                                                po.Href = Url_HealthCanadaConsumerPrefix + this.getURLFromNode(tr);
                                                break;
                                            }
                                            
                                        }    
                                    }
                                    if (po.Href != null && po.Href != "")
                                    {
                                        tmpItems.Add(po);
                                    } 
                                }
                            }
                        }
                    }
                }
            }
            foreach (ProductViewModel p in tmpItems.OrderByDescending(x => x._dateRecall))
            {
                this.Items.Add(p);
            }
            tmpItems.Clear();
            this.IsDataLoaded = true;
            NotifyPropertyChanged("WebDataRetrived");
        }
        private void parse_RecallListByCategory(object sender, HtmlDocumentLoadCompleted e)
        {
            IList < ProductViewModel >  tmpItems = new List<ProductViewModel>();
            IList<HtmlNode> hnc = e.Document.DocumentNode.DescendantNodes().ToList();
            String currentCategory = null;
            Boolean flag_comment = false;
            foreach (HtmlNode node in hnc)
            {
                if (!flag_comment && node.Name.ToLower() == "#comment")
                {
                    flag_comment = true;
                }
                else if (flag_comment && node.PreviousSibling != null && node.PreviousSibling.Name == "#comment")
                {
                    flag_comment = false;
                }

                if (!flag_comment && node.Name.ToLower() == "h3")
                {
                    currentCategory = node.InnerText;
                }
                else if (!flag_comment && node.Name.ToLower() == "li")
                {
                    if (node.ParentNode.Name == "ul" && node.ParentNode.Attributes.Count == 0)
                    {
                        ProductViewModel po = new ProductViewModel();
                        po.Category = currentCategory;
                        foreach (HtmlNode li in node.DescendantNodes().ToList())
                        {
                            if (li.Name.ToLower() == "a")
                            {
                                foreach (HtmlAttribute at in li.Attributes)
                                {
                                    if (at.Name.ToLower() == "href")
                                    {
                                        po.Href = at.Value;
                                    }
                                }
                                po.ShortDescription = ConvertWhitespacesToSingleSpaces(li.InnerText.Replace("�", "'")); 
                            }
                            else if (li.Name.ToLower() == "span")
                            {
                                po.RecallDateString = li.InnerText;
                            }
                            else if (li.Name.ToLower() == "#text")
                            {
                                if (li.ParentNode.Name.ToLower() == "li" && li.InnerText.Contains("20"))
                                {
                                    String date = "";
                                    if (li.PreviousSibling != null && li.PreviousSibling.Name.ToLower() == "abbr")
                                    {
                                        date += li.PreviousSibling.InnerText + " ";
                                    }
                                    date += li.InnerText;
                                    po.RecallDateString = date;
                                }
                            }
                        }
                      tmpItems.Add(po);
                    }
                }
            }

            foreach (ProductViewModel p in tmpItems.OrderByDescending(x => x._dateRecall))
            {
                this.Items.Add(p);
            }
            this.IsDataLoaded = true;
            NotifyPropertyChanged("WebDataRetrived"); 
        }
        private void load_FoodSafety(object sender, HtmlDocumentLoadCompleted e)
        {
            IList<ProductViewModel> tmpItems = new List<ProductViewModel>();
            IList<HtmlNode> hnc = e.Document.DocumentNode.DescendantNodes().ToList();
            String currentCategory = "Food Recalls and Allergy Alerts";

            Boolean content_flag = false;
            foreach (HtmlNode node in hnc)
            {
                if (node.Name.ToLower() == "#comment" && node.InnerText.Contains("start - recall index links"))
                {
                    content_flag = true;
                }
                else if(node.Name.ToLower() == "#comment" && node.InnerText.Contains("FOOTER BEGINS") )
                {
                    content_flag = false;
                }
                else if (content_flag && node.Name.ToLower() == "ul")
                {
                    foreach (HtmlNode li in node.DescendantNodes().ToList())
                    {
                        if (li.Name.ToLower() == "li")
                        {
                            ProductViewModel po = new ProductViewModel();
                            po.Category = currentCategory;

                            foreach (HtmlNode ee in li.DescendantNodes().ToList())
                            {
                                if (ee.Name.ToLower() == "strong")
                                {
                                    po.RecallDateString = ee.InnerText;
                                }
                                else if (ee.Name.ToLower() == "a")
                                {
                                    foreach (HtmlAttribute at in ee.Attributes)
                                    {
                                        if (at.Name.ToLower() == "href")
                                        {
                                            po.Href = "http://www.inspection.gc.ca"+ at.Value;
                                        }
                                    }
                                    po.ShortDescription = ConvertWhitespacesToSingleSpaces(ee.InnerText.Replace("�", "'").Replace("&rsquo;", "'"));
                                }
                            }
                            tmpItems.Add(po);
                        }
                    }
                }
            }                       
            foreach (ProductViewModel p in tmpItems.OrderByDescending(x => x._dateRecall))
            {
                this.Items.Add(p);
            }
            tmpItems.Clear();
            this.IsDataLoaded = true;
            NotifyPropertyChanged("WebDataRetrived");
        }
        //Because current contains uncategorized items
        private void parse_RecallListCurrent(object sender, HtmlDocumentLoadCompleted e)
        {
            IList<ProductViewModel> tmpItems = new List<ProductViewModel>();
            IList<HtmlNode> hnc = e.Document.DocumentNode.DescendantNodes().ToList();
            String currentCategory = "Advisories, Warnings and Recalls";
  
            foreach (HtmlNode node in hnc)
            {
                if (node.Name.ToLower() == "div")
                {
                    if (node.Attributes.Count == 1 && node.Attributes[0].Name.ToLower() == "class"
                        && node.Attributes[0].Value.ToLower() == "date")
                    {
                        foreach (HtmlNode child in node.DescendantNodes().ToList())
                        {
                             if (child.Name.ToLower() == "li")
                             {
                                if (child.ParentNode.Name == "ul" && child.ParentNode.Attributes.Count == 0)
                                {
                                    ProductViewModel po = new ProductViewModel();
                                    po.Category = currentCategory;
                                    foreach (HtmlNode li in child.DescendantNodes().ToList())
                                    {
                                        if (li.Name.ToLower() == "a")
                                        {
                                            foreach (HtmlAttribute at in li.Attributes)
                                            {
                                                if (at.Name.ToLower() == "href")
                                                {
                                                    po.Href = at.Value;
                                                }
                                            }
                                            po.ShortDescription = ConvertWhitespacesToSingleSpaces(li.InnerText.Replace("�", "'"));
                                        }
                                        else if (li.Name.ToLower() == "span")
                                        {
                                            po.RecallDateString = li.InnerText;
                                        }
                                        else if (li.Name.ToLower() == "#text")
                                        {
                                            if (li.ParentNode.Name.ToLower() == "li" && li.InnerText.Contains("20"))
                                            {
                                                String date = "";
                                                if (li.PreviousSibling != null && li.PreviousSibling.Name.ToLower() == "abbr")
                                                {
                                                    date += li.PreviousSibling.InnerText + " ";
                                                }
                                                date += li.InnerText;
                                                po.RecallDateString = date;

                                            }
                                        }
                                    }
                                    //if (po.RecallDateString == "Jun 7, 2011")
                                    //{
                                    //    goto EndParse;
                                    //}
                                    tmpItems.Add(po);
                                }
                             }
                        }
                    }        
                }
            } //EndParse:

            foreach (ProductViewModel p in tmpItems.OrderByDescending(x => x._dateRecall))
            {
                this.Items.Add(p);

            }
            tmpItems.Clear();
            this.IsDataLoaded = true;
            NotifyPropertyChanged("WebDataRetrived");
           
           
        }
        private void NotifyPropertyChanged(String propertyName)
        {
            if (propertyName == "WebDataRetrived")
            {
                IList<ProductViewModel> tmpItems = new List<ProductViewModel>(Items);
                Items.Clear();
                foreach (ProductViewModel p in tmpItems.OrderByDescending(x => x._dateRecall))
                {
                    this.Items.Add(p);

                }
                tmpItems.Clear();
                foreignProductAlerts = null;
                advisoriesWarningsRecalls = null;
                Spinnner.ShowSpinner = false;
                
            }
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
            
        }
Beispiel #15
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == true)
            {
                TextBox_InputName.Text = ofd.FileName;

                FFTW fftw = new FFTW();
                _input = DataLoader.Load(ofd.FileName);
                double[] inputCopy = new double[_input.Length];
                _input.CopyTo(inputCopy, 0);

                _frequencyDomain = fftw.Forward(inputCopy);
                _frequencyDomainLinkedToCheckboxes = new Complex[_frequencyDomain.Length];

                _frequencyDomain.CopyTo(_frequencyDomainLinkedToCheckboxes, 0);

                DataSeries<double, double> points = new DataSeries<double, double>("Magnitudes");
                TheList = new ObservableCollection<CheckBoxBinder>();
                List<CheckBoxBinder> mags = new List<CheckBoxBinder>();
                for (int c = 0; c < _frequencyDomain.Length; c++)
                {
                    points.Add(new DataPoint<double, double> { X = c, Y = _frequencyDomain[c].Magnitude });
                    mags.Add(new CheckBoxBinder { TheValue = _frequencyDomain[c].Magnitude, Index = c });
                }

                foreach (CheckBoxBinder d in mags.OrderByDescending(m => m.TheValue))
                {
                    TheList.Add(d);
                }

                exampleChart.Series[0].DataSeries = points;
                this.DataContext = this;

                DataSeries<double, double> data = new DataSeries<double, double>("Data");
                for (int c = 0; c < _input.Length; c++)
                {
                    data.Add(new DataPoint<double, double> { X = c, Y = _input[c] });
                }

                dataChart.Series[0].DataSeries = data;

                return;
            }
        }
Beispiel #16
0
        private void applyFilters()
        {
            #region Select/Deselect buttons
            if (listBox_years.SelectedItems.Count == listBox_years.Items.Count)
            {
                button_selectAllYears.Content = "Deselect all";
            }
            else
            {
                button_selectAllYears.Content = "Select all";
            }

            if (listBox_videoQuality.SelectedItems.Count == listBox_videoQuality.Items.Count)
            {
                button_selectAllVideo.Content = "Deselect all";
            }
            else
            {
                button_selectAllVideo.Content = "Select all";
            }

            if (listBox_audioQuality.SelectedItems.Count == listBox_audioQuality.Items.Count)
            {
                button_selectAllAudio.Content = "Deselect all";
            }
            else
            {
                button_selectAllAudio.Content = "Select all";
            }
            #endregion

            buffer.Clear();
            filterResult.Clear();

            filterResult.AddRange(final_list);

            if (textBox_name.Text.Trim() != "")
            {
                buffer.AddRange(filterResult.FindAll(listItem => listItem.Name.ToLower().Contains(textBox_name.Text.ToLower())));
            }
            else
            {
                buffer.AddRange(filterResult);
            }

            filterResult.Clear();
            filterResult.AddRange(buffer);
            buffer.Clear();

            if (listBox_videoQuality.SelectedItems.Count != 0 || listBox_audioQuality.SelectedItems.Count != 0 || listBox_years.SelectedItems.Count != 0)
            {
                foreach (var videoQualityItem in listBox_videoQuality.SelectedItems)
                {
                    buffer.AddRange(filterResult.FindAll(listItem => listItem.videoQuality == videoQualityItem.ToString()));
                }

                filterResult.Clear();
                filterResult.AddRange(buffer);
                buffer.Clear();

                foreach (var audioQualityItem in listBox_audioQuality.SelectedItems)
                {
                    buffer.AddRange(filterResult.FindAll(listItem => listItem.audioQuality == audioQualityItem.ToString()));
                }

                filterResult.Clear();
                filterResult.AddRange(buffer);
                buffer.Clear();

                foreach (var yearsItem in listBox_years.SelectedItems)
                {
                    buffer.AddRange(filterResult.FindAll(listItem => listItem.Year == yearsItem.ToString()));
                }

                filterResult.Clear();
                filterResult.AddRange(buffer);
                buffer.Clear();
            }

            filterResult = filterResult.OrderBy(Movie => Movie.Name).ToList();

            if (rating_list.Count != 0)
            {
                filterResult = filterResult.OrderByDescending(Movie => Movie.Rating).ToList();
            }

            dataGrid1.ItemsSource = filterResult;

            label5.Content = filterResult.Count.ToString();

            hideColumns();
        }
        //shows a list of airports
        public void showAirports(List<Airport> airports)
        {
            airportsList = airports;

            lbAirports.Items.Clear();

            if (this.sortDescending)
                airports = airports.OrderByDescending(sortCriteria).ThenBy(a=>a.Profile.Name).ToList();
            else
                airports = airports.OrderBy(sortCriteria).ThenBy(a => a.Profile.Name).ToList();

            foreach (Airport airport in airports)
                lbAirports.Items.Add(airport);
        }
        //shows the list of used airliners for sale
        private void showUsedAirliners()
        {
            lbUsedAirliners.Items.Clear();

            var lAirliners = new List<Airliner>(airliners.FindAll(a => a.Type.TypeAirliner == airlinerType));

            if (sortDescending)
                lAirliners = lAirliners.OrderByDescending(sortCriteriaUsed).ThenBy(a => a.TailNumber).ToList();
            else
                lAirliners = lAirliners.OrderBy(sortCriteriaUsed).ThenBy(a => a.TailNumber).ToList();

            foreach (Airliner airliner in lAirliners)
                lbUsedAirliners.Items.Add(airliner);
        }
        string AddBlancNotamStr(List<IntlNotam> ListOfNotams)
        {
            string strValid = "";
            int i = 0;
            List<IntlNotam> newList = ListOfNotams.OrderByDescending(n => Int32.Parse(n.Number)).ToList();
            int iLastNum=Int32.Parse(newList[0].Number);
            for (int iNumber=1;iNumber<iLastNum;iNumber++)
            {
                IntlNotam ntFind = ListOfNotams.Where(x => x.Number == iNumber.ToString()).FirstOrDefault();
                if (ntFind != null)
                {
                    if (!string.IsNullOrEmpty(ntFind.EFreeText) && !ntFind.EFreeText.Contains("THIS NOTAM IS NOT RECIEVED BY TEHRAN NOF"))
                        continue;
                }
                strValid += string.Format("{0:0000}",iNumber) + ",";
                i++;
                if (i % 12 == 0)
                    strValid += Environment.NewLine;
            }
            if (strValid.Length > 0 && strValid[strValid.Length - 1]==',')
                strValid = strValid.Remove(strValid.Length - 1);
            strValid += Environment.NewLine;
            return strValid;

        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var patches = new List<Patch>();

            if (true)
            {
                //C:\Users\johnw_000\Images\bigger

                string imageFolder = @"C:\Users\johnw_000\Images\imageset1";
                var imfiles = Directory.GetFiles(imageFolder, "*.jpg");
                var images = imfiles.Select(filename => new Image(System.IO.Path.Combine(imageFolder, filename))).ToList();

                // Image im = images[0];
                foreach (var im in images) im.AddPatches(patches, 31, 31, 31, 31);
            }
            else
            {
                string imageFolder = @"C:\Users\johnw_000\Images\bigger";
                var imfiles = Directory.GetFiles(imageFolder, "*.jpg");
                var images = imfiles.Select(filename => new Image(System.IO.Path.Combine(imageFolder, filename))).ToList();

                // Image im = images[0];
                foreach (var im in images.Take(800)) im.AddPatches(patches, 5,5, 47, 47);

            }

            var learner = new TreeLearner();

            Tree tree = null;
            for (int z = 0; z < 4; z++)
            {
                // Learn initial tree
                tree = learner.Learn(10, patches);

                // Learning rotations
                Console.WriteLine("Learning rotations & translations");
                for (int iters = 0; iters < 2; iters++)
                {
                    LearnRotations(patches, tree);
                    Console.WriteLine("Non-empty leaves: " + tree.Nodes.Count(nd => nd.IsLeaf && nd.Count > 0));
                    //LearnTranslations(patches, tree);
                    //Console.WriteLine("Non-empty leaves: " + tree.Nodes.Count(nd => nd.IsLeaf && nd.Count > 0));
                }
                //Console.WriteLine("Learning translations");

                //Console.WriteLine("Non-empty leaves: " + tree.Nodes.Count(nd => nd.IsLeaf && nd.Count > 0));
            }

            var clusters = new List<Cluster>();
            foreach (var nd in tree.Nodes)
            {
                if (nd.IsLeaf)
                {
                    var cl = new Cluster
                    {
                        Count = nd.Count,
                        SamplePatches = new List<Patch>()
                    };

                    var leafPatches = patches.Where(p => p.NodeIndex == nd.Index).ToList();
                    for(int i=0;i<leafPatches.Count;i+=5) {
                        cl.SamplePatches.Add(leafPatches[i]);
                        if (cl.SamplePatches.Count > 20) break;
                    }
                    clusters.Add(cl);
                }
            }
            Console.WriteLine("Empty clusters: " + clusters.Count(c => c.Count == 0) + " out of " + clusters.Count);
            MyClusters.ItemsSource = clusters.OrderByDescending(cl => cl.Count);
        }
Beispiel #21
0
        void loadData()
        {
            listBox1.ItemsSource = null;
            List<Resultado> resultados = new List<Resultado>();
            ContextoDatos ctx = new ContextoDatos();
            var data = ctx.Datas.Where(o=>o.IdUsuario == Convert.ToInt32(Id)).OrderBy(o => o.Fecha ).ThenBy(o=> o.Id);

            var cultura = CultureInfo.CurrentCulture;

              //  CultureInfo culture = new CultureInfo("en-GB");
            RegionInfo regionInfo = new RegionInfo(cultura.Name);
            bool isMetric = regionInfo.IsMetric;
            //listaUsuarios.Add(new Usuario { Id = user.Id, Nombre = user.Nombre });

            double pesoAnterior=0;
            bool entra = false;
            foreach (DataUser dato in data)
            {

                Datos datos = new Datos(dato.Genero,dato.Altura,dato.Edad,dato.Peso,dato.Indice);

                DateTime Fecha = new DateTime();

                resultados.Add	(
                                new Resultado()
                                {
                                            IdUsuario       = dato.IdUsuario.ToString(),
                                            IdDato          = dato.Id,
                                            FechaOrder		= dato.Fecha,
                                            Fecha			= dato.Fecha.ToShortDateString(),
                                            FechaDia        = dato.Fecha.Day.ToString(),
                                            NomDia			= CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedDayName(dato.Fecha.DayOfWeek),
                                            FechaMes        = CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(dato.Fecha.Month),
                                            imc				= string.Format("{0:#,#0.00}",datos.imc),
                                            Peso			= App.IsMetric?string.Format("{0:#,#0.000}kg",dato.Peso):string.Format("{0:#,#0}lb",Conversion.ToLibras(dato.Peso)),
                                            //Peso			= String.Format(cultura,"{0}{1}" ,Math.Round(App.IsMetric?datos.peso:Conversion.ToLibras(datos.peso) ,2), App.IsMetric ? "Kg" : "lb"),
                                            PorcentajeGrasa = String.Format(cultura,"{0}%"   ,Math.Round(datos.porcentajeGrasa	,2)),
                                            upVisible		= !entra?Visibility.Collapsed:dato.Peso > pesoAnterior?Visibility.Visible:Visibility.Collapsed,
                                            downVisible		= !entra?Visibility.Collapsed:dato.Peso < pesoAnterior?Visibility.Visible:Visibility.Collapsed,
                                            PesoDif			= !entra?"":resulDif(dato.Peso,pesoAnterior),
                                            ImcColor		= datos.imc < 18.5 || datos.imc > 25 ? new SolidColorBrush(Colors.Red): new SolidColorBrush(Colors.White)

                                }
                                );

                if(!entra)
                {
                    entra=true;
                }

                pesoAnterior =  dato.Peso;

            }

            listBox1.ItemsSource = resultados.OrderByDescending(o => o.FechaOrder ).ThenByDescending(o=> o.IdDato);
        }
        /// <summary>
        /// 過去のもの。頑張りすぎた。
        /// </summary>
        /// <returns></returns>
        ClusteringResult Run2()
        {
            List<ClusteringResult> tmpResult = new List<ClusteringResult>();
            OnReport("開始");
            for (int i = 0; i < wideCount; i++)
            {
                ClusteringResult cr = new ClusteringResult() { Parent = this };
                cr.CreateRandom(ClusterTable, random.Next());
                tmpResult.Add(cr);
            }

            int loopCount = 0;
            int sameCount = 0;
            double sameRate = 0;
            while (true)
            {

                loopCount++;
                if (tmpResult.First().GetLockRate() == sameRate)
                {
                    sameCount++;
                }
                else
                {
                    sameRate = tmpResult.First().GetLockRate();
                    sameCount = 0;
                }

                OnReport(loopCount + "回目開始");
                foreach (var item in tmpResult)
                {
                    item.Run();
                }
                OnReport("計算終了");

                var baseResult = tmpResult.OrderByDescending(n => n.GetPerformanceIndex()).First();
                foreach (var item in tmpResult)
                {
                    item.CategorySort(baseResult);
                }
                tmpResult = tmpResult.OrderByDescending(n => n.GetPerformanceIndex()).ToList();
                List<ClusteringResult> list = new List<ClusteringResult>();
                foreach (var item in tmpResult.Take(tmpResult.Count / 2))
                {
                    var clone = item.Clone();
                    list.Add(clone);
                }
                if (tmpResult.Count > 3)
                {
                    foreach (var item in tmpResult.Skip(tmpResult.Count / 2).ToArray())
                    {
                        tmpResult.Remove(item);
                    }
                    foreach (var item in list)
                    {
                        tmpResult.Add(item.Clone());
                    }
                }

                if (tmpResult.First().GetLockRate() < 0.9 && loopCount < 100 && sameCount < 10)
                {
                    int c = 0;
                    OnReport("マージ・ランダム振り開始");
                    foreach (var item in tmpResult)
                    {
                        var count = item.CreateMargeData(list, true);
                        //  lock (this)
                        {
                            c += count;
                        }
                    }
                    OnReport("レポート開始");
                    OnReport(tmpResult.First().View());

                    if (c == 0) break;
                }
                else
                {
                    foreach (var item in tmpResult)
                    {
                        var count = item.CreateMargeData(list, false);
                    }
                    tmpResult.First().Run();
                    break;
                }

                if (tmpResult.First().DivideCategory())
                {
                    OnReport("クラスタ分割発生");
                    var r = tmpResult.First();
                    tmpResult.Clear();
                    for (int i = 0; i < TryCount; i++)
                    {
                        tmpResult.Add(r.Clone());
                    }
                }
                GC.Collect();
            }
            GC.Collect();
            OnReport("完了");
            return tmpResult.First();
        }
Beispiel #23
0
        private void RenderNotifications(HtmlDocument doc)
        {
            List<Notification> data = new List<Notification>();

            try
            {
                var nodes = from e in doc.DocumentNode.DescendantNodes()
                            where e.Name == "li" &&
                                  e.Attributes.Contains("class") == true &&
                                  e.Attributes["class"].Value.Contains("short")
                            select e;
                foreach (HtmlNode node in nodes)
                {
                    Notification a = new Notification();
                    a.Description = (from e in node.DescendantNodes()
                                     where e.Name == "span" &&
                                           e.Attributes.Contains("class") == true &&
                                           e.Attributes["class"].Value.Contains("headline")
                                     select e).First().InnerText;
                    a.Date = (from e in node.DescendantNodes()
                              where e.Name == "span" &&
                                    e.Attributes.Contains("class") == true &&
                                    e.Attributes["class"].Value.Contains("date")
                              select e).First().InnerText.ToUpper();

                    data.Add(a);
                }

                this.notifications_listBox1.ItemsSource = data.OrderByDescending(i => i.Date);
            }
            catch
            {
                this.notifications_listBox1.Visibility = System.Windows.Visibility.Collapsed;
                this.notifications_textBlock0.Visibility = System.Windows.Visibility.Visible;
            }
        }
Beispiel #24
0
        public void PreencheLista(XElement xml)
        {
            var lista = new List<tumblelog>();

            foreach (var item in xml.Descendants("tumblelog"))
            {
                var t = new tumblelog();

                t.avatar_url = item.GetAttributeValue("avatar-url").Contains(".gif") ? @"..\Images\default_avatar.jpg" : item.GetAttributeValue("avatar-url");
                t.backup_post_limit = Convert.ToInt32(string.IsNullOrWhiteSpace(item.GetAttributeValue("backup-post-limit")) ? "0" : item.GetAttributeValue("backup-post-limit"));
                t.draft_count = Convert.ToInt32(string.IsNullOrWhiteSpace(item.GetAttributeValue("draft-count")) ? "0" : item.GetAttributeValue("draft-count"));
                t.followers = Convert.ToInt32(string.IsNullOrWhiteSpace(item.GetAttributeValue("followers")) ? "0" : item.GetAttributeValue("followers"));
                t.is_admin = item.GetAttributeValue("is-admin") == "1";
                t.is_primary = item.GetAttributeValue("is-primary") == "yes";
                t.messages_count = Convert.ToInt32(string.IsNullOrWhiteSpace(item.GetAttributeValue("messages-count")) ? "0" : item.GetAttributeValue("messages-count"));
                t.name = item.GetAttributeValue("name");
                t.posts = Convert.ToInt32(string.IsNullOrWhiteSpace(item.GetAttributeValue("posts")) ? "0" : item.GetAttributeValue("posts"));
                t.queue_count = Convert.ToInt32(string.IsNullOrWhiteSpace(item.GetAttributeValue("queue-count")) ? "0" : item.GetAttributeValue("queue-count"));
                t.title = item.GetAttributeValue("title");
                t.twitter_enabled = item.GetAttributeValue("twitter-enabled") == "1";
                t.facebook_opengraph_enabled = item.GetAttributeValue("facebook-opengraph-enabled") == "1";
                t.type = item.GetAttributeValue("type").Equals("public") ? "publico" : "privado";
                t.url = item.GetAttributeValue("url");
                t.tagButton = t.name + "," + t.twitter_enabled.ToString();

                lista.Add(t);
            }

            lblAguarde.Visibility = Visibility.Collapsed;
            customIndeterminateProgressBar.Visibility = Visibility.Collapsed;

            listMyBlogs.ItemsSource = lista.OrderByDescending(o => o.is_primary);
        }
 private void BuildView(List<IMessage> history)
 {
     var monthGroups = history.OrderByDescending(note => note.Date)
             .GroupBy(key => key.Date.ToString("MMMM yyyy"));
     foreach (var monthGroup in monthGroups)
     {
         HistoryView.Add(new HistoryView
         {
             Month = monthGroup.Key,
             ActiveDates = new ObservableCollection<DayMessageView>(
                     monthGroup.GroupBy(key => key.Date.ToShortDateString())
                             .Select(dayGroup => new DayMessageView
                             {
                                 Day = dayGroup.Key,
                                 Messages = new ObservableCollection<IMessage>(dayGroup),
                             }))
         });
     }
 }
        void node_NodeMouseDown(object sender, MouseButtonEventArgs e)
        {
            var nodeC = (MyWpfLib.Graph.NodeControl)sender;
            var category = nodeC.Tag as ClusterViewForSliverlinght.Models.Category;
            List<RelationData> list = new List<RelationData>();
            foreach (var item in clusterTable.Categories.Where(n => n != category))
            {
                list.Add(new RelationData()
                {
                    NameA = category.GetName(),
                    NameB = nodeDic[item].Node.NodeName,
                    Jaccard = MyWpfLib.Graph.Sort.Jaccard(useridDic[category].Intersect(useridDic[item]).Count(), useridDic[item].Count, useridDic[category].Count),
                    信頼度比 = MyWpfLib.Graph.Sort.信頼度比(useridDic[category].Intersect(useridDic[item]).Count(), useridDic[item].Count, useridDic[category].Count,allCount),
                    Parent = this
                });
        
            }
            list = list.OrderByDescending(n => n.Jaccard).ToList();
            ChangeDataGrid(this, new MyLib.Event.Args<List<RelationData>>(list));

        }
Beispiel #27
0
        private void GetTwitterStuff()
        {
            try
                {
                    using (var wc = new WebClient())
                    {
                        var str = wc.DownloadString(AppConfig.WebsitePath + "news.xml");
                        if (string.IsNullOrWhiteSpace(str))
                        {
                            throw new Exception("Null news feed.");
                        }

                        var doc = System.Xml.Linq.XDocument.Parse(str);
                        var nitems = doc.Root.Elements("item");
                        var feeditems = new List<NewsFeedItem>();
                        foreach (var f in nitems)
                        {
                            var nf = new NewsFeedItem { Message = (string)f };
                            var dt = f.Attribute("date");
                            if(dt == null) continue;
                            DateTime dto;
                            if(!DateTime.TryParse(dt.Value,out dto))
                                continue;
                            nf.Time = dto;
                            feeditems.Add(nf);
                        }

                        Dispatcher.BeginInvoke(
                            new Action(
                                () => this.ShowTwitterStuff(feeditems.OrderByDescending(x => x.Time).Take(5).ToList())));
                    }
                }
                catch(Exception)
                {
                    Dispatcher.Invoke(new Action(() => textBlock5.Text = "Could not retrieve news feed."));
                }
        }
Beispiel #28
0
        private void MoveRight_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            Pause();

            ActionStack.Did(ListFrames);

            #region Move Selected Frame to the Left

            var selected = new List<FrameListBoxItem>(FrameListView.SelectedItems.OfType<FrameListBoxItem>());
            var selectedOrdered = selected.OrderByDescending(x => x.FrameNumber).ToList();

            var listIndex = selectedOrdered.Select(frame => FrameListView.Items.IndexOf(frame)).ToList();

            foreach (var item in selectedOrdered)
            {
                #region Index

                var oldindex = listIndex[selectedOrdered.IndexOf(item)];
                var index = FrameListView.Items.IndexOf(item);
                var newIndex = index + 1;

                if (index == FrameListView.Items.Count - 1)
                    newIndex = 0;

                if (oldindex + 1 == index)
                {
                    continue;
                }

                #endregion

                #region Move

                var auxItem = ListFrames[index];

                FrameListView.Items.RemoveAt(index);
                ListFrames.RemoveAt(index);

                FrameListView.Items.Insert(newIndex, item);
                ListFrames.Insert(newIndex, auxItem);

                #endregion
            }

            #region Update Count

            var indexUpdate = listIndex.Last();

            if (listIndex.First() == FrameListView.Items.Count - 1)
                indexUpdate = 0;

            AdjustFrameNumbers(indexUpdate);

            #endregion

            #region Select Frames

            foreach (var item in selected)
            {
                FrameListView.SelectedItems.Add(item);
            }

            #endregion

            #endregion
        }
        /// <summary>
        /// 获取解约处理
        /// </summary>
        public void GetTerminationLstExcuted()
        {
            if (!CanGetTerminationLstExcuted)
            {
                return;
            }
            string state = "";
            switch (TerminationSelectCondition.State)
            {
                case "全部":
                    state = "All";
                    break;
                case "已申请":
                    state = "0";
                    break;
                case "已审核":
                    state = "1";
                    break;
                case "已拒绝":
                    state = "2";
                    break;

            }
            CJQueryConInfomation infomation = new CJQueryConInfomation
            {
                LoginID = _loginID,
                Account = TerminationSelectCondition.Account,
                Endtime = TerminationSelectCondition.EndTime.AddDays(1),
                Starttime = TerminationSelectCondition.StartTime,
                OrgName = TerminationSelectCondition.OrgName,
                State = state

            };
            int pageCount = 0;
            List<TradeJieYue> list = new List<TradeJieYue>();
            ErrType err = _businessService.GetMultiTerminationWithPage(infomation, TerminationSelectCondition.PageIndex, TerminationSelectCondition.PageSize,
            ref  pageCount, out  list);

            if (err == GeneralErr.Success)
            {
                if (list != null)
                    //按时间排序处理
                    TradeJieYueLst = new ObservableCollection<TradeJieYue>(list.OrderByDescending(item => item.ApplyTime));
                    TerminationSelectCondition.PageCount = pageCount;
            }
            else
                MessageBox.Show(err.ErrMsg, err.ErrTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
        }
        private void UpdateView()
        {
            notes = app.notes.Where(x => x.item_id == Task.id).ToList();
            notes = notes.OrderByDescending(e => DateTime.Parse(e.posted)).ToList();
            extractUrl(app.notes);

            NotesListBox.ItemsSource = null;
            NotesListBox.ItemsSource = notes;

            DataContext = null;
            DataContext = Task;
        }