예제 #1
0
 void GetStats(System.Collections.Generic.List <float> input, out float mean, out float median, out float min, out float max)
 {
     mean   = input.Average();
     min    = input.Min();
     max    = input.Max();
     median = input.OrderBy(sample => sample).ToList().ElementAt(input.Count / 2);
 }
예제 #2
0
        public RectangleFilter(Rectangle area, ObstacleRepresentation[] platforms, ObstacleRepresentation[] rectanglePlatforms, ObstacleRepresentation[] circlePlatforms) : base(area, platforms, rectanglePlatforms, circlePlatforms)
        {
            //xPlatforms = new List<ObstacleRepresentation>(platforms);
            yPlatforms = new List <ObstacleRepresentation>(platforms);
            yPlatforms.InsertRange(0, circlePlatforms);

            //xPlatforms = xPlatforms.OrderBy(o => o.X).ToList();
            yPlatforms = yPlatforms.OrderBy(o => o.Y).ToList();
        }
 /// <summary>
 /// Initializes the mappings
 /// </summary>
 public void Initialize()
 {
     System.Collections.Generic.List <IMapping> TempMappings = new System.Collections.Generic.List <IMapping>();
     foreach (Type Key in Mappings.Keys)
     {
         foreach (IMapping Mapping in Mappings[Key])
         {
             TempMappings.Add(Mapping);
         }
     }
     foreach (IMapping Mapping in TempMappings.OrderBy(x => x.Order))
     {
         Mapping.Initialize();
     }
 }
예제 #4
0
        /// <summary>
        /// 获得指定用户的基于用户的条目推荐结果
        /// 当规模小时,userDic可选用所有用户的userDic
        /// 当规模较大时,应通过getSimUser获取相似用户,再获取相似用户的itemDic
        /// </summary>
        /// <param name="userDic"></param>
        /// <param name="person"></param>
        /// <param name="n"></param>
        /// <returns></returns>
        public static List <objectSimilarity> getItemRecommUserBased
            (Dictionary <int, Dictionary <int, double> > userDic, int person, int n = 3)
        {
            Dictionary <int, double> totals  = new Dictionary <int, double>();
            Dictionary <int, double> simSums = new Dictionary <int, double>();

            foreach (int other in userDic.Keys)
            {
                if (other == person)
                {
                    continue;
                }
                double sim = simDistance(userDic[person], userDic[other]);
                if (sim <= 0)
                {
                    continue;
                }
                foreach (int item in userDic[other].Keys)
                {
                    if (!userDic[person].Keys.Contains(item) || userDic[person][item] == 0)
                    {
                        totals.DefaultIfEmpty(new System.Collections.Generic.KeyValuePair <int, double>(item, 0));
                        totals[item] += userDic[other][item] * sim;
                        simSums.DefaultIfEmpty(new System.Collections.Generic.KeyValuePair <int, double>(item, 0));
                        simSums[item] += sim;
                    }
                }
            }
            List <objectSimilarity> rankings = new System.Collections.Generic.List <objectSimilarity>();

            foreach (int item in totals.Keys)
            {
                rankings.Add(new objectSimilarity(item, totals[item] / simSums[item]));
            }
            rankings.OrderBy(x => x.similarity, new scoreComparer());
            var t = rankings.Take(n);
            List <objectSimilarity> ret = new List <objectSimilarity>();

            foreach (objectSimilarity item in t)
            {
                ret.Add(item);
            }
            return(ret);
        }
예제 #5
0
        public static Model.AgentInformation ComputeAgentInformation(
            string nodeName     = null,
            string ipAddress    = null,
            string agentVersion = DEFAULT_AGENT_VERSION)
        {
            if (nodeName == null)
            {
                nodeName = Dns.GetHostName();
            }

            if (ipAddress == null)
            {
                // TODO:  this *might* not be correct or complete -- based on issue #26
                // this is definitely a better approach than what we had before, but need
                // to do some more exploring and experimenting to see if this is all of it
                var ipList = new System.Collections.Generic.List <IPAddress>();
                foreach (var ni in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
                {
                    // Collect all IPv4 & IPVv6 address
                    foreach (var ua in ni.GetIPProperties().UnicastAddresses)
                    {
                        if (ua.Address.AddressFamily == AddressFamily.InterNetwork ||
                            ua.Address.AddressFamily == AddressFamily.InterNetworkV6)
                        {
                            ipList.Add(ua.Address);
                        }
                    }
                }
                // Sort by IPv4 first, then v6
                ipAddress = string.Join(";", ipList.OrderBy(x => x.AddressFamily)
                                        .Select(x => x.ToString()));
            }

            return(new Model.AgentInformation
            {
                LCMVersion = agentVersion,
                NodeName = nodeName,
                IPAddress = ipAddress,
            });
        }
예제 #6
0
        /// <summary>
        /// Processes the assets
        /// </summary>
        /// <param name="Assets">Assets to process</param>
        /// <param name="Context">The bundle context</param>
        /// <param name="Response">The bundle response</param>
        public void Process(IList <IAsset> Assets, BundleContext Context, BundleResponse Response)
        {
            foreach (IFilter Filter in Filters.Where(x => x.TimeToRun == RunTime.PreTranslate))
            {
                Assets = Filter.Filter(Assets);
            }
            foreach (ITranslator Translator in Translators)
            {
                Assets = Translator.Translate(Assets);
            }
            foreach (RunTime Item in RunOrder)
            {
                foreach (IFilter Filter in Filters.Where(x => x.TimeToRun == Item))
                {
                    Assets = Filter.Filter(Assets);
                }
            }
            string Content = Assets.OrderBy(x => x.Path).ToString(x => x.ToString(), "");

            foreach (IContentFilter Filter in ContentFilters)
            {
                Content = Filter.Filter(Content);
            }
            var Files = new System.Collections.Generic.List <BundleFile>();

            foreach (IAsset Asset in Assets)
            {
                if (Asset.Path.StartsWith("~", StringComparison.Ordinal) || Asset.Path.StartsWith("/", StringComparison.Ordinal))
                {
                    Files.Add(new BundleFile(Asset.Path, new VirtualFileHack(Asset.Path)));
                    Files.Add(Asset.Included.Where(x => x.Path.StartsWith("~", StringComparison.Ordinal) || x.Path.StartsWith("/", StringComparison.Ordinal)).Select(x => new BundleFile(x.Path, new VirtualFileHack(x.Path))));
                }
            }
            Response.Content      = Content;
            Response.Files        = Files.OrderBy(x => x.VirtualFile.VirtualPath);
            Response.ContentType  = Assets.First().Type == AssetType.CSS ? "text/css" : "text/javascript";
            Response.Cacheability = HttpCacheability.ServerAndPrivate;
        }
예제 #7
0
 /// <summary>
 /// Processes the assets
 /// </summary>
 /// <param name="Assets">Assets to process</param>
 /// <param name="Context">The bundle context</param>
 /// <param name="Response">The bundle response</param>
 public void Process(IList<IAsset> Assets, BundleContext Context, BundleResponse Response)
 {
     foreach (IFilter Filter in Filters.Where(x => x.TimeToRun == RunTime.PreTranslate))
     {
         Assets = Filter.Filter(Assets);
     }
     foreach (ITranslator Translator in Translators)
     {
         Assets = Translator.Translate(Assets);
     }
     foreach (RunTime Item in RunOrder)
     {
         foreach (IFilter Filter in Filters.Where(x => x.TimeToRun == Item))
         {
             Assets = Filter.Filter(Assets);
         }
     }
     string Content = Assets.OrderBy(x => x.Path).ToString(x => x.ToString(), "");
     foreach (IContentFilter Filter in ContentFilters)
     {
         Content = Filter.Filter(Content);
     }
     System.Collections.Generic.List<BundleFile> Files = new System.Collections.Generic.List<BundleFile>();
     foreach (IAsset Asset in Assets)
     {
         if (Asset.Path.StartsWith("~") || Asset.Path.StartsWith("/"))
         {
             Files.Add(new BundleFile(Asset.Path, new VirtualFileHack(Asset.Path)));
             Files.Add(Asset.Included.Where(x => x.Path.StartsWith("~") || x.Path.StartsWith("/")).Select(x => new BundleFile(x.Path, new VirtualFileHack(x.Path))));
         }
     }
     Response.Content = Content;
     Response.Files = Files.OrderBy(x => x.VirtualFile.VirtualPath);
     Response.ContentType = Assets.First().Type == AssetType.CSS ? "text/css" : "text/javascript";
     Response.Cacheability = HttpCacheability.ServerAndPrivate;
 }
        public void GenerarReporte()
        {
            try
            {
                if (SelectedFechaInicial == null)
                {
                    return;
                }

                if (SelectedFechaFinal == null)
                {
                    return;
                }

                var encabezado           = new System.Collections.Generic.List <cEncabezado>();
                var listaIngresosActivos = new System.Collections.Generic.List <cReporteIngresosActivosCierre>();
                var centro = new SSP.Controlador.Catalogo.Justicia.cCentro().Obtener(GlobalVar.gCentro).FirstOrDefault();
                encabezado.Add(new cEncabezado()
                {
                    ImagenDerecha = Parametro.LOGO_ESTADO_BC,
                    TituloUno     = Parametro.ENCABEZADO1,
                    TituloDos     = Parametro.ENCABEZADO2,
                    NombreReporte = centro != null ? !string.IsNullOrEmpty(centro.DESCR) ? centro.DESCR.Trim() : string.Empty : string.Empty,
                    PieUno        = string.Format("Reporte de Población Activa al Cierre \n Del {0} Al {1}",
                                                  SelectedFechaInicial.HasValue ? SelectedFechaInicial.Value.ToString("dd/MM/yyyy") : string.Empty,
                                                  SelectedFechaFinal.HasValue ? SelectedFechaFinal.Value.ToString("dd/MM/yyyy") : string.Empty)
                });

                var _IngresosActivos = new SSP.Controlador.Catalogo.Justicia.cIngreso().ObtenerIngresosActivosPorFecha(GlobalVar.gCentro, SelectedFechaInicial, SelectedFechaFinal);
                int alf = _IngresosActivos.Count(x => x.IMPUTADO.NACIMIENTO_PAIS != null);
                if (_IngresosActivos.Any())
                {
                    int _NoUbicados        = new int();
                    int _HombresNoUbicados = new int();
                    int _MujeresNoUbicadas = new int();
                    var _Agrupados         = _IngresosActivos.GroupBy(x => x.IMPUTADO.NACIMIENTO_PAIS);
                    if (_Agrupados.Any())
                    {
                        foreach (var item in _Agrupados)
                        {
                            var _NombrePais = new SSP.Controlador.Catalogo.Justicia.cPaises().GetData(x => x.ID_PAIS_NAC == item.Key).FirstOrDefault();
                            if (_NombrePais == null)
                            {
                                _NoUbicados        = _NoUbicados + item.Count();
                                _HombresNoUbicados = _HombresNoUbicados + (item.Any() ? item.Count(x => x.IMPUTADO != null && x.IMPUTADO.SEXO == "M") : 0);
                                _MujeresNoUbicadas = _MujeresNoUbicadas + (item.Any() ? item.Count(x => x.IMPUTADO != null && x.IMPUTADO.SEXO == "F") : 0);
                                continue;
                            }
                            else
                            if (string.IsNullOrEmpty(_NombrePais.PAIS))
                            {
                                _NoUbicados        = _NoUbicados + item.Count();
                                _HombresNoUbicados = _HombresNoUbicados + (item.Any() ? item.Count(x => x.IMPUTADO != null && x.IMPUTADO.SEXO == "M") : 0);
                                _MujeresNoUbicadas = _MujeresNoUbicadas + (item.Any() ? item.Count(x => x.IMPUTADO != null && x.IMPUTADO.SEXO == "F") : 0);
                                continue;
                            }
                            else
                            {
                                listaIngresosActivos.Add(new cReporteIngresosActivosCierre
                                {
                                    TotalM     = item.Any() ? item.Count(x => x.IMPUTADO != null && x.IMPUTADO.SEXO == "F") : 0,
                                    TotalH     = item.Any() ? item.Count(x => x.IMPUTADO != null && x.IMPUTADO.SEXO == "M") : 0,
                                    NombrePais = _NombrePais != null ? !string.IsNullOrEmpty(_NombrePais.PAIS) ? _NombrePais.PAIS.Trim() : "SIN CAPTURAR" : "SIN CAPTURAR",
                                    GrandTotal = item.Count(x => x.IMPUTADO != null && x.IMPUTADO.SEXO == "M") + item.Count(x => x.IMPUTADO != null && x.IMPUTADO.SEXO == "F")
                                });
                            }
                        }
                        ;

                        //Ya tengo el condensado de las personas que no tienen pais
                        listaIngresosActivos.Add(new cReporteIngresosActivosCierre
                        {
                            NombrePais = "SIN CAPTURAR",
                            TotalH     = _HombresNoUbicados,
                            TotalM     = _MujeresNoUbicadas,
                            GrandTotal = _HombresNoUbicados + _MujeresNoUbicadas
                        });
                    }
                }
                ;

                Reporte.LocalReport.ReportPath = "Reportes/rReporteIngresosActivosCierre.rdlc";
                Reporte.LocalReport.DataSources.Clear();

                Microsoft.Reporting.WinForms.ReportDataSource ReportDataSource_Encabezado = new Microsoft.Reporting.WinForms.ReportDataSource();
                ReportDataSource_Encabezado.Name  = "DataSet1";
                ReportDataSource_Encabezado.Value = encabezado;

                Microsoft.Reporting.WinForms.ReportDataSource ReportDataSource_Motivos = new Microsoft.Reporting.WinForms.ReportDataSource();
                ReportDataSource_Motivos.Name  = "DataSet2";
                ReportDataSource_Motivos.Value = listaIngresosActivos != null?listaIngresosActivos.Any() ? listaIngresosActivos.OrderBy(x => x.NombrePais).ToList() : new List <cReporteIngresosActivosCierre>() : new List <cReporteIngresosActivosCierre>();

                Reporte.LocalReport.DataSources.Add(ReportDataSource_Encabezado);
                Reporte.LocalReport.DataSources.Add(ReportDataSource_Motivos);

                System.Windows.Application.Current.Dispatcher.Invoke((System.Action)(delegate
                {
                    Reporte.Refresh();
                    Reporte.RefreshReport();
                }));
            }

            catch (System.Exception exc)
            {
                throw;
            }
        }
예제 #9
0
파일: Module.cs 프로젝트: tnsr1/AntlrVSIX
        public static IEnumerable <DocumentSymbol> Get(Workspaces.Range range, Document doc)
        {
            ParserDetails pd = ParserDetailsFactory.Create(doc);

            if (pd.ParseTree == null)
            {
                LanguageServer.Module.Compile();
            }

            List <DocumentSymbol> combined = new System.Collections.Generic.List <DocumentSymbol>();

            foreach (KeyValuePair <TerminalNodeImpl, int> p in pd.Tags)
            {
                if (p.Key.Symbol == null)
                {
                    continue;
                }

                int start_token_start = p.Key.Symbol.StartIndex;
                int end_token_end     = p.Key.Symbol.StopIndex + 1;
                if (start_token_start > range.End.Value)
                {
                    continue;
                }

                if (end_token_end < range.Start.Value)
                {
                    continue;
                }

                combined.Add(
                    new DocumentSymbol()
                {
                    name  = p.Key.Symbol.Text,
                    range = new Workspaces.Range(p.Key.Symbol.StartIndex, p.Key.Symbol.StopIndex),
                    kind  = p.Value
                });
            }
            foreach (KeyValuePair <Antlr4.Runtime.IToken, int> p in pd.Comments)
            {
                int start_token_start = p.Key.StartIndex;
                int end_token_end     = p.Key.StopIndex + 1;
                if (start_token_start > range.End.Value)
                {
                    continue;
                }

                if (end_token_end < range.Start.Value)
                {
                    continue;
                }

                combined.Add(
                    new DocumentSymbol()
                {
                    name  = p.Key.Text,
                    range = new Workspaces.Range(p.Key.StartIndex, p.Key.StopIndex),
                    kind  = p.Value
                });
            }

            // Sort the list.
            IEnumerable <DocumentSymbol>        result;
            IOrderedEnumerable <DocumentSymbol> sorted_combined_tokens = combined.OrderBy(t => t.range.Start.Value).ThenBy(t => t.range.End.Value);

            result = sorted_combined_tokens;
            return(result);
        }
예제 #10
0
        private static bool Check(string country, System.Collections.Generic.List <Referential> referential, CalendariumConfiguration cal, string region, List <string> listErrors)
        {
            if (country != "Algeria")
            {
                return(true);
            }

            if (!cal.GetKeys(country).Any())
            {
                return(false);
            }

            Trace.WriteLine($"Starting {country.ToString()}");

            var calendar = cal.GetConfigurationByCountry(country)[0].Calendar.GetCalendar();

            foreach (var item in referential)
            {
                item.Date2 = GetExpectedDate(item, calendar);
                if (item.ObservedDate != null)
                {
                    item.ObservedDate.Date2 = GetExpectedDate(item.ObservedDate, calendar);
                }
            }

            foreach (var item in referential.Where(c => c.Reconstitued && c.Date2 == c.ObservedDate.Date2).ToList())
            {
                var it = referential.Where(c => c.DayName == item.DayName && !c.Reconstitued).ToList();
                if (it.Count == 0)
                {
                }
                else
                {
                    var it2 = it.Where(c => c.DayName == item.DayName && !c.Reconstitued).Select(c => ($"{c.Date2.Month}-{c.Date2.Day}")).Distinct().ToList();
                    if (it2.Count == 1)
                    {
                        item.Date2 = new DateTime(item.Date2.Year, it[0].Date2.Month, it[0].Date2.Day); //not specify calendar is wrong only if the calendar is not gregorian.
                    }
                    else
                    {
                    }
                }
            }

            var _l2 = referential.OrderBy(c => c.Date2).ToList();

            foreach (var item in _l2)
            {
                var year = item.Date2.Year;
                List <EventDate> dates1 = GetEvents(country, cal, year, CalendarEnum.Default); // flat list
                List <EventDate> dates  = GetEvents(dates1, item.DayName);

                if (dates.Count == 0)
                {
                    listErrors.Add($"failed on '{item.DayName.Mark(Mark.Bold)}' expected : {item.Date2.ToString("D")} missing day\r\n");
                }

                else
                {
                    var date = dates.FirstOrDefault(c => c.Date == item.Date2);
                    if (date == null)
                    {
                        if (CountryDebugger.CheckStop(country, item.DayName, item.Date2.Year))
                        {
                            System.Diagnostics.Debugger.Break();
                        }

                        if (dates.Count == 1)
                        {
                            listErrors.Add($"failed on '{item.DayName}' expected : {item.Date2.ToString("D")} and computed : {dates[0].Date.ToString("D")}\r\n");
                        }

                        else
                        {
                        }
                    }
                    else
                    {
                        var date1 = dates[0];

                        if (item.ObservedDate != null)
                        {
                            if (date1.Observed.OriginalDate.Date != item.ObservedDate.Date2.Date)
                            {
                                listErrors.Add($"failed match observed date on '{item.DayName}' expected : {item.ObservedDate.Date2.ToString("D")} and computed :  {date1.Observed.ToString("D")}\r\n");
                            }
                        }
                        else if (date1.Observed != null && date1.Observed.OriginalDate.Date.Date != date1.Date.OriginalDate.Date)
                        {
                            listErrors.Add($"missing observed date in expected referential on '{item.DayName}' computed : {date1.Observed.ToString("D")}\r\n");
                        }
                    }
                }
            }

            return(true);
        }
예제 #11
0
        List<mTuple<bool, SubCalendarEvent>> stitchUnRestrictedSubCalendarEvent(TimeLine FreeBoundary, List<mTuple<bool, SubCalendarEvent>> restrictedSnugFitAvailable, Dictionary<TimeSpan, Dictionary<string, mTuple<bool, SubCalendarEvent>>> PossibleEntries, Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> CompatibleWithList,double Occupancy)
        {
            TimeLine[] AllFreeSpots = FreeBoundary.getAllFreeSlots();
            int TotalEventsForThisTImeLine = 0;

            foreach (KeyValuePair<TimeSpan, mTuple<int, TimeSpanWithStringID>> eachKeyValuePair in CompatibleWithList)
            {
                TotalEventsForThisTImeLine += eachKeyValuePair.Value.Item1;
            }

            CompatibleWithList.Clear();


            DateTime EarliestReferenceTIme = FreeBoundary.Start;
            List<mTuple<bool, SubCalendarEvent>> FrontPartials = new System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>();
            List<mTuple<bool, SubCalendarEvent>> EndPartials = new System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>();
            Dictionary<DateTime, List<mTuple<bool, SubCalendarEvent>>> FrontPartials_Dict = new System.Collections.Generic.Dictionary<DateTime, System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>>();
            Dictionary<DateTime, List<mTuple<bool, SubCalendarEvent>>> EndPartials_Dict = new System.Collections.Generic.Dictionary<DateTime, System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>>();
            Dictionary<TimeSpan, Dictionary<string, mTuple<bool, SubCalendarEvent>>> PossibleEntries_Cpy = new Dictionary<TimeSpan, Dictionary<string, mTuple<bool, SubCalendarEvent>>>();
            Dictionary<string, Dictionary<string, SubCalendarEvent>> CalendarIDAndNonPartialSubCalEvents = new Dictionary<string, Dictionary<string, SubCalendarEvent>>();//List of non partials for current Reference StartTime To End of FreeBoundary. Its gets updated with Partials once the earliest reference time passes the partial event start time

            foreach (KeyValuePair<TimeSpan, Dictionary<string, mTuple<bool, SubCalendarEvent>>> eachKeyValuePair in PossibleEntries)//populates PossibleEntries_Cpy. I need a copy to maintain all references to PossibleEntries
            {
                Dictionary<string, mTuple<bool, SubCalendarEvent>> NewDictEntry = new Dictionary<string, mTuple<bool, SubCalendarEvent>>();
                
                foreach (KeyValuePair<string, mTuple<bool, SubCalendarEvent>> KeyValuePair0 in eachKeyValuePair.Value)
                {
                    mTuple<bool, SubCalendarEvent> MyEvent = KeyValuePair0.Value;

                    if (MyEvent.Item2.ID == "469_471")
                    {
                        ;
                    }

                    bool isInrestrictedSnugFitAvailable = false;
                    if (CompatibleWithList.ContainsKey(eachKeyValuePair.Key))
                    {
                        ++CompatibleWithList[eachKeyValuePair.Key].Item1;
                    }
                    else
                    {
                        CompatibleWithList.Add(eachKeyValuePair.Key, new mTuple<int, TimeSpanWithStringID>(1, new TimeSpanWithStringID(KeyValuePair0.Value.Item2.ActiveDuration, KeyValuePair0.Value.Item2.ActiveDuration.Ticks.ToString())));
                    }

                    foreach (mTuple<bool, SubCalendarEvent> eachMtuple in restrictedSnugFitAvailable)//checks if event is in restricted list
                    {
                        if (eachMtuple.Item2.ID == MyEvent.Item2.ID)
                        {
                            isInrestrictedSnugFitAvailable = true;
                            break;
                        }

                    }


                    if (!isInrestrictedSnugFitAvailable)
                    {
                        NewDictEntry.Add(KeyValuePair0.Value.Item2.ID, KeyValuePair0.Value);
                        if (FreeBoundary.IsDateTimeWithin(KeyValuePair0.Value.Item2.getCalendarEventRange.Start))
                        {
                            FrontPartials.Add(KeyValuePair0.Value);
                        }
                        else
                        {
                            if (FreeBoundary.IsDateTimeWithin(KeyValuePair0.Value.Item2.getCalendarEventRange.End))
                            {
                                EndPartials.Add(KeyValuePair0.Value);
                            }
                            else 
                            {
                                string CalLevel0ID=KeyValuePair0.Value.Item2.SubEvent_ID.getLevelID(0);
                                if (CalendarIDAndNonPartialSubCalEvents.ContainsKey(CalLevel0ID))
                                {
                                    CalendarIDAndNonPartialSubCalEvents[CalLevel0ID].Add(KeyValuePair0.Value.Item2.ID, KeyValuePair0.Value.Item2);
                                }
                                else 
                                {
                                    //CalendarIDAndNonPartialSubCalEvents.Add(CalLevel0ID, new List<SubCalendarEvent>() { KeyValuePair0.Value.Item2 });
                                    CalendarIDAndNonPartialSubCalEvents.Add(CalLevel0ID, new Dictionary<string, SubCalendarEvent>());
                                    CalendarIDAndNonPartialSubCalEvents[CalLevel0ID].Add(KeyValuePair0.Value.Item2.ID, KeyValuePair0.Value.Item2);
                                }
                            
                            }
                        }
                    }
                }
                if (NewDictEntry.Count > 0)
                { PossibleEntries_Cpy.Add(eachKeyValuePair.Key, NewDictEntry); }

            }

            FrontPartials = FrontPartials.OrderBy(obj => obj.Item2.getCalendarEventRange.Start).ToList();
            EndPartials = EndPartials.OrderBy(obj => obj.Item2.getCalendarEventRange.End).ToList();

            foreach (mTuple<bool, SubCalendarEvent> eachmTuple in FrontPartials)//populates FrontPartials_Dict in ordered manner since FrontPartials is ordered
            {
                if (FrontPartials_Dict.ContainsKey(eachmTuple.Item2.getCalendarEventRange.Start))
                {
                    FrontPartials_Dict[eachmTuple.Item2.getCalendarEventRange.Start].Add(eachmTuple);
                }
                else
                {
                    FrontPartials_Dict.Add(eachmTuple.Item2.getCalendarEventRange.Start, new System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>() { eachmTuple });
                }

            }

            foreach (mTuple<bool, SubCalendarEvent> eachmTuple in EndPartials)//populates EndPartials_Dict in ordered manner since EndPartials is ordered
            {
                if (EndPartials_Dict.ContainsKey(eachmTuple.Item2.getCalendarEventRange.Start))
                {
                    EndPartials_Dict[eachmTuple.Item2.getCalendarEventRange.Start].Add(eachmTuple);
                }
                else
                {
                    EndPartials_Dict.Add(eachmTuple.Item2.getCalendarEventRange.Start, new System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>() { eachmTuple });
                }
            }


            List<SubCalendarEvent> CompleteArranegement = new System.Collections.Generic.List<SubCalendarEvent>();
            int StartingReferneceIndex = 0;


            /*foreach (mTuple<bool, SubCalendarEvent> eachmTuple in restrictedSnugFitAvailable)//removes the restricted from CompatibleWithList
            {
                --CompatibleWithList[eachmTuple.Item2.ActiveDuration.Ticks.ToString()].Item1;
                //PossibleEntries_Cpy[eachmTuple.Item2.ActiveDuration.Ticks.ToString()].Remove(eachmTuple.Item2.ID);
            }*/

            List<DateTime> ListOfFrontPartialsStartTime = FrontPartials_Dict.Keys.ToList();

            int i = 0;
            int j = 0;
            int FrontPartialCounter = 0;

            if (restrictedSnugFitAvailable.Count < 1)
            {
                ;
            }

            Tuple<DateTime, List<SubCalendarEvent>> TimeLineUpdated = null;
            SubCalendarEvent BorderElementBeginning = null;
            SubCalendarEvent BorderElementEnd = null;
            SubCalendarEvent LastSubCalElementForEarlierReferenceTime = null;
            for (; i < restrictedSnugFitAvailable.Count; i++)
            {
                //bool isFreeSpotBeforeRigid = AllFreeSpots[i].End <= restrictedSnugFitAvailable[i].Item2.Start;
                TimeLineUpdated = null;

                if (CompleteArranegement.Count == 46)
                {
                    ;
                }

                if (i ==2)
                {
                    ;
                }

                restrictedSnugFitAvailable[i].Item2.PinSubEventsToStart(new TimeLine(EarliestReferenceTIme, restrictedSnugFitAvailable[i].Item2.getCalendarEventRange.End));
                List<BusyTimeLine> RestrictedBusySlots = new System.Collections.Generic.List<BusyTimeLine>();
                FreeBoundary = new TimeLine(FreeBoundary.Start, FreeBoundary.End);
                foreach (mTuple<bool, SubCalendarEvent> eachmTuple in restrictedSnugFitAvailable)
                {
                    eachmTuple.Item1 = true;
                    RestrictedBusySlots.Add(eachmTuple.Item2.ActiveSlot);
                    string timeSpanString = eachmTuple.Item2.ActiveDuration.Ticks.ToString();
                    string SubEventID = eachmTuple.Item2.ID;

                }
                FreeBoundary.AddBusySlots(RestrictedBusySlots.ToArray());

                List<SubCalendarEvent> LowestCostArrangement = new System.Collections.Generic.List<SubCalendarEvent>();
                TimeLine PertinentFreeSpot = null;
                TimeLine FreeSpotUpdated = null;
                j = i + 1;
                if (ListOfFrontPartialsStartTime.Count > 0)//fits any sub calEvent in preceeding restricting free spot
                {
                    DateTime RestrictedStopper = restrictedSnugFitAvailable[i].Item2.Start;


                    bool breakForLoop = false;
                    bool PreserveRestrictedIndex = false;
                    for (; FrontPartialCounter < ListOfFrontPartialsStartTime.Count; FrontPartialCounter++)
                    {
                        TimeLineUpdated = null;
                        DateTime PertinentFreeSpotStart = EarliestReferenceTIme;
                        DateTime PertinentFreeSpotEnd;
                        if (CompleteArranegement.Count == 46)
                        {
                            ;
                        }
                        if ((ListOfFrontPartialsStartTime[FrontPartialCounter] < RestrictedStopper))
                        {
                            PertinentFreeSpotEnd = ListOfFrontPartialsStartTime[FrontPartialCounter];
                            //FrontPartials_Dict.Remove(ListOfFrontPartialsStartTime[FrontPartialCounter]);
                            ListOfFrontPartialsStartTime.RemoveAt(FrontPartialCounter);
                            --FrontPartialCounter;
                            PreserveRestrictedIndex = true;
                        }
                        else
                        {
                            PertinentFreeSpotEnd = RestrictedStopper;

                            if (breakForLoop)
                            {//populates with final boundary for each restricted
                                PertinentFreeSpot = new TimeLine(PertinentFreeSpotStart, PertinentFreeSpotEnd);

                                BorderElementBeginning = CompleteArranegement.Count>0?CompleteArranegement[CompleteArranegement.Count-1]:null;//Checks if Complete arrangement has partially being filled. Sets Last elements as boundary Element
                                BorderElementEnd = restrictedSnugFitAvailable[i].Item2;//uses restricted value as boundary element
                                LowestCostArrangement = OptimizeArrangeOfSubCalEvent(PertinentFreeSpot, new Tuple<SubCalendarEvent, SubCalendarEvent>(BorderElementBeginning, BorderElementEnd), CompatibleWithList.Values.ToList(), PossibleEntries_Cpy,Occupancy);
                                DateTime EarliestTimeForBetterEarlierReferenceTime = PertinentFreeSpot.Start;
                                LastSubCalElementForEarlierReferenceTime = ((CompleteArranegement.Count < 1) || (CompleteArranegement == null) ? null : CompleteArranegement[CompleteArranegement.Count - 1]);
                                    FreeSpotUpdated = PertinentFreeSpot.CreateCopy();
                                if (LowestCostArrangement.Count > 0)
                                {
                                    if (!(LowestCostArrangement[0].getCalendarEventRange.Start == PertinentFreeSpot.Start))//Pin SubEvents To Start
                                    {//if the first element is not a partial Sub Cal Event element
                                        FreeSpotUpdated = new TimeLine(EarliestReferenceTIme, PertinentFreeSpot.End);
                                        Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);
                                    }
                                    else
                                    {
                                        FreeSpotUpdated = PertinentFreeSpot.CreateCopy();// new TimeLine(LowestCostArrangement[0].getCalendarEventRange.Start, PertinentFreeSpot.End);
                                        Utility.PinSubEventsToStart(LowestCostArrangement, PertinentFreeSpot);
                                    }
                                    EarliestReferenceTIme = PertinentFreeSpot.End;// LowestCostArrangement[LowestCostArrangement.Count - 1].End;

                                    SubCalendarEvent LastSubCalEvent = LowestCostArrangement[LowestCostArrangement.Count - 1];
                                    EarliestTimeForBetterEarlierReferenceTime = LastSubCalEvent.End;
                                    LastSubCalElementForEarlierReferenceTime = LastSubCalEvent;
                                    
                                }
                                TimeLineUpdated = null;
                                TimeLineUpdated = ObtainBetterEarlierReferenceTime(LowestCostArrangement, CalendarIDAndNonPartialSubCalEvents, RestrictedStopper - EarliestTimeForBetterEarlierReferenceTime, EarliestReferenceTIme, new TimeLine(FreeSpotUpdated.Start, FreeBoundary.End), LastSubCalElementForEarlierReferenceTime);
                                if (TimeLineUpdated != null)
                                {
                                    LowestCostArrangement = TimeLineUpdated.Item2;
                                    EarliestReferenceTIme = TimeLineUpdated.Item1;
                                }
                                

                                foreach (SubCalendarEvent eachSubCalendarEvent in LowestCostArrangement)
                                {
                                    --CompatibleWithList[eachSubCalendarEvent.ActiveDuration].Item1;
                                    PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Remove(eachSubCalendarEvent.ID);
                                    string SubCalString = eachSubCalendarEvent.SubEvent_ID.getLevelID(0);
                                    if (CalendarIDAndNonPartialSubCalEvents.ContainsKey(SubCalString))
                                    {
                                        CalendarIDAndNonPartialSubCalEvents[SubCalString].Remove(eachSubCalendarEvent.ID);
                                        if (CalendarIDAndNonPartialSubCalEvents[SubCalString].Count < 1)
                                        {
                                            CalendarIDAndNonPartialSubCalEvents.Remove(SubCalString);
                                        }
                                    }
                                    if (PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Count < 1)
                                    {
                                        PossibleEntries_Cpy.Remove(eachSubCalendarEvent.ActiveDuration);
                                    }
                                }


                                LowestCostArrangement = CompleteArranegement.Concat(LowestCostArrangement).ToList();
                                LowestCostArrangement = PlaceSubCalEventInLowestCostPosition(FreeBoundary, restrictedSnugFitAvailable[i].Item2, LowestCostArrangement);
                                Utility.PinSubEventsToStart(LowestCostArrangement, FreeBoundary);

                                CompleteArranegement = LowestCostArrangement;
                                EarliestReferenceTIme = LowestCostArrangement[LowestCostArrangement.Count - 1].End;

                                PreserveRestrictedIndex = false;
                                break;
                            }

                            --FrontPartialCounter;
                            if (j < restrictedSnugFitAvailable.Count)
                            {
                                RestrictedStopper = restrictedSnugFitAvailable[i].Item2.getCalendarEventRange.End > restrictedSnugFitAvailable[j].Item2.Start ? restrictedSnugFitAvailable[j].Item2.Start : restrictedSnugFitAvailable[i].Item2.getCalendarEventRange.End;
                            }
                            else
                            {
                                RestrictedStopper = restrictedSnugFitAvailable[i].Item2.getCalendarEventRange.End > FreeBoundary.End ? FreeBoundary.End : restrictedSnugFitAvailable[i].Item2.getCalendarEventRange.End;
                            }
                            RestrictedStopper -= restrictedSnugFitAvailable[i].Item2.ActiveDuration;
                            breakForLoop = true;
                        }
                        PertinentFreeSpot = new TimeLine(PertinentFreeSpotStart, PertinentFreeSpotEnd);

                        BorderElementBeginning = CompleteArranegement.Count > 0 ? CompleteArranegement[CompleteArranegement.Count - 1] : null;//Checks if Complete arrangement has partially being filled. Sets Last elements as boundary Element
                        BorderElementEnd = restrictedSnugFitAvailable[i].Item2;//uses restricted value as boundary element

                        LowestCostArrangement = OptimizeArrangeOfSubCalEvent(PertinentFreeSpot, new Tuple<SubCalendarEvent, SubCalendarEvent>(BorderElementBeginning, BorderElementEnd), CompatibleWithList.Values.ToList(), PossibleEntries_Cpy, Occupancy);
                        DateTime LatestDaterforEarlierReferenceTime = PertinentFreeSpot.Start;
                        LastSubCalElementForEarlierReferenceTime = ((CompleteArranegement.Count < 1) || (CompleteArranegement == null) ? null : CompleteArranegement[CompleteArranegement.Count - 1]);//updates the last element as either null or the last element in the current Complete arrangement
                        FreeSpotUpdated = PertinentFreeSpot.CreateCopy();
                        if (LowestCostArrangement.Count > 0)
                        {
                            if (!(LowestCostArrangement[0].getCalendarEventRange.Start == PertinentFreeSpot.Start))//Pin SubEvents To Start
                            {//if the first element is not a partial Sub Cal Event element
                                FreeSpotUpdated = new TimeLine(EarliestReferenceTIme, PertinentFreeSpot.End);
                                Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);

                            }
                            else
                            {
                                //FreeSpotUpdated = new TimeLine(LowestCostArrangement[0].getCalendarEventRange.Start, PertinentFreeSpot.End);
                                FreeSpotUpdated = PertinentFreeSpot.CreateCopy();
                                Utility.PinSubEventsToStart(LowestCostArrangement, PertinentFreeSpot);
                            }
                            EarliestReferenceTIme = PertinentFreeSpot.End;
                            
                            ///Comeback to this
                            ///
                            SubCalendarEvent LastSubCalEvent = LowestCostArrangement[LowestCostArrangement.Count - 1];
                            LatestDaterforEarlierReferenceTime = LastSubCalEvent.End;
                            LastSubCalElementForEarlierReferenceTime = LastSubCalEvent;
                        }

                        TimeLineUpdated = ObtainBetterEarlierReferenceTime(LowestCostArrangement, CalendarIDAndNonPartialSubCalEvents, RestrictedStopper - LatestDaterforEarlierReferenceTime, EarliestReferenceTIme, new TimeLine(FreeSpotUpdated.Start, FreeBoundary.End), LastSubCalElementForEarlierReferenceTime);
                        //errorline
                        
                        if (TimeLineUpdated != null)
                        {
                            LowestCostArrangement = TimeLineUpdated.Item2;
                            EarliestReferenceTIme = TimeLineUpdated.Item1;
                        }
                        

                        foreach (SubCalendarEvent eachSubCalendarEvent in LowestCostArrangement)
                        {
                            --CompatibleWithList[eachSubCalendarEvent.ActiveDuration].Item1;
                            PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Remove(eachSubCalendarEvent.ID);
                            string SubCalString = eachSubCalendarEvent.SubEvent_ID.getLevelID(0);
                            if (CalendarIDAndNonPartialSubCalEvents.ContainsKey(SubCalString))
                            {
                                CalendarIDAndNonPartialSubCalEvents[SubCalString].Remove(eachSubCalendarEvent.ID);
                                if (CalendarIDAndNonPartialSubCalEvents[SubCalString].Count < 1)
                                {
                                    CalendarIDAndNonPartialSubCalEvents.Remove(SubCalString);
                                }
                            }
                            if (PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Count < 1)
                            {
                                PossibleEntries_Cpy.Remove(eachSubCalendarEvent.ActiveDuration);
                            }
                        }
                        CompleteArranegement.AddRange(LowestCostArrangement);


                        int DateTimeCounter = 0;
                        for (; DateTimeCounter < FrontPartials_Dict.Keys.Count; DateTimeCounter++)//updates CalendarIDAndNonPartialSubCalEvents if frontpartial Startime has been passed. Alls updates FrontPartials_Dict
                        {
                            DateTime eachDateTIme = FrontPartials_Dict.Keys.ToList()[DateTimeCounter];
                            if (EarliestReferenceTIme >= eachDateTIme)
                            {
                                List<mTuple<bool, SubCalendarEvent>> mTUpleSubCalEvents = FrontPartials_Dict[eachDateTIme];
                                foreach (mTuple<bool, SubCalendarEvent> eachmTUple in mTUpleSubCalEvents)
                                {

                                    string CalLevel0ID = eachmTUple.Item2.SubEvent_ID.getLevelID(0);
                                    if (!CompleteArranegement.Contains(eachmTUple.Item2))
                                    {
                                        if (CalendarIDAndNonPartialSubCalEvents.ContainsKey(CalLevel0ID))
                                        {
                                            CalendarIDAndNonPartialSubCalEvents[CalLevel0ID].Add(eachmTUple.Item2.ID, eachmTUple.Item2);
                                        }
                                        else
                                        {
                                            //CalendarIDAndNonPartialSubCalEvents.Add(CalLevel0ID, new List<SubCalendarEvent>() { KeyValuePair0.Value.Item2 });
                                            CalendarIDAndNonPartialSubCalEvents.Add(CalLevel0ID, new Dictionary<string, SubCalendarEvent>());
                                            CalendarIDAndNonPartialSubCalEvents[CalLevel0ID].Add(eachmTUple.Item2.ID, eachmTUple.Item2);
                                        }
                                    }
                                }
                                FrontPartials_Dict.Remove(eachDateTIme);
                            }
                        }


                    }
                    if (PreserveRestrictedIndex)//verifies if we took the path of restricted or front partial element. The latter needs a preservation of the current restricted Subcalevent index index 
                    {
                        --i;
                    }
                }
                else
                {//No FrontPartials
                    DateTime ReferenceEndTime = restrictedSnugFitAvailable[i].Item2.Start;
                    PertinentFreeSpot = new TimeLine(EarliestReferenceTIme, ReferenceEndTime);

                    BorderElementBeginning = CompleteArranegement.Count > 0 ? CompleteArranegement[CompleteArranegement.Count - 1] : null;//Checks if Complete arrangement has partially being filled. Sets Last elements as boundary Element
                    BorderElementEnd = restrictedSnugFitAvailable[i].Item2;//uses restricted value as boundary element

                    LowestCostArrangement = OptimizeArrangeOfSubCalEvent(PertinentFreeSpot, new Tuple<SubCalendarEvent, SubCalendarEvent>(BorderElementBeginning, BorderElementEnd), CompatibleWithList.Values.ToList(), PossibleEntries_Cpy,Occupancy);

                    if (LowestCostArrangement.Count > 0)
                    {
                        if (!(LowestCostArrangement[0].getCalendarEventRange.Start == PertinentFreeSpot.Start))//Pin SubEvents To Start
                        {//if the first element is not a partial Sub Cal Event element
                            FreeSpotUpdated = new TimeLine(EarliestReferenceTIme, PertinentFreeSpot.End);
                            Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);
                        }
                        else
                        {
                            FreeSpotUpdated = new TimeLine(LowestCostArrangement[0].getCalendarEventRange.Start, PertinentFreeSpot.End);
                            Utility.PinSubEventsToStart(LowestCostArrangement, PertinentFreeSpot);
                        }
                        EarliestReferenceTIme = FreeSpotUpdated.End;// LowestCostArrangement[LowestCostArrangement.Count - 1].End;
                    }

                    foreach (SubCalendarEvent eachSubCalendarEvent in LowestCostArrangement)
                    {
                        --CompatibleWithList[eachSubCalendarEvent.ActiveDuration].Item1;
                        PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Remove(eachSubCalendarEvent.ID);
                        string SubCalString = eachSubCalendarEvent.SubEvent_ID.getLevelID(0);
                        if (CalendarIDAndNonPartialSubCalEvents.ContainsKey(SubCalString))
                        {
                            CalendarIDAndNonPartialSubCalEvents[SubCalString].Remove(eachSubCalendarEvent.ID);
                            if (CalendarIDAndNonPartialSubCalEvents[SubCalString].Count < 1)
                            {
                                CalendarIDAndNonPartialSubCalEvents.Remove(SubCalString);
                            }
                        }
                        if (PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Count < 1)
                        {
                            PossibleEntries_Cpy.Remove(eachSubCalendarEvent.ActiveDuration);
                        }
                    }


                    List<SubCalendarEvent> AdditionalCOstArrangement = new System.Collections.Generic.List<SubCalendarEvent>();
                    if (j < restrictedSnugFitAvailable.Count)
                    {
                        DateTime StartDateTimeAfterFitting = PertinentFreeSpot.End;//this is the barring end time of the preceding boundary search

                        DateTime RelativeEndTime = restrictedSnugFitAvailable[i].Item2.getCalendarEventRange.End > restrictedSnugFitAvailable[j].Item2.Start ? restrictedSnugFitAvailable[j].Item2.Start : restrictedSnugFitAvailable[i].Item2.getCalendarEventRange.End;

                        RelativeEndTime -= restrictedSnugFitAvailable[i].Item2.ActiveDuration;
                        TimeLine CurrentlyFittedTimeLine = new TimeLine(StartDateTimeAfterFitting, RelativeEndTime);

                        BorderElementBeginning = CompleteArranegement.Count > 0 ? CompleteArranegement[CompleteArranegement.Count - 1] : null;//Checks if Complete arrangement has partially being filled. Sets Last elements as boundary Element
                        BorderElementEnd = restrictedSnugFitAvailable[i].Item2;//uses restricted value as boundary element

                        AdditionalCOstArrangement = OptimizeArrangeOfSubCalEvent(CurrentlyFittedTimeLine, new Tuple<SubCalendarEvent, SubCalendarEvent>(BorderElementBeginning, BorderElementEnd), CompatibleWithList.Values.ToList(), PossibleEntries_Cpy, Occupancy);
                        if (AdditionalCOstArrangement.Count > 0)
                        {//Additional get populated
                            if (!(AdditionalCOstArrangement[0].getCalendarEventRange.Start == CurrentlyFittedTimeLine.Start))//Pin SubEvents To Start
                            {//if the first element is not a partial Sub Cal Event element
                                FreeSpotUpdated = new TimeLine(EarliestReferenceTIme, CurrentlyFittedTimeLine.End);
                                Utility.PinSubEventsToStart(AdditionalCOstArrangement, FreeSpotUpdated);
                            }
                            else
                            {
                                FreeSpotUpdated = new TimeLine(AdditionalCOstArrangement[0].getCalendarEventRange.Start, CurrentlyFittedTimeLine.End);
                                Utility.PinSubEventsToStart(AdditionalCOstArrangement, FreeSpotUpdated);
                            }

                            foreach (SubCalendarEvent eachSubCalendarEvent in AdditionalCOstArrangement)
                            {
                                --CompatibleWithList[eachSubCalendarEvent.ActiveDuration].Item1;
                                PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Remove(eachSubCalendarEvent.ID);
                                string SubCalString = eachSubCalendarEvent.SubEvent_ID.getLevelID(0);
                                if (CalendarIDAndNonPartialSubCalEvents.ContainsKey(SubCalString))
                                {
                                    CalendarIDAndNonPartialSubCalEvents[SubCalString].Remove(eachSubCalendarEvent.ID);
                                    if (CalendarIDAndNonPartialSubCalEvents[SubCalString].Count < 1)
                                    {
                                        CalendarIDAndNonPartialSubCalEvents.Remove(SubCalString);
                                    }
                                }
                                if (PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Count < 1)
                                {
                                    PossibleEntries_Cpy.Remove(eachSubCalendarEvent.ActiveDuration);
                                }
                            }


                            RelativeEndTime = AdditionalCOstArrangement[AdditionalCOstArrangement.Count - 1].End;
                            RelativeEndTime += restrictedSnugFitAvailable[i].Item2.ActiveDuration; ;
                            FreeSpotUpdated = new TimeLine(FreeSpotUpdated.Start, RelativeEndTime);
                            AdditionalCOstArrangement = PlaceSubCalEventInLowestCostPosition(FreeSpotUpdated, restrictedSnugFitAvailable[i].Item2, AdditionalCOstArrangement);
                        }
                        else
                        {//if there is no other Restricted in list
                            RelativeEndTime += restrictedSnugFitAvailable[i].Item2.ActiveDuration;

                            CurrentlyFittedTimeLine = new TimeLine(CurrentlyFittedTimeLine.Start, RelativeEndTime);

                            AdditionalCOstArrangement = PlaceSubCalEventInLowestCostPosition(CurrentlyFittedTimeLine, restrictedSnugFitAvailable[i].Item2, AdditionalCOstArrangement);
                        }
                    }
                    else
                    {
                        DateTime RelativeEndTime = restrictedSnugFitAvailable[i].Item2.getCalendarEventRange.End > FreeBoundary.End ? FreeBoundary.End : restrictedSnugFitAvailable[i].Item2.getCalendarEventRange.End;
                        TimeLine CurrentlyFittedTimeLine = new TimeLine(EarliestReferenceTIme, RelativeEndTime);
                        AdditionalCOstArrangement = PlaceSubCalEventInLowestCostPosition(CurrentlyFittedTimeLine, restrictedSnugFitAvailable[i].Item2, AdditionalCOstArrangement);
                    }

                    List<SubCalendarEvent> var2 = new System.Collections.Generic.List<SubCalendarEvent>();//List is a addition of LowestCostArrangement and AdditionalCOstArrangement
                    var2 = LowestCostArrangement.Concat(AdditionalCOstArrangement).ToList();

                    CompleteArranegement.AddRange(LowestCostArrangement);
                    CompleteArranegement.AddRange(AdditionalCOstArrangement);
                    if (CompleteArranegement.Count > 0)
                    {
                        EarliestReferenceTIme = CompleteArranegement[CompleteArranegement.Count - 1].End;
                    }
                }
            }


            { //Handles THe Last Free Space outside of rigids
                TimeLine FreeSpotOutSideRigids = new TimeLine(EarliestReferenceTIme, FreeBoundary.End);
                TimeLine PertinentFreeSpot = new TimeLine(EarliestReferenceTIme, FreeBoundary.End); ;
                TimeLine FreeSpotUpdated;
                List<SubCalendarEvent> LowestCostArrangement;
                if (ListOfFrontPartialsStartTime.Count > 0)
                {
                    for (FrontPartialCounter = 0; FrontPartialCounter < ListOfFrontPartialsStartTime.Count; FrontPartialCounter++)
                    {
                        DateTime PertinentFreeSpotStart = EarliestReferenceTIme;
                        DateTime PertinentFreeSpotEnd;
                        PertinentFreeSpotEnd = ListOfFrontPartialsStartTime[FrontPartialCounter];
                        //FrontPartials_Dict.Remove(ListOfFrontPartialsStartTime[FrontPartialCounter]);
                        ListOfFrontPartialsStartTime.RemoveAt(FrontPartialCounter);
                        --FrontPartialCounter;
                        PertinentFreeSpot = new TimeLine(PertinentFreeSpotStart, PertinentFreeSpotEnd);
                        FreeSpotUpdated = PertinentFreeSpot.CreateCopy();

                        BorderElementBeginning = CompleteArranegement.Count > 0 ? CompleteArranegement[CompleteArranegement.Count - 1] : null;//Checks if Complete arrangement has partially being filled. Sets Last elements as boundary Element
                        BorderElementEnd = null;

                        LowestCostArrangement = OptimizeArrangeOfSubCalEvent(PertinentFreeSpot, new Tuple<SubCalendarEvent, SubCalendarEvent>(BorderElementBeginning, BorderElementEnd), CompatibleWithList.Values.ToList(), PossibleEntries_Cpy, Occupancy);
                        DateTime LatestTimeForBetterEarlierReferenceTime = PertinentFreeSpot.Start;
                        LastSubCalElementForEarlierReferenceTime = ((CompleteArranegement.Count < 1) || (CompleteArranegement == null) ? null : CompleteArranegement[CompleteArranegement.Count - 1]);
                        if (LowestCostArrangement.Count > 0)
                        {
                            if ((LowestCostArrangement[0].getCalendarEventRange.Start != PertinentFreeSpot.Start))//Pin SubEvents To Start
                            {//if the first element is not a partial Sub Cal Event element
                                FreeSpotUpdated = new TimeLine(EarliestReferenceTIme, PertinentFreeSpot.End);
                                Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);

                            }
                            else
                            {
                                FreeSpotUpdated = PertinentFreeSpot.CreateCopy();// new TimeLine(LowestCostArrangement[0].getCalendarEventRange.Start, PertinentFreeSpot.End);
                                Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);
                            }
                            EarliestReferenceTIme = PertinentFreeSpot.End;// LowestCostArrangement[LowestCostArrangement.Count - 1].End;
                            SubCalendarEvent LastSubCalEvent = LowestCostArrangement[LowestCostArrangement.Count - 1];
                            LatestTimeForBetterEarlierReferenceTime = LastSubCalEvent.End;
                            LastSubCalElementForEarlierReferenceTime = LastSubCalEvent;
                            /*
                            Dictionary<string, double> AllValidNodes = CalendarEvent.DistanceToAllNodes(LastSubCalEvent.SubEvent_ID.getLevelID(0));
                            SubCalendarEvent AppendableEVent;
                            foreach (string eachstring in AllValidNodes.Keys)
                            {
                                if (CalendarIDAndNonPartialSubCalEvents.ContainsKey(eachstring))
                                {
                                    AppendableEVent = CalendarIDAndNonPartialSubCalEvents[eachstring].ToList()[0].Value;//Assumes Theres Always an element
                                    

                                    if ((AppendableEVent.ActiveDuration <= (FreeBoundary.End - LastSubCalEvent.End)) && (!LowestCostArrangement.Contains(AppendableEVent)))
                                    {
                                        LowestCostArrangement.Add(AppendableEVent);
                                        CalendarIDAndNonPartialSubCalEvents[eachstring].Remove(AppendableEVent.ID);
                                        if (CalendarIDAndNonPartialSubCalEvents[eachstring].Count < 1)//checks if List is empty. Deletes keyValuepair if list is empty
                                        {
                                            CalendarIDAndNonPartialSubCalEvents.Remove(eachstring);
                                        }
                                        FreeSpotUpdated = new TimeLine(FreeSpotUpdated.Start, FreeBoundary.End);
                                        Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);
                                        EarliestReferenceTIme = AppendableEVent.End;
                                        break;
                                    }
                                }
                            }*/
                        }


                        TimeLineUpdated = null;
                        TimeLineUpdated = ObtainBetterEarlierReferenceTime(LowestCostArrangement, CalendarIDAndNonPartialSubCalEvents, FreeBoundary.End - LatestTimeForBetterEarlierReferenceTime, EarliestReferenceTIme, new TimeLine(FreeSpotUpdated.Start, FreeBoundary.End), LastSubCalElementForEarlierReferenceTime);
                        if (TimeLineUpdated != null)
                        {
                            LowestCostArrangement = TimeLineUpdated.Item2;
                            EarliestReferenceTIme = TimeLineUpdated.Item1;
                        }
                        
                        foreach (SubCalendarEvent eachSubCalendarEvent in LowestCostArrangement)
                        {
                            --CompatibleWithList[eachSubCalendarEvent.ActiveDuration].Item1;
                            PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Remove(eachSubCalendarEvent.ID);
                            string SubCalString = eachSubCalendarEvent.SubEvent_ID.getLevelID(0);
                            if (CalendarIDAndNonPartialSubCalEvents.ContainsKey(SubCalString))
                            {
                                CalendarIDAndNonPartialSubCalEvents[SubCalString].Remove(eachSubCalendarEvent.ID);
                                if (CalendarIDAndNonPartialSubCalEvents[SubCalString].Count < 1)
                                {
                                    CalendarIDAndNonPartialSubCalEvents.Remove(SubCalString);
                                }
                            }
                            if (PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Count < 1)
                            {
                                PossibleEntries_Cpy.Remove(eachSubCalendarEvent.ActiveDuration);
                            }
                        }
                        CompleteArranegement.AddRange(LowestCostArrangement);
                    }
                }


                DateTime ReferenceEndTime = FreeBoundary.End;
                PertinentFreeSpot = new TimeLine(EarliestReferenceTIme, ReferenceEndTime);
                /*LowestCostArrangement = OptimizeArrangeOfSubCalEvent(PertinentFreeSpot, new Tuple<SubCalendarEvent, SubCalendarEvent>(null, null), CompatibleWithList.Values.ToList(), PossibleEntries_Cpy);

                if (LowestCostArrangement.Count > 0)
                {
                    if (!(LowestCostArrangement[0].getCalendarEventRange.Start == PertinentFreeSpot.Start))//Pin SubEvents To Start
                    {//if the first element is not a partial Sub Cal Event element
                        FreeSpotUpdated = new TimeLine(EarliestReferenceTIme, PertinentFreeSpot.End);
                        Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);
                    }
                    else
                    {
                        FreeSpotUpdated = PertinentFreeSpot.CreateCopy();// new TimeLine(LowestCostArrangement[0].getCalendarEventRange.Start, PertinentFreeSpot.End);
                        Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);
                    }
                    EarliestReferenceTIme = FreeSpotUpdated.End;// LowestCostArrangement[LowestCostArrangement.Count - 1].End;
                }*/
                BorderElementBeginning = CompleteArranegement.Count > 0 ? CompleteArranegement[CompleteArranegement.Count - 1] : null;//Checks if Complete arrangement has partially being filled. Sets Last elements as boundary Element
                BorderElementEnd = null;

                LowestCostArrangement = OptimizeArrangeOfSubCalEvent(PertinentFreeSpot, new Tuple<SubCalendarEvent, SubCalendarEvent>(BorderElementBeginning, BorderElementEnd), CompatibleWithList.Values.ToList(), PossibleEntries_Cpy, Occupancy);
                LastSubCalElementForEarlierReferenceTime = ((CompleteArranegement.Count < 1) || (CompleteArranegement == null) ? null : CompleteArranegement[CompleteArranegement.Count - 1]);
                DateTime LimitForBetterEarlierReferencTime = EarliestReferenceTIme;
                FreeSpotUpdated = PertinentFreeSpot.CreateCopy();
                if (LowestCostArrangement.Count > 0)
                {
                    if ((LowestCostArrangement[0].getCalendarEventRange.Start != PertinentFreeSpot.Start))//Pin SubEvents To Start
                    {//if the first element is not a partial Sub Cal Event element
                        FreeSpotUpdated = new TimeLine(EarliestReferenceTIme, PertinentFreeSpot.End);
                        Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);

                    }
                    else
                    {
                        FreeSpotUpdated = PertinentFreeSpot.CreateCopy();// new TimeLine(LowestCostArrangement[0].getCalendarEventRange.Start, PertinentFreeSpot.End);
                        Utility.PinSubEventsToStart(LowestCostArrangement, PertinentFreeSpot);
                    }
                    EarliestReferenceTIme = PertinentFreeSpot.End;// LowestCostArrangement[LowestCostArrangement.Count - 1].End;
                    SubCalendarEvent LastSubCalEvent = LowestCostArrangement[LowestCostArrangement.Count - 1];
                    LimitForBetterEarlierReferencTime=LastSubCalEvent.End;
                    LastSubCalElementForEarlierReferenceTime = LastSubCalEvent;
                    
                    
                    
                    /*
                    
                    
                    Dictionary<string, double> AllValidNodes = CalendarEvent.DistanceToAllNodes(LastSubCalEvent.SubEvent_ID.getLevelID(0));
                    SubCalendarEvent AppendableEVent;
                    foreach (string eachstring in AllValidNodes.Keys)
                    {
                        if (CalendarIDAndNonPartialSubCalEvents.ContainsKey(eachstring))
                        {
                            AppendableEVent = CalendarIDAndNonPartialSubCalEvents[eachstring].ToList()[0].Value;//Assumes Theres Always an element

                            if ((AppendableEVent.ActiveDuration <= (FreeBoundary.End - LastSubCalEvent.End)) && (!LowestCostArrangement.Contains(AppendableEVent)))
                            {
                                LowestCostArrangement.Add(AppendableEVent);
                                CalendarIDAndNonPartialSubCalEvents[eachstring].Remove(AppendableEVent.ID);
                                if (CalendarIDAndNonPartialSubCalEvents[eachstring].Count < 1)//checks if List is empty. Deletes keyValuepair if list is empty
                                {
                                    CalendarIDAndNonPartialSubCalEvents.Remove(eachstring);
                                }
                                FreeSpotUpdated = new TimeLine(FreeSpotUpdated.Start, FreeBoundary.End);
                                Utility.PinSubEventsToStart(LowestCostArrangement, FreeSpotUpdated);
                                EarliestReferenceTIme = AppendableEVent.End;
                                break;
                            }
                        }
                    }*/

                }
                TimeLineUpdated = null;
                TimeLineUpdated = ObtainBetterEarlierReferenceTime(LowestCostArrangement, CalendarIDAndNonPartialSubCalEvents, FreeBoundary.End - LimitForBetterEarlierReferencTime, EarliestReferenceTIme, new TimeLine(FreeSpotUpdated.Start, FreeBoundary.End), LastSubCalElementForEarlierReferenceTime);
                if (TimeLineUpdated != null)
                {
                    LowestCostArrangement = TimeLineUpdated.Item2;
                    EarliestReferenceTIme = TimeLineUpdated.Item1;
                }


                foreach (SubCalendarEvent eachSubCalendarEvent in LowestCostArrangement)
                {
                    --CompatibleWithList[eachSubCalendarEvent.ActiveDuration].Item1;
                    PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Remove(eachSubCalendarEvent.ID);
                    string SubCalString = eachSubCalendarEvent.SubEvent_ID.getLevelID(0);
                    if(CalendarIDAndNonPartialSubCalEvents.ContainsKey(SubCalString))
                    {
                        CalendarIDAndNonPartialSubCalEvents[SubCalString].Remove(eachSubCalendarEvent.ID);
                        if (CalendarIDAndNonPartialSubCalEvents[SubCalString].Count < 1)
                        {
                            CalendarIDAndNonPartialSubCalEvents.Remove(SubCalString);
                        }
                    }

                    if (PossibleEntries_Cpy[eachSubCalendarEvent.ActiveDuration].Count < 1)
                    {
                        PossibleEntries_Cpy.Remove(eachSubCalendarEvent.ActiveDuration);
                    }
                }
                CompleteArranegement.AddRange(LowestCostArrangement);

            }






            List<mTuple<bool, SubCalendarEvent>> retValue = new System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>();

            foreach (SubCalendarEvent eachSubCalendarEvent in CompleteArranegement)
            {
                PossibleEntries[eachSubCalendarEvent.ActiveDuration][eachSubCalendarEvent.ID].Item1 = true;
                retValue.Add(PossibleEntries[eachSubCalendarEvent.ActiveDuration][eachSubCalendarEvent.ID]);
            }

            //List<List<SubCalendarEvent>> unrestrictedValidCombinations = generateCombinationForDifferentEntries(CompatibleWithList, PossibleEntries);

            retValue = reAlignSubCalEvents(FreeBoundary, retValue);
            if (TotalEventsForThisTImeLine != retValue.Count)
            {
                ;
            }
            return retValue;

        }
예제 #12
0
파일: Module.cs 프로젝트: wilsonk/AntlrVSIX
        public static IEnumerable <DocumentSymbol> Get(Workspaces.Range range, Document doc)
        {
            var pd = ParserDetailsFactory.Create(doc);

            if (pd.ParseTree == null)
            {
                return(new List <DocumentSymbol>());
            }
            var combined = new System.Collections.Generic.List <DocumentSymbol>();

            foreach (var p in pd.Tags)
            {
                if (p.Key.Symbol == null)
                {
                    continue;
                }
                int start_token_start = p.Key.Symbol.StartIndex;
                int end_token_end     = p.Key.Symbol.StopIndex + 1;
                if (start_token_start > range.End.Value)
                {
                    continue;
                }
                if (end_token_end < range.Start.Value)
                {
                    continue;
                }
                combined.Add(
                    new DocumentSymbol()
                {
                    name  = p.Key.Symbol.Text,
                    range = new Workspaces.Range(p.Key.Symbol.StartIndex, p.Key.Symbol.StopIndex),
                    kind  = p.Value
                });
            }
            foreach (var p in pd.Comments)
            {
                int start_token_start = p.Key.StartIndex;
                int end_token_end     = p.Key.StopIndex + 1;
                if (start_token_start > range.End.Value)
                {
                    continue;
                }
                if (end_token_end < range.Start.Value)
                {
                    continue;
                }
                combined.Add(
                    new DocumentSymbol()
                {
                    name  = p.Key.Text,
                    range = new Workspaces.Range(p.Key.StartIndex, p.Key.StopIndex),
                    kind  = p.Value
                });
            }

            // Sort the list.
            IEnumerable <DocumentSymbol> result;
            var sorted_combined_tokens = combined.OrderBy(t => t.range.Start.Value).ThenBy(t => t.range.End.Value);

            result = sorted_combined_tokens;
            return(result);
        }
 /// <summary>
 /// Initializes the mappings
 /// </summary>
 public void Initialize()
 {
     System.Collections.Generic.List<IMapping> TempMappings = new System.Collections.Generic.List<IMapping>();
     foreach (Type Key in Mappings.Keys)
     {
         foreach (IMapping Mapping in Mappings[Key])
         {
             TempMappings.Add(Mapping);
         }
     }
     foreach (IMapping Mapping in TempMappings.OrderBy(x => x.Order))
     {
         Mapping.Initialize();
     }
 }
예제 #14
0
        public void doResearch(System.String userNmae, System.String pass)
        {
            Uri adminUiri = new Uri("xxxxxxxxxxxxxxxx");
            TfsTeamProjectCollection projectCollection = new
                                                         TfsTeamProjectCollection(adminUiri, new System.Net.NetworkCredential("xxx", "xxxxx"));


            projectCollection.EnsureAuthenticated();
            Workspace workspace        = null;
            Boolean   createdWorkspace = false;
            String    newFolder        = String.Empty;

            VersionControlServer versionControl = projectCollection.GetService <VersionControlServer>();

            var teamProjects = new List <TeamProject>(versionControl.GetAllTeamProjects(false));



            String workspaceName = String.Format("{0}-{1}", Environment.MachineName, "Test");

            try
            {
                workspace = versionControl.GetWorkspace(workspaceName, versionControl.AuthorizedUser);
            }
            catch (WorkspaceNotFoundException)
            {
                workspace        = versionControl.CreateWorkspace(workspaceName, versionControl.AuthorizedUser);
                createdWorkspace = true;
            }
            //int id = workspace.VersionControlServer.GetLatestChangesetId();

            var serverFolder  = String.Format("$/{0}", teamProjects[0].Name) + "/xxxxx";
            var localFolder   = "D:/xxxxxxx/";
            var workingFolder = new WorkingFolder(serverFolder, localFolder);

            // Create a workspace mapping.
            workspace.CreateMapping(workingFolder);

            if (!workspace.HasReadPermission)
            {
                throw new SecurityException(
                          String.Format("{0} does not have read permission for {1}",
                                        versionControl.AuthorizedUser, serverFolder));
            }

            // Get the files from the repository.
            workspace.Get();
            string[] directories = Directory.GetDirectories(workspace.Folders[0].LocalItem);

            System.Collections.Generic.List <SourceElement> fileLiset =
                new System.Collections.Generic.List <SourceElement>();

            foreach (string dir in directories)
            {
                foreach (string file in Directory.GetFiles(dir))
                {
                    string filenamae = System.IO.Path.GetFileName(file);
                    var    lineCount = File.ReadLines(dir + "\\" + filenamae).Count();
                    Item   source    = versionControl.GetItem(file);
                    System.Collections.IEnumerable history = versionControl.QueryHistory(file,
                                                                                         VersionSpec.Latest, 0, RecursionType.Full, null, null, null, 300, true, true, false, false);
                    int numberOfModification = 0;
                    foreach (Changeset item in history)
                    {
                        SourceElement fileElement = new SourceElement();
                        fileElement.filename             = filenamae;
                        fileElement.numberOfModification = numberOfModification;
                        fileElement.contentLenght        = source.ContentLength;
                        fileElement.lineCount            = lineCount;
                        fileElement.startDate            = item.CreationDate;
                        fileLiset.Add(fileElement);
                    }
                }
            }
            var sortedList = fileLiset.OrderBy(x => x.numberOfModification);
            // Loop through keys.
            FileStream   outputFile = new FileStream("TfsQueryResults.txt", FileMode.Create);
            StreamWriter writer     = new StreamWriter(outputFile);

            foreach (var key in sortedList)
            {
                writer.WriteLine("{0}; {1} ;{2}",
                                 key.filename,
                                 key.lineCount,
                                 key.startDate
                                 );
            }
            writer.Close();
        }
예제 #15
0
 public void Shuffle()
 {
     items = items.OrderBy(a => System.Guid.NewGuid()).ToList();
 }