Example #1
0
        /// <summary>
        /// 计算所需高(暂不考虑英文的word wrapper)
        /// </summary>
        /// <param name="width">目标宽度</param>
        /// <param name="pagePadding">页边距</param>
        /// <param name="lineDistance">行距</param>
        /// <param name="font">字体</param>
        /// <returns>分行完毕的文本</returns>
        private List<string> CalculateHeight(int width, int pagePadding, int lineDistance, PixelFont font, string text)
        {
            List<string> result = new List<string>();
            int availableWidth = width - pagePadding * 2;//除去页边距之后的可用宽度
            List<char> line = new List<char>();
            string[] lines = text.Split(new string[] {"\r\n" }, StringSplitOptions.None);
            int length = 0;
            foreach (var l in lines)
            {
                line.Clear();
                length = 0;
                foreach (var c in l)
                {
                    int len = font.MeasureCharDrawingLength(c);
                    if (len + length > availableWidth)
                    {
                        result.Add(new string(line.ToArray()));
                        line.Clear();
                        line.Add(c);
                        length = len;
                    }
                    else
                    {
                        length += len;
                        line.Add(c);
                    }
                }
                result.Add(new string(line.ToArray()));

            }
            return result;
        }
        public async Task BuildIndexes()
        {
            TableQuery<TableUser> query = new TableQuery<TableUser>();
            TableQuerySegment<TableUser> querySegment = null;
            List<Task> insertOperation = new List<Task>();

            while (querySegment == null || querySegment.ContinuationToken != null)
            {
                querySegment = await _userTable.ExecuteQuerySegmentedAsync(query, querySegment != null ? querySegment.ContinuationToken : null);
                foreach (TableUser tableUser in querySegment.Results)
                {
                    TableUserIdIndex indexItem = new TableUserIdIndex(tableUser.UserName, tableUser.Id);
                    insertOperation.Add(_userIndexTable.ExecuteAsync(TableOperation.InsertOrReplace(indexItem)));
                    if (insertOperation.Count > 100)
                    {
                        await Task.WhenAll(insertOperation);
                        insertOperation.Clear();
                    }
                }
                if (insertOperation.Count > 0)
                {
                    await Task.WhenAll(insertOperation);
                    insertOperation.Clear();
                }
            }
        }
    static void Main()
    {
        int[] numbers = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
        List<int> temp = new List<int>();
        List<int> longest = new List<int>();

        for (int i = 0, j = 1; i < numbers.Length; i++, j++)
        {
            temp.Add(numbers[i]);

            if ((j < numbers.Length) && (numbers[i] <= numbers[j]))
            {
                continue;
            }
            else
            {
                if (temp.Count > longest.Count)
                {
                    longest.Clear();
                    longest.AddRange(temp);
                    Console.WriteLine(string.Join(" ", temp));
                    temp.Clear();
                }
                else
                {
                    Console.WriteLine(string.Join(" ", temp));
                    temp.Clear();
                }
            }
        }

        Console.WriteLine("Longest: " + string.Join(" ", longest));
    }
        public void Handlers_Can_Be_Unsubscribed()
        {
            var pub = new Publisher();
            var calledSubscribers = new List<int>();
            var sub1 = new InstanceSubscriber(1, pub, calledSubscribers.Add);
            var sub2 = new InstanceSubscriber(2, pub, calledSubscribers.Add);
            StaticSubscriber.FooWasRaised = false;
            StaticSubscriber.Subscribe(pub);

            // Make sure they really were subscribed
            pub.Raise();
            calledSubscribers.Should().Equal(1, 2);
            StaticSubscriber.FooWasRaised.Should().BeTrue();

            calledSubscribers.Clear();
            sub1.Unsubscribe(pub);
            pub.Raise();
            calledSubscribers.Should().Equal(2);

            StaticSubscriber.FooWasRaised = false;
            StaticSubscriber.Unsubscribe(pub);
            pub.Raise();
            StaticSubscriber.FooWasRaised.Should().BeFalse();

            calledSubscribers.Clear();
            sub2.Unsubscribe(pub);
            pub.Raise();
            calledSubscribers.Should().BeEmpty();

            // Make sure subscribers are not collected before the end of the test
            GC.KeepAlive(sub1);
            GC.KeepAlive(sub2);
        }
        public void ParseCorrect()
        {
            List<string> zList = new List<string>();

            zList.Clear();
            zList.Add("AT+TASKPLANNER?");
            zList.Add("");
            zList.Add("+TASKPLANNER: 0, 11:20, 23:12");
            zList.Add("OK");
            Assert.True(_TaskPlannerCommand.Parse(zList));

            Assert.Equal(SyncMode.CustomSync, _TaskPlannerCommand.DeviceSyncMode);

            Assert.Equal(_TaskPlannerCommand.WindowOpenTime.Hour, 11);
            Assert.Equal(_TaskPlannerCommand.WindowOpenTime.Minute, 20);

            Assert.Equal(_TaskPlannerCommand.ActivityPeriod.Hours, 23);
            Assert.Equal(_TaskPlannerCommand.ActivityPeriod.Minutes, 12);

            zList.Clear();
            zList.Add("+TASKPLANNER: 1, 11:20, 23:12");
            zList.Add("OK");
            Assert.True(_TaskPlannerCommand.Parse(zList));

            Assert.Equal(SyncMode.OperatorSync, _TaskPlannerCommand.DeviceSyncMode);
        }
        private static void FlipImagesWithOptionalRetry(List<string> imageFilepaths, string targetDirectoryPath)
        {
            while (imageFilepaths.Count > 0)
            {
                try
                {
                    FlipImages(imageFilepaths, targetDirectoryPath);
                    imageFilepaths.Clear();
                }
                catch (AggregateException e)
                {
                    imageFilepaths.Clear();
                    var failedFilepaths = new List<string>();
                    foreach (var exception in e.InnerExceptions)
                    {
                        var flipFailed = exception as FileFlipFailedException;
                        if (flipFailed != null)
                        {
                            failedFilepaths.Add(flipFailed.FailedFilepath);
                        }
                    }

                    Console.WriteLine("The following files could not be flipped due to errors:");
                    Console.WriteLine(string.Join(System.Environment.NewLine, failedFilepaths));

                    Console.Write("Would you like to reprocess them? (y/n): ");
                    if (Console.ReadLine()[0] == 'y')
                    {
                        imageFilepaths.AddRange(failedFilepaths);
                    }
                }
            }
        }
Example #7
0
        public DialogResult Start(Form parent, ref List<Int32> selectedCommodities)
        { 
            try
            {
                m_selectedCommodities = selectedCommodities;

                this.ShowDialog(parent);

                if(DialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    m_selectedCommodities.Clear();

                    foreach (SQL.Datasets.dsEliteDB.tbcommodityRow dRow in m_Table.Select("is_selected = true"))
		                m_selectedCommodities.Add(dRow.id);
                }
                else if(DialogResult == System.Windows.Forms.DialogResult.Yes)
                {
                    DialogResult = System.Windows.Forms.DialogResult.OK;
                    m_selectedCommodities.Clear();
                }
                
                return this.DialogResult;
            }
            catch (Exception ex)
            {
                throw new Exception("Error while starting form", ex);
            }
        }
        public bool Delete(Room value)
        {
            bool result = false;

            MachineHibernate machineHibernate = new MachineHibernate();
            result = machineHibernate.DeleteByRoom(value.Guid);

            DatabaseHibernate hibernate = new DatabaseHibernate();
            List<Parameter> parameters = new List<Parameter>();

            if (result)
            {
                string sql = string.Format("delete from e_user_room as t where [t].[room_id] = '{0}'", value.Guid);
                parameters.Clear();

                result = hibernate.Write(Variable.Link, sql, parameters);
            }

            if (result)
            {
                string sql = string.Format("delete from e_room as t where [t].[guid] = '{0}'", value.Guid);
                parameters.Clear();

                result = hibernate.Write(Variable.Link, sql, parameters);
            }

            return result;
        }
        public static List<int> FindLongestSequence(List<int> numbers)
        {
            List<int> result = new List<int>();
            List<int> currentSequence = new List<int>();

            if (numbers.Count == 1)
            {
                return numbers;
            }

            int i = 0;
            while (i < numbers.Count - 1)
            {
                int j = i;
                currentSequence.Add(numbers[j]);
                while (j < numbers.Count-1 && numbers[j] == numbers[j + 1])
                {
                    currentSequence.Add(numbers[j + 1]);
                    j++;
                }
                if (currentSequence.Count > result.Count)
                {
                    result.Clear();
                    result.AddRange(currentSequence);
                    currentSequence.Clear();
                }
                else
                {
                    currentSequence.Clear();
                }
                i = j + 1;
            }

            return result;
        }
        public void LoadCharacters(ContentManager myContentManager)
        {
            // ############## ALL THE INGAME CHARACTERS ARE DEFINED HERE ################

            // Dummy Player Char
            List<String> body = new List<String>();
            List<String> face = new List<String>();
            AddCharacter("Spieler", body, face, myContentManager);

            // Testy
            body.Clear();
            face.Clear();
            body.Add("testy_normal");
            body.Add("testy_angry");
            body.Add("testy_happy");
            body.Add("testy_shy");
            AddCharacter("Testy", body, face, myContentManager);

            // Blondie
            body.Clear();
            face.Clear();
            body.Add("blondie1");
            body.Add("blondie2");
            body.Add("blondie3");
            AddCharacter("Blondie", body, face, myContentManager);

            // Schwarz
            body.Clear();
            face.Clear();
            body.Add("schwarz1");
            body.Add("schwarz2");
            AddCharacter("Schwarz", body, face, myContentManager);
        }
Example #11
0
    static List<string> MaxSequenceIncols(string[,] matrix)
    {
        List<string> maxSequenceIncols = new List<string>();

        for (int i = 0; i < matrix.GetLength(1); i++)
        {
            List<string> currentSequence = new List<string>();
            currentSequence.Add(matrix[0, i]);
            for (int j = 1; j < matrix.GetLength(0); j++)
            {
                if (!currentSequence[0].Equals(matrix[j, i]))
                {
                    if (currentSequence.Count > maxSequenceIncols.Count)
                    {
                        maxSequenceIncols.Clear();
                        maxSequenceIncols = CopyList(maxSequenceIncols, currentSequence);
                    }
                    currentSequence.Clear();
                }
                currentSequence.Add(matrix[j, i]);
            }
            if (currentSequence.Count > maxSequenceIncols.Count)
            {
                maxSequenceIncols.Clear();
                maxSequenceIncols = CopyList(maxSequenceIncols, currentSequence);
            }
        }

        return maxSequenceIncols;
    }
Example #12
0
        static void Main(string[] args)
        {
            string ruleTypeName = ConfigurationSettings.AppSettings["RuleType"];
            Assembly assem = Assembly.Load("SalesTaxes.Items");
            ITaxedRule taxedRule = assem.CreateInstance(ruleTypeName) as ITaxedRule;
          
            List<AbstractItem> items = new List<AbstractItem>();
            items.Add(new Item(Category.BOOK, false, 12.49m));
            items.Add(new Item(Category.OTHERS, false, 14.99m));
            items.Add(new Item(Category.FOOD, false, 0.85m));

            PrintPrice(taxedRule.Apply(items));
            Console.WriteLine("--------------");

            items.Clear();
            items.Add(new Item(Category.FOOD, true, 10.00m));
            items.Add(new Item(Category.OTHERS, true, 47.50m));
            PrintPrice(taxedRule.Apply(items));
            Console.WriteLine("--------------");

            items.Clear();
            items.Add(new Item(Category.OTHERS, true, 27.99m));
            items.Add(new Item(Category.OTHERS, false, 18.99m));
            items.Add(new Item(Category.MEDICAL, false, 9.75m));
            items.Add(new Item(Category.FOOD, true, 11.25m));
            PrintPrice(taxedRule.Apply(items));
            Console.Read();
        }
		private IEnumerable<IEnumerable<JsonDocument>> YieldDocuments()
		{
			var list = new List<JsonDocument>();
			while (true)
			{
				JsonDocument item;
				if (queue.TryTake(out item, 100) == false)
				{
					if (list.Count != 0)
					{
						ReportProgress(list);
						yield return list;
						list.Clear();
					}
					continue;
				}
				if (item == null) //marker
				{
					ReportProgress(list); 
					yield return list; 
					yield break;
				}

				list.Add(item);
				if (list.Count >= options.BatchSize)
				{
					ReportProgress(list); 
					yield return list;
					list.Clear();
				}
			}
		}
Example #14
0
        public static int SetValue(string strName, string strValue)
        {
            string sql = "SELECT value FROM Params WHERE [email protected];";
            List<SQLiteParameter> cmdParams = new List<SQLiteParameter>()
            {
                new SQLiteParameter("Name",strName),
            };
            DataTable dt = DBAdapter.Select(sql, cmdParams);
            if (dt == null)
                return -1;

            if (dt.Rows.Count <= 0)
            {
                sql = "INSERT INTO Params (name,value) VALUES (@Name,@Value);";
                cmdParams.Clear();
                cmdParams.Add(new SQLiteParameter("Name", strName));
                cmdParams.Add(new SQLiteParameter("Value", strValue));
                return DBAdapter.Execute(sql, cmdParams);
            }
            else
            {
                sql = "UPDATE Params SET [email protected] WHERE [email protected];";
                cmdParams.Clear();
                cmdParams.Add(new SQLiteParameter("Name", strName));
                cmdParams.Add(new SQLiteParameter("Value", strValue));
                return DBAdapter.Execute(sql, cmdParams);
            }
              
        }
Example #15
0
        static void Main(string[] args)
        {
            for (int k = 0; k < 100; k++)
            {

                //tth
                int AWinCount = 0;
                int BWinCount = 0;

                var resultStack = new List<bool>();

                for (int i = 0; i < 1000; i++)
                {
                    bool coinResult = RandomGenerator.GetCoin();

                    resultStack.Add(coinResult);
                    if (AWin(resultStack))
                    {
                        AWinCount++;
                        resultStack.Clear();
                    }
                    else if (BWin(resultStack))
                    {
                        BWinCount++;
                        resultStack.Clear();
                    }

                }

                Console.WriteLine("A win {0}, B win {1}", AWinCount, BWinCount);
            }
        }
Example #16
0
File: U9T.cs Project: unit9/swip3
	public static U9SerialTransition PrioritySequence( U9Transition[] transitions, float staggerTime = 0f ) {

		//Debug.Log ("START PRIORITY SEQUENCE -------------");
		List<U9Transition> transList = new List<U9Transition>( transitions );
		//transList.Sort( CompareTransitionPriority );
		IEnumerable enumerator = transList.OrderBy (t => t.Priority);

		int? currentPriority = null;
		U9SerialTransition serial = new U9SerialTransition ();
		List<U9Transition> parallelGroup = new List<U9Transition> ();

		foreach (U9Transition t in enumerator) {

			if (t != null) {
				if (t.Priority != currentPriority) {
					if (parallelGroup.Count > 0) {
						//Debug.Log ("Priority group: " + currentPriority + " = " + parallelGroup.Count );
						serial.AddTransition (U9T.Stagger (staggerTime, parallelGroup.ToArray ()));
						parallelGroup.Clear ();
					}
					currentPriority = t.Priority;
				}
				parallelGroup.Add (t);
			}

		}
		if (parallelGroup.Count > 0) {
			//Debug.Log ("Priority group: " + currentPriority + " = " + parallelGroup.Count );
			serial.AddTransition( U9T.Stagger( staggerTime, parallelGroup.ToArray() ) );
			parallelGroup.Clear ();
		}
		return serial;
	}
Example #17
0
        private static string[] SplitStringIntoWords(this string input, char separator)
        {
            var results = new List<string>();
            var word = new List<Char>();

            var e = input.GetEnumerator();
            if (!e.MoveNext())
            {
                return new string[0];
            }

            word.Add(e.Current);

            while (e.MoveNext())
            {
                if (e.Current != separator)
                {
                    word.Add(e.Current);
                }
                else
                {
                    results.Add(new string(word.ToArray()));
                    word.Clear();
                }
            }
            results.Add(new string(word.ToArray()));
            word.Clear();

            return results.ToArray();
        }
Example #18
0
        private static bool GetProperties(Type type, List<string> methodPath, List<string> properties)
        {
            if (null == type)
                return false;

            if (methodPath.Count == 0)
            {
                properties.Clear();
                properties.AddRange(type.GetProperties().Select(pro2 => pro2.Name));
                return true;
            }

            foreach (PropertyInfo prop in type.GetProperties())
            {
                Trace.WriteLine(prop.PropertyType.Name);
                if (prop.Name == methodPath[0])
                {
                    methodPath.RemoveAt(0);
                    return GetProperties(prop.PropertyType, methodPath, properties);
                }
            }

            properties.Clear();
            return false;
        }
        static PrincipalFactory()
        {
            _principals = new List<ClaimsPrincipal>();

            List<Claim> claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.Name, "adam", ClaimValueTypes.String, Issuer));
            claims.Add(new Claim(ClaimTypes.DateOfBirth, new DateTime(2000, 01, 01).ToString("u"), ClaimValueTypes.DateTime, Issuer));
            claims.Add(new Claim(ClaimTypes.Role, "User", ClaimValueTypes.String, Issuer));
            claims.Add(new Claim("Documents", "CRUD", ClaimValueTypes.String, "urn:microsoft.com"));
            _principals.Add(new ClaimsPrincipal(new ClaimsIdentity(claims, AuthenticationType)));
            claims.Clear();

            claims.Add(new Claim(ClaimTypes.Name, "barry", ClaimValueTypes.String, Issuer));
            claims.Add(new Claim(ClaimTypes.DateOfBirth, new DateTime(1970, 06, 08).ToString("u"), ClaimValueTypes.DateTime, Issuer));
            claims.Add(new Claim(ClaimTypes.Role, "Administrator", ClaimValueTypes.String, Issuer));
            claims.Add(new Claim(ClaimTypes.Role, "User", ClaimValueTypes.String, Issuer));
            claims.Add(new Claim("CanWeFixIt", "YesWeCan", ClaimValueTypes.String, "urn:bobthebuilder.com"));
            claims.Add(new Claim("Documents", "CRUD", ClaimValueTypes.String, "urn:idunno.org"));
            _principals.Add(new ClaimsPrincipal(new ClaimsIdentity(claims, AuthenticationType)));
            claims.Clear();

            claims.Add(new Claim(ClaimTypes.Name, "charlie", ClaimValueTypes.String, Issuer));
            claims.Add(new Claim(ClaimTypes.DateOfBirth, new DateTime(1990, 01, 01).ToString("u"), ClaimValueTypes.DateTime, Issuer));
            claims.Add(new Claim(ClaimTypes.Role, "Administrator", ClaimValueTypes.String, Issuer));
            claims.Add(new Claim("CanWeFixIt", "NoWeCant", ClaimValueTypes.String, "urn:bobthebuilder.com"));
            claims.Add(new Claim("Documents", "R", ClaimValueTypes.String, "urn:idunno.org"));
            _principals.Add(new ClaimsPrincipal(new ClaimsIdentity(claims, AuthenticationType)));
            claims.Clear();

            claims.Add(new Claim(ClaimTypes.Name, "david", ClaimValueTypes.String, Issuer));
            claims.Add(new Claim(ClaimTypes.DateOfBirth, new DateTime(1990, 01, 01).ToString("u"), ClaimValueTypes.DateTime, Issuer));
            claims.Add(new Claim(ClaimTypes.Role, "Guest", ClaimValueTypes.String, Issuer));
            _principals.Add(new ClaimsPrincipal(new ClaimsIdentity(claims, AuthenticationType)));
            claims.Clear();
        }
Example #20
0
        public async Task InstallPackageTest() {
            await Workflow.RSession.EnsureHostStartedAsync(new RHostStartupInfo {Name = nameof(InstallPackageTest)}, null, 50000);

            var completionSets = new List<CompletionSet>();
            for (int i = 0; i < 2; i++) {
                try {
                    await Workflow.Packages.UninstallPackageAsync("abc", null);
                    //await Workflow.RSession.ExecuteAsync("remove.packages('abc')", REvaluationKind.Mutating);
                } catch (RException) { }

                await PackageIndex.BuildIndexAsync();

                completionSets.Clear();
                RCompletionTestUtilities.GetCompletions(EditorShell, "abc::", 5, completionSets);

                completionSets.Should().ContainSingle();
                // Try again one more time
                if (completionSets[0].Completions.Count == 0) {
                    break;
                }
            }
            completionSets[0].Completions.Should().BeEmpty();

            try {
                await Workflow.RSession.ExecuteAsync("install.packages('abc')", REvaluationKind.Mutating);
            } catch (RException) { }

            await PackageIndex.BuildIndexAsync();

            completionSets.Clear();
            RCompletionTestUtilities.GetCompletions(EditorShell, "abc::", 5, completionSets);

            completionSets.Should().ContainSingle();
            completionSets[0].Completions.Should().NotBeEmpty();
        }
Example #21
0
		public List<Node> BuildTree(List<Token> tokens)
		{
			if (tokens == null) throw new ArgumentNullException("tokens");

			Int32 tokenindex = 0;
			List<Node> output = new List<Node>();

			while (GetToken(tokens, tokenindex) != null)
			{
				Node node = ParseNode(tokens, ref tokenindex);
				if (node == null)
				{
					output.Clear();
					return output;
				}

				output.Add(node);

				if (GetToken(tokens, tokenindex) != null)
				{
					if (GetToken(tokens, tokenindex).AsSymbol == Symbol.Comma)
					{
						++tokenindex;
					}
					else
					{
						output.Clear();
						return output;
					}
				}
			}

			return output;
		}
    private static bool calculateWeight(char[] result, int start, int end)
    {
        List<Char> chars = new List<Char>();
        int weight = 0;

        for (int i = 1; i <= result.Length; i++)
        {
            if (chars.Contains(result[i - 1]) == false)
            {
                chars.Add(result[i - 1]);
                switch (chars[chars.Count - 1])
                {
                    case 'a': weight += chars.Count * 5; break;
                    case 'b': weight += chars.Count * (-12); break;
                    case 'c': weight += chars.Count * 47; break;
                    case 'd': weight += chars.Count * 7; break;
                    case 'e': weight += chars.Count * (-32); break;
                    default: break;
                }
            }
        }
        if (weight >= start && weight <= end)
        {
            chars.Clear();
            weight = 0;
            return true;
        }
        else
        {
            chars.Clear();
            weight = 0;
            return false;
        }
    }
Example #23
0
        public void PlayGame(Bot bot)
        {
            List<string> input = new List<string>();

            try {
                while (true) {
                    string line = System.Console.In.ReadLine().Trim().ToLower();

                    if (line.Equals(READY)) {
                        ParseSetup(input);
                        FinishTurn();
                        input.Clear();
                    } else if (line.Equals(GO)) {
                        state.StartNewTurn();
                        ParseUpdate(input);
                        bot.DoTurn(state);
                        FinishTurn();
                        input.Clear();
                    } else if (line.Equals(END)) {
                        bot.OnGameEnd(state);
                        break;
                    } else {
                        input.Add(line);
                    }
                }
            } catch (Exception e) {
                #if DEBUG
                    FileStream fs = new FileStream("debug.log", System.IO.FileMode.Create, System.IO.FileAccess.Write);
                    StreamWriter sw = new StreamWriter(fs);
                    sw.WriteLine(e);
                    sw.Close();
                    fs.Close();
                #endif
            }
        }
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Change all guids to lowercase to help the Chorus diff/merge code.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
		{
			DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000024);

			const string dateCreated = "DateCreated";
			var properties = new List<string> { dateCreated, "DateModified" };

			ConvertClassAndSubclasses(domainObjectDtoRepository, domainObjectDtoRepository.AllInstancesWithSubclasses("CmProject"), properties); // Tested
			ConvertClassAndSubclasses(domainObjectDtoRepository, domainObjectDtoRepository.AllInstancesWithSubclasses("CmMajorObject"), properties); // Tested
			ConvertClassAndSubclasses(domainObjectDtoRepository, domainObjectDtoRepository.AllInstancesWithSubclasses("CmPossibility"), properties); // Tested
			ConvertClassAndSubclasses(domainObjectDtoRepository, domainObjectDtoRepository.AllInstancesWithSubclasses("CmAnnotation"), properties); // Tested
			ConvertClassAndSubclasses(domainObjectDtoRepository, domainObjectDtoRepository.AllInstancesWithSubclasses("StJournalText"), properties); // Tested
			ConvertClassAndSubclasses(domainObjectDtoRepository, domainObjectDtoRepository.AllInstancesWithSubclasses("LexEntry"), properties); // Tested
			ConvertClassAndSubclasses(domainObjectDtoRepository, domainObjectDtoRepository.AllInstancesWithSubclasses("RnGenericRec"), properties); // Tested
			// Since ScrScriptureNote derives from CmBaseAnnotation, which has already had it DateCreated & DateModified updated,
			// we have to clear those two out of the dictioanry, or they will be updated twice, and the test on ScrScriptureNote will fail.
			properties.Clear();
			properties.Add("DateResolved");
			ConvertClassAndSubclasses(domainObjectDtoRepository, domainObjectDtoRepository.AllInstancesWithSubclasses("ScrScriptureNote"), properties); // Tested
			properties.Clear();
			properties.Add(dateCreated);
			ConvertClassAndSubclasses(domainObjectDtoRepository, domainObjectDtoRepository.AllInstancesWithSubclasses("ScrDraft"), properties);
			properties.Clear();
			properties.Add("RunDate");
			ConvertClassAndSubclasses(domainObjectDtoRepository, domainObjectDtoRepository.AllInstancesWithSubclasses("ScrCheckRun"), properties);

			DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
		}
Example #25
0
 public Instruction[] Parse(TextReader reader)
 {
     Token token;
     mReader = reader;
     mScratchpad = new List<Instruction>();
     mState = Idle;
     while(mState != null && ReadNextToken(out token)) {
         mState = mState(token);
         if (mState == null) {
             mReader = null;
             mBuilder.Length = 0;
             mScratchpad.Clear();
             mBlock.Clear();
             return null;
         }
     }
     mReader = null;
     var result = mScratchpad.ToArray();
     mBuilder.Length = 0;
     mScratchpad.Clear();
     if (mBlock.Count > 0) {
         mBlock.Clear();
         return null;
     }
     return result;
 }
        public void ParseCorrect()
        {
            bool zResult;

            List<string> zList = new List<string>();

            zList.Add("AT+MODE?");
            zList.Add("");
            zList.Add("+MODE: \"GPRS\", \"AWAIT\"");
            zList.Add("OK");            

            zResult = _AppModeCommand.Parse(zList);
            Assert.True(zResult);
            Assert.Equal(_AppModeCommand.DeviceConnectionMode, ConnectionMode.GPRS);
            Assert.Equal(_AppModeCommand.DeviceConnectionType, ConnectionType.AWAIT);

            zList.Clear();
            zList.Add("+MODE: \"CSD\", \"AWAIT\"");
            zList.Add("OK");            

            zResult = _AppModeCommand.Parse(zList);
            Assert.True(zResult);
            Assert.Equal(_AppModeCommand.DeviceConnectionMode, ConnectionMode.CSD);
            Assert.Equal(_AppModeCommand.DeviceConnectionType, ConnectionType.AWAIT);

            zList.Clear();
            zList.Add("+MODE: \"GPRS\", \"ACTIVE\"");
            zList.Add("OK");            

            zResult = _AppModeCommand.Parse(zList);
            Assert.True(zResult);
            Assert.Equal(_AppModeCommand.DeviceConnectionMode, ConnectionMode.GPRS);
            Assert.Equal(_AppModeCommand.DeviceConnectionType, ConnectionType.ACTIVE);
        }
        /// <summary>
        /// AggregateException 의 내부 Exception이 AggregateException인 경우, 재귀호출을 통해, Exception만을 <paramref name="predicate"/>를 통해 실행시킨다.
        /// </summary>
        /// <param name="aggregateException"></param>
        /// <param name="predicate"></param>
        /// <returns></returns>
        private static AggregateException HandleRecursively(this AggregateException aggregateException,
                                                            Func<Exception, bool> predicate = null) {
            predicate = predicate ?? (_ => true);

            var innerExceptions = new List<Exception>();

            foreach(var inner in aggregateException.InnerExceptions) {
                var innerAsAggregate = inner as AggregateException;

                // 내부 Exception이 AggregateException인 경우
                if(innerAsAggregate != null) {
                    AggregateException newChildAggregate = HandleRecursively(innerAsAggregate, predicate);

                    if(newChildAggregate != null) {
                        if(innerExceptions.Count > 0)
                            innerExceptions.Clear();
                        innerExceptions.Add(newChildAggregate);
                    }
                }
                else if(predicate(inner) == false) {
                    if(innerExceptions.Count > 0)
                        innerExceptions.Clear();
                    innerExceptions.Add(inner);
                }
            }

            return innerExceptions.Count > 0 ? new AggregateException(aggregateException.Message, innerExceptions) : null;
        }
        public void plotNetOutputs()
        {
            List<double> auxInput = new List<double>();

            resultVals.Clear();
            auxInput.Clear();

            auxInput.Add(inputVals[0]);
            myNet.feedForward(auxInput);
            myNet.getResults(resultVals);

            Point lastP = new Point((int)Math.Round((inputVals[0] / ratioX - inX) / step), oy - (int)Math.Round(resultVals[0] / ratioY / step));
            Point currentP = new Point();

            for (int p = 1; p < inputVals.Count(); p++)
            {
                resultVals.Clear();
                auxInput.Clear();

                auxInput.Add(inputVals[p]);
                myNet.feedForward(auxInput);
                myNet.getResults(resultVals);
                currentP.X = (int)Math.Round((inputVals[p] / ratioX - inX) / step);
                currentP.Y = oy - (int)Math.Round(resultVals[0] / ratioY / step);

                gfx.DrawLine(greenP, lastP, currentP);

                lastP = currentP;
            }
        }
Example #29
0
 //методы
 //создание нейрона
 //попытка прочитать данные из файла с именем (символ+".txt")
 //при неудачном чтении из файла - заполнение матрицы весов случайными числами
 public Neuron(char RecognizingSymbol, int PointCount)
 {
     symbol = RecognizingSymbol;
     SetFileName();
     pointCount = PointCount + 1;
     w = new List<double>(pointCount);
     try
     {
         file = new FileStream(FileName, FileMode.Open);
         sr = new StreamReader(file);
         string line;
         while ((line = sr.ReadLine()) != null)
         {
             double temp;
             double.TryParse(line, out temp);
             w.Add(temp);
         }
         sr.Close();
         file.Close();
     }
     catch
     {
         w.Clear();
         change = true;
         FillW();
     }
     if (w.Count < pointCount)
     {
         w.Clear();
         change = true;
         FillW();
     }
 }
Example #30
0
        public override string Solve()
        {
            var primes = Helper.BuildPrimes();
            var numberToLookFor = 4;
            var consecutive = 0;
            var results = new List<int>();
            var allNumbers = new List<int>();
            for (int i = 130000; i < 140000; i++) {
                allNumbers.Add(i);
            }

            foreach (var i in allNumbers) {
                if (primes.Contains(i)) {
                    consecutive = 0;
                    results.Clear();
                    continue;
                }
                var factors = GetFactors(i, primes);
                if (factors.Count == numberToLookFor) {
                    consecutive++;
                    results.Add(i);
                }
                else {
                    consecutive = 0;
                    results.Clear();
                }

                if (consecutive == numberToLookFor) {
                    return results.Min().ToString();
                }
            }

            return Helper.GARF;
        }