Example #1
0
        // MLE does not work well when the item reponses is either all correct or all incorrect.  See the bottom section on page 354 of Ayala for a discussion of this.
        // In this case, we use the strategy described in the paragraph spanning pages 378-379 of Ayala.
        private bool IsZeroVarianceReponsePattern(List<int> responseVector)
        {
            bool allResponsesIncorrect = responseVector.TrueForAll(x => x == 0);
            bool allResponsesCorrect = responseVector.TrueForAll(x => x == 1);

            return allResponsesCorrect || allResponsesIncorrect;
        }
 internal static GroupType GetGroupType(List<CUEToolsLocalDBEntry> group)
 {
     if (group.Count < 2)
         return GroupType.Single;
     if (!group.TrueForAll(i => i.OffsetSafeCRC != null))
         return GroupType.Unverified;
     if (!group.TrueForAll(i => i.OffsetSafeCRC.DifferByOffset(group[0].OffsetSafeCRC)))
         return GroupType.Different;
     if (!group.TrueForAll(i => i.OffsetSafeCRC == group[0].OffsetSafeCRC))
         return GroupType.Offsetted;
     return GroupType.Equal;
 }
Example #3
0
        /*
         * 1. TrueForAll() - Returns true or false depending on whether if every element in the list matches the condition defined by the specified predicate.
         *
         * 2. AsReadOnly() - Returns a read only wrapper for the current collection. Use this method, if you don't want the client to modify the collection.
         *      i.e add or remove any element from the collection. The ReadOnlyCollection will not have methods to add or remove items from the collection.
         *      You can only read items from the collection.
         *
         * 3. TrimExcess() - Sets the capacity to the actual number of elements in the list, if that number is less than a threshold value.
         *
         * According to MSDN:
         *      This method can be used to minimize a collection's memory overhead if no new wlement will be added to the collection.
         *      The cost of reallocation and copying a large List<T> can be considrable.
         *      So the TrimExcess() method does nothing if the list is at more than 90% of capacity.
         *      This avoids incurring a large reallocation cost for a relatively small gain. The current threshold s 90%, but this could change in the future.
         */
        static void Main(string[] args)
        {
            Customer customer1 = new Customer() { ID = 101, Name = "Anand Dev", Salary = 4000 };
            Customer customer2 = new Customer() { ID = 102, Name = "Nanhi", Salary = 8000 };
            Customer customer3 = new Customer() { ID = 103, Name = "Praveen", Salary = 6000 };

            List<Customer> listCustomers = new List<Customer>();
            listCustomers.Add(customer1);
            listCustomers.Add(customer3);
            listCustomers.Add(customer2);

            #region 1. TrueForAll() method.
            bool trueForAll = listCustomers.TrueForAll(x => x.Salary > 4000);
            Console.WriteLine("Are all salaries greater than 4000 = {0}", trueForAll);
            #endregion

            #region 2. AsReadOnly() method.
            ReadOnlyCollection<Customer> listReadOnlyCustomers = listCustomers.AsReadOnly();
            Console.WriteLine("Number of items = " + listReadOnlyCustomers.Count);
            #endregion

            #region 3. TrimExcess() method.
            List<Customer> listTrimCstomers = new List<Customer>(100);
            listTrimCstomers.AddRange(listCustomers);
            Console.WriteLine("\nCapacity before trim = " + listTrimCstomers.Capacity);

            listTrimCstomers.TrimExcess();
            Console.WriteLine("Capacity after trim = " + listTrimCstomers.Capacity);
            #endregion

            Console.ReadKey();
        }
Example #4
0
        public static Event Compound(this Event ev, Action<Event> action)
        {
            List<Event> events = new List<Event> ();
            Event comp = Event.Create();
            action(comp);

            ev.Started += (args) =>
            {
                Event e = comp;
                do
                {
                    events.Add(e);
                    e.StartEx(true, true);
                    Event t = e.Next;
                    e.Detach();
                    e = t;

                }while(e != null);
            };

            ev.Updated += (args) =>
            {
                return events.TrueForAll(e=>!e.IsRunningSingular);
            };

            return ev.Extend ();
        }
Example #5
0
		public IfStmt(Position position, List<ConditionalStmt>/*!!*/ conditions)
			: base(position)
		{
			Debug.Assert(conditions != null && conditions.Count > 0);
			Debug.Assert(conditions.TrueForAll(delegate(ConditionalStmt stmt) { return stmt != null; }));
			this.conditions = conditions;
		}
 public ScriptInventory(string scriptPath, bool deepSearch)
 {
     this.scriptPath = Directory.GetCurrentDirectory();
     if (!string.IsNullOrEmpty(scriptPath)) {
         this.scriptPath = Path.Combine(this.scriptPath, scriptPath);
     }
     List<Statement> unsupportedStatements = new List<Statement>();
     foreach (string fileName in Directory.GetFiles(this.scriptPath, "*.sql", deepSearch ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)) {
         unsupportedStatements.Clear();
         using (TextReader reader = new StreamReader(fileName, true)) {
             try {
                 ProcessSingleScript(reader, unsupportedStatements.Add);
             } catch (ParseException ex) {
                 ex.FileName = fileName;
                 throw;
             }
         }
         if (unsupportedStatements.Count > 0) {
             // only files which have no DDL as "unsupported statements" are assumed to be setup scripts
             if (unsupportedStatements.TrueForAll(statement => !(statement is DdlStatement))) {
                 foreach (Statement statement in unsupportedStatements) {
                     AddAdditionalSetupStatement(statement);
                 }
             } else {
                 Trace.WriteLine(string.Format("Script {0} contains {1} unsupported statements", fileName, unsupportedStatements.Count));
             }
         }
     }
     AdditionalSetupStatementSetSchemaOverride();
 }
        /// <summary>
        /// Processes the list of events asynchronously.
        /// </summary>
        /// <param name="evs">List of events.</param>
        /// <returns>Returns <c>True</c>, if all events have been consumed; otherwise returns <c>False.</c></returns>
        public async Task<bool> ProcessEventsAsync(IEnumerable<BaseEvent> evs)
        {
            var results = new List<bool>();
            using (var uow = this._uowm.CreateInstance<SampleDbContext>())
            {
                uow.BeginTransaction();

                try
                {
                    foreach (var ev in evs)
                    {
                        var handlers = this.GetHandlers(ev);
                        foreach (var handler in handlers)
                        {
                            var result = await handler.ProcessAsync(ev);
                            results.Add(result);
                        }
                    }

                    uow.Commit();
                }
                catch
                {
                    uow.Rollback();
                    results.Add(false);
                    throw;
                }
            }

            return await Task.FromResult(results.TrueForAll(p => p));
        }
Example #8
0
        public void ClearRemovesAllStreams(List<string> ids)
        {
            List<IConnection<User, string>> connections =
                ids.Select(id => Connect(id)).ToList();

            Clear();

            ids.TrueForAll(id => false == ExistsFor(id)).Should().BeTrue();
        }
Example #9
0
        static void Main(string[] args)
        {
            var lista = new List<int>();

            lista.AddRange(new int[]{36,30,8,4,2});

            bool pares = lista.TrueForAll(n => n%2 == 0); // Esto es equivalente a lo que aparece en: I)

            pares = lista.TrueForAll(EsPar); // I)

            if (pares) {
                Console.WriteLine("Todos los numeros de lista son pares.");
            } else {
                Console.WriteLine("No todos los numeros de lista son pares.");
            }

            Console.ReadKey();
        }
Example #10
0
 public BulkPutRequest(string bucketName, List<Ds3Object> objects)
 {
     this.BucketName = bucketName;
     this.Objects = objects;
     if (!objects.TrueForAll(obj => obj.Size.HasValue))
     {
         throw new Ds3RequestException(Resources.ObjectsMissingSizeException);
     }
     QueryParams.Add("operation", "start_bulk_put");
 }
Example #11
0
 private static int SolveProblem()
 {
     var primes = new List<int> {2, 3, 5, 7, 11, 13};
     for (var i = 15; primes.Count < 10001; i += 2)
     {
         var i1 = i;
         if(primes.TrueForAll(x => i1%x != 0))
             primes.Add(i1);
     }
     return primes.Max();
 }
		public override VetoResult AllowPut(string key, RavenJObject document, RavenJObject metadata, TransactionInformation transactionInformation)
		{
		    if (Database.Name != null && Database.Name != Constants.SystemDatabase)
		        return VetoResult.Allowed;

		    if (key.StartsWith(RavenDatabasesPrefix, StringComparison.InvariantCultureIgnoreCase) == false)
		        return VetoResult.Allowed;

		    var tempPermission = metadata[Constants.AllowBundlesChange];

		    if (tempPermission != null)
		        metadata.Remove(Constants.AllowBundlesChange); // this is a temp marker so do not persist this medatada

		    var bundlesChangesAllowed = tempPermission != null &&
		                                tempPermission.Value<string>()
		                                              .Equals("true", StringComparison.InvariantCultureIgnoreCase);

		    if (bundlesChangesAllowed)
		        return VetoResult.Allowed;

		    var existingDbDoc = Database.Documents.Get(key, transactionInformation);

		    if (existingDbDoc == null)
		        return VetoResult.Allowed;

		    var currentDbDocument = existingDbDoc.DataAsJson.JsonDeserialization<DatabaseDocument>();

		    var currentBundles = new List<string>();
		    string value;
		    if (currentDbDocument.Settings.TryGetValue(Constants.ActiveBundles, out value))
		        currentBundles = value.GetSemicolonSeparatedValues();

		    var newDbDocument = document.JsonDeserialization<DatabaseDocument>();
		    var newBundles = new List<string>();
		    if (newDbDocument.Settings.TryGetValue(Constants.ActiveBundles, out value))
		        newBundles = value.GetSemicolonSeparatedValues();


		    if (currentBundles.Count == newBundles.Count)
		        return VetoResult.Allowed;

		    if (currentBundles.Count == 0)
		        return VetoResult.Allowed;

		    if (currentBundles.TrueForAll(x => newBundles.Contains(x)))
                return VetoResult.Allowed;

		    return VetoResult.Deny(
		        "You should not change 'Raven/ActiveBundles' setting for a database. This setting should be set only once when a database is created. " +
				"If you really need to override it you have to specify {\"" + Constants.AllowBundlesChange +
		        "\": true} in metadata of a database document every time when you send it." + Environment.NewLine +
		        "Current: " + string.Join("; ", currentBundles) + Environment.NewLine +
		        "New: " + string.Join("; '", newBundles));
		}
Example #13
0
        public ListEx(Position p, List<Expression>/*!*/ lvalues, Expression rvalue)
            : base(p)
        {
            Debug.Assert(lvalues != null /*&& rvalue != null*/);    // rvalue can be determined during runtime in case of list in list.
            Debug.Assert(lvalues.TrueForAll(delegate(Expression lvalue)
            {
                return lvalue == null || lvalue is VarLikeConstructUse || lvalue is ListEx;
            }));

            this.LValues = lvalues;
            this.RValue = rvalue;
        }
Example #14
0
        public bool IsMatch(string filename)
        {
            var matches = new List<bool>();
            if (Path != null)
            {
                matches.Add(Regex.IsMatch(filename, PathPattern));
            }
            if (Name != null)
            {
                matches.Add(Regex.IsMatch(filename, NamePattern));
            }

            return matches.Any() && matches.TrueForAll(m => m);
        }
        public bool Archive()
        {
            var result = new List<bool>();

            var applications = _applicationRepository.GetApplicationsOutsideCurrentWindow();

            foreach (var application in applications.GenerateStatuses(_statusGeneratorFactory, _pipelinePositionGenerator))
            {
                if (!application.PipelinePosition.IsActive())
                {
                    result.Add(_applicationRepository.Archive(application.ApplicationReference));
                }
            }

            return result.TrueForAll(x => x);
        }
Example #16
0
		public static void Initialize()
		{
			var tables = new List<ClilocTable>(Tables.Values);

			//bool noFind = false;

			Core.DataDirectories.TakeWhile(path => !tables.TrueForAll(t => t.Loaded))
				.Where(path => !String.IsNullOrWhiteSpace(path))
				.ForEach(
					path => Parallel.ForEach(
						Tables,
						kvp =>
						{
							if (kvp.Value.Loaded)
							{
								return;
							}

							string file = "Cliloc." + kvp.Key.ToString().ToLower();
							string stub = IOUtility.GetSafeFilePath(path + "/" + file, true);

							if (!File.Exists(stub))
							{
                                Console.WriteLine("WARNING: {0} not found!", file);
								//CSOptions.ToConsole("WARNING: {0} not found!", file);
								//noFind = true;
								return;
							}

                            Console.WriteLine("SUCCESS: {0} processed!", file);
							kvp.Value.Load(new FileInfo(stub));
						}));

			/*if (noFind)
			{
				CSOptions.ToConsole(
					"WARNING: One or more required cliloc files could not be loaded, any features that rely on this service will not work as expected and/or may cause a fatal exception!");
			}*/

			tables.Clear();
			tables.TrimExcess();
		}
Example #17
0
		private static void CSConfig()
		{
			CommandUtility.Register("ExportCliloc", AccessLevel.Administrator, ExportCommand);

			var tables = new List<ClilocTable>(Tables.Values);

			//bool noFind = false;

			Core.DataDirectories.TakeWhile(path => !tables.TrueForAll(t => t.Loaded))
				.Where(path => !String.IsNullOrWhiteSpace(path))
				.ForEach(
					path => Parallel.ForEach(
						Tables,
						kvp =>
						{
							if (kvp.Value.Loaded)
							{
								return;
							}

							var file = "Cliloc." + kvp.Key.ToString().ToLower();
							var stub = IOUtility.GetSafeFilePath(path + "/" + file, true);

							if (!File.Exists(stub))
							{
								//CSOptions.ToConsole("WARNING: {0} not found!", file);
								//noFind = true;
								return;
							}

							kvp.Value.Load(new FileInfo(stub));
						}));

			/*if (noFind)
			{
				CSOptions.ToConsole(
					"WARNING: One or more required cliloc files could not be loaded, any features that rely on this service will not work as expected and/or may cause a fatal exception!");
			}*/

			tables.Free(true);
		}
        /// <summary>
        /// Generate zone points using Poisson sampling
        /// </summary>
        /// <param name="count"></param>
        /// <param name="landBounds"></param>
        /// <param name="density"></param>
        /// <returns></returns>
        protected override Vector2[] GeneratePoints(int count, Bounds2i landBounds, Vector2 density)
        {
            var checkedPoints = new List<Vector2>();
            var uncheckedPoints = new List<Vector2>();

            //Generate start point
            var zoneCenterX = Random.Range((float)landBounds.Min.X, landBounds.Max.X);
            var zoneCenterY = Random.Range((float)landBounds.Min.Z, landBounds.Max.Z);
            var startPoint = new Vector2(zoneCenterX, zoneCenterY);

            uncheckedPoints.Add(startPoint);

            //Generate point around first unchecked
            while (uncheckedPoints.Any())
            {
                var processedPoint = uncheckedPoints.First();
                uncheckedPoints.RemoveAt(0);

                for (int i = 0; i < 10; i++)
                {
                    var r = Random.Range(density.x + 0.1f, density.y);
                    var a = Random.Range(0, 2*Mathf.PI);
                    var newPoint = processedPoint + new Vector2(r * Mathf.Cos(a), r*Mathf.Sin(a));

                    if (landBounds.Contains((Vector2i) newPoint))
                    {
                        if(checkedPoints.TrueForAll(p => Vector2.SqrMagnitude(p - newPoint) > density.x * density.x)
                            && uncheckedPoints.TrueForAll(p => Vector2.SqrMagnitude(p - newPoint) > density.x * density.x))
                            uncheckedPoints.Add(newPoint);
                    }
                }

                checkedPoints.Add(processedPoint);
                if (checkedPoints.Count >= count)
                    break;
            }

            return checkedPoints.ToArray();
        }
Example #19
0
		public void SetData(List<PartyMember> memberList)
		{
			if (memberList.TrueForAll(_member => _member.IsFullData))
			{
				if(m_members == null || m_members.Count == 0)
				{
					((EOGame)Game).Hud.SetStatusLabel(DATCONST2.STATUS_LABEL_TYPE_INFORMATION, DATCONST2.STATUS_LABEL_PARTY_YOU_JOINED);
					((EOGame)Game).Hud.AddChat(ChatTabs.System, "", World.GetString(DATCONST2.STATUS_LABEL_PARTY_YOU_JOINED), ChatType.PlayerParty, ChatColor.PM);
				}

				Visible = true;
				m_numMembers.Text = string.Format("{0}", memberList.Count);
				m_members = memberList;

				m_mainIsLeader = m_members.FindIndex(_member => _member.IsLeader && _member.ID == World.Instance.MainPlayer.ActiveCharacter.ID) >= 0;
				m_scrollBar.UpdateDimensions(memberList.Count);

				m_buttons.Clear();

				foreach (PartyMember member in m_members)
				{
					_addRemoveButtonForMember(member);
				}
			}
			else
			{
				//update HP only
// ReSharper disable once ForCanBeConvertedToForeach
				for (int i = 0; i < memberList.Count; ++i)
				{
					int ndx = m_members.FindIndex(_member => _member.ID == memberList[i].ID);
					PartyMember member = m_members[ndx];
					member.SetPercentHealth(memberList[i].PercentHealth);
					m_members[ndx] = member;
				}
			}
		}
Example #20
0
        private static void AddKeysFrom(HashSet <string> permissions, ILocalTextRegistry registry,
                                        Type type, string languageID)
        {
            var thisKeys = new List <string>();

            foreach (var member in type.GetFields(BindingFlags.Static | BindingFlags.DeclaredOnly |
                                                  BindingFlags.Public | BindingFlags.NonPublic))
            {
                if (member.FieldType != typeof(string))
                {
                    continue;
                }

                if (!(member.GetValue(null) is string key) ||
                    string.IsNullOrEmpty(key) ||
                    key.IndexOfAny(splitChar) >= 0) // skip permissions with logical operators
                {
                    continue;
                }

                DescriptionAttribute descr;

                if (key.EndsWith(":"))
                {
                    if (registry != null)
                    {
                        descr = member.GetCustomAttribute <DescriptionAttribute>();
                        registry.Add(languageID, "Permission." + key, descr != null ? descr.Description : member.Name);
                    }

                    continue;
                }

                thisKeys.Add(key);

                if (permissions != null)
                {
                    permissions.Add(key);
                }

                if (registry != null)
                {
                    descr = member.GetCustomAttribute <DescriptionAttribute>();
                    registry.Add(languageID, "Permission." + key, descr != null ? descr.Description : member.Name);
                }
            }

            if (registry != null && thisKeys.Count > 0)
            {
                var displayName = type.GetCustomAttribute <DisplayNameAttribute>();

                var lastColonIndex = thisKeys[0].LastIndexOf(":");
                if (displayName != null &&
                    lastColonIndex > 0 &&
                    lastColonIndex < thisKeys[0].Length - 1 &&
                    thisKeys.TrueForAll(x => x.LastIndexOf(":") == lastColonIndex))
                {
                    registry.Add(languageID, "Permission." + thisKeys[0].Substring(0, lastColonIndex + 1), displayName.DisplayName);
                }
            }

            foreach (var nested in type.GetNestedTypes(BindingFlags.Public | BindingFlags.DeclaredOnly))
            {
                AddKeysFrom(permissions, registry, nested, languageID);
            }
        }
Example #21
0
 public bool IsEmpty(List <Vector2Int> poss) => poss.TrueForAll(IsEmpty);
 private bool CompareTwoTitlesSections(List <WhoWeAreTitledSection> current, List <WhoWeAreTitledSection> other)
 {
     return(current.TrueForAll(l => other.Any(li => li.Equals(l))) && current.Count == other.Count);
 }
        List <TextWord> ParseLine(IDocument document)
        {
            List <TextWord> words    = new List <TextWord>();
            HighlightColor  markNext = null;

            currentOffset = 0;
            currentLength = 0;
            UpdateSpanStateVariables();

            int currentLineLength = currentLine.Length;
            int currentLineOffset = currentLine.Offset;

            for (int i = 0; i < currentLineLength; ++i)
            {
                char ch = document.GetCharAt(currentLineOffset + i);
                switch (ch)
                {
                case '\n':
                case '\r':
                    PushCurWord(document, ref markNext, words);
                    ++currentOffset;
                    break;

                case ' ':
                    PushCurWord(document, ref markNext, words);
                    if (activeSpan != null && activeSpan.Color.HasBackground)
                    {
                        words.Add(new TextWord.SpaceTextWord(activeSpan.Color));
                    }
                    else
                    {
                        words.Add(TextWord.Space);
                    }
                    ++currentOffset;
                    break;

                case '\t':
                    PushCurWord(document, ref markNext, words);
                    if (activeSpan != null && activeSpan.Color.HasBackground)
                    {
                        words.Add(new TextWord.TabTextWord(activeSpan.Color));
                    }
                    else
                    {
                        words.Add(TextWord.Tab);
                    }
                    ++currentOffset;
                    break;

                default:
                {
                    // handle escape characters
                    char escapeCharacter = '\0';
                    if (activeSpan != null && activeSpan.EscapeCharacter != '\0')
                    {
                        escapeCharacter = activeSpan.EscapeCharacter;
                    }
                    else if (activeRuleSet != null)
                    {
                        escapeCharacter = activeRuleSet.EscapeCharacter;
                    }
                    if (escapeCharacter != '\0' && escapeCharacter == ch)
                    {
                        // we found the escape character
                        if (activeSpan != null && activeSpan.End != null && activeSpan.End.Length == 1 &&
                            escapeCharacter == activeSpan.End[0])
                        {
                            // the escape character is a end-doubling escape character
                            // it may count as escape only when the next character is the escape, too
                            if (i + 1 < currentLineLength)
                            {
                                if (document.GetCharAt(currentLineOffset + i + 1) == escapeCharacter)
                                {
                                    currentLength += 2;
                                    PushCurWord(document, ref markNext, words);
                                    ++i;
                                    continue;
                                }
                            }
                        }
                        else
                        {
                            // this is a normal \-style escape
                            ++currentLength;
                            if (i + 1 < currentLineLength)
                            {
                                ++currentLength;
                            }
                            PushCurWord(document, ref markNext, words);
                            ++i;
                            continue;
                        }
                    }

                    // highlight digits
                    if (!inSpan && (Char.IsDigit(ch) || (ch == '.' && i + 1 < currentLineLength && Char.IsDigit(document.GetCharAt(currentLineOffset + i + 1)))) && currentLength == 0)
                    {
                        bool ishex           = false;
                        bool isfloatingpoint = false;

                        if (ch == '0' && i + 1 < currentLineLength && Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1)) == 'X')                                           // hex digits
                        {
                            const string hex = "0123456789ABCDEF";
                            ++currentLength;
                            ++i;                                             // skip 'x'
                            ++currentLength;
                            ishex = true;
                            while (i + 1 < currentLineLength && hex.IndexOf(Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1))) != -1)
                            {
                                ++i;
                                ++currentLength;
                            }
                        }
                        else
                        {
                            ++currentLength;
                            while (i + 1 < currentLineLength && Char.IsDigit(document.GetCharAt(currentLineOffset + i + 1)))
                            {
                                ++i;
                                ++currentLength;
                            }
                        }
                        if (!ishex && i + 1 < currentLineLength && document.GetCharAt(currentLineOffset + i + 1) == '.')
                        {
                            isfloatingpoint = true;
                            ++i;
                            ++currentLength;
                            while (i + 1 < currentLineLength && Char.IsDigit(document.GetCharAt(currentLineOffset + i + 1)))
                            {
                                ++i;
                                ++currentLength;
                            }
                        }

                        if (i + 1 < currentLineLength && Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1)) == 'E')
                        {
                            isfloatingpoint = true;
                            ++i;
                            ++currentLength;
                            if (i + 1 < currentLineLength && (document.GetCharAt(currentLineOffset + i + 1) == '+' || document.GetCharAt(currentLine.Offset + i + 1) == '-'))
                            {
                                ++i;
                                ++currentLength;
                            }
                            while (i + 1 < currentLine.Length && Char.IsDigit(document.GetCharAt(currentLineOffset + i + 1)))
                            {
                                ++i;
                                ++currentLength;
                            }
                        }

                        if (i + 1 < currentLine.Length)
                        {
                            char nextch = Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1));
                            if (nextch == 'F' || nextch == 'M' || nextch == 'D')
                            {
                                isfloatingpoint = true;
                                ++i;
                                ++currentLength;
                            }
                        }

                        if (!isfloatingpoint)
                        {
                            bool isunsigned = false;
                            if (i + 1 < currentLineLength && Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1)) == 'U')
                            {
                                ++i;
                                ++currentLength;
                                isunsigned = true;
                            }
                            if (i + 1 < currentLineLength && Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1)) == 'L')
                            {
                                ++i;
                                ++currentLength;
                                if (!isunsigned && i + 1 < currentLineLength && Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1)) == 'U')
                                {
                                    ++i;
                                    ++currentLength;
                                }
                            }
                        }

                        words.Add(new TextWord(document, currentLine, currentOffset, currentLength, DigitColor, false));
                        currentOffset += currentLength;
                        currentLength  = 0;
                        continue;
                    }

                    // Check for SPAN ENDs
                    if (inSpan)
                    {
                        if (activeSpan.End != null && activeSpan.End.Length > 0)
                        {
                            if (MatchExpr(currentLine, activeSpan.End, i, document, activeSpan.IgnoreCase))
                            {
                                PushCurWord(document, ref markNext, words);
                                string regex = GetRegString(currentLine, activeSpan.End, i, document);
                                currentLength += regex.Length;
                                words.Add(new TextWord(document, currentLine, currentOffset, currentLength, activeSpan.EndColor, false));
                                currentOffset += currentLength;
                                currentLength  = 0;
                                i             += regex.Length - 1;
                                currentSpanStack.Pop();
                                UpdateSpanStateVariables();
                                continue;
                            }
                        }
                    }

                    // check for SPAN BEGIN
                    if (activeRuleSet != null)
                    {
                        foreach (Span span in activeRuleSet.Spans)
                        {
                            if ((!span.IsBeginSingleWord || currentLength == 0) &&
                                (!span.IsBeginStartOfLine.HasValue || span.IsBeginStartOfLine.Value == (currentLength == 0 && words.TrueForAll(delegate(TextWord textWord) { return(textWord.Type != TextWordType.Word); }))) &&
                                MatchExpr(currentLine, span.Begin, i, document, activeRuleSet.IgnoreCase))
                            {
                                PushCurWord(document, ref markNext, words);
                                string regex = GetRegString(currentLine, span.Begin, i, document);

                                if (!OverrideSpan(regex, document, words, span, ref i))
                                {
                                    currentLength += regex.Length;
                                    words.Add(new TextWord(document, currentLine, currentOffset, currentLength, span.BeginColor, false));
                                    currentOffset += currentLength;
                                    currentLength  = 0;

                                    i += regex.Length - 1;
                                    if (currentSpanStack == null)
                                    {
                                        currentSpanStack = new SpanStack();
                                    }
                                    currentSpanStack.Push(span);
                                    span.IgnoreCase = activeRuleSet.IgnoreCase;

                                    UpdateSpanStateVariables();
                                }

                                goto skip;
                            }
                        }
                    }

                    // check if the char is a delimiter
                    if (activeRuleSet != null && (int)ch < 256 && activeRuleSet.Delimiters[(int)ch])
                    {
                        PushCurWord(document, ref markNext, words);
                        if (currentOffset + currentLength + 1 < currentLine.Length)
                        {
                            ++currentLength;
                            PushCurWord(document, ref markNext, words);
                            goto skip;
                        }
                    }

                    ++currentLength;
                    skip : continue;
                }
                }
            }

            PushCurWord(document, ref markNext, words);

            OnParsedLine(document, currentLine, words);

            return(words);
        }
        public static void MainWorking(GraphModel graphModel)
        {
            var paramsMain = new List <double>
            {
                graphModel.ParamOne ?? throw new Exception("Ошибка! Один из параметров NULL!"),
                      graphModel.ParamTwo ?? throw new Exception("Ошибка! Один из параметров NULL!"),
                            graphModel.ParamThree ?? throw new Exception("Ошибка! Один из параметров NULL!"),
                                  graphModel.ParamFour ?? throw new Exception("Ошибка! Один из параметров NULL!")
            };

            var paramsDynamic = new List <double>
            {
                graphModel.IntervalParamOne ?? throw new Exception("Ошибка! Один из параметров NULL!"),
                      graphModel.IntervalParamTwo ?? throw new Exception("Ошибка! Один из параметров NULL!")
            };

            var step    = (paramsDynamic[1] - paramsDynamic[0]) / graphModel.IterationCount;
            var current = paramsDynamic[0];

            var xPoint = new List <double>();
            var yPoint = new List <double>();

            for (var i = 0; i < graphModel.IterationCount; i++)
            {
                var alg = new ParabolasAlg(graphModel.FuncStr, paramsMain[1],
                                           paramsMain[0],
                                           paramsMain[2],
                                           paramsMain[3]);

                switch (graphModel.ChangedParam)
                {
                case 0:
                    alg.X1 = current; alg.MainWorking();

                    if (alg.FuncStarX.Equals(0))
                    {
                        continue;
                    }

                    xPoint.Add(alg.X1);
                    break;

                case 1:
                    alg.DeltaX = current; alg.MainWorking();

                    if (alg.FuncStarX.Equals(0))
                    {
                        continue;
                    }

                    xPoint.Add(alg.DeltaX);
                    break;

                case 2:
                    alg.OneEps = current; alg.MainWorking();

                    if (alg.FuncStarX.Equals(0))
                    {
                        continue;
                    }

                    xPoint.Add(alg.OneEps);
                    break;

                case 3:
                    alg.TwoEps = current; alg.MainWorking();

                    if (alg.FuncStarX.Equals(0))
                    {
                        continue;
                    }

                    xPoint.Add(alg.TwoEps);
                    break;
                }

                yPoint.Add(alg.FuncStarX);
                current += step;
            }

            if (xPoint.Count == 0 || yPoint.Count == 0 || xPoint.TrueForAll(d => d.Equals(xPoint[0])) || yPoint.TrueForAll(d => d.Equals(yPoint[0])))
            {
                throw new Exception("Массив точек пуст, или не изменяется!\n" +
                                    $"yPoint[0] = {yPoint[0]}\nyPoint[{yPoint.Count}] = {yPoint[yPoint.Count - 1]}");
            }

            File.WriteAllLines("values.txt", xPoint.Select((t, i) => $"{t};{yPoint[i]}"));
            Process.Start("PlotGraph.exe");
        }
    }
}
Example #25
0
 public bool AreActiveCardsLie()
 {
     return(!activeCards.TrueForAll(x => x.rank == roundRank));
 }
Example #26
0
 /// <summary>
 /// 是否已经被人和AI填满
 /// </summary>
 public bool IsFull()
 {
     return(PlayerList.TrueForAll((PlayerInRoom Player) =>
                                  Player.PlayerType.Equals(PPlayerType.AI) || Player.PlayerType.Equals(PPlayerType.Player)));
 }
        private void ProcessCommand(char c)
        {
            switch (c)
            {
            case 'A':
                ArticlePanel.Children.OfType <SearchSimpleElements>().ToList().ForEach(x => x.Select = true);
                break;

            case 'C':
                ArticlePanel.Children.OfType <SearchSimpleElements>().ToList().ForEach(x => {
                    x.Select = false;
                    x.Transparent();
                });
                break;

            case 'R':
                ArticlePanel.Children.OfType <SearchSimpleElements>().ToList().ForEach(x => {
                    x.Select = !x.Select;
                    if (!x.Select)
                    {
                        x.Transparent();
                    }
                });
                break;

            case 'S':
                List <string> titles = new List <string>();
                for (int i = 0; i < ArticlePanel.Children.Count; i++)
                {
                    string ttitle = (ArticlePanel.Children[i] as SearchSimpleElements).Article.Title.Split('|')[0];
                    if (titles.Count > 0 && !titles.TrueForAll((title) => Strings.ComputeLevenshteinDistance(ttitle, title) > Settings.Instance.Hitomi.TextMatchingAccuracy))
                    {
                        (ArticlePanel.Children[i] as SearchSimpleElements).Select = false;
                        (ArticlePanel.Children[i] as SearchSimpleElements).Transparent();
                        continue;
                    }

                    titles.Add(ttitle);
                }
                break;

            case 'G':
                ArticlePanel.Children.OfType <SearchSimpleElements>().ToList().ForEach(x => {
                    if (HitomiLog.Instance.Contains((x.Article as HitomiArticle).Magic))
                    {
                        x.Select = false;
                        x.Transparent();
                    }
                });
                break;

            case 'B':
                BookmarkModelManager.Instance.Model.groups.Add(new Tuple <string, BookmarkItemModel>("/미분류", new BookmarkItemModel
                {
                    stamp   = DateTime.Now,
                    content = Group.Replace('_', ' '),
                    path    = ""
                }));
                BookmarkModelManager.Instance.Save();
                MessageBox.Show("북마크에 추가되었습니다!", "Koromo Copy", MessageBoxButton.OK, MessageBoxImage.Information);
                break;

            case 'D':
                break;
            }
        }
Example #28
0
 private bool CheckRulesForPosition(Board p_Board, int p_X, int p_Y)
 {
     CheckRulesForPositionCalled++;
     CheckRules?.Invoke(p_Board, p_X, p_Y);
     return(_Rules?.TrueForAll(r => r.CheckRuleForPosition(p_Board, p_X, p_Y)) ?? false);
 }
Example #29
0
        /**
         * Purpose: Reads user input for new incident information
         * Return:
         *     void
         */
        public static void ReadInput()
        {
            Console.WriteLine("Enter the customers first and last name to start:");
            Console.WriteLine("***********************************************************************");

            CustomerFactory customerFactory = new CustomerFactory();
            List <Customer> customerList    = customerFactory.getAll();

            foreach (Customer customer in customerList)
            {
                Console.WriteLine($"{ customer.FirstName} {customer.LastName} ");
            }
            Console.WriteLine("***********************************************************************");

            Console.WriteLine(@"
                ====================================
                BANGAZON INC CUSTOMER SERVICE PORTAL
                ====================================");

            string   customerName = Console.ReadLine();
            Customer customerId   = customerFactory.getCustomerByFullName(customerName);

            while (customerId == null)
            {
                customerId = customerFactory.getCustomerByFullName(customerName);
                if (customerId == null)
                {
                    Console.WriteLine("This is not a valid answer. Please try again!");
                    customerName = Console.ReadLine();
                }
            }

            int orderID = 0;

            Console.WriteLine(@"
                ====================================
                BANGAZON INC CUSTOMER SERVICE PORTAL
                ====================================");
            Console.WriteLine("Choose a customer order:");
            OrderFactory orderFactory = new OrderFactory();
            List <Order> orderList    = orderFactory.getAllOrdersFromCustomer(customerId.CustomerId);

            foreach (Order order in orderList)
            {
                Console.WriteLine($"Order {order.OrderId}: { order.Date}");
            }
            Console.WriteLine("X.Exit");

            while (orderID == 0)
            {
                string orderIDAnswer = Console.ReadLine();
                if (orderIDAnswer.ToLower() == "x")
                {
                    return;
                    // to main menu
                }
                try
                {
                    orderID = Convert.ToInt32(orderIDAnswer);
                }
                catch
                {
                    Console.WriteLine("Please enter an order number.");
                }
            }

            IncidentFactory     incidentFactory     = new IncidentFactory();
            IncidentTypeFactory incidentTypeFactory = new IncidentTypeFactory();
            List <IncidentType> incidentTypeList    = incidentTypeFactory.getAll();
            List <Incident>     incidents           = incidentFactory.getAll();
            Incident            incident            = new Incident();

            incident.DateCreated = DateTime.Now;
            while (incident.OrderId <= 0 || orderList.TrueForAll(o => incident.OrderId != orderID))
            {
                if (orderList.Find(o => o.OrderId == orderID) != null)
                {
                    break;
                }

                if (orderList.TrueForAll(o => incident.OrderId != orderID) || orderID == 0)
                {
                    Console.WriteLine("This is not a valid answer. Try again!");
                    try
                    {
                        orderID = Convert.ToInt32(Console.ReadLine());
                    }
                    catch
                    {
                        Console.WriteLine("Please enter a number");
                    }
                }
            }

            incident.OrderId = orderID;
            Console.WriteLine(@"
                ====================================
                BANGAZON INC CUSTOMER SERVICE PORTAL
                ====================================");
            Console.WriteLine("Choose incident type: ");
            foreach (IncidentType incidentType in incidentTypeList)
            {
                Console.WriteLine($"{incidentType.IncidentTypeId} {incidentType.Label}");
            }
            Console.WriteLine("X.Exit");
            int incidentTypeId = 0;

            while (incidentTypeId == 0)
            {
                string incidentTypeIdAnswer = Console.ReadLine();
                if (incidentTypeIdAnswer.ToLower() == "x")
                {
                    // to main menu
                    return;
                }
                try
                {
                    incidentTypeId = Convert.ToInt32(incidentTypeIdAnswer);
                }
                catch
                {
                    Console.WriteLine("This is not a valid answer. Try again!");
                }
            }

            while (incident.IncidentTypeId <= 0 || incidentTypeList.TrueForAll(o => incident.IncidentTypeId != incidentTypeId))
            {
                if (incidentTypeList.Find(it => it.IncidentTypeId == incidentTypeId) != null)
                {
                    break;
                }

                if (incidentTypeList.TrueForAll(o => incident.IncidentTypeId != incidentTypeId) || incidentTypeId == 0)
                {
                    Console.WriteLine("This is not a valid answer. Try again!");
                    try
                    {
                        incidentTypeId = Convert.ToInt32(Console.ReadLine());
                    }
                    catch
                    {
                        Console.WriteLine("Please enter a number");
                    }
                }
            }
            incident.IncidentTypeId = incidentTypeId;
            CustomerFactory.Instance.ActiveCustomer = customerId;
            IncidentFactory.Instance.ActiveIncident = incident;
            ShowSingleIncidentAction.ReadInput();
        }
        public override VetoResult AllowPut(string key, RavenJObject document, RavenJObject metadata, TransactionInformation transactionInformation)
        {
            if (Database.Name != null && Database.Name != Constants.SystemDatabase)
            {
                return(VetoResult.Allowed);
            }

            if (key.StartsWith(RavenDatabasesPrefix, StringComparison.InvariantCultureIgnoreCase) == false)
            {
                return(VetoResult.Allowed);
            }

            var tempPermission = metadata[Constants.AllowBundlesChange];

            if (tempPermission != null)
            {
                metadata.Remove(Constants.AllowBundlesChange);         // this is a temp marker so do not persist this medatada
            }
            var bundlesChangesAllowed = tempPermission != null &&
                                        tempPermission.Value <string>()
                                        .Equals("true", StringComparison.InvariantCultureIgnoreCase);

            if (bundlesChangesAllowed)
            {
                return(VetoResult.Allowed);
            }

            var existingDbDoc = Database.Documents.Get(key, transactionInformation);

            if (existingDbDoc == null)
            {
                return(VetoResult.Allowed);
            }

            var currentDbDocument = existingDbDoc.DataAsJson.JsonDeserialization <DatabaseDocument>();

            var    currentBundles = new List <string>();
            string value;

            if (currentDbDocument.Settings.TryGetValue(Constants.ActiveBundles, out value))
            {
                currentBundles = value.GetSemicolonSeparatedValues();
            }

            var newDbDocument = document.JsonDeserialization <DatabaseDocument>();
            var newBundles    = new List <string>();

            if (newDbDocument.Settings.TryGetValue(Constants.ActiveBundles, out value))
            {
                newBundles = value.GetSemicolonSeparatedValues();
            }


            if (currentBundles.Count == newBundles.Count)
            {
                return(VetoResult.Allowed);
            }

            if (currentBundles.Count == 0)
            {
                return(VetoResult.Allowed);
            }

            if (currentBundles.TrueForAll(x => newBundles.Contains(x)))
            {
                return(VetoResult.Allowed);
            }

            return(VetoResult.Deny(
                       "You should not change 'Raven/ActiveBundles' setting for a database. This setting should be set only once when a database is created. " +
                       "If you really need to override it you have to specify {\"" + Constants.AllowBundlesChange +
                       "\": true} in metadata of a database document every time when you send it." + Environment.NewLine +
                       "Current: " + string.Join("; ", currentBundles) + Environment.NewLine +
                       "New: " + string.Join("; '", newBundles)));
        }
        void OnGUI()
        {
            using (new EditorGUILayout.VerticalScope()) {
                EditorGUILayout.Space();

                //EditorGUILayout.BeginHorizontal();
                if (GUILayout.Button("Refresh"))
                {
                    RefreshAllResults();
                }

                var canCompile = checkResults.TrueForAll(item => item.state == CheckerResult.State.Passed);
                using (new EditorGUI.DisabledGroupScope(canCompile == false)) {
                    if (GUILayout.Button("Compile All"))
                    {
                        CompileAllScripts();
                    }
                }

                if (canCompile == false)
                {
                    EditorGUILayout.HelpBox("All scripts must be valid in order to " +
                                            "compile. Click Refresh to check them again.", MessageType.Info);
                }

                EditorGUILayout.Space();

                using (var scroll = new EditorGUILayout.ScrollViewScope(scrollPos)) {
                    scrollPos = scroll.scrollPosition;

                    foreach (var result in checkResults)
                    {
                        DrawScriptGUI(result);
                    }

                    // Draw any diagnoses that resulted
                    foreach (var diagnosis in diagnoses)
                    {
                        MessageType messageType;

                        switch (diagnosis.severity)
                        {
                        case Yarn.Analysis.Diagnosis.Severity.Error:
                            messageType = MessageType.Error;
                            break;

                        case Yarn.Analysis.Diagnosis.Severity.Warning:
                            messageType = MessageType.Warning;
                            break;

                        case Yarn.Analysis.Diagnosis.Severity.Note:
                            messageType = MessageType.Info;
                            break;

                        default:
                            throw new System.ArgumentOutOfRangeException();
                        }

                        EditorGUILayout.HelpBox(diagnosis.ToString(showSeverity: false), messageType);
                    }
                }
            }
        }
Example #32
0
        /// <summary>
        /// Trova tutti i percorsi tra tutte le coppie
        /// </summary>
        /// <param name="indexCoin"></param>
        /// <param name="maxRange"></param>
        /// <returns></returns>
        public void FindAllPathByCoin(int maxRange, string indexCoin = null)
        {
            try
            {
                StartCoin = indexCoin ?? StartCoin;
                MaxRange  = maxRange;
                List <PairToOvercome> lstPairToOvercome = new List <PairToOvercome>();

                Vertex source = _lstAdj.FirstOrDefault(x => x.Coin.Equals(StartCoin));

                if (source == null)
                {
                    Console.WriteLine("Nodo sorgente non trovato!");
                    return;
                }

                // MULTITHREAD METHOD
                List <Task> lstTask = new List <Task>();
                foreach (var edge in source.LstEdge)
                {
                    lstTask.Add(Task.Run(() =>
                    {
                        Edge e = edge;

                        var pToOverCome = new PairToOvercome(source.Coin, ref e);

                        Edge VertexEdge = _lstAdj.First(x => x.Coin == edge.Vertex.Coin).LstEdge
                                          .First(y => y.Vertex.Coin == source.Coin);

                        pToOverCome.LstPath = FindAllPathByPair(source, edge.Vertex, maxRange);

                        lstPairToOvercome.Add(pToOverCome);
                    }));
                }
                while (!lstTask.TrueForAll(x => x.Status == TaskStatus.RanToCompletion))
                {
                }

                // SINGLE THREAD METHOD
                //foreach (var edge in source.LstEdge)
                //{
                //    Edge e = edge;

                //    var pToOverCome = new PairToOvercome(source.Coin, ref e);

                //    Edge VertexEdge = _lstAdj.First(x => x.Coin == edge.Vertex.Coin).LstEdge
                //        .First(y => y.Vertex.Coin == source.Coin);
                //    //    decimal amountToOvercome = edge.Action == "BUY" ? 1 / VertexEdge.LstOrderBook.First().Key  : 1 * VertexEdge.LstOrderBook.First().Key;
                //    pToOverCome.LstPath = FindAllPathByPair(source, edge.Vertex, maxRange);

                //    lstPairToOvercome.Add(pToOverCome);

                //}

                _lstPairToOvercome = lstPairToOvercome;
            }
            catch (Exception e)
            {
                Console.WriteLine("Eccezione: " + e.ToString());
                return;
            }
        }
Example #33
0
 public bool AllExecuted(TimeSpan tCurrentTime)
 {
     return(_timedEvents.TrueForAll(x => !x.FirstExecution && x.EndTime < tCurrentTime));
 }
Example #34
0
        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            var mm = kannet.Count();

            for (var i = 0; i < mm; i++)
            {
                var ll = kannet.FirstOrDefault();
                kannet.Remove(ll);
            }



            if (ekaKertaMeniJo == true)
            {
                tuplaKuvat.AddRange(kopio);
            }

            if (tuplaKuvat.TrueForAll(n => n.Name == "käytetty"))
            {
                arvaukset = 0;
                foreach (var tuplakuva in tuplaKuvat)
                {
                    var ekaNimi = nimet.FirstOrDefault();
                    tuplakuva.Name = ekaNimi;
                    nimet.Remove(ekaNimi);
                    var kopit = kopio.FirstOrDefault();
                    kopio.Remove(kopit);
                }

                var kk = kielletytKlikit.Count();

                for (var i = 0; i < kk; i++)
                {
                    var oo = kielletytKlikit.FirstOrDefault();
                    kielletytKlikit.Remove(oo);
                }

                var viim = viimeksAvattuKoordinaatti.FirstOrDefault();
                viimeksAvattuKoordinaatti.Remove(viim);
                ekaKertaMeniJo = false;
                odota          = false;
                tasoLoppu      = true;

                tuplaKuvat.Shuffle();

                kopio.AddRange(tuplaKuvat);
            }
            if (ekaKertaMeniJo == false)
            {
                foreach (var tt in tuplaKuvat)
                {
                    var nimiTalteen = tt.Name;
                    nimet.Add(nimiTalteen);
                }
            }
            GraphicsDevice.Clear(Color.CadetBlue);

            // TODO: Add your drawing code here
            spriteBatch.Begin(SpriteSortMode.FrontToBack);

            var num = koopa.LastOrDefault();

            spriteBatch.DrawString(Hiiri, "Hiiri: " + hiiriPaikka, new Vector2(20, 50), Color.Black);
            spriteBatch.DrawString(Klikkaus, "Klikkaus: " + kliikkaa, new Vector2(20, 80), Color.Black);
            spriteBatch.DrawString(TextuurinPaikka, "TexPaikka: " + num, new Vector2(20, 110), Color.Black);
            spriteBatch.DrawString(Arvaukset, "Arvaukset: " + arvaukset, new Vector2(20, 140), Color.Black);
            spriteBatch.DrawString(KaikkiArvaukset, "Kaikki arvaukset: " + kaikkiArvaukset, new Vector2(20, 290), Color.Black);

            //if (onAvattu == false)
            //{

            //}

            if (tasoLoppu == false)
            {
                for (int i = 0; i <= map.GetUpperBound(0); i++)
                {
                    for (int j = 0; j <= map.GetUpperBound(1); j++)
                    {
                        int textureId = map[i, j];
                        if (textureId != 0)
                        {
                            if (ekaKerta == false && map[i, j] != avattuPala)
                            {
                                return;
                            }
                            //avattuPala = map[i,j];
                            Vector2 texturePosition = new Vector2(i * tileSize, j * tileSize) + position;

                            //Tokan palan avaus
                            if (odota == true && texturePosition == ekaKuvaKoordit.koordinaatit && tokaAvattu == true || odota == true && texturePosition == tokaKuvaKoordit.koordinaatit && tokaAvattu == true)
                            {
                                spriteBatch.Draw(tuplaKuvat.FirstOrDefault(), texturePosition, null, Color.White, 0, Vector2.Zero, 1.0f, SpriteEffects.None, 0f);
                                avattuPala = map[i, j];
                            }
                            //Ekan palan avaus
                            else if (kliikkaa.X >= texturePosition.X && kliikkaa.X <= texturePosition.X + 46 && kliikkaa.Y >= texturePosition.Y && kliikkaa.Y <= texturePosition.Y + 46 && ekaAvattu == true)
                            {
                                //klikkauspaikka = Vector2.Zero;

                                spriteBatch.Draw(tyhjäKansi, texturePosition, null, Color.White, 0, Vector2.Zero, 1.0f, SpriteEffects.None, 0.11f);
                                avattuPala = map[i, j];

                                onAvattu = true;
                            }
                            else
                            {
                                spriteBatch.Draw(kansi, texturePosition, null, Color.White, 0, Vector2.Zero, 1.0f, SpriteEffects.None, 0.1f);
                                kannet.Add(Content.Load <Texture2D>("TestiMuistipala48"));
                                //onAvattu = false;
                            }



                            if (tuplaKuvat.Count != 0)
                            {
                                var eka = tuplaKuvat.FirstOrDefault();
                                if (eka.Name != "tyhjä" && eka.Name != "käytetty")
                                {
                                    if (laitaKiinni == true)
                                    {
                                        if (odotusOhi == true)
                                        {
                                            spriteBatch.Draw(kansi, texturePosition, null, Color.White, 0, Vector2.Zero, 1.0f, SpriteEffects.None, 0.1f);
                                            odotusOhi   = false;
                                            laitaKiinni = false;
                                        }
                                    }
                                    else
                                    {
                                        spriteBatch.Draw(tuplaKuvat.FirstOrDefault(), texturePosition, null, Color.White, 0, Vector2.Zero, 1.0f, SpriteEffects.None, 0f);
                                    }
                                }
                                else if (eka.Name == "käytetty" && texturePosition == ekaKuvaKoordit.koordinaatit || eka.Name == "käytetty" && texturePosition == tokaKuvaKoordit.koordinaatit)
                                {
                                    if (oikeaPariOdotus == false)
                                    {
                                        spriteBatch.Draw(tyhjäRuutu, texturePosition, null, Color.White, 0, Vector2.Zero, 1.0f, SpriteEffects.None, 1f);
                                    }
                                }
                                else if (eka.Name == "käytetty")
                                {
                                    spriteBatch.Draw(tyhjäRuutu, texturePosition, null, Color.White, 0, Vector2.Zero, 1.0f, SpriteEffects.None, 1f);
                                }
                                //else if(pari==true)
                                //{
                                //    pari = false;
                                //    if (odotusOhi == true)
                                //    {
                                //        spriteBatch.Draw(tyhjäRuutu, texturePosition, null, Color.White, 0, Vector2.Zero, 1.0f, SpriteEffects.None, 0.99f);
                                //        odotusOhi = false;
                                //    }
                                //}
                                else
                                {
                                    if (odota == true && eka.Name == "tyhjä")
                                    {
                                        spriteBatch.Draw(tuplaKuvat.FirstOrDefault(), texturePosition, null, Color.White, 0, Vector2.Zero, 1.0f, SpriteEffects.None, 0f);
                                        eka.Name = "käytetty";

                                        //Koordit kiellettyKlikki = new Koordit();
                                        //kiellettyKlikki.koordinaatit = texturePosition;
                                        //kiellettyKlikki.nimi = eka.Name;
                                        //kielletytKlikit.Add(kiellettyKlikki);

                                        oikeaPariOdotus = true;
                                    }
                                }

                                if (kliikkaa.X >= texturePosition.X && kliikkaa.X <= texturePosition.X + 46 && kliikkaa.Y >= texturePosition.Y && kliikkaa.Y <= texturePosition.Y + 46 && painettu == true)
                                {
                                    Koordit taa  = new Koordit();
                                    Koordit taa1 = new Koordit();


                                    if (ekaAvattu == true)
                                    {
                                        tokaKuva                     = tuplaKuvat.FirstOrDefault();
                                        ekaKuvaKoordit               = koordit.FirstOrDefault();
                                        tokaKuvaKoordit.nimi         = tokaKuva.Name;
                                        tokaKuvaKoordit.koordinaatit = texturePosition;
                                        var t = 4;
                                        if (ekaKuvaKoordit.koordinaatit != texturePosition && ekaKuvaKoordit.nimi == tokaKuva.Name)
                                        {
                                            foreach (var textuuri in tuplaKuvat.Where(n => n.Name == ekaKuvaKoordit.nimi))
                                            {
                                                textuuri.Name = "tyhjä";
                                                pari          = true;

                                                kielletytKlikit.Add(texturePosition);
                                                kielletytKlikit.Add(ekaKuvaKoordit.koordinaatit);
                                            }
                                        }
                                        else
                                        {
                                            laitaKiinni = true;
                                        }

                                        var jj = koordit.FirstOrDefault();
                                        koordit.Remove(jj);
                                        onAvattu    = false;
                                        ekaAvattu   = false;
                                        tokaAvattu  = true;
                                        painettu    = false;
                                        arvausBooli = true;
                                        odota       = true;
                                    }

                                    else
                                    {
                                        laitaKiinni = false;
                                        koopa.Add(texturePosition);//näyttöä varten

                                        var    gg   = tuplaKuvat.FirstOrDefault();
                                        string nimi = gg.Name;

                                        taa.koordinaatit = texturePosition;
                                        taa.nimi         = nimi;
                                        koordit.Add(taa);
                                        painettu = false;

                                        //var avattuListanEka = koordit.FirstOrDefault();
                                        ekaAvattu = true;
                                        var vv = viimeksAvattuKoordinaatti.FirstOrDefault();
                                        viimeksAvattuKoordinaatti.Remove(vv);
                                        viimeksAvattuKoordinaatti.Add(texturePosition);
                                    }



                                    //else
                                    //{

                                    //    koopa.Add(texturePosition);

                                    //    var af = tuplaKuvat.FirstOrDefault();
                                    //    string nimi1 = af.Name;

                                    //    taa1.koordinaatit = texturePosition;
                                    //    taa1.nimi = nimi1;
                                    //    koordit.Add(taa1);
                                    //    painettu = false;

                                    //    var avattuListanEka = koordit.LastOrDefault();
                                    //    tokaAvaus = false;

                                    //    if (taa1.koordinaatit != taa.koordinaatit && taa1.nimi == taa.nimi)
                                    //    {
                                    //        foreach (var textuuri in tuplaKuvat.Where(n => n.Name == taa1.nimi))
                                    //        {
                                    //            var hemuli = textuuri;
                                    //        }
                                    //    }
                                    //}
                                }
                                //else
                                //{
                                //    var jj = koordit.FirstOrDefault();
                                //    koordit.Remove(jj);
                                //    onAvattu = false;
                                //}

                                var itemToRemove = tuplaKuvat.FirstOrDefault();
                                if (itemToRemove != null)
                                {
                                    tuplaKuvat.Remove(itemToRemove);
                                }
                            }

                            ekaKerta = true;
                        }
                    }
                }
            }

            spriteBatch.End();

            if (tuplaKuvat.Count == 0)
            {
                ekaKertaMeniJo = true;
            }

            base.Draw(gameTime);
        }
Example #35
0
 public void TrueForAllTest()
 {
     Assert.IsFalse(_list1.TrueForAll(FindMultipleOfFour));
     Assert.IsTrue(_list1.TrueForAll(IsPositive));
 }
Example #36
0
        internal void GenerateSource(SourceStreamWriter sw, RegistryContext ctx)
        {
            if (sw == null)
            {
                throw new ArgumentNullException("sw");
            }
            if (ctx == null)
            {
                throw new ArgumentNullException("ctx");
            }

            bool bitmask = Enums.TrueForAll(delegate(Enumerant item) {
                Enumerant actualEnumerant = ctx.Registry.GetEnumerant(item.Name);

                return(actualEnumerant == null || actualEnumerant.ParentEnumerantBlock.Type == "bitmask");
            });

            // Collect group enumerants by their value
            Dictionary <string, List <Enumerant> > groupEnums = new Dictionary <string, List <Enumerant> >();

            // ...include all enums defined in this group
            foreach (Enumerant item in Enums)
            {
                Enumerant itemValue = ctx.Registry.GetEnumerant(item.Name);

                if (itemValue != null)
                {
                    if (!groupEnums.ContainsKey(itemValue.Value))
                    {
                        groupEnums.Add(itemValue.Value, new List <Enumerant>());
                    }
                    groupEnums[itemValue.Value].Add(itemValue);
                }
            }

            // Modify canonical enumeration (value/block/group) definition
            CommandFlagsDatabase.EnumerantItem enumerantExtension = CommandFlagsDatabase.FindEnumerant(Name);

            if (enumerantExtension != null)
            {
                // ...override group information
                if (enumerantExtension.Type != null)
                {
                    switch (enumerantExtension.Type)
                    {
                    case "bitmask":
                        bitmask = true;
                        break;
                    }
                }

                // ...include all enums to be added by additional configuration
                foreach (string addedEnum in enumerantExtension.AddEnumerants)
                {
                    Enumerant addedEnumValue = ctx.Registry.GetEnumerant(addedEnum);

                    if (addedEnumValue != null)
                    {
                        if (!groupEnums.ContainsKey(addedEnumValue.Value))
                        {
                            groupEnums.Add(addedEnumValue.Value, new List <Enumerant>());
                        }

                        // Note: since specification can be updated while the CommandFlags.xml is not in synch, the specification
                        // may defined missed enumerant values. In this case do not add enumerant value
                        if (groupEnums[addedEnumValue.Value].Contains(addedEnumValue) == false)
                        {
                            groupEnums[addedEnumValue.Value].Add(addedEnumValue);
                        }
                    }
                }
            }

            // Make enumerants distinct (discard duplicated enumerants, mainly from extensions _ARB, _EXT, ...)
            List <Enumerant> uniqueEnums = new List <Enumerant>();

            foreach (KeyValuePair <string, List <Enumerant> > pair in groupEnums)
            {
                if (pair.Value.Count > 1)
                {
                    List <Enumerant> uniqueNames = new List <Enumerant>();

                    foreach (Enumerant item in pair.Value)
                    {
                        if (item.Alias != null)
                        {
                            continue;
                        }
                        if (item.EnumAlias != null)
                        {
                            continue;
                        }
                        if (uniqueNames.FindIndex(delegate(Enumerant item1) { return(item.Name.StartsWith(item1.Name)); }) >= 0)
                        {
                            continue;
                        }

                        if (uniqueNames.FindIndex(delegate(Enumerant item1) { return(item1.Name.StartsWith(item.Name)); }) >= 0)
                        {
                            uniqueNames.RemoveAll(delegate(Enumerant item1) { return(item1.Name.StartsWith(item.Name)); });
                        }

                        uniqueNames.Add(item);
                    }

                    uniqueEnums.AddRange(uniqueNames);
                }
                else
                {
                    uniqueEnums.AddRange(pair.Value);
                }
            }

            sw.WriteLine("/// <summary>");
            sw.WriteLine("/// Strongly typed enumeration {0}.", Name);
            sw.WriteLine("/// </summary>");
            if (bitmask)
            {
                sw.WriteLine("[Flags()]");
            }
            sw.WriteLine("public enum {0}{1}", Name, bitmask ? " : uint" : String.Empty);
            sw.WriteLine("{");
            sw.Indent();
            foreach (Enumerant enumerant in uniqueEnums)
            {
                List <Enumerant> allEnums    = groupEnums[enumerant.Value];
                string           bindingName = enumerant.EnumAlias == null ? enumerant.ImplementationName : enumerant.EnumAlias.ImplementationName;
                string           camelCase   = SpecificationStyle.GetCamelCase(bindingName);

                sw.WriteLine("/// <summary>");
                if (allEnums.Count > 1)
                {
                    StringBuilder sb = new StringBuilder();

                    sb.Append("Strongly typed for value ");
                    for (int i = 0; i < allEnums.Count; i++)
                    {
                        sb.Append(allEnums[i].Name);
                        if (i < allEnums.Count - 1)
                        {
                            sb.Append(", ");
                        }
                    }
                    sb.Append(".");

                    foreach (string docLine in RegistryDocumentation.SplitDocumentationLines(sb.ToString()))
                    {
                        sw.WriteLine("/// {0}", docLine);
                    }
                }
                else
                {
                    sw.WriteLine("/// Strongly typed for value {0}.", enumerant.Name);
                }
                sw.WriteLine("/// </summary>");

                Enumerant enumvalue       = ctx.Registry.GetEnumerant(ctx.Class.ToUpperInvariant() + "_" + bindingName);
                string    classDefaultApi = ctx.Class.ToLower();

                if (enumvalue != null)
                {
                    // RequiredByFeature
                    foreach (IFeature feature in enumvalue.RequiredBy)
                    {
                        sw.WriteLine(feature.GenerateRequiredByAttribute(null, classDefaultApi));
                    }
                    // RequiredByFeature (from aliases) Note: not sure that Profile is considered here
                    foreach (Enumerant aliasOf in enumvalue.AliasOf)
                    {
                        foreach (IFeature feature in aliasOf.RequiredBy)
                        {
                            sw.WriteLine(feature.GenerateRequiredByAttribute(null, classDefaultApi));
                        }
                    }
                    // RemovedByFeature
                    foreach (IFeature feature in enumvalue.RemovedBy)
                    {
                        sw.WriteLine(feature.GenerateRemovedByAttribute(classDefaultApi));
                    }
                }

                sw.WriteLine("{0} = {1}.{2},", camelCase, ctx.Class, bindingName);
                sw.WriteLine();
            }
            sw.Unindent();
            sw.WriteLine("}");
        }
        private void RecreateLocations(bool toggle)
        {
            foreach (Location location in locations)
            {
                location.Name = entries [location].Text;
            }

            int i, j;

            if (rbnSingleStore.Active)
            {
                int removeUntil = 1;
                if (toggle)
                {
                    removeUntil = 0;
                }

                for (i = locations.Count - 1; i >= removeUntil; i--)
                {
                    Location location = locations [i];
                    entries.Remove(location);
                    locations.Remove(location);
                }

                if (locations.Count == 0)
                {
                    locations.Add(new Location {
                        Name = Translator.GetString("Store")
                    });
                }
            }
            else
            {
                int removeUntil = spbNumStores.ValueAsInt;
                if (toggle)
                {
                    removeUntil = 0;
                }

                for (i = locations.Count - 1; i >= removeUntil; i--)
                {
                    Location location = locations [i];
                    entries.Remove(location);
                    locations.Remove(location);
                }

                for (i = locations.Count, j = locations.Count; i < spbNumStores.ValueAsInt; i++)
                {
                    string [] newName = { GetNewName(j++) };
                    while (!locations.TrueForAll(l => l.Name != newName [0]))
                    {
                        newName [0] = GetNewName(j++);
                    }

                    locations.Add(new Location {
                        Name = newName [0]
                    });
                }
            }

            RecreateLocationsTable();
        }
        public DicomFile Serialize(SegmentationSerializerCallback callback)
        {
            Platform.CheckForNullReference(callback, "callback");

            Debug.Assert(!_segDocument.Saved, "Cannot serialize previously saved document");

            // TODO: validate that all Segs are coming from the same study!

            IPresentationImage firstIPresentationImage = null;
            if (_segDocument.Segs != null)
            {
                var oneSeg = _segDocument.Segs.FirstOrDefault(item => item != null && item.SegGraphics != null && item.SegGraphics.OfType<PolygonalRoiSegGraphic>().Any());
                if (oneSeg != null)
                {
                    var polyGraphic = oneSeg.SegGraphics.OfType<PolygonalRoiSegGraphic>().First();
                    firstIPresentationImage = callback(polyGraphic.ImageSopInstanceUid, polyGraphic.ImageFrameNumber);
                }
            }
            var firstImageSopProvider = firstIPresentationImage as IImageSopProvider;
            if (firstImageSopProvider == null)
                return null;

            var sourceSop = firstImageSopProvider.ImageSop; // source of the common DICOM attributes
            var dicomFile = _sopInstanceFactory.CreateFile(sourceSop);

            // NOTE. These modules are initialized by the factory:
            // patient IE
            // - PatientModule
            // - ClinicalTrialSubjectModule
            // study IE
            // - GeneralStudyModule
            // - PatientStudyModule
            // - ClinicalTrialStudyModule
            // equipment IE
            // - GeneralEquipmentModule

            // Data values
            const int instanceNumber = 1;
            var contentDateTime = DateTime.Now;

            var segDocumentIod = new SegmentationDocumentIod(dicomFile.DataSet);

            // PatientModule
            var patientModule = segDocumentIod.PatientModuleIod;
            // patientModule.PatientBreedDescription = null; // bug in CC code
            patientModule.DicomAttributeProvider[DicomTags.PatientBreedDescription].SetEmptyValue();

            // GeneralEquipmentModule
            var generalEquipmentModuleIod = segDocumentIod.GeneralEquipmentModuleIod;
            generalEquipmentModuleIod.DeviceSerialNumber = EnvironmentUtilities.MachineIdentifier;

            // GeneralSeriesModule
            var srcGeneralSeriesModuleIod = new GeneralSeriesModuleIod(sourceSop.DataSource);
            var generalSeriesModuleIod = segDocumentIod.GeneralSeriesModuleIod;
            generalSeriesModuleIod.SeriesDescription = _segDocument.SeriesDescription;
            generalSeriesModuleIod.SeriesNumber = _segDocument.SeriesNumber;
            generalSeriesModuleIod.Modality = Modality.Seg;
            generalSeriesModuleIod.SeriesInstanceUid = DicomUid.GenerateUid().UID;
            generalSeriesModuleIod.Laterality = srcGeneralSeriesModuleIod.Laterality;
            generalSeriesModuleIod.SeriesDateTime = _segDocument.CreationDateTime;
            generalSeriesModuleIod.PerformingPhysiciansName = srcGeneralSeriesModuleIod.PerformingPhysiciansName;
            generalSeriesModuleIod.PerformingPhysicianIdentificationSequence = srcGeneralSeriesModuleIod.PerformingPhysicianIdentificationSequence;
            generalSeriesModuleIod.ProtocolName = srcGeneralSeriesModuleIod.ProtocolName;
            {
                // General Description Code Sequence is missing from the GeneralSeriesModuleIod implementation
                var seriesDescriptionCodeSequence = new CodeSequenceMacro
                    {
                        CodeValue = "113076",
                        CodeMeaning = "Segmentation",
                        CodingSchemeDesignator = "DCM"
                    };
                var result = new[] { seriesDescriptionCodeSequence.DicomSequenceItem };

                generalSeriesModuleIod.DicomAttributeProvider[DicomTags.SeriesDescriptionCodeSequence].Values = result;
            }
            string userDicomName = null;
            if (_segDocument.UserInfo != null && !string.IsNullOrEmpty(_segDocument.UserInfo.Name))
            {
                userDicomName = FormatDicomName(_segDocument.UserInfo.Name);
                if (userDicomName != null)
                    generalSeriesModuleIod.OperatorsName = userDicomName;

                // NOTE: Login name is being ignored for now
            }
            generalSeriesModuleIod.BodyPartExamined = srcGeneralSeriesModuleIod.BodyPartExamined;
            generalSeriesModuleIod.PatientPosition = srcGeneralSeriesModuleIod.PatientPosition;
            generalSeriesModuleIod.RequestAttributesSequence = srcGeneralSeriesModuleIod.RequestAttributesSequence;
            //generalSeriesModuleIod.AnatomicalOrientationType = srcGeneralSeriesModuleIod.AnatomicalOrientationType;  // Not needed

            // FrameOfReferenceModule
            var srcFrameOfReferenceModuleIod = new FrameOfReferenceModuleIod(sourceSop.DataSource);
            segDocumentIod.FrameOfReferenceModuleIod.FrameOfReferenceUid = srcFrameOfReferenceModuleIod.FrameOfReferenceUid;
            segDocumentIod.FrameOfReferenceModuleIod.PositionReferenceIndicator = srcFrameOfReferenceModuleIod.PositionReferenceIndicator;

            // Initialize Segmentation Image Module first
            var segmentationImageModuleIod = segDocumentIod.SegmentationImageModuleIod;
            segmentationImageModuleIod.InitializeAttributes();

            // General Image Module and Segmentation Image Module
            var srcGeneralImageModuleIod = new GeneralImageModuleIod(sourceSop.DataSource);
            var generalImageModuleIod = segDocumentIod.GeneralImageModuleIod;
            generalImageModuleIod.InstanceNumber = instanceNumber;
            generalImageModuleIod.PatientOrientation = srcGeneralImageModuleIod.PatientOrientation;
            generalImageModuleIod.ContentDateTime = contentDateTime;
            generalImageModuleIod.ImageType = "DERIVED\\PRIMARY";
            generalImageModuleIod.AcquisitionNumber = srcGeneralImageModuleIod.AcquisitionNumber;
            generalImageModuleIod.AcquisitionDateTime = srcGeneralImageModuleIod.AcquisitionDateTime;
            generalImageModuleIod.QualityControlImage = srcGeneralImageModuleIod.QualityControlImage;
            generalImageModuleIod.BurnedInAnnotation = srcGeneralImageModuleIod.BurnedInAnnotation;
            generalImageModuleIod.RecognizableVisualFeatures = srcGeneralImageModuleIod.RecognizableVisualFeatures;
            generalImageModuleIod.LossyImageCompression = srcGeneralImageModuleIod.LossyImageCompression.HasValue && srcGeneralImageModuleIod.LossyImageCompression.Value;
            generalImageModuleIod.LossyImageCompressionMethod = srcGeneralImageModuleIod.LossyImageCompressionMethod;
            generalImageModuleIod.LossyImageCompressionRatio = srcGeneralImageModuleIod.LossyImageCompressionRatio;
            generalImageModuleIod.IrradiationEventUid = srcGeneralImageModuleIod.IrradiationEventUid;

            // Image Pixel Module and Segmentation Image Module
            var srcImagePixelModule = new ImagePixelMacroIod(sourceSop.DataSource);
            var imagePixelModule = segDocumentIod.ImagePixelModuleIod;
            imagePixelModule.Rows = srcImagePixelModule.Rows; // same height as the the image
            imagePixelModule.Columns = srcImagePixelModule.Columns; // same width as the image
            //imagePixelModule.PixelAspectRatio = srcImagePixelModule.PixelAspectRatio; // same as the image

            // Continue initialization of non-default values for the Segmentation Image Module
            segmentationImageModuleIod.ContentLabel = SanitizeDicomCsValue(_segDocument.ContentLabel);
            if (!string.IsNullOrEmpty(userDicomName))
                segmentationImageModuleIod.ContentCreatorsName = userDicomName;
            segmentationImageModuleIod.SegmentationType = SegmentationType.BINARY;

            // Per segmentation and per frame item initialization
            var docHasOneFrame = _segDocument.Segs.Where(item => item != null && item.SegGraphics != null).Sum(seg => seg.SegGraphics.OfType<PolygonalRoiSegGraphic>().Count()) == 1;
            var docHasOneSeg = _segDocument.Segs.Count(item => item != null && item.SegGraphics != null && item.SegGraphics.OfType<PolygonalRoiSegGraphic>().Any()) == 1;
            var multiFrameDimensionsModuleIod = segDocumentIod.MultiFrameDimensionModuleIod;
            multiFrameDimensionsModuleIod.InitializeAttributes();
            var segmentSequenceItems = new List<SegmentSequence>();
            var dimensionIndexSequenceItems = new List<DimensionIndexSequenceItem>();
            var dimensionOrganizationSequenceItems = new List<DimensionOrganizationSequenceItem>();
            var multiFrameFunctionalGroupsModuleIod = segDocumentIod.MultiFrameFunctionalGroupsModuleIod;
            multiFrameFunctionalGroupsModuleIod.InitializeAttributes();
            var perFrameFunctionalGroupSequenceItems = new List<FunctionalGroupsSequenceItem>();
            var frameBytesList = new List<byte[]>(); // list of pixel data for each frame
            var seriesUidToSopClassUidToSopInstanceUid = new Dictionary<string, Dictionary<string, HashSet<string>>>();
            var segmentNumber = 0;
            foreach (var seg in _segDocument.Segs)
            {
                segmentNumber++;
                Debug.Assert(segmentNumber == 1, "We're only supposed to create one Segment per document for now");

                // Segment Sequence initialization
                var segmentSequenceItemIod = segmentationImageModuleIod.CreateSegmentSequence();
                segmentSequenceItemIod.SegmentNumber = segmentNumber;
                segmentSequenceItemIod.SegmentLabel = seg.Label;
                segmentSequenceItemIod.SegmentDescription = seg.Description;
                segmentSequenceItemIod.SegmentAlgorithmType = "MANUAL";

                #region Category, Type, Anatomic Region, Anatomic Region Modifier

                var selectedCategory = seg.SelectedCategory;
                if (selectedCategory != null)
                {
                    // Category
                    var segmentedPropertyCategoryCodeSequenceItem = segmentSequenceItemIod.CreateSegmentedPropertyCategoryCodeSequence();
                    segmentedPropertyCategoryCodeSequenceItem.CodeValue = selectedCategory.CodeValue;
                    segmentedPropertyCategoryCodeSequenceItem.CodeMeaning = selectedCategory.CodeMeaning;
                    segmentedPropertyCategoryCodeSequenceItem.CodingSchemeDesignator = selectedCategory.CodingSchemeDesignator;
                    //if (!string.IsNullOrEmpty(selectedCategory.CodingSchemeVersion))
                    //    segmentedPropertyCategoryCodeSequenceItem.CodingSchemeVersion = selectedCategory.CodingSchemeVersion;
                    segmentSequenceItemIod.SegmentedPropertyCategoryCodeSequence = new[] { segmentedPropertyCategoryCodeSequenceItem };

                    // Type
                    if (selectedCategory.SelectedType != null)
                    {
                        var segmentedPropertyTypeCodeSequenceItem = segmentSequenceItemIod.CreateSegmentedPropertyTypeCodeSequence();
                        segmentedPropertyTypeCodeSequenceItem.CodeValue = selectedCategory.SelectedType.CodeValue;
                        segmentedPropertyTypeCodeSequenceItem.CodeMeaning = selectedCategory.SelectedType.CodeMeaning;
                        segmentedPropertyTypeCodeSequenceItem.CodingSchemeDesignator = selectedCategory.SelectedType.CodingSchemeDesignator;
                        //if (!string.IsNullOrEmpty(selectedCategory.SelectedType.CodingSchemeVersion))
                        //    segmentedPropertyTypeCodeSequenceItem.CodingSchemeVersion = selectedCategory.SelectedType.CodingSchemeVersion;

                        // Type modifier
                        if (selectedCategory.SelectedType.SelectedTypeModifier != null)
                        {
                            var segmentedPropertyTypeModifierCodeSequenceItem = new CodeSequenceMacro();
                            segmentedPropertyTypeModifierCodeSequenceItem.CodeValue = selectedCategory.SelectedType.SelectedTypeModifier.CodeValue;
                            segmentedPropertyTypeModifierCodeSequenceItem.CodeMeaning = selectedCategory.SelectedType.SelectedTypeModifier.CodeMeaning;
                            segmentedPropertyTypeModifierCodeSequenceItem.CodingSchemeDesignator = selectedCategory.SelectedType.SelectedTypeModifier.CodingSchemeDesignator;
                            //if (!string.IsNullOrEmpty(selectedCategory.SelectedType.SelectedTypeModifier.CodingSchemeVersion))
                            //    segmentedPropertyTypeModifierCodeSequenceItem.CodingSchemeVersion = selectedCategory.SelectedType.SelectedTypeModifier.CodingSchemeVersion;

                            segmentedPropertyTypeCodeSequenceItem.SegmentedPropertyTypeModifierCodeSequence = new[] {segmentedPropertyTypeModifierCodeSequenceItem};
                        }
                        segmentSequenceItemIod.SegmentedPropertyTypeCodeSequence = new[] { segmentedPropertyTypeCodeSequenceItem };
                    }

                    // Anatomic Region
                    var selectedAnatomicRegion = selectedCategory.SelectedAnatomicRegion;
                    if (selectedAnatomicRegion != null)
                    {
                        var anatomicRegionSequenceItem = segmentSequenceItemIod.CreateAnatomicRegionSequence();
                        anatomicRegionSequenceItem.CodeValue = selectedAnatomicRegion.CodeValue;
                        anatomicRegionSequenceItem.CodeMeaning = selectedAnatomicRegion.CodeMeaning;
                        anatomicRegionSequenceItem.CodingSchemeDesignator = selectedAnatomicRegion.CodingSchemeDesignator;
                        //if (!string.IsNullOrEmpty(selectedAnatomicRegion.CodingSchemeVersion))
                        //    anatomicRegionSequenceItem.CodingSchemeVersion = selectedAnatomicRegion.CodingSchemeVersion;

                        // Anatomic region Modifier
                        if (selectedAnatomicRegion.SelectedAnatomicRegionModifier != null)
                        {
                            var anatomicRegionModifierSequenceItem = new CodeSequenceMacro();
                            anatomicRegionModifierSequenceItem.CodeValue = selectedAnatomicRegion.SelectedAnatomicRegionModifier.CodeValue;
                            anatomicRegionModifierSequenceItem.CodeMeaning = selectedAnatomicRegion.SelectedAnatomicRegionModifier.CodeMeaning;
                            anatomicRegionModifierSequenceItem.CodingSchemeDesignator = selectedAnatomicRegion.SelectedAnatomicRegionModifier.CodingSchemeDesignator;
                            //if (!string.IsNullOrEmpty(selectedAnatomicRegion.SelectedAnatomicRegionModifier.CodingSchemeVersion))
                            //    anatomicRegionModifierSequenceItem.CodingSchemeVersion = selectedAnatomicRegion.SelectedAnatomicRegionModifier.CodingSchemeVersion;

                            anatomicRegionSequenceItem.AnatomicRegionModifierSequence = new[] { anatomicRegionModifierSequenceItem };
                        }
                        segmentSequenceItemIod.AnatomicRegionSequence = new[] { anatomicRegionSequenceItem };
                    }
                }

                #endregion

                segmentSequenceItemIod.RecomendedDisplayCIELabValue = LabColorHelpers.RgbColorToCIELabColor(seg.Color);
                segmentSequenceItems.Add(segmentSequenceItemIod);

                // Dimension Organization Sequence item
                var dimensionOrganizationUid = DicomUid.GenerateUid().UID;
                var dimensionOrganizationSequenceItem = multiFrameDimensionsModuleIod.CreateDimensionOrganizationSequenceItem();
                dimensionOrganizationSequenceItem.DimensionOrganizationUid = dimensionOrganizationUid;
                dimensionOrganizationSequenceItems.Add(dimensionOrganizationSequenceItem);

                // Dimension Index Sequence items
                var dimensionIndexSequenceItem1 = multiFrameDimensionsModuleIod.CreateDimensionIndexSequenceItem();
                dimensionIndexSequenceItem1.DimensionIndexPointer = DicomTags.StackId;
                dimensionIndexSequenceItem1.FunctionalGroupPointer = DicomTags.FrameContentSequence;
                dimensionIndexSequenceItem1.DimensionOrganizationUid = dimensionOrganizationUid;
                dimensionIndexSequenceItem1.DimensionDescriptionLabel = "Stack ID";
                dimensionIndexSequenceItems.Add(dimensionIndexSequenceItem1);
                var dimensionIndexSequenceItem2 = multiFrameDimensionsModuleIod.CreateDimensionIndexSequenceItem();
                dimensionIndexSequenceItem2.DimensionIndexPointer = DicomTags.InStackPositionNumber;
                dimensionIndexSequenceItem2.FunctionalGroupPointer = DicomTags.FrameContentSequence;
                dimensionIndexSequenceItem2.DimensionOrganizationUid = dimensionOrganizationUid;
                dimensionIndexSequenceItem2.DimensionDescriptionLabel = "In Stack Position Number";
                dimensionIndexSequenceItems.Add(dimensionIndexSequenceItem2);

                var inStackPositionIndex = 0;

                var presentationImagePolygons = new Dictionary<IPresentationImage, List<PolygonalRoiSegGraphic>>();
                foreach (var polygonalSegGraphic in seg.SegGraphics.OfType<PolygonalRoiSegGraphic>())
                {
                    var poly = polygonalSegGraphic.PolygonalRoiGraphic.Roi as PolygonalRoi;
                    if (poly != null)
                    {
                        var currentPresentationImage = callback(polygonalSegGraphic.ImageSopInstanceUid, polygonalSegGraphic.ImageFrameNumber);
                        if (presentationImagePolygons.ContainsKey(currentPresentationImage))
                            presentationImagePolygons[currentPresentationImage].Add(polygonalSegGraphic);
                        else
                            presentationImagePolygons.Add(poly.PresentationImage, new List<PolygonalRoiSegGraphic> { polygonalSegGraphic });
                    }
                    else
                    {
                        Debug.Assert(false, "Encountered non-polygonal graphic during segmentation serialization");
                    }
                }

                foreach (var presentationImage in presentationImagePolygons.Keys)
                {
                    var currentImageSopProvider = presentationImage as IImageSopProvider;

                    if (presentationImage == null)
                    {
                        Debug.Assert(false, "Failed to get IImageSopProvider for the current Segmentation graphic");
                        continue;
                    }

                    Debug.Assert(presentationImagePolygons[presentationImage].FirstOrDefault().ImageFrameNumber ==
                        currentImageSopProvider.Frame.FrameNumber,
                                 "Stored frame number must match with the current SOP Instance's value");

                    #region PerFrameFunctionalGroupSequenceItem

                    // Initialize Per Frame Functional Groups here and groups
                    var perFrameFunctionalGroupSequenceItem = multiFrameFunctionalGroupsModuleIod.CreatePerFrameFunctionalGroupsSequence();

                    if (!docHasOneSeg)
                    {
                        // Pixel Measures Functional Group (per frame)
                        InitializePixelMeasureFunctionalGroup(perFrameFunctionalGroupSequenceItem, currentImageSopProvider.Frame);

                        // Initialize Segmentation Functional Group (per frame)
                        InitializeSegmentationFunctionalGroup(perFrameFunctionalGroupSequenceItem, segmentNumber);

                        // Plane Orientation (Patient) Functional Group
                        InitializePlaneOrientationPatientFunctionalGroup(perFrameFunctionalGroupSequenceItem, currentImageSopProvider.Frame.ImageOrientationPatient);
                    }
                    if (!docHasOneFrame)
                    {
                        // Plain Position Patient Functional Group (per frame)
                        InitializePlanePositionPatientFunctionalGroup(perFrameFunctionalGroupSequenceItem, currentImageSopProvider.Frame.ImagePositionPatient);

                        // Derivation Image Functional Group (per frame)
                        InitializeDerivationImageFunctionalGroup(perFrameFunctionalGroupSequenceItem, currentImageSopProvider.ImageSop, currentImageSopProvider.Frame.FrameNumber);
                    }
                    else
                    {
                        Debug.Assert(firstImageSopProvider.ImageSop.SeriesInstanceUid == currentImageSopProvider.Frame.SeriesInstanceUid &&
                                     firstImageSopProvider.ImageSop.SopInstanceUid == currentImageSopProvider.ImageSop.SopInstanceUid,
                                     "initial image reference and the single image reference must be the same");
                    }

                    // Initialize Frame Content Functional Group
                    InitializeFrameContentFunctionalGroup(perFrameFunctionalGroupSequenceItem, segmentNumber, ++inStackPositionIndex);

                    perFrameFunctionalGroupSequenceItems.Add(perFrameFunctionalGroupSequenceItem);

                    #endregion PerFrameFunctionalGroupSequenceItem

                    // Store referenced image info in a dictionary for later use
                    {
                        var currentSeriesInstanceUid = currentImageSopProvider.ImageSop.SeriesInstanceUid;
                        var currentSopClassUid = currentImageSopProvider.ImageSop.SopClassUid;
                        var currentSopInstanceUid = currentImageSopProvider.ImageSop.SopInstanceUid;
                        if (!seriesUidToSopClassUidToSopInstanceUid.ContainsKey(currentSeriesInstanceUid))
                            seriesUidToSopClassUidToSopInstanceUid.Add(currentSeriesInstanceUid, new Dictionary<string, HashSet<string>>());
                        var sopClassToSopInstanceDic = seriesUidToSopClassUidToSopInstanceUid[currentSeriesInstanceUid];
                        if (!sopClassToSopInstanceDic.ContainsKey(currentSopClassUid))
                            sopClassToSopInstanceDic.Add(currentSopClassUid, new HashSet<string>());
                        sopClassToSopInstanceDic[currentSopClassUid].Add(currentSopInstanceUid);
                    }

                    var polygons = new List<IList<PointF>>();

                    // Get frame's pixel data here
                    foreach (var polygonalSegGraphic in presentationImagePolygons[presentationImage])
                    {
                        var poly = polygonalSegGraphic.PolygonalRoiGraphic.Roi as PolygonalRoi;
                        if (poly != null)
                        {
                            polygons.Add(poly.Polygon.Vertices);
                        }
                        else
                        {
                            Debug.Assert(false, "Encountered non-polygonal graphic during segmentation serialization");
                        }
                    }

                    var grayscalePixelData = CreateFramePixelData(presentationImage, polygons);
                    frameBytesList.Add(grayscalePixelData.Raw);
                }
            }

            segmentationImageModuleIod.SegmentSequence = segmentSequenceItems.ToArray();

            // Per Frame Functional Groups module
            multiFrameFunctionalGroupsModuleIod.PerFrameFunctionalGroupsSequence = perFrameFunctionalGroupSequenceItems.ToArray();

            #region SharedFunctionalGroupSequence

            // Shared Functional Group Sequence Item
            var sharedFunctionalGroupSequenceItem = multiFrameFunctionalGroupsModuleIod.CreateSharedFunctionalGroupsSequence();

            if (docHasOneSeg)
            {
                Debug.Assert(segmentNumber == 1, "This is for a single segment only");

                // Pixel Measures Functional Group (shared)
                InitializePixelMeasureFunctionalGroup(sharedFunctionalGroupSequenceItem, firstImageSopProvider.Frame);

                // Initialize Segmentation Functional Group (shared)
                InitializeSegmentationFunctionalGroup(sharedFunctionalGroupSequenceItem, segmentNumber);

                // Plane Orientation (Patient) Functional Group
                InitializePlaneOrientationPatientFunctionalGroup(sharedFunctionalGroupSequenceItem, firstImageSopProvider.Frame.ImageOrientationPatient);
            }

            if (docHasOneFrame)
            {
                // Plain Position Patient Functional Group
                InitializePlanePositionPatientFunctionalGroup(sharedFunctionalGroupSequenceItem, firstImageSopProvider.Frame.ImagePositionPatient);

                // Derivation Image Functional Group
                InitializeDerivationImageFunctionalGroup(sharedFunctionalGroupSequenceItem, firstImageSopProvider.ImageSop, firstImageSopProvider.Frame.FrameNumber);
            }

            multiFrameFunctionalGroupsModuleIod.SharedFunctionalGroupsSequence = sharedFunctionalGroupSequenceItem;

            #endregion SharedFunctionalGroupSequence

            // Multi-frame Dimensions module
            multiFrameDimensionsModuleIod.DimensionIndexSequence = dimensionIndexSequenceItems.ToArray();
            multiFrameDimensionsModuleIod.DimensionOrganizationSequence = dimensionOrganizationSequenceItems.ToArray();
            multiFrameDimensionsModuleIod.DimensionOrganizationType = "3D";

            // Multi-frame Functional Groups module
            multiFrameFunctionalGroupsModuleIod.SharedFunctionalGroupsSequence = sharedFunctionalGroupSequenceItem;
            multiFrameFunctionalGroupsModuleIod.PerFrameFunctionalGroupsSequence = perFrameFunctionalGroupSequenceItems.ToArray();
            multiFrameFunctionalGroupsModuleIod.NumberOfFrames = perFrameFunctionalGroupSequenceItems.Count;

            // Specimen Module
            var srcSpecimenModuleIod = new SpecimenModuleIod(sourceSop.DataSource);
            var specimenModuleIod = segDocumentIod.SpecimenModuleIod;
            //specimenModuleIod.ContainerIdentifier = srcSpecimenModuleIod.ContainerIdentifier;
            specimenModuleIod.IssuerOfTheContainterIdentifier = srcSpecimenModuleIod.IssuerOfTheContainterIdentifier;
            specimenModuleIod.AlternateContainerIdentifierSequence = srcSpecimenModuleIod.AlternateContainerIdentifierSequence;
            specimenModuleIod.ContainerTypeCodeSequence = srcSpecimenModuleIod.ContainerTypeCodeSequence;
            //specimenModuleIod.ContainerDescription = srcSpecimenModuleIod.ContainerDescription;
            specimenModuleIod.ContainerComponentSequence = srcSpecimenModuleIod.ContainerComponentSequence;
            specimenModuleIod.SpecimenDescriptionSequence = srcSpecimenModuleIod.SpecimenDescriptionSequence;

            // Common Instance Reference Module
            var referencedSeriesSequenceItems = new List<ReferencedSeriesSequenceIod>();
            foreach (
                var seriesToSopClassToSopInstanceDic in
                    seriesUidToSopClassUidToSopInstanceUid.Where(seriesToSopClassToSopInstanceDic => seriesToSopClassToSopInstanceDic.Value != null))
            {
                var referencedSopInstances = new List<ReferencedInstanceSequenceIod>();
                foreach (var sopClassToSopInstanceDic in seriesToSopClassToSopInstanceDic.Value.Where(sopClassToSopInstanceDic => sopClassToSopInstanceDic.Value != null))
                {
                    referencedSopInstances.AddRange(sopClassToSopInstanceDic.Value.Select(sopInstanceUid => new ReferencedInstanceSequenceIod
                        {
                            ReferencedSopClassUid = sopClassToSopInstanceDic.Key,
                            ReferencedSopInstanceUid = sopInstanceUid
                        }));
                }
                if (referencedSopInstances.Count > 0)
                {
                    referencedSeriesSequenceItems.Add(new ReferencedSeriesSequenceIod
                        {
                            SeriesInstanceUid = seriesToSopClassToSopInstanceDic.Key,
                            ReferencedInstanceSequence = referencedSopInstances.ToArray()
                        });
                }
            }
            if (referencedSeriesSequenceItems.Count > 0)
            {
                var commonInstanceReferenceModuleIod = segDocumentIod.CommonInstanceReferenceModuleIod;
                commonInstanceReferenceModuleIod.InitializeAttributes();
                commonInstanceReferenceModuleIod.ReferencedSeriesSequence = referencedSeriesSequenceItems.ToArray();
            }

            // SOP Common Module
            var srcSopCommonModuleIod = new SopCommonModuleIod(sourceSop.DataSource);
            var sopCommonModuleIod = segDocumentIod.SopCommonModuleIod;
            sopCommonModuleIod.SopClass = SopClass.SegmentationStorage;
            sopCommonModuleIod.SopInstanceUid = DicomUid.GenerateUid().UID;
            //sopCommonModuleIod.SpecificCharacterSet = "UTF-8"; // TBD -it's ISO_IR 192 by default
            sopCommonModuleIod.InstanceCreationDateTime = contentDateTime;
            sopCommonModuleIod.InstanceCreatorUid = InstanceCreatorUid;
            sopCommonModuleIod.TimezoneOffsetFromUtc = contentDateTime.ToString("zzz", DateTimeFormatInfo.InvariantInfo);
            //sopCommonModuleIod.LongitudinalTemporalInformationModified = srcSopCommonModuleIod.LongitudinalTemporalInformationModified; // has a bug in CC

            // Pixel data
            {
                Debug.Assert(frameBytesList.TrueForAll(bytes => bytes.Length == frameBytesList[0].Length), "Allocated buffers for all frames must be of the same size");
                var byteBuffer = new byte[frameBytesList[0].Length * frameBytesList.Count];
                using (var stream = new MemoryStream(byteBuffer))
                {
                    foreach (var frameBytes in frameBytesList)
                        stream.Write(frameBytes, 0, frameBytes.Length);
                }
                // Byte Packing
                // TODO FIXME: we can do in-place byte packing without allocating the second array!
                var packetBuffer = new byte[(int) Math.Ceiling(byteBuffer.Length/8.0)];
                var numberOfFullBytes = byteBuffer.Length/8;
                for (var i = 0; i < numberOfFullBytes; i++)
                {
                    var newByte = packetBuffer[i];
                    for (var y = 0; y < 8; y++)
                    {
                        var bitMask = (byte) (1 << y);
                        newByte = (byte) ((byteBuffer[8*i + y] & 0xFF) > 0 ? newByte | bitMask : newByte & ~bitMask);
                    }
                    packetBuffer[i] = newByte;
                }
                // last byte(s) TODO VK: handle padding for non-even number of bytes. make sure padded bits are initialized to 0
                if (numberOfFullBytes < packetBuffer.Length)
                {
                    // Pack leftover bytes ( < 8)
                    Debug.Assert(packetBuffer.Length - numberOfFullBytes == 1, "Wrong destination bytes count during packing");
                    Debug.Assert(byteBuffer.Length - numberOfFullBytes*8 < 8, "Wrong leftover bytes count during packing");
                    var newByte = packetBuffer[packetBuffer.Length - 1];
                    for (var y = numberOfFullBytes * 8; y < byteBuffer.Length; y++)
                    {
                        var bitMask = (byte) (1 << (y%8));
                        newByte = (byte) ((byteBuffer[y] & 0xFF) > 0 ? newByte | bitMask : newByte & ~bitMask);
                    }
                    packetBuffer[packetBuffer.Length - 1] = newByte;
                }
                var pdAttribute = new DicomAttributeOW(DicomTags.PixelData);
                using (var stream = pdAttribute.AsStream())
                {
                    stream.Write(packetBuffer, 0, packetBuffer.Length);
                }

                multiFrameFunctionalGroupsModuleIod.DicomAttributeProvider[DicomTags.PixelData] = pdAttribute;
            }

            dicomFile.MediaStorageSopClassUid = SopClass.SegmentationStorageUid;
            dicomFile.MediaStorageSopInstanceUid = segDocumentIod.SopInstanceUid;

            // Update the original document with new values
            _segDocument.SeriesInstanceUid = segDocumentIod.SeriesInstanceUid;
            _segDocument.SopInstanceUid = segDocumentIod.SopInstanceUid;

            return dicomFile;
        }
Example #39
0
        public MazeGraph(W4Maze maze, bool isSimplify)
        {
            _Cells     = new List <MazeGraphCell>(maze.RowCount * maze.ColumnCount);
            _PathEdges = new List <Edge>();
            _WallEdges = new List <Edge>();
            for (int i = 0; i < _Cells.Capacity; i++)
            {
                _Cells.Add(new MazeGraphCell());
            }
            for (int j = 0; j < maze.RowCount; j++)
            {
                for (int i = 0; i < maze.ColumnCount; i++)
                {
                    var cell  = maze.GetCell(i, j);
                    int index = i + j * maze.ColumnCount;

                    MazeGraphCellFromW4Cell(
                        _Cells[index],
                        cell,
                        i,
                        j,
                        maze.ColumnCount
                        );

                    _Cells[index].Position = new Vector2(
                        i + 0.5f,
                        j + 0.5f);
                    _Cells[index].CanBeSimplifiied
                        = (!cell.BotWall && !cell.TopWall &&
                           cell.RightWall && cell.LeftWall) ||
                          (cell.BotWall && cell.TopWall &&
                           !cell.RightWall && !cell.LeftWall);

                    if (cell.BotWall)
                    {
                        var edge = new Edge();
                        edge.Begin = new Vector2(
                            _Cells[index].Position.x - 0.5f,
                            _Cells[index].Position.y - 0.5f);
                        edge.End = new Vector2(
                            _Cells[index].Position.x + 0.5f,
                            _Cells[index].Position.y - 0.5f);
                        if (_WallEdges.TrueForAll(x => x != edge))
                        {
                            _WallEdges.Add(edge);
                        }
                    }
                    if (cell.TopWall)
                    {
                        var edge = new Edge();
                        edge.Begin = new Vector2(
                            _Cells[index].Position.x - 0.5f,
                            _Cells[index].Position.y + 0.5f);
                        edge.End = new Vector2(
                            _Cells[index].Position.x + 0.5f,
                            _Cells[index].Position.y + 0.5f);
                        if (_WallEdges.TrueForAll(x => x != edge))
                        {
                            _WallEdges.Add(edge);
                        }
                    }
                    if (cell.LeftWall)
                    {
                        var edge = new Edge();
                        edge.Begin = new Vector2(
                            _Cells[index].Position.x - 0.5f,
                            _Cells[index].Position.y - 0.5f);
                        edge.End = new Vector2(
                            _Cells[index].Position.x - 0.5f,
                            _Cells[index].Position.y + 0.5f);
                        if (_WallEdges.TrueForAll(x => x != edge))
                        {
                            _WallEdges.Add(edge);
                        }
                    }
                    if (cell.RightWall)
                    {
                        var edge = new Edge();
                        edge.Begin = new Vector2(
                            _Cells[index].Position.x + 0.5f,
                            _Cells[index].Position.y + 0.5f);
                        edge.End = new Vector2(
                            _Cells[index].Position.x + 0.5f,
                            _Cells[index].Position.y - 0.5f);
                        if (_WallEdges.TrueForAll(x => x != edge))
                        {
                            _WallEdges.Add(edge);
                        }
                    }
                }
            }
            if (isSimplify)
            {
                for (int i = 0; i < _Cells.Count; i++)
                {
                    if (_Cells[i].CanBeSimplifiied)
                    {
                        SimplifyCell(_Cells[i]);
                        i--;
                    }
                }
            }
            CalculatePathEdges();
            ProcessWallEdges();
        }
Example #40
0
        public TilesetTexture(params TilesetImage[] tilesetImages)
        {
            Debug.Assert(tilesetImages != null && tilesetImages.Length > 0);


            foreach (TilesetImage tilesetImage in tilesetImages)
            {
                if (tilesetImage == null || tilesetImage.ImagePath == null)
                {
                    m_textures.Add(null);
                    continue;
                }

                using (FileStream stream = new FileStream(tilesetImage.ImagePath, FileMode.Open, FileAccess.Read))
                    using (Bitmap bmp = new Bitmap(Image.FromStream(stream, true)))
                    {
                        if (bmp.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppArgb)
                        {
                            throw new ArgumentException("The image on the specified path is not in the required RGBA format.", "tilesetImages");
                        }

                        int tilesPerRow    = bmp.Width / (tilesetImage.TileSize.X + tilesetImage.TileMargin.X);
                        int tilesPerColumn = bmp.Height / (tilesetImage.TileSize.Y + tilesetImage.TileMargin.Y);

                        using (Bitmap bmpTextureWithBorders = new Bitmap(
                                   tilesPerRow * (tilesetImage.TileSize.X + tilesetImage.TileMargin.X + tilesetImage.TileBorder.X * 2),
                                   tilesPerColumn * (tilesetImage.TileSize.Y + tilesetImage.TileMargin.Y + tilesetImage.TileBorder.Y * 2),
                                   System.Drawing.Imaging.PixelFormat.Format32bppArgb))
                        {
                            BitmapData dataOrig = bmp.LockBits(
                                new Rectangle(0, 0, bmp.Width, bmp.Height),
                                ImageLockMode.ReadOnly,
                                System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                            BitmapData dataNew = bmpTextureWithBorders.LockBits(
                                new Rectangle(0, 0, bmpTextureWithBorders.Width, bmpTextureWithBorders.Height),
                                ImageLockMode.ReadWrite,
                                System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                            IncreaseTileBorders(
                                dataOrig, dataNew,
                                tilesPerRow, tilesPerColumn,
                                tilesetImage);

                            try
                            {
                                BasicTexture2D texture = new BasicTexture2D(bmpTextureWithBorders.Width, bmpTextureWithBorders.Height);

                                texture.Init2D(
                                    dataNew.Scan0.ArgbToArgbArray(dataNew.Width * dataNew.Height),
                                    generateMipmap: true);

                                texture.SetParameters(TextureMinFilter.LinearMipmapLinear);

                                m_textures.Add(texture);
                            }
                            finally
                            {
                                bmp.UnlockBits(dataOrig);
                                bmpTextureWithBorders.UnlockBits(dataNew);
                            }
                        }
                    }
            }

            Size = m_textures[0].Size;
            Debug.Assert(m_textures.TrueForAll(a => a.Size == Size), "Tilesets have to be of the same dimensionality.");
        }
        private ToolStripMenuItem GeneratePoolFilterItem(Pool p)
        {
            List<ToolStripMenuItem> subItems = new List<ToolStripMenuItem>();

            foreach (Host h in p.Connection.Cache.Hosts)
            {
                var hostItem = GenerateFilterItem(h, h.uuid);
                hostItem.Checked = HostCheckStates.ContainsKey(h.uuid);
                subItems.Add(hostItem);
            }

            var poolItem = GenerateFilterItem(p, p.uuid);
            poolItem.DropDownItems.AddRange(subItems.ToArray());
            poolItem.CheckState = subItems.TrueForAll(item => item.Checked)
                                      ? CheckState.Checked
                                      : subItems.TrueForAll(item => !item.Checked)
                                            ? CheckState.Unchecked
                                            : CheckState.Indeterminate;
            poolItem.DropDownItemClicked += poolItem_DropDownItemClicked;
            return poolItem;
        }
Example #42
0
        public void LoadCIFAR10DataSet(bool normalizeContrast = false)
        {
            string path = DataSetPath[(int)DataProviderSets.CIFAR10];

            stopwatch.Restart();
            SampleWidth       = 32;
            SampleHeight      = 32;
            SampleSize        = SampleWidth * SampleHeight;
            SampleChannels    = 3;
            UsedPixelFormat   = PixelFormats.Rgb24;
            ClassCount        = 10;
            GaussianFieldSize = 25;

            int counter = 0;

            ImageData[] CIFAR10Training = new ImageData[50000];
            ImageData[] CIFAR10Testing  = new ImageData[10000];

            List <Task> tasks = new List <Task>(6);

            tasks.Add(new Task(() =>
            {
                byte[] samples = new byte[30730000];
                using (FileStream fileStreamTrainPatterns = System.IO.File.Open(path + @"\data_batch_1.bin", FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    fileStreamTrainPatterns.Read(samples, 0, 30730000);
                }
                for (int index = 0; index < 10000; index++)
                {
                    CIFAR10Training[index].Label = samples[3073 * index];
                    byte[] image = new byte[3072];
                    for (int i = 0; i < 3072; i++)
                    {
                        image[i] = samples[((3073 * index) + 1) + i];
                    }
                    CIFAR10Training[index].Image = image;
                    System.Threading.Interlocked.Increment(ref counter);
                }
            }));

            tasks.Add(new Task(() =>
            {
                byte[] samples = new byte[30730000];
                using (FileStream fileStreamTrainPatterns = System.IO.File.Open(path + @"\data_batch_2.bin", FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    fileStreamTrainPatterns.Read(samples, 0, 30730000);
                }
                for (int index = 10000; index < 20000; index++)
                {
                    CIFAR10Training[index].Label = samples[3073 * (index - 10000)];
                    byte[] image = new byte[3072];
                    for (int i = 0; i < 3072; i++)
                    {
                        image[i] = samples[((3073 * (index - 10000)) + 1) + i];
                    }
                    CIFAR10Training[index].Image = image;
                    System.Threading.Interlocked.Increment(ref counter);
                }
            }));

            tasks.Add(new Task(() =>
            {
                byte[] samples = new byte[30730000];
                using (FileStream fileStreamTrainPatterns = System.IO.File.Open(path + @"\data_batch_3.bin", FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    fileStreamTrainPatterns.Read(samples, 0, 30730000);
                }
                for (int index = 20000; index < 30000; index++)
                {
                    CIFAR10Training[index].Label = samples[3073 * (index - 20000)];
                    byte[] image = new byte[3072];
                    for (int i = 0; i < 3072; i++)
                    {
                        image[i] = samples[((3073 * (index - 20000)) + 1) + i];
                    }
                    CIFAR10Training[index].Image = image;
                    System.Threading.Interlocked.Increment(ref counter);
                }
            }));

            tasks.Add(new Task(() =>
            {
                byte[] samples = new byte[30730000];
                using (FileStream fileStreamTrainPatterns = System.IO.File.Open(path + @"\data_batch_4.bin", FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    fileStreamTrainPatterns.Read(samples, 0, 30730000);
                }
                for (int index = 30000; index < 40000; index++)
                {
                    CIFAR10Training[index].Label = samples[3073 * (index - 30000)];
                    byte[] image = new byte[3072];
                    for (int i = 0; i < 3072; i++)
                    {
                        image[i] = samples[((3073 * (index - 30000)) + 1) + i];
                    }
                    CIFAR10Training[index].Image = image;
                    System.Threading.Interlocked.Increment(ref counter);
                }
            }));

            tasks.Add(new Task(() =>
            {
                byte[] samples = new byte[30730000];
                using (FileStream fileStreamTrainPatterns = System.IO.File.Open(path + @"\data_batch_5.bin", FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    fileStreamTrainPatterns.Read(samples, 0, 30730000);
                }
                for (int index = 40000; index < 50000; index++)
                {
                    CIFAR10Training[index].Label = samples[3073 * (index - 40000)];
                    byte[] image = new byte[3072];
                    for (int i = 0; i < 3072; i++)
                    {
                        image[i] = samples[((3073 * (index - 40000)) + 1) + i];
                    }
                    CIFAR10Training[index].Image = image;
                    System.Threading.Interlocked.Increment(ref counter);
                }
            }));

            tasks.Add(new Task(() =>
            {
                byte[] samples = new byte[30730000];
                using (FileStream fileStreamTrainPatterns = System.IO.File.Open(path + @"\test_batch.bin", FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    fileStreamTrainPatterns.Read(samples, 0, 30730000);
                }
                for (int index = 0; index < 10000; index++)
                {
                    CIFAR10Testing[index].Label = samples[3073 * index];
                    byte[] image = new byte[3072];
                    for (int i = 0; i < 3072; i++)
                    {
                        image[i] = samples[((3073 * index) + 1) + i];
                    }
                    CIFAR10Testing[index].Image = image;
                    System.Threading.Interlocked.Increment(ref counter);
                }
            }));

            foreach (Task task in tasks)
            {
                task.Start();
            }

            while (!tasks.TrueForAll(task => task.IsCompleted))
            {
                OnRaiseDataProgressEvent(new DataProviderEventArgs((int)(counter / 1200), "CIFAR-10 Dataset loading...", stopwatch.Elapsed));
                Thread.Sleep(10);
            }

            foreach (Task task in tasks)
            {
                task.Dispose();
            }
            tasks = null;

            OnRaiseDataProgressEvent(new DataProviderEventArgs(50, "Creating Training Samples...", stopwatch.Elapsed));

            // substractive mean
            Mean = new double[SampleSize * SampleChannels];

            TrainingSamplesCount = 100000;
            RandomTrainingSample = new int[TrainingSamplesCount];
            TrainingSamples      = new ImageData[TrainingSamplesCount];
            int part = TrainingSamplesCount / 2;

            for (int i = 0; i < SampleSize; i++)
            {
                for (int c = 0; c < SampleChannels; c++)
                {
                    Mean[i + (c * SampleSize)] = 0D;
                }
            }

            OnRaiseDataProgressEvent(new DataProviderEventArgs(70, String.Format("Creating Training Samples..."), stopwatch.Elapsed));

            Parallel.For(0, part, ParallelOption, j =>
            {
                RandomTrainingSample[j] = j;
                TrainingSamples[j]      = CIFAR10Training[j];
            });

            Parallel.For(part, 2 * part, ParallelOption, j =>
            {
                RandomTrainingSample[j] = j;
                TrainingSamples[j]      = TrainingSamples[j - part].Mirror(32, 32, 3);
            });

            Parallel.For(0, part, ParallelOption, j =>
            {
                for (int i = 0; i < SampleSize; i++)
                {
                    for (int c = 0; c < SampleChannels; c++)
                    {
                        Mean[i + (c * SampleSize)] += (double)TrainingSamples[j].Image[i + (c * SampleSize)] / 255D;
                    }
                }
            });

            Parallel.For(part, 2 * part, ParallelOption, j =>
            {
                for (int i = 0; i < SampleSize; i++)
                {
                    for (int c = 0; c < SampleChannels; c++)
                    {
                        Mean[i + (c * SampleSize)] += (double)TrainingSamples[j].Image[i + (c * SampleSize)] / 255D;
                    }
                }
            });

            for (int i = 0; i < SampleSize; i++)
            {
                for (int c = 0; c < SampleChannels; c++)
                {
                    Mean[i + (c * SampleSize)] /= (double)TrainingSamplesCount;
                }
            }

            //OnRaiseDataProgressEvent(new DataProviderEventArgs(60, String.Format("Creating Training Patterns..."), stopwatch.Elapsed));
            //Parallel.For(2 * part, 3 * part, ParallelOption, j =>
            //{
            //    RandomTrainingPattern[j] = j;
            //    CIFAR10TrainingPatterns[j] = CIFAR10TrainingPatterns[j - (2 * part)].GetReducedSample(RGBImageData.Position.TopRight, 24, 24).Resize(32, 32, RGBImageData.Interpolation.Bilinear);
            //});

            //OnRaiseDataProgressEvent(new DataProviderEventArgs(65, String.Format("Creating Training Patterns..."), stopwatch.Elapsed));
            //Parallel.For(3 * part, 4 * part, ParallelOption, j =>
            //{
            //    RandomTrainingPattern[j] = j;
            //    CIFAR10TrainingPatterns[j] = CIFAR10TrainingPatterns[j - (3 * part)].GetReducedSample(RGBImageData.Position.TopLeft, 24, 24).GetMirroredImage().Resize(32, 32, RGBImageData.Interpolation.Bilinear);
            //});

            //OnRaiseDataProgressEvent(new DataProviderEventArgs(70, String.Format("Creating Training Patterns..."), stopwatch.Elapsed));
            //Parallel.For(4 * part, 5 * part, ParallelOption, j =>
            //{
            //    RandomTrainingPattern[j] = j;
            //    CIFAR10TrainingPatterns[j] = CIFAR10TrainingPatterns[j - (4 * part)].GetReducedSample(RGBImageData.Position.BottomRight, 24, 24).Resize(32, 32, RGBImageData.Interpolation.Bilinear);
            //});

            //OnRaiseDataProgressEvent(new DataProviderEventArgs(75, String.Format("Creating Training Patterns..."), stopwatch.Elapsed));
            //Parallel.For(5 * part, 6 * part, ParallelOption, j =>
            //{
            //    RandomTrainingPattern[j] = j;
            //    CIFAR10TrainingPatterns[j] = CIFAR10TrainingPatterns[j - (5 * part)].GetReducedSample(RGBImageData.Position.BottomLeft, 24, 24).GetMirroredImage().Resize(32, 32, RGBImageData.Interpolation.Bilinear);
            //});

            //OnRaiseDataProgressEvent(new DataProviderEventArgs(80, String.Format("Creating Training Patterns..."), stopwatch.Elapsed));
            //Parallel.For(6 * part, 7 * part, ParallelOption, j =>
            //{
            //    RandomTrainingPattern[j] = j;
            //    CIFAR10TrainingPatterns[j] = CIFAR10TrainingPatterns[j - (6 * part)].GetReducedSample(RGBImageData.Position.Center, 24, 24).GetMirroredImage().Resize(32, 32, RGBImageData.Interpolation.Bilinear);
            //});

            //OnRaiseDataProgressEvent(new DataProviderEventArgs(85, String.Format("Creating Training Patterns..."), stopwatch.Elapsed));
            //Parallel.For(7 * part, 8 * part, ParallelOption, j =>
            //{
            //    RandomTrainingPattern[j] = j;
            //    CIFAR10TrainingPatterns[j] = CIFAR10TrainingPatterns[j - (7 * part)].GetReducedSample(RGBImageData.Position.Center, 24, 24).Resize(32, 32, RGBImageData.Interpolation.Bilinear);
            //});

            OnRaiseDataProgressEvent(new DataProviderEventArgs(90, "Creating Testing Samples...", stopwatch.Elapsed));
            TestingSamplesCount = 10000;
            TestingSamples      = new ImageData[TestingSamplesCount];
            Parallel.For(0, TestingSamplesCount, ParallelOption, j =>
            {
                TestingSamples[j] = CIFAR10Testing[j];
            });

            CIFAR10Training = null;
            CIFAR10Testing  = null;
            CurrentDataSet  = DataProviderSets.CIFAR10;

            OnRaiseDataLoadedEvent(new DataProviderEventArgs(100, String.Format("Dataset loaded at {0}", DateTime.Now.ToString()), stopwatch.Elapsed));

            stopwatch.Stop();
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
            GC.WaitForPendingFinalizers();
            GC.Collect();
            stopwatch.Reset();
        }
	public static bool HasAllTags(List<string> tags){
		return tags.TrueForAll (tag => HasTag (tag));
		//TrueForAll returns true if the list has no elements.
	}
Example #44
0
        public void RaciveHartbeat(AppendEntryMessage appendEntry)
        {
            if (_serverIdentifier.Equals(appendEntry.Leader))
                return;

            if (_options.UseLogging)
                _logger.LogInformation($"Processing {nameof(RaciveHartbeat)} \n\t\t Leader {appendEntry.Leader} \n\t\t Term {appendEntry.Term}");
            
            // If not in your term reject request
            if (appendEntry.Term < _election.CurrentTerm)
            {
                _entryReply.OnNext(new AppendEntryResultMessage()
                {
                    Term = _election.CurrentTerm,
                    Success = false,
                });

                return;
            }

            // Update to follow new term
            if (appendEntry.Term > _election.CurrentTerm)
            {                
                _election.CurrentTerm = appendEntry.Term;
                _election.VotedFor = appendEntry.Leader;

                _state?.OnNext(ServerStateType.Follower);

                _entryReply.OnNext(new AppendEntryResultMessage()
                {
                    Term = _election.CurrentTerm,
                    Success = false,
                });

                return;
            }

            _hartbeat.Reset();

            var term = _election.CurrentTerm;
            var outOfSync = false;

            if (_logReplication.Contains(appendEntry.PreviousLogIndex))
            {
                // If the appendEntry from the leader is in sync with us, the follower
                if (_logReplication.Term(appendEntry.PreviousLogIndex) == appendEntry.PreviousLogTerm)
                {       
                    // If we need to rollback the logs       
                    var lastApplied = appendEntry.PreviousLogIndex + 1;
                    if (lastApplied != _logReplication.LastApplied)
                    {
                        _logReplication.Rollback(lastApplied);                        
                    }

                    // We can start processing the logs
                    var successes = new List<bool>();
                    if (appendEntry.Entries != null)
                    {
                        foreach (var log in appendEntry.Entries)
                        {
                            successes.Add(_logReplication.Append(log));
                        }
                    }

                    // Confirm Log append  
                    _entryReply.OnNext(new AppendEntryResultMessage()
                    {
                        Term = term,
                        LogIndex = _logReplication.LastApplied,
                        LogTerm = _logReplication.LastTerm,
                        Success = successes.TrueForAll(p => p),
                        From = _serverIdentifier
                    });                    
                }
                else
                {
                    outOfSync = true;
                }
            }
            else
            {
                outOfSync = true;
            }

            // reject the append entry as the leader is out of sync with the follower
            if (outOfSync)
            {
                // Will keep moving the log index back until the followr and the leader match on the log consistency 
                // This will let the lead overwrite the followers logs to bring it back into full consistency.
                var previousIndex = _logReplication.LastApplied;
                if (appendEntry.PreviousLogIndex <= previousIndex)
                {
                    previousIndex = appendEntry.PreviousLogIndex - 1;
                }                
                var previousTerm = _logReplication.Term(previousIndex);
              
                // update the lead with our last index and term of a successfully append 
                _entryReply.OnNext(new AppendEntryResultMessage()
                {
                    Term = term,
                    LogIndex = previousIndex,
                    LogTerm = previousTerm,
                    Success = false,
                    From = _serverIdentifier
                });
            }

            var logsToProcess = _logReplication.ToCommit(appendEntry.LeaderCommit, appendEntry.Term);

            // Process the logs to commit as a task so not to block RPC
            ProcessLogs(logsToProcess);
        }
Example #45
0
 private bool IsEndGame()
 {
     return(hero.HealthPoints <= 0 || enemies.TrueForAll(e => e.HealthPoints <= 0));
 }
Example #46
0
        public static void TestMaxItemsPerTask(int maxConcurrency, int maxItemsPerTask, bool completeBeforeTaskWait)
        {
            //Create a custom TaskScheduler with specified max concurrency (TrackingTaskScheduler is defined in Common\tools\CommonUtils\TPLTestSchedulers.cs)
            TrackingTaskScheduler scheduler = new TrackingTaskScheduler(maxConcurrency);
            //We need to use the custom scheduler to achieve the results. As a by-product, we test to ensure custom schedulers are supported
            ConcurrentExclusiveSchedulerPair schedPair = new ConcurrentExclusiveSchedulerPair(scheduler, maxConcurrency, maxItemsPerTask);
            TaskFactory readers = new TaskFactory(schedPair.ConcurrentScheduler); //get reader and writer schedulers
            TaskFactory writers = new TaskFactory(schedPair.ExclusiveScheduler);

            //These are threadlocals to ensure that no concurrency side effects occur
            ThreadLocal<int> itemsExecutedCount = new ThreadLocal<int>(); //Track the items executed by CEScheduler Task
            ThreadLocal<int> schedulerIDInsideTask = new ThreadLocal<int>(); //Used to store the Scheduler ID observed by a Task Executed by CEScheduler Task

            //Work done by both reader and writer tasks  
            Action work = () =>
            {
                //Get the id of the parent Task (which is the task created by the scheduler). Each task run by the scheduler task should
                //see the same SchedulerID value since they are run on the same thread
                int id = ((TrackingTaskScheduler)scheduler).SchedulerID.Value;
                if (id == schedulerIDInsideTask.Value)
                { //since ids match, this is one more Task being executed by the CEScheduler Task
                    itemsExecutedCount.Value = ++itemsExecutedCount.Value;
                    //This does not need to be thread safe since we are looking to ensure that only n number of tasks were executed and not the order
                    //in which they were executed. Also asserting inside the thread is fine since we just want the test to be marked as failure
                    Assert.True(itemsExecutedCount.Value <= maxItemsPerTask, string.Format("itemsExecutedCount={0} cant be greater than maxValue={1}. Parent TaskID={2}",
                        itemsExecutedCount, maxItemsPerTask, id));
                }
                else
                { //Since ids dont match, this is the first Task being executed in the CEScheduler Task
                    schedulerIDInsideTask.Value = id; //cache the scheduler ID seen by the thread, so other tasks running in same thread can see this
                    itemsExecutedCount.Value = 1;
                }
                //Give enough time for a Task to stay around, so that other tasks will be executed by the same CEScheduler Task
                //or else the CESchedulerTask will die and each Task might get executed by a different CEScheduler Task. This does not affect the 
                //verifications, but its increases the chance of finding a bug if the maxItemPerTask is not respected
                new ManualResetEvent(false).WaitOne(20);
            };

            List<Task> taskList = new List<Task>();
            int maxConcurrentTasks = maxConcurrency * maxItemsPerTask * 5;
            int maxExclusiveTasks = maxConcurrency * maxItemsPerTask * 2;

            // Schedule Tasks in both concurrent and exclusive mode
            for (int i = 0; i < maxConcurrentTasks; i++)
                taskList.Add(readers.StartNew(work));
            for (int i = 0; i < maxExclusiveTasks; i++)
                taskList.Add(writers.StartNew(work));

            if (completeBeforeTaskWait)
            {
                schedPair.Complete();
                schedPair.Completion.Wait();
                Assert.True(taskList.TrueForAll(t => t.IsCompleted), "All tasks should have completed for scheduler to complete");
            }

            //finally wait for all of the tasks, to ensure they all executed properly
            Task.WaitAll(taskList.ToArray());

            if (!completeBeforeTaskWait)
            {
                schedPair.Complete();
                schedPair.Completion.Wait();
                Assert.True(taskList.TrueForAll(t => t.IsCompleted), "All tasks should have completed for scheduler to complete");
            }
        }
Example #47
0
 public bool TrueForAll(Predicate <T> match)
 {
     return(theList.TrueForAll(match));
 }
Example #48
0
 public bool IsPlaceable(List <Vector2Int> poss) => poss.TrueForAll(IsPlaceable);
Example #49
0
        private static bool IsAnonymousUserAuthorizedForMultipleSecurityActions(SecurityActions securityRequests, bool isPrivateAlbum, IGallerySettings gallerySettings, SecurityActionsOption secActionsOption)
        {
            // There are multiple security actions in securityAction enum.  Iterate through each one and determine if the user
            // has permission for it.
            List<bool> authResults = new List<bool>();
            foreach (SecurityActions securityAction in SecurityActionEnumHelper.ParseSecurityAction(securityRequests))
            {
                authResults.Add(IsAnonymousUserAuthorizedForSingleSecurityAction(securityAction, isPrivateAlbum, gallerySettings));
            }

            if (secActionsOption == SecurityActionsOption.RequireAll)
            {
                return (authResults.Count > 0 ? authResults.TrueForAll(delegate(bool value) { return value; }) : false);
            }
            else if (secActionsOption == SecurityActionsOption.RequireOne)
            {
                return authResults.Contains(true);
            }
            else
            {
                throw new InvalidEnumArgumentException("secActionsOption", (int)secActionsOption, typeof(SecurityActionsOption));
            }
        }
Example #50
0
 public virtual void Update(double gameTime)
 {
     TrainerSprites.ForEach(t => t.Update(gameTime));
     TrainerPokemonStatuses.ForEach(t => t.Update(gameTime));
     IsDone = TrainerSprites.TrueForAll(t => t.IsDone);
 }
        private static void TestDescriptorIsExceptionSafeCore(DiagnosticDescriptor descriptor)
        {
            var localizableTitle = descriptor.Title;
            var localizableMessage = descriptor.MessageFormat;
            var localizableDescription = descriptor.Description;

            // Verify exceptions from LocalizableResourceString don't go unhandled.
            var title = localizableTitle.ToString();
            var message = localizableMessage.ToString();
            var description = localizableDescription.ToString();

            // Verify exceptions from LocalizableResourceString are raised if OnException is set.
            var exceptions = new List<Exception>();
            var handler = new EventHandler<Exception>((sender, ex) => exceptions.Add(ex));
            localizableTitle.OnException += handler;
            localizableMessage.OnException += handler;
            localizableDescription.OnException += handler;

            // Access and evaluate localizable fields.
            var unused1 = localizableTitle.ToString();
            var unused2 = localizableMessage.ToString();
            var unused3 = localizableDescription.ToString();

            Assert.Equal(3, exceptions.Count);

            // Verify DiagnosticAnalyzer.SupportedDiagnostics is also exception safe.
            var analyzer = new MyAnalyzer(descriptor);
            var exceptionDiagnostics = new List<Diagnostic>();

            Action<Exception, DiagnosticAnalyzer, Diagnostic> onAnalyzerException = (ex, a, diag) => exceptionDiagnostics.Add(diag);
            var analyzerExecutor = AnalyzerExecutor.CreateForSupportedDiagnostics(onAnalyzerException, AnalyzerManager.Instance);
            var descriptors = AnalyzerManager.Instance.GetSupportedDiagnosticDescriptors(analyzer, analyzerExecutor);

            Assert.Equal(1, descriptors.Length);
            Assert.Equal(descriptor.Id, descriptors[0].Id);

            // Access and evaluate localizable fields.
            unused1 = descriptors[0].Title.ToString();
            unused2 = descriptors[0].MessageFormat.ToString();
            unused3 = descriptors[0].Description.ToString();

            // Verify logged analyzer exception diagnostics.
            Assert.Equal(3, exceptionDiagnostics.Count);
            Assert.True(exceptionDiagnostics.TrueForAll(AnalyzerExecutor.IsAnalyzerExceptionDiagnostic));
        }
Example #52
0
 /// <inheritdoc cref="List{T}.TrueForAll" />
 public bool TrueForAll(Predicate <T> match)
 {
     using (EnterReadLock.Enter(LockObject))
         return(_lstData.TrueForAll(match));
 }
		List<TextWord> ParseLine(IDocument document)
		{
			List<TextWord> words = new List<TextWord>();
			HighlightColor markNext = null;
			
			currentOffset = 0;
			currentLength = 0;
			UpdateSpanStateVariables();
			
			int currentLineLength = currentLine.Length;
			int currentLineOffset = currentLine.Offset;
			
			for (int i = 0; i < currentLineLength; ++i) {
				char ch = document.GetCharAt(currentLineOffset + i);
				switch (ch) {
					case '\n':
					case '\r':
						PushCurWord(document, ref markNext, words);
						++currentOffset;
						break;
					case ' ':
						PushCurWord(document, ref markNext, words);
						if (activeSpan != null && activeSpan.Color.HasBackground) {
							words.Add(new TextWord.SpaceTextWord(activeSpan.Color));
						} else {
							words.Add(TextWord.Space);
						}
						++currentOffset;
						break;
					case '\t':
						PushCurWord(document, ref markNext, words);
						if (activeSpan != null && activeSpan.Color.HasBackground) {
							words.Add(new TextWord.TabTextWord(activeSpan.Color));
						} else {
							words.Add(TextWord.Tab);
						}
						++currentOffset;
						break;
					default:
						{
							// handle escape characters
							char escapeCharacter = '\0';
							if (activeSpan != null && activeSpan.EscapeCharacter != '\0') {
								escapeCharacter = activeSpan.EscapeCharacter;
							} else if (activeRuleSet != null) {
								escapeCharacter = activeRuleSet.EscapeCharacter;
							}
							if (escapeCharacter != '\0' && escapeCharacter == ch) {
								// we found the escape character
								if (activeSpan != null && activeSpan.End != null && activeSpan.End.Length == 1
								    && escapeCharacter == activeSpan.End[0])
								{
									// the escape character is a end-doubling escape character
									// it may count as escape only when the next character is the escape, too
									if (i + 1 < currentLineLength) {
										if (document.GetCharAt(currentLineOffset + i + 1) == escapeCharacter) {
											currentLength += 2;
											PushCurWord(document, ref markNext, words);
											++i;
											continue;
										}
									}
								} else {
									// this is a normal \-style escape
									++currentLength;
									if (i + 1 < currentLineLength) {
										++currentLength;
									}
									PushCurWord(document, ref markNext, words);
									++i;
									continue;
								}
							}
							
							// highlight digits
							if (!inSpan && (Char.IsDigit(ch) || (ch == '.' && i + 1 < currentLineLength && Char.IsDigit(document.GetCharAt(currentLineOffset + i + 1)))) && currentLength == 0) {
								bool ishex = false;
								bool isfloatingpoint = false;
								
								if (ch == '0' && i + 1 < currentLineLength && Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1)) == 'X') { // hex digits
									const string hex = "0123456789ABCDEF";
									++currentLength;
									++i; // skip 'x'
									++currentLength;
									ishex = true;
									while (i + 1 < currentLineLength && hex.IndexOf(Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1))) != -1) {
										++i;
										++currentLength;
									}
								} else {
									++currentLength;
									while (i + 1 < currentLineLength && Char.IsDigit(document.GetCharAt(currentLineOffset + i + 1))) {
										++i;
										++currentLength;
									}
								}
								if (!ishex && i + 1 < currentLineLength && document.GetCharAt(currentLineOffset + i + 1) == '.') {
									isfloatingpoint = true;
									++i;
									++currentLength;
									while (i + 1 < currentLineLength && Char.IsDigit(document.GetCharAt(currentLineOffset + i + 1))) {
										++i;
										++currentLength;
									}
								}
								
								if (i + 1 < currentLineLength && Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1)) == 'E') {
									isfloatingpoint = true;
									++i;
									++currentLength;
									if (i + 1 < currentLineLength && (document.GetCharAt(currentLineOffset + i + 1) == '+' || document.GetCharAt(currentLine.Offset + i + 1) == '-')) {
										++i;
										++currentLength;
									}
									while (i + 1 < currentLine.Length && Char.IsDigit(document.GetCharAt(currentLineOffset + i + 1))) {
										++i;
										++currentLength;
									}
								}
								
								if (i + 1 < currentLine.Length) {
									char nextch = Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1));
									if (nextch == 'F' || nextch == 'M' || nextch == 'D') {
										isfloatingpoint = true;
										++i;
										++currentLength;
									}
								}
								
								if (!isfloatingpoint) {
									bool isunsigned = false;
									if (i + 1 < currentLineLength && Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1)) == 'U') {
										++i;
										++currentLength;
										isunsigned = true;
									}
									if (i + 1 < currentLineLength && Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1)) == 'L') {
										++i;
										++currentLength;
										if (!isunsigned && i + 1 < currentLineLength && Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1)) == 'U') {
											++i;
											++currentLength;
										}
									}
								}
								
								words.Add(new TextWord(document, currentLine, currentOffset, currentLength, DigitColor, false));
								currentOffset += currentLength;
								currentLength = 0;
								continue;
							}

							// Check for SPAN ENDs
							if (inSpan) {
								if (activeSpan.End != null && activeSpan.End.Length > 0) {
									if (MatchExpr(currentLine, activeSpan.End, i, document, activeSpan.IgnoreCase)) {
										PushCurWord(document, ref markNext, words);
										string regex = GetRegString(currentLine, activeSpan.End, i, document);
										currentLength += regex.Length;
										words.Add(new TextWord(document, currentLine, currentOffset, currentLength, activeSpan.EndColor, false));
										currentOffset += currentLength;
										currentLength = 0;
										i += regex.Length - 1;
										currentSpanStack.Pop();
										UpdateSpanStateVariables();
										continue;
									}
								}
							}
							
							// check for SPAN BEGIN
							if (activeRuleSet != null) {
								foreach (Span span in activeRuleSet.Spans) {
									if ((!span.IsBeginSingleWord || currentLength == 0)
									    && (!span.IsBeginStartOfLine.HasValue || span.IsBeginStartOfLine.Value == (currentLength == 0 && words.TrueForAll(delegate(TextWord textWord) { return textWord.Type != TextWordType.Word; })))
									    && MatchExpr(currentLine, span.Begin, i, document, activeRuleSet.IgnoreCase)) {
										PushCurWord(document, ref markNext, words);
										string regex = GetRegString(currentLine, span.Begin, i, document);
										
										if (!OverrideSpan(regex, document, words, span, ref i)) {
											currentLength += regex.Length;
											words.Add(new TextWord(document, currentLine, currentOffset, currentLength, span.BeginColor, false));
											currentOffset += currentLength;
											currentLength = 0;
											
											i += regex.Length - 1;
											if (currentSpanStack == null) {
												currentSpanStack = new SpanStack();
											}
											currentSpanStack.Push(span);
											span.IgnoreCase = activeRuleSet.IgnoreCase;
											
											UpdateSpanStateVariables();
										}
										
										goto skip;
									}
								}
							}
							
							// check if the char is a delimiter
							if (activeRuleSet != null && (int)ch < 256 && activeRuleSet.Delimiters[(int)ch]) {
								PushCurWord(document, ref markNext, words);
								if (currentOffset + currentLength +1 < currentLine.Length) {
									++currentLength;
									PushCurWord(document, ref markNext, words);
									goto skip;
								}
							}
							
							++currentLength;
							skip: continue;
						}
				}
			}
			
			PushCurWord(document, ref markNext, words);
			
			OnParsedLine(document, currentLine, words);
			
			return words;
		}
Example #54
0
 private bool CompareTwoSections(List <DoctorsOfficePageSection> current, List <DoctorsOfficePageSection> other)
 {
     return(current.TrueForAll(l => other.Any(li => li.Equals(l))) && current.Count == other.Count);
 }
Example #55
0
 bool IsFlush(List<Pair<int, string>> cards)
 {
     var suit = cards.First().Second;
     return cards.TrueForAll(c => c.Second == suit);
 }
        public async Task <ReturnResult> DeleteItemsAsync(IEnumerable <IStorageItemWithPath> source, bool showDialog, bool permanently, bool registerHistory)
        {
            PostedStatusBanner banner;

            if (permanently)
            {
                banner = associatedInstance.BottomStatusStripControl.OngoingTasksControl.PostBanner(string.Empty,
                                                                                                    associatedInstance.FilesystemViewModel.WorkingDirectory,
                                                                                                    0,
                                                                                                    ReturnResult.InProgress,
                                                                                                    FileOperationType.Delete);
            }
            else
            {
                banner = associatedInstance.BottomStatusStripControl.OngoingTasksControl.PostBanner(string.Empty,
                                                                                                    associatedInstance.FilesystemViewModel.WorkingDirectory,
                                                                                                    0,
                                                                                                    ReturnResult.InProgress,
                                                                                                    FileOperationType.Recycle);
            }

            ReturnResult returnStatus = ReturnResult.InProgress;

            banner.ErrorCode.ProgressChanged += (s, e) => returnStatus = e.ToStatus();

            var pathsUnderRecycleBin = GetPathsUnderRecycleBin(source);

            if (App.AppSettings.ShowConfirmDeleteDialog && showDialog) // Check if the setting to show a confirmation dialog is on
            {
                var deleteFromRecycleBin = pathsUnderRecycleBin.Count > 0;

                ConfirmDeleteDialog dialog = new ConfirmDeleteDialog(
                    deleteFromRecycleBin,
                    !deleteFromRecycleBin ? permanently : deleteFromRecycleBin,
                    associatedInstance.ContentPage.SelectedItemsPropertiesViewModel);

                if (Interacts.Interaction.IsAnyContentDialogOpen())
                {
                    // Can show only one dialog at a time
                    banner.Remove();
                    return(ReturnResult.Cancelled);
                }
                await dialog.ShowAsync();

                if (dialog.Result != DialogResult.Delete) // Delete selected items if the result is Yes
                {
                    banner.Remove();
                    return(ReturnResult.Cancelled); // Return if the result isn't delete
                }

                permanently = dialog.PermanentlyDelete;
            }

            Stopwatch sw = new Stopwatch();

            sw.Start();

            IStorageHistory history;
            var             rawStorageHistory = new List <IStorageHistory>();

            bool  originalPermanently = permanently;
            float progress;

            for (int i = 0; i < source.Count(); i++)
            {
                if (pathsUnderRecycleBin.Contains(source.ElementAt(i).Path))
                {
                    permanently = true;
                }
                else
                {
                    permanently = originalPermanently;
                }

                rawStorageHistory.Add(await filesystemOperations.DeleteAsync(source.ElementAt(i), null, banner.ErrorCode, permanently, cancellationToken));
                progress = ((float)i / (float)source.Count()) * 100.0f;
                ((IProgress <float>)banner.Progress).Report(progress);
            }

            if (rawStorageHistory.TrueForAll((item) => item != null))
            {
                history = new StorageHistory(
                    rawStorageHistory[0].OperationType,
                    rawStorageHistory.SelectMany((item) => item.Source).ToList(),
                    rawStorageHistory.SelectMany((item) => item.Destination).ToList());

                if (!permanently && registerHistory)
                {
                    App.HistoryWrapper.AddHistory(history);
                }
            }

            banner.Remove();
            sw.Stop();

            PostBannerHelpers.PostBanner_Delete(returnStatus, permanently ? FileOperationType.Delete : FileOperationType.Recycle, sw, associatedInstance);

            return(returnStatus);
        }
Example #57
0
        private static bool ValidatePassengers(List<Passenger> passengers, out string errorMessage)
        {
            string message = string.Empty;

            bool boolResponse = passengers.
                TrueForAll(x =>
                               {
                                   bool response = false;
                                   if (x.DateOfBirth > DateTime.Today)
                                       message = "Birth Date cannot be greater than today.";
                                   else if (string.IsNullOrEmpty(x.FirstName) ||
                                            x.FirstName.Length < 2)
                                       message =
                                           "First Name null or invalid. Name should be atleast 2 characters long.";
                                   else if (string.IsNullOrEmpty(x.LastName) ||
                                            x.LastName.Length < 2)
                                       message =
                                           "Last Name null or invalid. Name should be atleast 2 characters long.";
                                   else if (string.IsNullOrEmpty(x.Gender) ||
                                            !(string.Equals(x.Gender, "Male",
                                                            StringComparison.
                                                                OrdinalIgnoreCase) ||
                                              string.Equals(x.Gender, "Female",
                                                            StringComparison.
                                                                OrdinalIgnoreCase)))
                                       message =
                                           "Invalid Gender. Allowed values are 'Male' and 'Female'.";
                                   else
                                       response = true;
                                   return response;
                               });
            errorMessage = message;
            return boolResponse;
        }
Example #58
0
        public ActionResult Edit(AssessmentsView assessmentView, FormCollection form)
        {
            if (ModelState.IsValid)
            {
                IAssessmentsRepository assessmentsRepository = new AssessmentsRepository(db);
                Assessment             assessment            = assessmentsRepository.GetAssessmentByPK((int)assessmentView.AssessmentPK);

                IAssessmentAnswersRepository assessmentAnswersRepository = new AssessmentAnswersRepository(db);

                // Delete old values
                assessmentAnswersRepository.Delete(a => a.AssessmentFK == assessment.AssessmentPK);

                // Add new values
                IAssessmentGroupsRepository    assessmentGroupsRepository    = new AssessmentGroupsRepository(db);
                IAssessmentQuestionsRepository assessmentQuestionsRepository = new AssessmentQuestionsRepository(db);
                IAssessmentTypesRepository     assessmentTypesRepository     = new AssessmentTypesRepository(db);

                assessmentView.AssessmentsTypesView = AssessmentsView.FillQuiz(assessmentTypesRepository.GetValid(), assessmentGroupsRepository, assessmentQuestionsRepository, form);

                // Fetching answered type
                AssessmentsTypeView atw = assessmentView.AssessmentsTypesView.Where(a => a.AssessmentType.AssessmentTypePK == assessmentView.AssessmentTypeFK).First();

                List <AssessmentAnswers> assessmentAnswers = AssessmentAnswerView.ExtractQuizAnswers(atw, assessment.AssessmentPK);

                ILegalEntitiesRepository legalEntitiesRepository = new LegalEntitiesRepository(db);
                LegalEntity legalEntity             = legalEntitiesRepository.GetLegalEntityByPK((int)assessmentView.LegalEntityFK);
                bool        activityHighRisky       = legalEntity.Activity.HighRisk != null && (bool)legalEntity.Activity.HighRisk ? true : false;
                bool        activityLowRisky        = legalEntity.Activity.LowRisk != null && (bool)legalEntity.Activity.LowRisk ? true : false;
                bool        headquarterCountryRisky = legalEntity.Country.Risk != null && (bool)legalEntity.Country.Risk ? true : false;

                IRisksRepository risksRepository = new RisksRepository(db);
                if (activityHighRisky || headquarterCountryRisky) // check explicitly if related legalEntity activity is high risk
                {
                    assessmentView.RiskFK = risksRepository.GetRiskByName("Visok").RiskPK;
                }
                else if (activityLowRisky) // check explicitly if related legalEntity activity is low risk
                {
                    assessmentView.RiskFK = risksRepository.GetRiskByName("Nizak").RiskPK;
                }
                else // run assesment quiz
                {
                    ILegalEntityOwnersRepository  legalEntityOwnersRepository = new LegalEntityOwnersRepository(db);
                    IQueryable <LegalEntityOwner> legalEntityOwnersTable      = legalEntityOwnersRepository.GetValid();
                    ICountriesRepository          countriesRepository         = new CountriesRepository(db);

                    IActivitiesRepository activitiesRepository = new ActivitiesRepository(db);

                    List <LegalEntityOwner> coList = legalEntityOwnersRepository.GetFirstLegalEntityOwnersForLegalEntity((int)assessmentView.LegalEntityFK).ToList();

                    legalEntityOwnersTable = LegalEntityOwnerView.GetLegalEntityOwnersForLegalEntity(Convert.ToInt32(assessmentView.LegalEntityFK), coList, legalEntityOwnersTable);

                    IQueryable <LegalEntity> legalEntityView = LegalEntityOwnerView.GetRelatedLegalEntities(legalEntityOwnersTable, legalEntitiesRepository.GetValid(), countriesRepository.GetValid(), activitiesRepository.GetValid());

                    // check owners risks
                    bool ownersResidenceCountryRisky = false;
                    bool ownersActivitiesHighlyRisky = false;
                    bool ownersActivitiesLowRisky    = false;

                    if (legalEntityView.Count() > 0)
                    {
                        if (legalEntityView.ToList().TrueForAll(le => le.Country.Risk == null || (le.Country.Risk != null && (bool)le.Country.Risk != true)) == false)
                        {
                            ownersResidenceCountryRisky = true;
                        }

                        if (legalEntityView.ToList().TrueForAll(le => le.Activity == null || (le.Activity.HighRisk == null || (le.Activity.HighRisk != null && (bool)le.Activity.HighRisk != true))) == false)
                        {
                            ownersActivitiesHighlyRisky = true;
                        }

                        if (legalEntityView.ToList().TrueForAll(le => le.Activity == null || (le.Activity.LowRisk == null || (le.Activity.LowRisk != null && (bool)le.Activity.LowRisk != true))) == false)
                        {
                            ownersActivitiesLowRisky = true;
                        }
                    }

                    // check form
                    bool allAnswersYes = false;
                    bool allAnswersNo  = false;
                    bool mixedAnswers  = false;

                    if (assessmentAnswers.TrueForAll(aa => aa.AssessmentAnswer != null && (bool)aa.AssessmentAnswer == true))
                    {
                        allAnswersYes = true;
                    }

                    if (assessmentAnswers.TrueForAll(aa => aa.AssessmentAnswer != null && (bool)aa.AssessmentAnswer == false))
                    {
                        allAnswersNo = true;
                    }

                    if (allAnswersYes == false && allAnswersNo == false)
                    {
                        mixedAnswers = true;
                    }

                    // check general conditions
                    if (ownersActivitiesLowRisky)
                    {
                        assessmentView.RiskFK = risksRepository.GetRiskByName("Nizak").RiskPK;
                    }
                    else if (allAnswersYes || ownersResidenceCountryRisky || ownersActivitiesHighlyRisky)
                    {
                        assessmentView.RiskFK = risksRepository.GetRiskByName("Visok").RiskPK;
                    }
                    else if (allAnswersNo || mixedAnswers)
                    {
                        assessmentView.RiskFK = risksRepository.GetRiskByName("Srednji").RiskPK;
                    }
                }

                if (assessmentAnswers.Count() > 0)
                {
                    assessmentAnswersRepository.AddAll(assessmentAnswers);
                    assessmentAnswersRepository.SaveChanges();
                }

                assessmentView.ConvertTo(assessmentView, assessment);
                assessmentsRepository.SaveChanges();

                TempData["message"] = LayoutHelper.GetMessage("UPDATE", assessment.AssessmentPK);

                return(RedirectToAction("Index", "Assessment"));
            }
            else
            {
                IAssessmentGroupsRepository    assessmentGroupsRepository    = new AssessmentGroupsRepository(db);
                IAssessmentQuestionsRepository assessmentQuestionsRepository = new AssessmentQuestionsRepository(db);

                //Assessment types ddl
                IAssessmentTypesRepository assessmentTypesRepository = new AssessmentTypesRepository(db);
                assessmentView.AssessmentTypes = new SelectList(assessmentTypesRepository.GetValid().OrderBy("Name ASC").ToList(), "AssessmentTypePK", "Name");

                //legalEntities ddl
                ILegalEntitiesRepository legalEntitiesRepository = new LegalEntitiesRepository(db);
                assessmentView.LegalEntities = new SelectList(legalEntitiesRepository.GetValidLegalEntities().ToList(), "LegalEntityPK", "Name");

                assessmentView.AssessmentsTypesView = AssessmentsView.FillQuiz(assessmentTypesRepository.GetValid(), assessmentGroupsRepository, assessmentQuestionsRepository, form);

                return(View(assessmentView));
            }
        }
Example #59
0
        internal void EventTimer_Tick(object sender, EventArgs e)
        {
            if (_ShutdownProcess == null)
            {
                _Main.ClearTable();
                List<bool> readyItems = new List<bool>(_Events.Count);
                foreach (Event item in _Events)
                {
                    bool ready = item.Ready();
                    int index = _Main.AddEvent(item);
                    _Main.SetReadyState(index, ready);
                    readyItems.Add(ready);
                }

                //if all elements in the list are 'true'
                if (readyItems.TrueForAll(item => { return item; }))
                    this.InitiateShutdown();
            }
        }
        public async Task <ReturnResult> Redo(IStorageHistory history)
        {
            ReturnResult returnStatus = ReturnResult.InProgress;
            Progress <FileSystemStatusCode> errorCode = new Progress <FileSystemStatusCode>();

            errorCode.ProgressChanged += (s, e) => { returnStatus = e.ToStatus(); };

            switch (history.OperationType)
            {
            case FileOperationType.CreateNew:     // CreateNew PASS
            {
                if (IsHistoryNull(history))
                {
                    break;
                }

                for (int i = 0; i < history.Source.Count(); i++)
                {
                    await filesystemOperations.CreateAsync(history.Source.ElementAt(i), errorCode, cancellationToken);
                }

                break;
            }

            case FileOperationType.Rename:     // Rename PASS
            {
                if (IsHistoryNull(history))
                {
                    break;
                }

                NameCollisionOption collision = NameCollisionOption.GenerateUniqueName;
                for (int i = 0; i < history.Source.Count(); i++)
                {
                    await filesystemOperations.RenameAsync(
                        history.Source.ElementAt(i),
                        Path.GetFileName(history.Destination.ElementAt(i).Path),
                        collision,
                        errorCode,
                        cancellationToken);
                }

                break;
            }

            case FileOperationType.Copy:     // Copy PASS
            {
                if (IsHistoryNull(history))
                {
                    break;
                }

                return(await filesystemHelpers.CopyItemsAsync(history.Source, history.Destination.Select((item) => item.Path), false));
            }

            case FileOperationType.Move:     // Move PASS
            {
                if (IsHistoryNull(history))
                {
                    break;
                }

                return(await filesystemHelpers.MoveItemsAsync(history.Source, history.Destination.Select((item) => item.Path), false));
            }

            case FileOperationType.Extract:     // Extract PASS
            {
                returnStatus = ReturnResult.Success;
                Debugger.Break();

                break;
            }

            case FileOperationType.Recycle:     // Recycle PASS
            {
                if (IsHistoryNull(history.Destination))
                {
                    break;
                }

                List <IStorageHistory> rawStorageHistory = new List <IStorageHistory>();
                for (int i = 0; i < history.Source.Count(); i++)
                {
                    rawStorageHistory.Add(await filesystemOperations.DeleteAsync(
                                              history.Source.ElementAt(i),
                                              null,
                                              errorCode,
                                              false,
                                              cancellationToken));
                }

                if (rawStorageHistory.TrueForAll((item) => item != null))
                {
                    IStorageHistory newHistory = new StorageHistory(
                        FileOperationType.Recycle,
                        rawStorageHistory.SelectMany((item) => item?.Source).ToList(),
                        rawStorageHistory.SelectMany((item) => item?.Destination).ToList());

                    // We need to change the recycled item paths (since IDs are different) - for Undo() to work
                    App.HistoryWrapper.ModifyCurrentHistory(newHistory);
                }
                else
                {
                    App.HistoryWrapper.RemoveHistory(history, true);
                }

                break;
            }

            case FileOperationType.Restore:     // Restore PASS
            {
                if (IsHistoryNull(history))
                {
                    break;
                }

                for (int i = 0; i < history.Destination.Count(); i++)
                {
                    await filesystemHelpers.RestoreFromTrashAsync(history.Source.ElementAt(i), history.Destination.ElementAt(i).Path, false);
                }

                break;
            }

            case FileOperationType.Delete:     // Delete PASS
            {
                returnStatus = ReturnResult.Success;

                break;
            }
            }

            return(returnStatus);
        }