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 #4
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 #5
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 #7
0
        public static int SetValue(string strName, string strValue)
        {
            string sql = "SELECT value FROM Params WHERE name=@Name;";
            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 value=@Value WHERE name=@Name;";
                cmdParams.Clear();
                cmdParams.Add(new SQLiteParameter("Name", strName));
                cmdParams.Add(new SQLiteParameter("Value", strValue));
                return DBAdapter.Execute(sql, cmdParams);
            }
              
        }
Example #8
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 #9
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 #10
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;
        }
Example #11
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;
 }
        /// <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 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();
                }
            }
        }
Example #14
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
            }
        }
        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);
        }
Example #16
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;
		}
        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);
        }
        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 #19
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);
            }
        }
Example #20
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();
        }
        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);
                    }
                }
            }
        }
        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 #23
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);
            }
        }
		/// ------------------------------------------------------------------------------------
		/// <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);
		}
        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);
        }
Example #26
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();
        }
    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));
    }
    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 #29
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;
        }
Example #30
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;
        }
Example #31
0
 public void ClearDomainEvents()
 {
     _domainEvents?.Clear();
 }
Example #32
0
        public void BuildCurveCurrentList(vec3 pivot)
        {
            double minDistA = 1000000, minDistB;
            //move the ABLine over based on the overlap amount set in vehicle
            double widthMinusOverlap = mf.tool.toolWidth - mf.tool.toolOverlap;

            int refCount = refList.Count;

            if (refCount < 5)
            {
                curList?.Clear();
                return;
            }

            //close call hit
            int cc = 0, dd;

            for (int j = 0; j < refCount; j += 10)
            {
                double dist = ((mf.guidanceLookPos.easting - refList[j].easting) * (mf.guidanceLookPos.easting - refList[j].easting))
                              + ((mf.guidanceLookPos.northing - refList[j].northing) * (mf.guidanceLookPos.northing - refList[j].northing));
                if (dist < minDistA)
                {
                    minDistA = dist;
                    cc       = j;
                }
            }

            minDistA = minDistB = 1000000;

            dd = cc + 7; if (dd > refCount - 1)
            {
                dd = refCount;
            }
            cc -= 7; if (cc < 0)
            {
                cc = 0;
            }

            //find the closest 2 points to current close call
            for (int j = cc; j < dd; j++)
            {
                double dist = ((mf.guidanceLookPos.easting - refList[j].easting) * (mf.guidanceLookPos.easting - refList[j].easting))
                              + ((mf.guidanceLookPos.northing - refList[j].northing) * (mf.guidanceLookPos.northing - refList[j].northing));
                if (dist < minDistA)
                {
                    minDistB = minDistA;
                    rB       = rA;
                    minDistA = dist;
                    rA       = j;
                }
                else if (dist < minDistB)
                {
                    minDistB = dist;
                    rB       = j;
                }
            }

            //reset the line over jump
            isLateralTriggered = false;

            if (rA >= refCount - 1 || rB >= refCount)
            {
                return;
            }

            if (rA > rB)
            {
                C = rA; rA = rB; rB = C;
            }

            //same way as line creation or not
            isHeadingSameWay = Math.PI - Math.Abs(Math.Abs(pivot.heading - refList[rA].heading) - Math.PI) < glm.PIBy2;

            if (mf.yt.isYouTurnTriggered)
            {
                isHeadingSameWay = !isHeadingSameWay;
            }

            //which side of the closest point are we on is next
            //calculate endpoints of reference line based on closest point
            refPoint1.easting  = refList[rA].easting - (Math.Sin(refList[rA].heading) * 100.0);
            refPoint1.northing = refList[rA].northing - (Math.Cos(refList[rA].heading) * 100.0);

            refPoint2.easting  = refList[rA].easting + (Math.Sin(refList[rA].heading) * 100.0);
            refPoint2.northing = refList[rA].northing + (Math.Cos(refList[rA].heading) * 100.0);

            //x2-x1
            double dx = refPoint2.easting - refPoint1.easting;
            //z2-z1
            double dz = refPoint2.northing - refPoint1.northing;

            //how far are we away from the reference line at 90 degrees - 2D cross product and distance
            distanceFromRefLine = ((dz * mf.guidanceLookPos.easting) - (dx * mf.guidanceLookPos.northing) + (refPoint2.easting
                                                                                                             * refPoint1.northing) - (refPoint2.northing * refPoint1.easting))
                                  / Math.Sqrt((dz * dz) + (dx * dx));

            double RefDist = (distanceFromRefLine + (isHeadingSameWay ? mf.tool.toolOffset : -mf.tool.toolOffset)) / widthMinusOverlap;

            if (RefDist < 0)
            {
                howManyPathsAway = (int)(RefDist - 0.5);
            }
            else
            {
                howManyPathsAway = (int)(RefDist + 0.5);
            }

            //build current list
            isCurveValid = true;

            //build the current line
            curList?.Clear();

            double distAway = widthMinusOverlap * howManyPathsAway + (isHeadingSameWay ? -mf.tool.toolOffset : mf.tool.toolOffset);

            double distSqAway = (distAway * distAway) - 0.01;

            for (int i = 0; i < refCount - 1; i++)
            {
                vec3 point = new vec3(
                    refList[i].easting + (Math.Sin(glm.PIBy2 + refList[i].heading) * distAway),
                    refList[i].northing + (Math.Cos(glm.PIBy2 + refList[i].heading) * distAway),
                    refList[i].heading);
                bool Add = true;
                for (int t = 0; t < refCount; t++)
                {
                    double dist = ((point.easting - refList[t].easting) * (point.easting - refList[t].easting))
                                  + ((point.northing - refList[t].northing) * (point.northing - refList[t].northing));
                    if (dist < distSqAway)
                    {
                        Add = false;
                        break;
                    }
                }
                if (Add)
                {
                    if (curList.Count > 0)
                    {
                        double dist = ((point.easting - curList[curList.Count - 1].easting) * (point.easting - curList[curList.Count - 1].easting))
                                      + ((point.northing - curList[curList.Count - 1].northing) * (point.northing - curList[curList.Count - 1].northing));
                        if (dist > 1)
                        {
                            curList.Add(point);
                        }
                    }
                    else
                    {
                        curList.Add(point);
                    }
                }
            }

            //int cnt;
            //if (style == 1)
            //{
            //    cnt = curList.Count;
            //    vec3[] arr = new vec3[cnt];
            //    cnt--;
            //    curList.CopyTo(arr);
            //    curList.Clear();

            //    //middle points
            //    for (int i = 1; i < cnt; i++)
            //    {
            //        vec3 pt3 = arr[i];
            //        pt3.heading = Math.Atan2(arr[i + 1].easting - arr[i - 1].easting, arr[i + 1].northing - arr[i - 1].northing);
            //        if (pt3.heading < 0) pt3.heading += glm.twoPI;
            //        curList.Add(pt3);
            //    }

            //    return;
            //}

            int cnt = curList.Count;

            if (cnt > 6)
            {
                vec3[] arr = new vec3[cnt];
                curList.CopyTo(arr);

                for (int i = 1; i < (curList.Count - 1); i++)
                {
                    arr[i].easting  = (curList[i - 1].easting + curList[i].easting + curList[i + 1].easting) / 3;
                    arr[i].northing = (curList[i - 1].northing + curList[i].northing + curList[i + 1].northing) / 3;
                }
                curList.Clear();

                for (int i = 0; i < (arr.Length - 1); i++)
                {
                    arr[i].heading = Math.Atan2(arr[i + 1].easting - arr[i].easting, arr[i + 1].northing - arr[i].northing);
                    if (arr[i].heading < 0)
                    {
                        arr[i].heading += glm.twoPI;
                    }
                    if (arr[i].heading >= glm.twoPI)
                    {
                        arr[i].heading -= glm.twoPI;
                    }
                }

                arr[arr.Length - 1].heading = arr[arr.Length - 2].heading;


                if (mf.tool.isToolTrailing)
                {
                    //depending on hitch is different profile of draft
                    double hitch;
                    if (mf.tool.isToolTBT && mf.tool.toolTankTrailingHitchLength < 0)
                    {
                        hitch  = mf.tool.toolTankTrailingHitchLength * 0.85;
                        hitch += mf.tool.toolTrailingHitchLength * 0.65;
                    }
                    else
                    {
                        hitch = mf.tool.toolTrailingHitchLength * 1.0; // - mf.vehicle.wheelbase;
                    }
                    //move the line forward based on hitch length ratio
                    for (int i = 0; i < arr.Length; i++)
                    {
                        arr[i].easting  -= Math.Sin(arr[i].heading) * (hitch);
                        arr[i].northing -= Math.Cos(arr[i].heading) * (hitch);
                    }

                    ////average the points over 3, center weighted
                    //for (int i = 1; i < arr.Length - 2; i++)
                    //{
                    //    arr2[i].easting = (arr[i - 1].easting + arr[i].easting + arr[i + 1].easting) / 3;
                    //    arr2[i].northing = (arr[i - 1].northing + arr[i].northing + arr[i + 1].northing) / 3;
                    //}

                    //recalculate the heading
                    for (int i = 0; i < (arr.Length - 1); i++)
                    {
                        arr[i].heading = Math.Atan2(arr[i + 1].easting - arr[i].easting, arr[i + 1].northing - arr[i].northing);
                        if (arr[i].heading < 0)
                        {
                            arr[i].heading += glm.twoPI;
                        }
                        if (arr[i].heading >= glm.twoPI)
                        {
                            arr[i].heading -= glm.twoPI;
                        }
                    }

                    arr[arr.Length - 1].heading = arr[arr.Length - 2].heading;
                }

                //replace the array
                //curList.AddRange(arr);
                cnt = arr.Length;
                double distance;
                double spacing = 0.5;

                //add the first point of loop - it will be p1
                curList.Add(arr[0]);
                curList.Add(arr[1]);

                for (int i = 0; i < cnt - 3; i++)
                {
                    // add p1
                    curList.Add(arr[i + 1]);

                    distance = glm.Distance(arr[i + 1], arr[i + 2]);

                    if (distance > spacing)
                    {
                        int loopTimes = (int)(distance / spacing + 1);
                        for (int j = 1; j < loopTimes; j++)
                        {
                            vec3 pos = new vec3(glm.Catmull(j / (double)(loopTimes), arr[i], arr[i + 1], arr[i + 2], arr[i + 3]));
                            curList.Add(pos);
                        }
                    }
                }

                curList.Add(arr[cnt - 2]);
                curList.Add(arr[cnt - 1]);

                //to calc heading based on next and previous points to give an average heading.
                cnt = curList.Count;
                arr = new vec3[cnt];
                cnt--;
                curList.CopyTo(arr);
                curList.Clear();

                //middle points
                for (int i = 1; i < cnt; i++)
                {
                    vec3 pt3 = arr[i];
                    pt3.heading = Math.Atan2(arr[i + 1].easting - arr[i - 1].easting, arr[i + 1].northing - arr[i - 1].northing);
                    if (pt3.heading < 0)
                    {
                        pt3.heading += glm.twoPI;
                    }
                    curList.Add(pt3);
                }
            }
            lastSecond = mf.secondsSinceStart;
        }
Example #33
0
 // Internal for testing
 internal void ResetFeatureCollection()
 {
     FastReset();
     MaybeExtra?.Clear();
     _featureRevision++;
 }
 public void ResetFeatureCollection()
 {
     Initialize();
     MaybeExtra?.Clear();
     _featureRevision++;
 }
Example #35
0
 //Reset the contour to zip
 public void ResetContour()
 {
     stripList.Clear();
      ptList?.Clear();
      ctList?.Clear();
 }
Example #36
0
 private void ShutdownHeightMap()
 {
     // Release the HeightMap Data loaded from the file.
     HeightMap?.Clear();
     HeightMap = null;
 }
Example #37
0
 public void Cleaar()
 {
     _dataStore?.Clear();
 }
Example #38
0
 public void ClearDomainEvents() => domainEvents?.Clear();
Example #39
0
 public void LimparEventos()
 {
     _notificacoes?.Clear();
 }
Example #40
0
 public void LimparEventos()
 {
     _eventos?.Clear();
 }
Example #41
0
 public void Clear() => _attributes?.Clear();
Example #42
0
 public virtual void SetNavigationProperties(params Expression <Func <T, object> >[] navigationProperties)
 {
     NavigationProperties?.Clear();
     AddNavigationProperties(navigationProperties);
 }
Example #43
0
 /// <summary>Clears the dictionary.</summary>
 public void Clear()
 {
     allIDs?.Clear();
     list.Clear();
 }
Example #44
0
 public void LimparEventos()
 {
     _notifications?.Clear();
 }
Example #45
0
        public bool Read()
        {
            if (_Reader == null)
            {
                throw new ObjectDisposedException("_Reader");
            }
            var s = State.NewField;

            _Buffer?.Clear();
            _Fields?.Clear();

            for (; ;)
            {
                var ci = _NextChar >= 0 ? _NextChar : _Reader.Read();
                _NextChar = -1;

                if (ci < 0)
                {
                    switch (s)
                    {
                    case State.Plain:
                    case State.Quoted:
                    case State.Escaping:
                        PushField();
                        break;
                    }
                    return(_Fields?.Count > 0);
                }

                var c = (char)ci;

                switch (s)
                {
                case State.NewField:
                    switch (c)
                    {
                    case '\r':
                        s = State.Cr;
                        break;

                    case '\n':
                        return(true);

                    case '"':
                        s = State.Quoted;
                        break;

                    case ',':
                        (_Fields ?? (_Fields = new List <string>())).Add(string.Empty);
                        break;

                    default:
                        s = State.Plain;
                        (_Buffer ?? (_Buffer = new StringBuilder())).Append(c);
                        break;
                    }
                    break;

                case State.Cr:
                    _NextChar = c == '\n' ? -1 : ci;
                    return(true);

                case State.Plain:
                    switch (c)
                    {
                    case '\r':
                        PushField();
                        s = State.Cr;
                        break;

                    case '\n':
                        PushField();
                        return(true);

                    case ',':
                        PushField();
                        s = State.NewField;
                        break;

                    default:
                        PushChar(c);
                        break;
                    }
                    break;

                case State.Quoted:
                    switch (c)
                    {
                    case '"':
                        s = State.Escaping;
                        break;

                    default:
                        PushChar(c);
                        break;
                    }
                    break;

                case State.Escaping:
                    switch (c)
                    {
                    case '\r':
                        PushField();
                        s = State.Cr;
                        break;

                    case '\n':
                        PushField();
                        return(true);

                    case ',':
                        PushField();
                        s = State.NewField;
                        break;

                    default:         // valid only for '"'
                        PushChar(c);
                        s = State.Quoted;
                        break;
                    }
                    break;
                }
            }
        }
Example #46
0
 /// <inheritdoc />
 public virtual void Dispose()
 {
     _nodeParents?.Clear();
     _idsMapping?.Clear();
     _data = null;
 }
Example #47
0
 /// <summary>
 /// Clears the log.
 /// </summary>
 public void Clear()
 {
     _entries?.Clear();
     Refresh();
 }
Example #48
0
 public void ResetGeoFence()
 {
     calcList?.Clear();
     geoFenceLine?.Clear();
 }
Example #49
0
 public static void ClearAll()
 {
     paramsList?.Clear();
     paramsList = null;
 }
 void ClearLogs()
 {
     m_Debugger.ClearLogs();
     m_SelectedEvents?.Clear();
     Refresh();
 }
 public static void Unload()
 {
     accessories?.Clear();
     accessories = null;
 }
Example #52
0
 /// <summary>
 /// dispose
 /// </summary>
 public void Clear()
 {
     _buffer?.Clear();
 }
        public override void DrawHairAndHeadGear(Vector3 hairLoc, Vector3 headgearLoc,
                                                 RotDrawMode bodyDrawType,
                                                 Quaternion headQuat,
                                                 bool renderBody,
                                                 bool portrait, Vector3 hatInFrontOfFace)
        {
            Mesh hairMesh = this.GetPawnHairMesh(portrait);
            List <ApparelGraphicRecord> apparelGraphics  = this.Graphics.apparelGraphics;
            List <ApparelGraphicRecord> headgearGraphics = null;

            if (!apparelGraphics.NullOrEmpty())
            {
                headgearGraphics = apparelGraphics
                                   .Where(x => x.sourceApparel.def.apparel.LastLayer == ApparelLayerDefOf.Overhead ||
                                          x.sourceApparel.def.apparel.LastLayer == DefDatabase <ApparelLayerDef> .GetNamedSilentFail("OnHead") ||
                                          x.sourceApparel.def.apparel.LastLayer == DefDatabase <ApparelLayerDef> .GetNamedSilentFail("StrappedHead") ||
                                          x.sourceApparel.def.apparel.LastLayer == DefDatabase <ApparelLayerDef> .GetNamedSilentFail("MiddleHead")).ToList();
            }

            CompBodyAnimator animator = this.CompAnimator;

            bool noRenderGoggles = Controller.settings.FilterHats;

            bool showRoyalHeadgear = this.Pawn.royalty?.MostSeniorTitle != null && Controller.settings.ShowRoyalHeadgear;
            bool noRenderRoofed    = animator != null && animator.HideHat && !showRoyalHeadgear;
            bool noRenderBed       = Controller.settings.HideHatInBed && !renderBody && !showRoyalHeadgear;

            if (!headgearGraphics.NullOrEmpty())
            {
                bool filterHeadgear = portrait && Prefs.HatsOnlyOnMap || !portrait && noRenderRoofed;

                // Draw regular hair if appparel or environment allows it (FS feature)
                if (bodyDrawType != RotDrawMode.Dessicated)
                {
                    // draw full or partial hair
                    bool apCoversFullHead =
                        headgearGraphics.Any(
                            x => x.sourceApparel.def.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf
                                                                                     .FullHead) &&
                            !x.sourceApparel.def.apparel.hatRenderedFrontOfFace);

                    bool apCoversUpperHead =
                        headgearGraphics.Any(
                            x => x.sourceApparel.def.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf
                                                                                     .UpperHead) &&
                            !x.sourceApparel.def.apparel.hatRenderedFrontOfFace);

                    if (this.CompFace.Props.hasOrganicHair || noRenderBed || filterHeadgear ||
                        (!apCoversFullHead && !apCoversUpperHead && noRenderGoggles))
                    {
                        Material mat = this.Graphics.HairMatAt(this.HeadFacing);
                        GenDraw.DrawMeshNowOrLater(hairMesh, hairLoc, headQuat, mat, portrait);
                    }
                    else if (Controller.settings.MergeHair) // && !apCoversFullHead)
                    {
                        // If not, display the hair cut
                        HairCutPawn hairPawn   = CutHairDB.GetHairCache(this.Pawn);
                        Material    hairCutMat = hairPawn.HairCutMatAt(this.HeadFacing);
                        if (hairCutMat != null)
                        {
                            GenDraw.DrawMeshNowOrLater(hairMesh, hairLoc, headQuat, hairCutMat, portrait);
                        }
                    }
                }
                else
                {
                    filterHeadgear = false;
                }

                if (filterHeadgear)
                {
                    // Filter the head gear to only show non-hats, show nothing while in bed
                    if (noRenderGoggles)
                    {
                        headgearGraphics = headgearGraphics
                                           .Where(
                            x =>
                            !x.sourceApparel.def.apparel.bodyPartGroups
                            .Contains(BodyPartGroupDefOf.FullHead) &&
                            !x.sourceApparel.def.apparel.bodyPartGroups.Contains(
                                BodyPartGroupDefOf
                                .UpperHead))
                                           .ToList();
                    }
                    else
                    {
                        // Clear if nothing to show
                        headgearGraphics?.Clear();
                    }
                }

                if (noRenderBed && !showRoyalHeadgear)
                {
                    headgearGraphics?.Clear();
                }

                // headgearGraphics = headgearGraphics
                // .OrderBy(x => x.sourceApparel.def.apparel.bodyPartGroups.Max(y => y.listOrder)).ToList();
                if (headgearGraphics.NullOrEmpty())
                {
                    return;
                }

                for (int index = 0; index < headgearGraphics?.Count; index++)
                {
                    ApparelGraphicRecord headgearGraphic = headgearGraphics[index];
                    Material             headGearMat     = headgearGraphic.graphic.MatAt(this.HeadFacing);
                    headGearMat = this.Graphics.flasher.GetDamagedMat(headGearMat);

                    if (headgearGraphic.sourceApparel.def.apparel.hatRenderedFrontOfFace)
                    {
                        headgearLoc = hatInFrontOfFace;
                    }

                    GenDraw.DrawMeshNowOrLater(hairMesh, headgearLoc, headQuat, headGearMat, portrait);
                    headgearLoc.y += Offsets.YOffsetInterval_Clothes;
                }
            }
            else
            {
                // Draw regular hair if no hat worn
                if (bodyDrawType != RotDrawMode.Dessicated)
                {
                    Material hairMat = this.Graphics.HairMatAt(this.HeadFacing);
                    GenDraw.DrawMeshNowOrLater(hairMesh, hairLoc, headQuat, hairMat, portrait);
                }
            }
        }
Example #54
0
 public void Dispose()
 {
     hierachy?.Clear();
     track_idx = 0;
     hierachy  = null;
 }
Example #55
0
        public void UpdateLoadMenu(IEnumerable <string> saveFiles = null)
        {
            prevSaveFiles?.Clear();
            prevSaveFiles = null;
            loadGameContainer.ClearChildren();

            if (saveFiles == null)
            {
                saveFiles = SaveUtil.GetSaveFiles(isMultiplayer ? SaveUtil.SaveType.Multiplayer : SaveUtil.SaveType.Singleplayer);
            }

            var leftColumn = new GUILayoutGroup(new RectTransform(isMultiplayer ? new Vector2(1.0f, 0.85f) : new Vector2(0.5f, 1.0f), loadGameContainer.RectTransform), childAnchor: Anchor.TopCenter)
            {
                Stretch         = true,
                RelativeSpacing = 0.03f
            };

            saveList = new GUIListBox(new RectTransform(Vector2.One, leftColumn.RectTransform))
            {
                OnSelected = SelectSaveFile
            };

            if (!isMultiplayer)
            {
                new GUIButton(new RectTransform(new Vector2(0.6f, 0.08f), leftColumn.RectTransform), TextManager.Get("showinfolder"))
                {
                    OnClicked = (btn, userdata) =>
                    {
                        try
                        {
                            ToolBox.OpenFileWithShell(SaveUtil.SaveFolder);
                        }
                        catch (Exception e)
                        {
                            new GUIMessageBox(
                                TextManager.Get("error"),
                                TextManager.GetWithVariables("showinfoldererror", new string[] { "[folder]", "[errormessage]" }, new string[] { SaveUtil.SaveFolder, e.Message }));
                        }
                        return(true);
                    }
                };
            }

            foreach (string saveFile in saveFiles)
            {
                string fileName          = saveFile;
                string subName           = "";
                string saveTime          = "";
                string contentPackageStr = "";
                var    saveFrame         = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.1f), saveList.Content.RectTransform)
                {
                    MinSize = new Point(0, 45)
                }, style: "ListBoxElement")
                {
                    UserData = saveFile
                };

                var nameText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), saveFrame.RectTransform), "")
                {
                    CanBeFocused = false
                };

                bool isCompatible = true;
                prevSaveFiles ??= new List <string>();
                if (!isMultiplayer)
                {
                    nameText.Text = Path.GetFileNameWithoutExtension(saveFile);
                    XDocument doc = SaveUtil.LoadGameSessionDoc(saveFile);

                    if (doc?.Root == null)
                    {
                        DebugConsole.ThrowError("Error loading save file \"" + saveFile + "\". The file may be corrupted.");
                        nameText.TextColor = GUI.Style.Red;
                        continue;
                    }
                    if (doc.Root.GetChildElement("multiplayercampaign") != null)
                    {
                        //multiplayer campaign save in the wrong folder -> don't show the save
                        saveList.Content.RemoveChild(saveFrame);
                        continue;
                    }
                    subName           = doc.Root.GetAttributeString("submarine", "");
                    saveTime          = doc.Root.GetAttributeString("savetime", "");
                    isCompatible      = SaveUtil.IsSaveFileCompatible(doc);
                    contentPackageStr = doc.Root.GetAttributeString("selectedcontentpackages", "");
                    prevSaveFiles?.Add(saveFile);
                }
                else
                {
                    prevSaveFiles?.Add(saveFile);
                    string[] splitSaveFile = saveFile.Split(';');
                    saveFrame.UserData = splitSaveFile[0];
                    fileName           = nameText.Text = Path.GetFileNameWithoutExtension(splitSaveFile[0]);
                    if (splitSaveFile.Length > 1)
                    {
                        subName = splitSaveFile[1];
                    }
                    if (splitSaveFile.Length > 2)
                    {
                        saveTime = splitSaveFile[2];
                    }
                    if (splitSaveFile.Length > 3)
                    {
                        contentPackageStr = splitSaveFile[3];
                    }
                }
                if (!string.IsNullOrEmpty(saveTime) && long.TryParse(saveTime, out long unixTime))
                {
                    DateTime time = ToolBox.Epoch.ToDateTime(unixTime);
                    saveTime = time.ToString();
                }
                if (!string.IsNullOrEmpty(contentPackageStr))
                {
                    List <string> contentPackagePaths = contentPackageStr.Split('|').ToList();
                    if (!GameSession.IsCompatibleWithEnabledContentPackages(contentPackagePaths, out string errorMsg))
                    {
                        nameText.TextColor = GUI.Style.Red;
                        saveFrame.ToolTip  = string.Join("\n", errorMsg, TextManager.Get("campaignmode.contentpackagemismatchwarning"));
                    }
                }
                if (!isCompatible)
                {
                    nameText.TextColor = GUI.Style.Red;
                    saveFrame.ToolTip  = TextManager.Get("campaignmode.incompatiblesave");
                }

                new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), saveFrame.RectTransform, Anchor.BottomLeft),
                                 text: subName, font: GUI.SmallFont)
                {
                    CanBeFocused = false,
                    UserData     = fileName
                };

                new GUITextBlock(new RectTransform(new Vector2(1.0f, 1.0f), saveFrame.RectTransform),
                                 text: saveTime, textAlignment: Alignment.Right, font: GUI.SmallFont)
                {
                    CanBeFocused = false,
                    UserData     = fileName
                };
            }

            saveList.Content.RectTransform.SortChildren((c1, c2) =>
            {
                string file1            = c1.GUIComponent.UserData as string;
                string file2            = c2.GUIComponent.UserData as string;
                DateTime file1WriteTime = DateTime.MinValue;
                DateTime file2WriteTime = DateTime.MinValue;
                try
                {
                    file1WriteTime = File.GetLastWriteTime(file1);
                }
                catch
                {
                    //do nothing - DateTime.MinValue will be used and the element will get sorted at the bottom of the list
                };
                try
                {
                    file2WriteTime = File.GetLastWriteTime(file2);
                }
                catch
                {
                    //do nothing - DateTime.MinValue will be used and the element will get sorted at the bottom of the list
                };
                return(file2WriteTime.CompareTo(file1WriteTime));
            });

            loadGameButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.12f), loadGameContainer.RectTransform, Anchor.BottomRight), TextManager.Get("LoadButton"))
            {
                OnClicked = (btn, obj) =>
                {
                    if (string.IsNullOrWhiteSpace(saveList.SelectedData as string))
                    {
                        return(false);
                    }
                    LoadGame?.Invoke(saveList.SelectedData as string);
                    if (isMultiplayer)
                    {
                        CoroutineManager.StartCoroutine(WaitForCampaignSetup(), "WaitForCampaignSetup");
                    }
                    return(true);
                },
                Enabled = false
            };
            deleteMpSaveButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.12f), loadGameContainer.RectTransform, Anchor.BottomLeft),
                                               TextManager.Get("Delete"), style: "GUIButtonSmall")
            {
                OnClicked = DeleteSave,
                Visible   = false
            };
        }
        async Task <HttpURLConnection> SetupRequestInternal(HttpRequestMessage request, URLConnection conn)
        {
            if (conn == null)
            {
                throw new ArgumentNullException(nameof(conn));
            }
            var httpConnection = conn.JavaCast <HttpURLConnection> ();

            if (httpConnection == null)
            {
                throw new InvalidOperationException($"Unsupported URL scheme {conn.URL.Protocol}");
            }

            httpConnection.RequestMethod = request.Method.ToString();

            // SSL context must be set up as soon as possible, before adding any content or
            // headers. Otherwise Java won't use the socket factory
            SetupSSL(httpConnection as HttpsURLConnection);
            if (request.Content != null)
            {
                AddHeaders(httpConnection, request.Content.Headers);
            }
            AddHeaders(httpConnection, request.Headers);

            List <string> accept_encoding = null;

            decompress_here = false;
            if ((AutomaticDecompression & DecompressionMethods.GZip) != 0)
            {
                AppendEncoding(GZIP_ENCODING, ref accept_encoding);
                decompress_here = true;
            }

            if ((AutomaticDecompression & DecompressionMethods.Deflate) != 0)
            {
                AppendEncoding(DEFLATE_ENCODING, ref accept_encoding);
                decompress_here = true;
            }

            if (AutomaticDecompression == DecompressionMethods.None)
            {
                accept_encoding?.Clear();
                AppendEncoding(IDENTITY_ENCODING, ref accept_encoding);                  // Turns off compression for the Java client
            }

            if (accept_encoding?.Count > 0)
            {
                httpConnection.SetRequestProperty("Accept-Encoding", String.Join(",", accept_encoding));
            }

            if (UseCookies && CookieContainer != null)
            {
                string cookieHeaderValue = CookieContainer.GetCookieHeader(request.RequestUri);
                if (!String.IsNullOrEmpty(cookieHeaderValue))
                {
                    httpConnection.SetRequestProperty("Cookie", cookieHeaderValue);
                }
            }

            HandlePreAuthentication(httpConnection);
            await SetupRequest(request, httpConnection).ConfigureAwait(continueOnCapturedContext: false);;
            SetupRequestBody(httpConnection, request);

            return(httpConnection);
        }
Example #57
0
        /// <summary>
        /// Updates the query search filter.
        /// </summary>
        /// <param name="filterText">The filter text.</param>
        public void UpdateFilter(string filterText)
        {
            // SKip hidden actors
            var actor = Actor;

            if (actor != null && (actor.HideFlags & HideFlags.HideInHierarchy) != 0)
            {
                return;
            }

            bool noFilter = string.IsNullOrWhiteSpace(filterText);

            _hasSearchFilter = !noFilter;

            // Update itself
            bool isThisVisible;

            if (noFilter)
            {
                // Clear filter
                _highlights?.Clear();
                isThisVisible = true;
            }
            else
            {
                QueryFilterHelper.Range[] ranges;
                var text = Text;
                if (QueryFilterHelper.Match(filterText, text, out ranges))
                {
                    // Update highlights
                    if (_highlights == null)
                    {
                        _highlights = new List <Rectangle>(ranges.Length);
                    }
                    else
                    {
                        _highlights.Clear();
                    }
                    var style    = Style.Current;
                    var font     = style.FontSmall;
                    var textRect = TextRect;
                    for (int i = 0; i < ranges.Length; i++)
                    {
                        var start = font.GetCharPosition(text, ranges[i].StartIndex);
                        var end   = font.GetCharPosition(text, ranges[i].EndIndex);
                        _highlights.Add(new Rectangle(start.X + textRect.X, textRect.Y, end.X - start.X, textRect.Height));
                    }
                    isThisVisible = true;
                }
                else
                {
                    // Hide
                    _highlights?.Clear();
                    isThisVisible = false;
                }
            }

            // Update children
            bool isAnyChildVisible = false;

            for (int i = 0; i < _children.Count; i++)
            {
                if (_children[i] is ActorTreeNode child)
                {
                    child.UpdateFilter(filterText);
                    isAnyChildVisible |= child.Visible;
                }
            }

            bool isExpanded = isAnyChildVisible;

            // Restore cached state on query filter clear
            if (noFilter && actor != null)
            {
                var id = actor.ID;
                isExpanded = Editor.Instance.ProjectCache.IsExpandedActor(ref id);
            }

            if (isExpanded)
            {
                Expand(true);
            }
            else
            {
                Collapse(true);
            }

            Visible = isThisVisible | isAnyChildVisible;
        }
Example #58
0
 public void ClearDiagnosis()
 => PositiveDiagnoses?.Clear();
Example #59
0
        public void BuildTram()
        {
            mf.tram.BuildTramBnd();

            tramList?.Clear();
            tramArr?.Clear();
            List <vec2> tramRef = new List <vec2>();

            bool isBndExist = mf.bnd.bndArr.Count != 0;

            double pass = 0.5;
            double hsin = Math.Sin(abHeading);
            double hcos = Math.Cos(abHeading);

            //divide up the AB line into segments
            vec2 P1 = new vec2();

            for (int i = 0; i < 3200; i += 4)
            {
                P1.easting  = (hsin * i) + refABLineP1.easting;
                P1.northing = (hcos * i) + refABLineP1.northing;
                tramRef.Add(P1);
            }

            //create list of list of points of triangle strip of AB Highlight
            double headingCalc = abHeading + glm.PIBy2;

            hsin = Math.Sin(headingCalc);
            hcos = Math.Cos(headingCalc);

            tramList?.Clear();
            tramArr?.Clear();

            for (int i = 0; i < mf.tram.passes; i++)
            {
                tramArr = new List <vec2>();
                tramList.Add(tramArr);

                for (int j = 0; j < tramRef.Count; j++)
                {
                    P1.easting  = (hsin * ((mf.tram.tramWidth * (pass + i)) - mf.tram.halfWheelTrack + mf.tram.abOffset)) + tramRef[j].easting;
                    P1.northing = (hcos * ((mf.tram.tramWidth * (pass + i)) - mf.tram.halfWheelTrack + mf.tram.abOffset)) + tramRef[j].northing;

                    if (isBndExist)
                    {
                        if (mf.bnd.bndArr[0].IsPointInsideBoundaryEar(P1))
                        {
                            tramArr.Add(P1);
                            P1.easting  = (hsin * mf.tram.wheelTrack) + P1.easting;
                            P1.northing = (hcos * mf.tram.wheelTrack) + P1.northing;
                            tramArr.Add(P1);
                        }
                    }
                    else
                    {
                        tramArr.Add(P1);

                        P1.easting  = (hsin * mf.tram.wheelTrack) + P1.easting;
                        P1.northing = (hcos * mf.tram.wheelTrack) + P1.northing;
                        tramArr.Add(P1);
                    }
                }
            }

            tramRef?.Clear();
            //outside tram

            if (mf.bnd.bndArr.Count == 0 || mf.tram.passes != 0)
            {
                //return;
            }
        }
Example #60
0
        public override async Task ObserveAsync(CancellationToken token)
        {
            // Only run once per specified time in Settings.xml. (default is already set to 1 day for CertificateObserver)
            // See Settings.xml, CertificateObserverConfiguration section, RunInterval parameter.
            if (RunInterval > TimeSpan.MinValue &&
                DateTime.Now.Subtract(LastRunDateTime) < RunInterval)
            {
                return;
            }

            if (token.IsCancellationRequested)
            {
                return;
            }

            if (!IsTestRun)
            {
                await Initialize(token).ConfigureAwait(true);
            }

            ExpiredWarnings  = new List <string>();
            ExpiringWarnings = new List <string>();
            NotFoundWarnings = new List <string>();

            // Unix LocalMachine X509Store is limited to the Root and CertificateAuthority stores.
            var store = new X509Store(RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? StoreName.Root : StoreName.My, StoreLocation.LocalMachine);

            try
            {
                store?.Open(OpenFlags.ReadOnly);

                // Cluster Certificates
                if (SecurityConfiguration.SecurityType == SecurityType.CommonName)
                {
                    CheckLatestBySubjectName(store, SecurityConfiguration.ClusterCertThumbprintOrCommonName, DaysUntilClusterExpireWarningThreshold);
                }
                else if (SecurityConfiguration.SecurityType == SecurityType.Thumbprint)
                {
                    CheckByThumbprint(store, SecurityConfiguration.ClusterCertThumbprintOrCommonName, DaysUntilClusterExpireWarningThreshold);
                }

                // App certificates
                foreach (string commonName in AppCertificateCommonNamesToObserve)
                {
                    token.ThrowIfCancellationRequested();
                    CheckLatestBySubjectName(store, commonName, DaysUntilAppExpireWarningThreshold);
                }

                foreach (string thumbprint in AppCertificateThumbprintsToObserve)
                {
                    token.ThrowIfCancellationRequested();
                    CheckByThumbprint(store, thumbprint, DaysUntilAppExpireWarningThreshold);
                }

                await ReportAsync(token).ConfigureAwait(true);
            }
            catch (SecurityException e)
            {
                WriteToLogWithLevel(
                    ObserverName,
                    $"Can't access {store.Name} due to {e.Message} - {e.StackTrace}",
                    LogLevel.Warning);
            }
            finally
            {
                store?.Dispose();
            }

            ExpiredWarnings?.Clear();
            ExpiredWarnings = null;
            ExpiringWarnings?.Clear();
            ExpiringWarnings = null;
            NotFoundWarnings?.Clear();
            NotFoundWarnings = null;

            LastRunDateTime = DateTime.Now;
        }