Example #1
0
        /// <summary>
        /// Declares a variable if there is a declaration and deletes unnessesary stuff
        /// </summary>
        /// <param name="listE"> stream of tokens </param>
        /// <returns> true if we need to launch the function again </returns>
        public static bool DeclareVariable(List<Element> listE)
        {
            if (listE.Count > 2) // it can be a declaration only if the list has more than 2 elements
            {
                if (listE[0].Type == C.Number && listE[1].Type == C.Control) // if it is a number
                {
                    string name = listE[0].GetNumber().Name;
                    if (name != "" && listE[1].ToString() == "=") // if it is a variable
                    {
                        listE.RemoveRange(0, 2);
                        Number num = new Number(Parse(listE).Value.ToString());
                        num.Name = name;
                        Variable.Add(num);

                        return false;
                    }
                }
            }

            int index = listE.FindIndex(delegate(Element e)
                                        { if (e.ToString() == "=") return true; return false; });
            if (index != -1) { listE.RemoveRange(0, index + 1); return true; }

            return false;
        }
Example #2
0
 private static void Last(List<int> array, string p1, string p2)
 {
     int count = int.Parse(p1);
     if (count > array.Count)
     {
         Console.WriteLine("Invalid count");
     }
     else
     {
         List<int> temp = new List<int>();
         if (p2 == "odd")
         {
             temp = array.Where(x => x % 2 == 1).ToList();
             if (count < temp.Count)
             {
                 temp.RemoveRange(0, temp.Count - count);
             }
             Console.WriteLine("[{0}]", string.Join(", ", temp));
         }
         else
         {
             temp = array.Where(x => x % 2 == 0).ToList();
             if (count < temp.Count)
             {
                 temp.RemoveRange(0, temp.Count - count);
             }
             Console.WriteLine("[{0}]", string.Join(", ", temp));
         }
     }
 }
Example #3
0
		List<byte> CreateInputBytes(List<byte> messageBytes)
		{
			var bytes = new List<byte>();
			var previousByte = new byte();
			messageBytes.RemoveRange(0, messageBytes.IndexOf(0x7E) + 1);
			messageBytes.RemoveRange(messageBytes.IndexOf(0x3E), messageBytes.Count - messageBytes.IndexOf(0x3E));
			foreach (var b in messageBytes)
			{
				if ((b == 0x7D) || (b == 0x3D))
				{ previousByte = b; continue; }
				if (previousByte == 0x7D)
				{
					previousByte = new byte();
					if (b == 0x5E)
					{ bytes.Add(0x7E); continue; }
					if (b == 0x5D)
					{ bytes.Add(0x7D); continue; }
				}
				if (previousByte == 0x3D)
				{
					previousByte = new byte();
					if (b == 0x1E)
					{ bytes.Add(0x3E); continue; }
					if (b == 0x1D)
					{ bytes.Add(0x3D); continue; }
				}
				bytes.Add(b);
			}
			return bytes;
		}
Example #4
0
	public static AudioClip TrimSilence(List<float> samples, float min, int channels, int hz, bool _3D, bool stream) {
		int i;
 
		// remove samples at the beginning
		for (i=0; i<samples.Count; i++) {
			if (Mathf.Abs(samples[i]) > min) {
				break;
			}
		} 
		samples.RemoveRange(0, i);

		// sanity check
		if ( samples.Count != 0 )
		{ 
			// remove samples at the end
			for (i=samples.Count - 1; i>0; i--) {
				if (Mathf.Abs(samples[i]) > min) {
					break;
				}
			}
			samples.RemoveRange(i, samples.Count - i);
			UnityEngine.Debug.Log ("SaveWav.TrimSilence() samples after begin trim = " + samples.Count);
		}
		else
			UnityEngine.Debug.Log ("SaveWav.TrimSilence() no samples!");

		var clip = AudioClip.Create("TempClip", samples.Count, channels, hz, _3D, stream);
 
		if ( samples.Count != 0 )
			clip.SetData(samples.ToArray(), 0);

		return clip;
	}
        private void button1_Click(object sender, EventArgs e)
        {
            license = richTextBox1.Lines;
            IEnumerable<string> files = Directory.GetFiles (folder, textBox1.Text, SearchOption.AllDirectories);
            foreach (string file in files)
            {
                List<string> newLines = new List<string> ();
                newLines.AddRange (license);
                string[] lines = File.ReadAllLines (file);

                if (lines[0].StartsWith ("/*"))
                {
                    int endLine = 0;
                    for (int i = 0; i < lines.Length; i++)
                    {
                        if (lines[i].StartsWith (" */"))
                        {
                            endLine = i;
                            break;
                        }
                    }
                    List<string> l = new List<string>(lines);
                    l.RemoveRange(0, endLine + 1);
                    if (l[0] == "")
                        l.RemoveRange (0, 1);
                    newLines.AddRange (l);
                }
                else
                {
                    newLines.AddRange (lines);
                }
                File.WriteAllLines (file, newLines.ToArray ());
            }
        }
    static void Main()
    {
        string s;
        int inputLines = int.Parse(Console.ReadLine());
        int desiredWidth = int.Parse(Console.ReadLine());
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < inputLines; i++)
        {
            s = Console.ReadLine();
            sb.Append(s.Trim() + " ");
        }
        sb.Remove(sb.Length - 1, 1);
        string[] sWords = sb.ToString().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        List<string> words = new List<string>(sWords);
        do
        {

            sb.Clear();
            sb.Append(words[0]);
            int currentWord = 1;
            while (sb.Length < desiredWidth && currentWord < words.Count)
            {
                sb.Append(" " + words[currentWord]);
                currentWord++;
            }
            if (sb.Length > desiredWidth)
            {
                sb.Remove(sb.Length - words[currentWord - 1].Length - 1, words[currentWord - 1].Length + 1);
                currentWord--;
            }
                if (sb.Length == desiredWidth || currentWord == 1)
            {
                Console.WriteLine(sb);
                words.RemoveRange(0, currentWord);
                continue;
            }
            int spacecount = currentWord - 1;
            int sizeOfSpaces = (desiredWidth - sb.Length + spacecount) / spacecount; // / (currentWord - 1)
            int numOfLongSpaces = (desiredWidth - sb.Length + spacecount) % spacecount;
            sb.Clear();
            sb.Append(words[0]);
            for (int i = 1; i <= spacecount; i++)
            {
                if (i <= numOfLongSpaces)
                    sb.Append(" ");
                sb.Append(new string(' ',sizeOfSpaces) + words[i]);
            }
            Console.WriteLine(sb);
            words.RemoveRange(0, currentWord);
        } while (words.Count > 0);
    }
Example #7
0
        public object CreateDataShapeObject(DTO.ExpenseGroup expenseGroup, List<string> lstFields)
        {
            List<string> lstFieldsIncluded = new List<string>(lstFields);

            if (!lstFieldsIncluded.Any())
            {
                return expenseGroup;
            }
            else
            {
                var lstExpenseFields = lstFieldsIncluded.Where(s => s.Contains("expenses")).ToList();

                bool returnPartialExpense = lstFieldsIncluded.Any() && !lstFieldsIncluded.Contains("expenses");

                if (returnPartialExpense)
                {
                    lstFieldsIncluded.RemoveRange(lstExpenseFields);
                    lstExpenseFields = lstExpenseFields.Select(f => f.Substring(f.IndexOf(".") + 1)).ToList();
                }
                else
                {
                    lstExpenseFields.Remove("expenses");
                    lstFieldsIncluded.RemoveRange(lstExpenseFields);
                }


                ExpandoObject objToReturn = new ExpandoObject();
                foreach (var field in lstFieldsIncluded)
                {
                    var fieldValue = expenseGroup.GetType()
                        .GetProperty(field, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance)
                        .GetValue(expenseGroup, null);

                    ((IDictionary<string, object>)objToReturn).Add(field, fieldValue);
                }

                if(returnPartialExpense)
                {
                    List<object> expenses = new List<object>();
                    foreach(var expense in expenseGroup.Expenses)
                    {
                        expenses.Add(expenseFactory.CreateDataShapeObject(expense, lstExpenseFields));
                    }
                    ((IDictionary<string, object>)objToReturn).Add("expenses", expenses);
                }

                return objToReturn;
            }
        }
Example #8
0
        public static string ReplacePathSegment(string path, string value, List<object> segments)
        {
            var segment = segments.SingleOrDefault(s => s.Equals(string.Format("?{0}=", value)) || s.Equals(string.Format("&{0}=", value)));
            if (segment != null)
            {
                var index = segments.IndexOf(segment);
                path = path.Replace(string.Format("{{{0}}}", value), string.Concat(segments[index + 1]));
                segments.RemoveRange(index, 2);

                // Replace missing ? if the segment was first in the series (after format)
                if(index == 1 && segments.Count > 1)
                {
                    var first = segments[index].ToString();
                    if(first.StartsWith("&"))
                    {
                        segments[index] = string.Concat("?", first.Substring(1));
                    }
                }
            }
            else
            {
                path = path.Replace(string.Format("/{{{0}}}", value), "");
            }
            return path;
        }
Example #9
0
        private static List<decimal> Test(List<decimal> testSetIpds, List<decimal> trainingIpds, int sampleSize)
        {
            List<decimal> results = new List<decimal>();

            while (testSetIpds.Count > 0)
            {
                List<decimal> sampleIpds;

                if (testSetIpds.Count > sampleSize)
                {
                    sampleIpds = testSetIpds.GetRange(0, sampleSize);
                    testSetIpds.RemoveRange(0, sampleSize);
                }
                else
                {
                    sampleIpds = testSetIpds.GetRange(0, testSetIpds.Count);
                    testSetIpds.Clear();
                }

                decimal result = CalculateKs(sampleIpds, trainingIpds);

                results.Add(result);
            }

            return results;
        }
        public ASCommandResponse(HttpWebResponse httpResponse)
        {
            httpStatus = httpResponse.StatusCode;

            Stream responseStream = httpResponse.GetResponseStream();
            List<byte> bytes = new List<byte>();
            byte[] byteBuffer = new byte[256];
            int count = 0;

            // Read the WBXML data from the response stream
            // 256 bytes at a time.
            count = responseStream.Read(byteBuffer, 0, 256);
            while (count > 0)
            {
                // Add the 256 bytes to the List
                bytes.AddRange(byteBuffer);

                if (count < 256)
                {
                    // If the last read did not actually read 256 bytes
                    // remove the extra.
                    int excess = 256 - count;
                    bytes.RemoveRange(bytes.Count - excess, excess);
                }

                // Read the next 256 bytes from the response stream
                count = responseStream.Read(byteBuffer, 0, 256);
            }

            wbxmlBytes = bytes.ToArray();

            // Decode the WBXML
            xmlString = DecodeWBXML(wbxmlBytes);
        }
Example #11
0
        private static void Adjust_score_for_frame_11(List<int> frameScores)
        {
            if (frameScores.Count <= 10) return;

            frameScores.RemoveRange(10, frameScores.Count() - 10);
            frameScores.Add(0);
        }
Example #12
0
 public override void ProcessTree()
 {
     if (Root == null || Root.Items.Count == 0)
         return;
     List<ANY_TreeNode> Nodes = new List<ANY_TreeNode>();
     List<SourceEntity> Result = new List<SourceEntity>();
     foreach (ANY_TreeNode node in Root.Items)
     {
         if (node.Value.Count == 0)
             continue;
         if (node is CommentStart)
             Nodes.Add(node);
         if (node is CommentEnd)
         {
             int startIndex;
             for (startIndex = Nodes.Count - 1; startIndex >= 0; --startIndex)
                 if (node.Value[0] == Nodes[startIndex].Value[0])
                     break;
             if (startIndex < 0)
                 continue;
             ANY_TreeNode newNode = new ANY_TreeNode(Nodes[startIndex].Value, Nodes[startIndex].Location.Merge(node.Location));
             for (int i = startIndex + 1; i < Nodes.Count; ++i)
                 if (Nodes[i].GetType() == typeof(ANY_TreeNode))
                     newNode.Items.Add(Nodes[i]);
             Nodes.RemoveRange(startIndex, Nodes.Count - startIndex);
             Nodes.Add(newNode);
         }
     }
     foreach (ANY_TreeNode node in Nodes)
         if (node.GetType() == typeof(ANY_TreeNode))
             Result.Add(node);
     Root.Items = Result;
 }
Example #13
0
        public Sampler(List<List<String>> csvData, int sampleRate)
        {
            this.csvData = csvData;
            this.sampleRate = sampleRate;

            // Find column numbers of relevant data
            foreach (List<String> row in csvData)
            {
                int i = 0;
                foreach (String content in row)
                {
                    if (content == "Time") { timestampPosition = i; }
                    else if (content == "L POR X [px]") { eyeXColumnNo = i; }
                    else if (content == "L POR Y [px]") { eyeYColumnNo = i; }
                    else
                    {
                        foreach (Electrode electrode in (Electrode[])Enum.GetValues(typeof(Electrode)))
                        {
                            if (content == "EEG_RAW_" + electrode)
                            {
                                columnNumbers.Add(electrode, i);
                            }
                        }
                    }
                    i++;
                }
                if (i > 0) break;
            }

            csvData.RemoveRange(0, 2);
            csvData.RemoveAt(csvData.Count - 1);

            FindAllGoodSamples();
        }
        public override object Deserialize(List<byte> byteList, TLPropertyAttribute attribute)
        {
            int count = byteList.ReadByte();
            int startOffset = 1;

            if (count >= 254)
            {
                count = byteList.ReadByte();
                count += byteList.ReadByte() << 8;
                count += byteList.ReadByte() << 16;
                startOffset = 4;
            }

            TLBytes bytes = new TLBytes(byteList.Take(count).ToArray());
            byteList.RemoveRange(0, count);

            int offset = (count + startOffset) % 4;
            if (offset != 0)
            {
                int offsetCount = 4 - offset;
                for (int i = 0; i < offsetCount; i++)
                    byteList.ReadByte();
            }

            return bytes;
        }
Example #15
0
 public void FilterResultsInInterval(DateTime dtStart, DateTime dtEnd, List<Object> list)
 {
     if (null == list) return;
     if (list.Count < 2) return;
     list.Sort();
     list.RemoveRange(1, list.Count - 1);
 }
Example #16
0
	public static AudioClip TrimSilence(List<float> samples, float min, int channels, int hz, bool _3D, bool stream) {
		int i;

		for (i=0; i<samples.Count; i++) {
			if (Mathf.Abs(samples[i]) > min) {
				break;
			}
		}

		samples.RemoveRange(0, i);

		for (i=samples.Count - 1; i>0; i--) {
			if (Mathf.Abs(samples[i]) > min) {
				break;
			}
		}

		samples.RemoveRange(i, samples.Count - i);

		var clip = AudioClip.Create("TempClip", samples.Count, channels, hz, _3D, stream);

		clip.SetData(samples.ToArray(), 0);

		return clip;
	}
Example #17
0
        private void proc(List<int> Input, int step)
        {
            if (Input.Count < 1 || SELECT - step > Input.Count)
                return;
            if (step == SELECT - 1)
            {
                foreach (var item in Input)
                {
                    result[step] = item;
                    //OutputToArray();
                    //tets
                    print(result);
                }
            }

            else
            {
                foreach (var item in Input)
                {
                    List<int> tempInput = new List<int>();
                    tempInput.AddRange(Input);
                    result[step] = item;
                    tempInput.RemoveRange(0, tempInput.IndexOf(item) + 1);
                    proc(tempInput, step + 1);
                }
            }
        }
Example #18
0
 static void Main(string[] args)
 {
     InitComplements();
       var seq = new List<byte[]>();
       var b = new Block { Count = -1 };
       Index line = Index.None, start = Index.None, end = Index.None;
       using (var r = new BinaryReader(Console.OpenStandardInput())) {
      using (var w = Console.OpenStandardOutput()) {
         while (b.Read(r) > 0) {
            seq.Add(b.Data);
            if (line.Pos < 0) line = b.IndexOf(Gt, 0);
            while (line.Pos >= 0) {
               if (start.Pos < 0) {
                  var off = line.InBlock(b) ? line.Pos : 0;
                  start = b.IndexOf(Lf, off);
                  if (start.Pos < 0) {
                      w.Write(b.Data, off, b.Data.Length - off);
                      seq.Clear(); break;
                  }
                  w.Write(b.Data, off, start.Pos + 1 - off);
               }
               if (end.Pos < 0) {
                  end = b.IndexOf(Gt, start.InBlock(b) ? start.Pos : 0);
                  if (end.Pos < 0) break;
               }
               w.Reverse(start.Pos, end.Pos, seq);
               if (seq.Count > 1) seq.RemoveRange(0, seq.Count - 1);
               line = end; end = Index.None; start = Index.None;
            }
         }
         if (start.Pos >= 0 && end.Pos < 0)
            w.Reverse(start.Pos, seq[seq.Count -1].Length, seq);
      }
       }
 }
        public void ZnajdzOtoczke(List<Punkt> lista)
        {
            List<Punkt> listaTmp = new List<Punkt>();
            Stack stos = new Stack();

            stos.Push(lista[0]);
            stos.Push(lista[1]);
            stos.Push(lista[2]);

            listaTmp.Add(lista[0]);
            listaTmp.Add(lista[1]);
            listaTmp.Add(lista[2]);

            for (int i = 3; i < lista.Count; i++)
            {
                int j = i;
                while (ObliczDet(listaTmp[stos.Count - 2], listaTmp[stos.Count - 1], lista[i]) < 0)
                {
                    //Console.WriteLine(ObliczDet(lista[j - 2], lista[j - 1], lista[i]));
                    stos.Pop();
                    listaTmp.RemoveRange(stos.Count, 1);
                }
                stos.Push(lista[i]);
                listaTmp.Add(lista[i]);
            }
            int ileWierz = stos.Count;
            for (int i = 0; i < ileWierz; i++)
            {
                wierzcholki.Add((Punkt)stos.Pop());
            }
            wierzcholki.Reverse();
        }
 public override void Visit(ParallelComposition node)
 {
     List<string> children = PopChildren();
     List<string> procChildren = new List<string>(children);
     procChildren.RemoveRange(0, 2);
     Return(CheckProc(Join(@" \mid\ ", procChildren), children));
 }
    /// <summary>
    /// Joins all sub sub scopes of the given <paramref name="scope"/>, reduces the number of sub 
    /// scopes by 1 and uniformly partitions the sub sub scopes again, maintaining the order.
    /// </summary>
    /// <exception cref="InvalidOperationException">Thrown when there are less than 2 sub-scopes available or when VillageCount does not equal the number of sub-scopes.</exception>
    /// <param name="scope">The current scope whose sub scopes to reduce.</param>
    /// <returns><c>null</c>.</returns>
    public override IOperation Apply() {
      IScope scope = ExecutionContext.Scope;
      if (VillageCountParameter.ActualValue == null) VillageCountParameter.ActualValue = new IntValue(scope.SubScopes.Count);
      int villageCount = VillageCountParameter.ActualValue.Value;
      if (villageCount <= 1)
        throw new InvalidOperationException(Name + ": Reunification requires 2 or more sub-scopes");
      if (villageCount != scope.SubScopes.Count)
        throw new InvalidOperationException(Name + ": VillageCount does not equal the number of sub-scopes");

      // get all villages
      List<IScope> population = new List<IScope>();
      for (int i = 0; i < villageCount; i++) {
        population.AddRange(scope.SubScopes[i].SubScopes);
        scope.SubScopes[i].SubScopes.Clear();
      }

      // reduce number of villages by 1 and partition the population again
      scope.SubScopes.RemoveAt(scope.SubScopes.Count - 1);
      villageCount--;
      int populationPerVillage = population.Count / villageCount;
      for (int i = 0; i < villageCount; i++) {
        scope.SubScopes[i].SubScopes.AddRange(population.GetRange(0, populationPerVillage));
        population.RemoveRange(0, populationPerVillage);
      }

      // add remaining individuals to last village
      scope.SubScopes[scope.SubScopes.Count - 1].SubScopes.AddRange(population);
      population.Clear();

      VillageCountParameter.ActualValue.Value = villageCount;

      return base.Apply();
    }
Example #22
0
        public void Test(int arg)
        {
            ArrayList items = new ArrayList();
            items.Add(1);
            items.AddRange(1, 2, 3);
            items.Clear();
            bool b1 = items.Contains(2);
            items.Insert(0, 1);
            items.InsertRange(1, 0, 5);
            items.RemoveAt(4);
            items.RemoveRange(4, 3);
            items.Remove(1);
            object[] newItems = items.GetRange(5, 2);
            object[] newItems2 = items.GetRange(5, arg);

            List<int> numbers = new List<int>();
            numbers.Add(1);
            numbers.AddRange(1, 2, 3);
            numbers.Clear();
            bool b2 = numbers.Contains(4);
            numbers.Insert(1, 10);
            numbers.InsertRange(2, 10, 3);
            numbers.RemoveAt(4);
            numbers.RemoveRange(4, 2);
            int[] newNumbers = items.GetRange(5, 2);
            int[] newNumbers2 = items.GetRange(5, arg);

            string[] words = new string[5];
            words[0] = "hello";
            words[1] = "world";
            bool b3 = words.Contains("hi");
            string[] newWords = words.GetRange(5, 2);
            string[] newWords2 = words.GetRange(5, arg);
        }
        /// <summary>
        /// Apply selection to the specified population.
        /// </summary>
        /// 
        /// <param name="chromosomes">Population, which should be filtered.</param>
        /// <param name="size">The amount of chromosomes to keep.</param>
        /// 
        /// <remarks>Filters specified population keeping only specified amount of best
        /// chromosomes.</remarks>
        /// 
        public void ApplySelection( List<IChromosome> chromosomes, int size )
        {
            // sort chromosomes
            //chromosomes.Sort( );

            // current population size
            int elitesize = chromosomes.Count;

            // Sorting by fitness
            for (int i = elitesize - 1; i >= 1; i--)
            {
                for (int j = 0; j < i; j++)
                {
                    if (chromosomes[j].Fitness > chromosomes[j + 1].Fitness)
                    {
                        // faz a ordenacao
                        IChromosome aux = chromosomes[j];
                        chromosomes[j] = chromosomes[j + 1];
                        chromosomes[j + 1] = aux;
                    }
                }
            }

            // remove bad chromosomes
            chromosomes.RemoveRange( size, chromosomes.Count - size );
        }
        public void DownloadImage(string link, string pathAdding = null) {
            var path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            var fileName = link.Split('/')[7];
            var subs = pathAdding.Split('/');
            var name = subs[3];
            var list = new List<string>(subs);
            list.RemoveRange(0, 3);

            CreateDirectoryIfNeed(path);
            foreach (var info in list) {
                if (info.Contains("http"))
                    continue;

                if (string.IsNullOrEmpty(info))
                    continue;

                if (info.Contains("?mature"))
                    path += "\\" + info.Split('?')[0];
                else
                    path += "\\" + info;

                CreateDirectoryIfNeed(path);
            }

            _downloader.DownloadImage(link, path + "\\" + fileName);
        }
Example #25
0
    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2: The generic type is type of string");

        try
        {
            string[] strArray = { "dog", "apple", "joke", "banana", "chocolate", "dog", "food" };
            List<string> listObject = new List<string>(strArray);
            listObject.RemoveRange(3, 3);
            string[] expected = { "dog", "apple", "joke", "food" };
            for (int i = 0; i < 4; i++)
            {
                if (listObject[i] != expected[i])
                {
                    TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,result is: " + listObject[i]);
                    retVal = false;
                }
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
Example #26
0
        private static void CheckForFlush(Player player)
        {
            var allCards = player.Hand.Concat(deck.BoardCards).ToList();//Combine the board & the players cards.
            List<int> flushCardsRanks = new List<int>();

            for (int a = 0; a < 4; a++)
            {
                foreach (Card card in allCards)
                {
                    if (card.Suit == a)
                    {
                        flushCardsRanks.Add(card.Rank);
                    }
                }

                if (flushCardsRanks.Count > 4)
                {
                    CheckForStraight(player, flushCardsRanks, true); //Sends all cards with same suit for straight check.

                    if (player.HandRank < 5) //No straight/royal flush setted by CheckfotStraight(), setting normal flush.
                    {
                        flushCardsRanks.Sort();
                        flushCardsRanks.RemoveRange(0, flushCardsRanks.Count - 5); //Leaving top 5 ranks from the flush.
                        flushCardsRanks.Reverse();
                        List<int> kickers = new List<int>();
                        kickers.Add(0); //No kickers in Flush.
                        player.SetRank(5, flushCardsRanks, kickers);
                    }
                    break; //Max one flush in a hand. Breaking.
                }

                flushCardsRanks.Clear();
            }
        }
Example #27
0
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Remove all the elements in the int type list");

        try
        {
            int[] iArray = { 1, 9, 3, 6, -1, 8, 7, 10, 2, 4 };
            List<int> listObject = new List<int>(iArray);
            listObject.RemoveRange(0, 10);
            if (listObject.Count != 0)
            {
                TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,count is: " + listObject.Count);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
        protected override void OnCreate(Android.OS.Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
           
						m_ImageLoader = new ImageLoader(this);

						
            _friends = Util.GenerateFriends();
            _friends.RemoveRange(0, _friends.Count - 2);
            var title = Intent.GetStringExtra("Title");
            var image = Intent.GetStringExtra("Image");

            title = string.IsNullOrWhiteSpace(title) ? "New Friend" : title;
            this.Title = title;

            if (string.IsNullOrWhiteSpace(image))
                image = _friends[0].Image;


            m_ImageLoader.DisplayImage(image, this.FindViewById<ImageView>(Resource.Id.friend_image), -1);
            this.FindViewById<TextView>(Resource.Id.friend_description).Text = title;

            var grid = FindViewById<GridView>(Resource.Id.grid);
            grid.Adapter = new MonkeyAdapter(this, _friends);
            grid.ItemClick += GridOnItemClick;

            //set title here
						SupportActionBar.Title = Title;
        }
Example #29
0
        public List<int> GetPriceSum(List<int> costs, int numberOfGroup)
        {
            var result = new List<int>();

            if (numberOfGroup < 0) numberOfGroup = 1;

            var group = costs.Count % numberOfGroup == 0 ?
                costs.Count / numberOfGroup : costs.Count / numberOfGroup + 1;

            for (int i = 0; i < group; i++)
            {
                int total;
                if (costs.Count >= numberOfGroup)
                {
                    total = costs.Take(numberOfGroup).Sum();
                    result.Add(total);
                }
                else
                {
                    total = costs.Sum();
                    result.Add(total);
                    break;
                }

                costs.RemoveRange(0, numberOfGroup);
            }

            return result;
        }
Example #30
0
        /// <summary>
        ///
        /// </summary>
        private void InitStraightList()
        {
            var tempDic   = _nbOccurencesValue.ToList();
            var straights = new List <List <Card> >()
            {
                new List <Card>()
                {
                    GetCardMatchSuit(tempDic[0].Value)
                }
            };
            int listIndex = 0;

            for (int i = 1; i < tempDic.Count; i++)
            {
                var kvp      = tempDic[i];
                int previous = (int)tempDic[i - 1].Key,
                    current  = (int)kvp.Key;
                if (previous != current + 1)
                {
                    listIndex++;
                    straights.Add(new List <Card>());
                }
                straights[listIndex].Add(GetCardMatchSuit(kvp.Value));
            }

            _straightList = straights.OrderByDescending(l => l.Count)
                            .FirstOrDefault(l => l.Count >= 5);
            _straightList?.RemoveRange(5, _straightList.Count - 5);
        }
Example #31
0
        public List<KeyValuePair<string, string>> GetKeysAndValues(string category)
        {
            // if category doesn't exist, should return an empty list.
            string returnString = new string(' ', MAXKEYSLENGTH);
            int res = GetPrivateProfileString(category, null, null, returnString, MAXKEYSLENGTH, this.m_fileName);
            /*if (res == 0)
            {
             maybe we just wrote 0 characters. TODO. how to distinguish between error case and nothing found case?
                Win32Exception wexp = new Win32Exception(Marshal.GetLastWin32Error());
                throw new IniFileParsingException("win32:" + wexp.Message);
            }*/
            if (res == MAXKEYSLENGTH - 2) //see docs: means buffer is full
            {
                throw new IniFileParsingException("data in key names is too long. must be <" + MAXKEYSLENGTH);
            }
            List<string> listKeys = new List<string>(returnString.Split('\0'));
            listKeys.RemoveRange(listKeys.Count - 2, 2); //removes the last 2 entries.

            //now let's build the actual list
            List<KeyValuePair<string, string>> result = new List<KeyValuePair<string,string>>();
            foreach (string sKey in listKeys)
            {
                result.Add( new KeyValuePair<string,string>(sKey, this.ReadValue(category, sKey)));
            }
            return result;
        }
Example #32
0
        // Group: Functions
        // __________________________________________________________________________


        /* Function: MergeTopics
         * Takes a list of <Topics> that come from the same class but multiple source files and combines them into a
         * single coherent list.  It assumes all topics from a single file will be consecutive, but otherwise the groups of
         * topics can be in any order.
         */
        public static void MergeTopics(List <Topic> topics, Builder builder)
        {
            if (topics.Count == 0)
            {
                return;
            }

                        #if DEBUG
            // Validate that they're all from the same class and that all of a file's topics are consecutive.

            int         classID     = topics[0].ClassID;
            ClassString classString = topics[0].ClassString;

            if (classID == 0)
            {
                throw new Exception("All topics passed to MergeTopics() must have a class ID set.");
            }

            int currentFileID = topics[0].FileID;
            IDObjects.NumberSet previousFileIDs = new IDObjects.NumberSet();

            for (int i = 1; i < topics.Count; i++)
            {
                if (topics[i].ClassID != classID || topics[i].ClassString != classString)
                {
                    throw new Exception("All topics passed to MergeTopics() must have the same class string and ID.");
                }

                if (topics[i].FileID != currentFileID)
                {
                    if (previousFileIDs.Contains(topics[i].FileID))
                    {
                        throw new Exception("MergeTopics() requires all topics that share a file ID be consecutive.");
                    }

                    previousFileIDs.Add(currentFileID);
                    currentFileID = topics[i].FileID;
                }
            }
                        #endif

            // If the first and last topic have the same file ID, that means the entire list does and we can return it as is.
            if (topics[0].FileID == topics[topics.Count - 1].FileID)
            {
                // We do still have to make sure the first topic isn't embedded though so that classes documented in lists will
                // appear correctly.
                if (topics[0].IsEmbedded)
                {
                    topics[0]            = topics[0].Duplicate();
                    topics[0].IsEmbedded = false;
                }

                return;
            }

            var files        = builder.EngineInstance.Files;
            var commentTypes = builder.EngineInstance.CommentTypes;


            // First we have to sort the topic list by file name.  This ensures that the merge occurs consistently no matter
            // what order the files in the list are in or how the file IDs were assigned.

            List <Topic> sortedTopics = new List <Topic>(topics.Count);

            do
            {
                var lowestFile      = files.FromID(topics[0].FileID);
                var lowestFileIndex = 0;
                var lastCheckedID   = lowestFile.ID;

                for (int i = 1; i < topics.Count; i++)
                {
                    if (topics[i].FileID != lastCheckedID)
                    {
                        var file = files.FromID(topics[i].FileID);

                        if (Path.Compare(file.FileName, lowestFile.FileName) < 0)
                        {
                            lowestFile      = file;
                            lowestFileIndex = i;
                        }

                        lastCheckedID = file.ID;
                    }
                }

                int count = 0;
                for (int i = lowestFileIndex; i < topics.Count && topics[i].FileID == lowestFile.ID; i++)
                {
                    count++;
                }

                sortedTopics.AddRange(topics.GetRange(lowestFileIndex, count));
                topics.RemoveRange(lowestFileIndex, count);
            }while (topics.Count > 0);


            // The topics are all in sortedTopics now, and "topics" is empty.  For clarity going forward, let's rename sortedTopics
            // to remainingTopics, since we have to move them back into topics now.

            List <Topic> remainingTopics = sortedTopics;
            sortedTopics = null;              // for safety


            // Find the best topic to serve as the class definition.

            Topic bestDefinition      = remainingTopics[0];
            int   bestDefinitionIndex = 0;

            for (int i = 1; i < remainingTopics.Count; i++)
            {
                Topic topic = remainingTopics[i];

                if (topic.DefinesClass &&
                    builder.EngineInstance.CodeDB.IsBetterClassDefinition(bestDefinition, topic))
                {
                    bestDefinition      = topic;
                    bestDefinitionIndex = i;
                }
            }


            // Copy the best definition in and everything that follows it in the file.  That will serve as the base for merging.

            int bestDefinitionTopicCount = 1;

            for (int i = bestDefinitionIndex + 1; i < remainingTopics.Count && remainingTopics[i].FileID == bestDefinition.FileID; i++)
            {
                bestDefinitionTopicCount++;
            }

            topics.AddRange(remainingTopics.GetRange(bestDefinitionIndex, bestDefinitionTopicCount));
            remainingTopics.RemoveRange(bestDefinitionIndex, bestDefinitionTopicCount);


            // Make sure the first topic isn't embedded so that classes documented in lists still appear correctly.

            if (topics[0].IsEmbedded)
            {
                topics[0]            = topics[0].Duplicate();
                topics[0].IsEmbedded = false;
            }


            // Delete all the other topics that define the class.  We don't need them anymore.

            for (int i = 0; i < remainingTopics.Count; /* don't auto increment */)
            {
                if (remainingTopics[i].DefinesClass)
                {
                    remainingTopics.RemoveAt(i);
                }
                else
                {
                    i++;
                }
            }


            // Merge any duplicate topics into the list.  This is used for things like header vs. source definitions in C++.

            // First we go through the primary topic list to handle removing list topics and merging individual topics into list
            // topics in the remaining topic list.  Everything else will be handled when iterating through the remaining topic list.

            int topicIndex = 0;
            while (topicIndex < topics.Count)
            {
                var topic = topics[topicIndex];

                // Ignore group topics
                if (topic.IsGroup)
                {
                    topicIndex++;
                    continue;
                }

                int embeddedTopicCount = CountEmbeddedTopics(topics, topicIndex);


                // We don't need to worry about enums until we do remaining topics.

                if (topic.IsEnum)
                {
                    topicIndex += 1 + embeddedTopicCount;
                }


                // If it's not an enum and it's a standalone topic see if it will merge with an embedded topic in the remaining topic
                // list.  We don't have to worry about merging with standalone topics until we do the remaining topic list.

                else if (embeddedTopicCount == 0)
                {
                    int duplicateIndex = FindDuplicateTopic(topic, remainingTopics, builder);

                    if (duplicateIndex == -1)
                    {
                        topicIndex++;
                    }
                    else if (remainingTopics[duplicateIndex].IsEmbedded &&
                             CodeDB.Manager.ScoreTopic(topic) < CodeDB.Manager.ScoreTopic(remainingTopics[duplicateIndex]))
                    {
                        topics.RemoveAt(topicIndex);
                    }
                    else
                    {
                        topicIndex++;
                    }
                }


                // If it's not an enum and we're at a list topic, only remove it if EVERY member has a better definition in the other
                // list.  We can't pluck them out individually.  If even one is documented here that isn't documented elsewhere we
                // keep the entire thing in even if that leads to some duplicates.

                else
                {
                    bool allHaveBetterMatches = true;

                    for (int i = 0; i < embeddedTopicCount; i++)
                    {
                        Topic embeddedTopic  = topics[topicIndex + 1 + i];
                        int   duplicateIndex = FindDuplicateTopic(embeddedTopic, remainingTopics, builder);

                        if (duplicateIndex == -1 ||
                            CodeDB.Manager.ScoreTopic(embeddedTopic) > CodeDB.Manager.ScoreTopic(remainingTopics[duplicateIndex]))
                        {
                            allHaveBetterMatches = false;
                            break;
                        }
                    }

                    if (allHaveBetterMatches)
                    {
                        topics.RemoveRange(topicIndex, 1 + embeddedTopicCount);
                    }
                    else
                    {
                        topicIndex += 1 + embeddedTopicCount;
                    }
                }
            }


            // Now do a more comprehensive merge of the remaining topics into the primary topic list.

            int remainingTopicIndex = 0;
            while (remainingTopicIndex < remainingTopics.Count)
            {
                var remainingTopic = remainingTopics[remainingTopicIndex];

                // Ignore group topics
                if (remainingTopic.IsGroup)
                {
                    remainingTopicIndex++;
                    continue;
                }

                int embeddedTopicCount = CountEmbeddedTopics(remainingTopics, remainingTopicIndex);


                // If we're merging enums, the one with the most embedded topics (documented values) wins.  In practice one
                // should be documented and one shouldn't be, so this will be any number versus zero.

                if (remainingTopic.IsEnum)
                {
                    int duplicateIndex = FindDuplicateTopic(remainingTopic, topics, builder);

                    if (duplicateIndex == -1)
                    {
                        remainingTopicIndex += 1 + embeddedTopicCount;
                    }
                    else
                    {
                        int duplicateEmbeddedTopicCount = CountEmbeddedTopics(topics, duplicateIndex);

                        if (embeddedTopicCount > duplicateEmbeddedTopicCount ||
                            (embeddedTopicCount == duplicateEmbeddedTopicCount &&
                             CodeDB.Manager.ScoreTopic(remainingTopic) > CodeDB.Manager.ScoreTopic(topics[duplicateIndex])))
                        {
                            topics.RemoveRange(duplicateIndex, 1 + duplicateEmbeddedTopicCount);
                            topics.InsertRange(duplicateIndex, remainingTopics.GetRange(remainingTopicIndex, 1 + embeddedTopicCount));
                        }

                        remainingTopics.RemoveRange(remainingTopicIndex, 1 + embeddedTopicCount);
                    }
                }


                // If it's not an enum and it's a standalone topic the one with the best score wins.

                else if (embeddedTopicCount == 0)
                {
                    int duplicateIndex = FindDuplicateTopic(remainingTopic, topics, builder);

                    if (duplicateIndex == -1)
                    {
                        remainingTopicIndex++;
                    }
                    else if (CodeDB.Manager.ScoreTopic(remainingTopic) > CodeDB.Manager.ScoreTopic(topics[duplicateIndex]))
                    {
                        if (topics[duplicateIndex].IsEmbedded)
                        {
                            // Just leave them both in
                            remainingTopicIndex++;
                        }
                        else
                        {
                            topics[duplicateIndex] = remainingTopic;
                            remainingTopics.RemoveAt(remainingTopicIndex);
                        }
                    }
                    else
                    {
                        remainingTopics.RemoveAt(remainingTopicIndex);
                    }
                }


                // If it's not an enum and we're at a list topic, only remove it if EVERY member has a better definition in the other
                // list.  We can't pluck them out individually.  If even one is documented here that isn't documented elsewhere we
                // keep the entire thing in even if that leads to some duplicates.

                else
                {
                    bool allHaveBetterMatches = true;

                    for (int i = 0; i < embeddedTopicCount; i++)
                    {
                        Topic embeddedTopic  = remainingTopics[remainingTopicIndex + 1 + i];
                        int   duplicateIndex = FindDuplicateTopic(embeddedTopic, topics, builder);

                        if (duplicateIndex == -1 ||
                            CodeDB.Manager.ScoreTopic(embeddedTopic) > CodeDB.Manager.ScoreTopic(topics[duplicateIndex]))
                        {
                            allHaveBetterMatches = false;
                            break;
                        }
                    }

                    if (allHaveBetterMatches)
                    {
                        remainingTopics.RemoveRange(remainingTopicIndex, 1 + embeddedTopicCount);
                    }
                    else
                    {
                        remainingTopicIndex += 1 + embeddedTopicCount;
                    }
                }
            }


            // Generate groups from the topic lists.

            // Start at 1 to skip the class topic.
            // Don't group by file ID because topics from other files may have been combined into the list.
            var groupedTopics = GetTopicGroups(topics, 1, false);

            var groupedRemainingTopics = GetTopicGroups(remainingTopics);


            // Delete any empty groups.  We do this on the main group list too for consistency.

            for (int i = 0; i < groupedTopics.Groups.Count; /* don't auto increment */)
            {
                if (groupedTopics.Groups[i].IsEmpty)
                {
                    groupedTopics.RemoveGroupAndTopics(i);
                }
                else
                {
                    i++;
                }
            }

            for (int i = 0; i < groupedRemainingTopics.Groups.Count; /* don't auto increment */)
            {
                if (groupedRemainingTopics.Groups[i].IsEmpty)
                {
                    groupedRemainingTopics.RemoveGroupAndTopics(i);
                }
                else
                {
                    i++;
                }
            }


            // Now merge groups.  If any remaining groups match the title of an existing group, move its members to
            // the end of the existing group.

            int remainingGroupIndex = 0;
            while (remainingGroupIndex < groupedRemainingTopics.Groups.Count)
            {
                var  remainingGroup = groupedRemainingTopics.Groups[remainingGroupIndex];
                bool merged         = false;

                if (remainingGroup.Title != null)
                {
                    for (int groupIndex = 0; groupIndex < groupedTopics.Groups.Count; groupIndex++)
                    {
                        if (groupedTopics.Groups[groupIndex].Title == remainingGroup.Title)
                        {
                            groupedRemainingTopics.MergeGroupInto(remainingGroupIndex, groupedTopics, groupIndex);
                            merged = true;
                            break;
                        }
                    }
                }

                if (merged == false)
                {
                    remainingGroupIndex++;
                }
            }


            // Move any groups with titles that didn't match to the other list.  We insert it after the last group
            // of the same dominant type so function groups stay with other function groups, variable groups stay
            // with other variable groups, etc.

            remainingGroupIndex = 0;
            while (remainingGroupIndex < groupedRemainingTopics.Groups.Count)
            {
                var remainingGroup = groupedRemainingTopics.Groups[remainingGroupIndex];

                if (remainingGroup.Title != null)
                {
                    int bestMatchIndex = -1;

                    // Walk the list backwards because we want it to be after the last group of the type, not the first.
                    for (int i = groupedTopics.Groups.Count - 1; i >= 0; i--)
                    {
                        if (groupedTopics.Groups[i].DominantTypeID == remainingGroup.DominantTypeID)
                        {
                            bestMatchIndex = i;
                            break;
                        }
                    }

                    if (bestMatchIndex == -1)
                    {
                        // Just add them to the end if nothing matches.
                        groupedRemainingTopics.MoveGroupTo(remainingGroupIndex, groupedTopics);
                    }
                    else
                    {
                        groupedRemainingTopics.MoveGroupTo(remainingGroupIndex, groupedTopics, bestMatchIndex + 1);
                    }
                }
                else
                {
                    remainingGroupIndex++;
                }
            }


            // Now we're left with topics that are not in groups.  See if the list contains any titled groups at all.

            bool groupsWithTitles = false;

            foreach (var group in groupedTopics.Groups)
            {
                if (group.Title != null)
                {
                    groupsWithTitles = true;
                    break;
                }
            }


            // If there's no titles we can just append the remaining topics as is.

            if (groupsWithTitles == false)
            {
                groupedTopics.Topics.AddRange(groupedRemainingTopics.Topics);
            }


            // If there are titled groups, see if we can add them to the end of existing groups.  However, only do
            // this if TitleMatchesType is set.  It's okay to put random functions into the group "Functions" but
            // not into something more specific.  If there aren't appropriate groups to do this with, create new ones.

            else
            {
                // We don't care about the remaining groups anymore so we can just work directly on the topics.
                remainingTopics        = groupedRemainingTopics.Topics;
                groupedRemainingTopics = null;                  // for safety

                while (remainingTopics.Count > 0)
                {
                    int type = remainingTopics[0].CommentTypeID;
                    int matchingGroupIndex = -1;

                    for (int i = groupedTopics.Groups.Count - 1; i >= 0; i--)
                    {
                        if (groupedTopics.Groups[i].DominantTypeID == type &&
                            groupedTopics.Groups[i].TitleMatchesType)
                        {
                            matchingGroupIndex = i;
                            break;
                        }
                    }

                    // Create a new group if there's no existing one we can use.
                    if (matchingGroupIndex == -1)
                    {
                        Topic generatedTopic = new Topic(builder.EngineInstance.CommentTypes);
                        generatedTopic.TopicID       = 0;
                        generatedTopic.Title         = builder.EngineInstance.CommentTypes.FromID(type).PluralDisplayName;
                        generatedTopic.Symbol        = SymbolString.FromPlainText_NoParameters(generatedTopic.Title);
                        generatedTopic.ClassString   = topics[0].ClassString;
                        generatedTopic.ClassID       = topics[0].ClassID;
                        generatedTopic.CommentTypeID = builder.EngineInstance.CommentTypes.IDFromKeyword("group");
                        generatedTopic.FileID        = topics[0].FileID;
                        generatedTopic.LanguageID    = topics[0].LanguageID;

                        // In case there's nothing that defines the "group" keyword.
                        if (generatedTopic.CommentTypeID != 0)
                        {
                            groupedTopics.Topics.Add(generatedTopic);
                            groupedTopics.CreateGroup(groupedTopics.Topics.Count - 1, 1);
                        }

                        matchingGroupIndex = groupedTopics.Groups.Count - 1;
                    }

                    for (int i = 0; i < remainingTopics.Count; /* don't auto increment */)
                    {
                        var remainingTopic = remainingTopics[i];

                        // Need to check IsEmbedded because enums values will not have the same type as their parent.
                        if (remainingTopic.CommentTypeID == type || remainingTopic.IsEmbedded)
                        {
                            groupedTopics.AppendToGroup(matchingGroupIndex, remainingTopic);
                            remainingTopics.RemoveAt(i);
                        }
                        else
                        {
                            i++;
                        }
                    }
                }
            }
        }
        public override Vector3[] GetPointsArray(Vector3 originPos, Vector3 targetPos, AC.Char _char = null)
        {
            List <Vector3> pointsList = new List <Vector3>();

            if (KickStarter.sceneSettings && KickStarter.sceneSettings.navMesh && KickStarter.sceneSettings.navMesh.GetComponent <Collider>())
            {
                Vector3 originalOriginPos = originPos;
                Vector3 originalTargetPos = targetPos;
                originPos = GetNearestToMesh(originPos);
                targetPos = GetNearestToMesh(targetPos);

                pointsList.Add(originPos);

                if (!IsLineClear(targetPos, originPos, false))
                {
                    pointsList = FindComplexPath(originPos, targetPos, false);

                    if (pathFailed)
                    {
                        Vector3 newTargetPos = GetLineBreak(pointsList [pointsList.Count - 1], targetPos);

                        if (newTargetPos != Vector3.zero)
                        {
                            targetPos = newTargetPos;

                            if (!IsLineClear(targetPos, originPos, true))
                            {
                                pointsList = FindComplexPath(originPos, targetPos, true);

                                if (pathFailed)
                                {
                                    // Couldn't find an alternative, so just clear the path
                                    pointsList.Clear();
                                    pointsList.Add(originPos);
                                }
                            }
                            else
                            {
                                // Line between origin and new target is clear
                                pointsList.Clear();
                                pointsList.Add(originPos);
                            }
                        }
                    }
                }

                // Finally, remove any extraneous points
                if (pointsList.Count > 2)
                {
                    for (int i = 0; i < pointsList.Count; i++)
                    {
                        for (int j = i; j < pointsList.Count; j++)
                        {
                            if (IsLineClear(pointsList[i], pointsList[j], false) && j > i + 1)
                            {
                                // Point i+1 is irrelevant, remove and reset
                                pointsList.RemoveRange(i + 1, j - i - 1);
                                j = 0;
                                i = 0;
                            }
                        }
                    }
                }
                pointsList.Add(targetPos);

                if (pointsList[0] == originalOriginPos)
                {
                    pointsList.RemoveAt(0);                             // Remove origin point from start
                }
                // Special case: where player is stuck on a Collider above the mesh
                if (pointsList.Count == 1 && pointsList[0] == originPos)
                {
                    pointsList[0] = originalTargetPos;
                }
            }
            else
            {
                // Special case: no Collider, no path
                pointsList.Add(targetPos);
            }

            return(pointsList.ToArray());
        }
Example #34
0
 public void Clear()
 {
     _commands.RemoveRange(0, _commandIndex + 1);
     _commandIndex = -1;
 }
Example #35
0
    void showOff()
    {
        Vector3[] newVertices  = this.mesh.vertices;
        int[]     newTriangles = this.mesh.triangles;     // 128 * 3 = 384


        List <int> squares = new List <int>();       // A list of the corners of the newest squares
        // Each element is an index from verticesHelper

        // Initialize corrner values
        int tempIndex = this.verticesHelper[0, 0];

        newVertices[tempIndex].z = 1;
        squares.Add(tempIndex);

        tempIndex = this.verticesHelper[8, 0];
        newVertices[tempIndex].z = 1;
        squares.Add(tempIndex);

        tempIndex = this.verticesHelper[8, 8];
        newVertices[tempIndex].z = 1;
        squares.Add(tempIndex);

        tempIndex = this.verticesHelper[0, 8];
        newVertices[tempIndex].z = 1;
        squares.Add(tempIndex);

        for (int i = 0; i < this.timesUpdated; i++)
        {
            if ((i % 2) == 0)
            {
                print("domond step");
                // dimond step => find center
                print(squares.Count / 4);
                for (int j = 0; j < (squares.Count / 4); j++)
                {
                    print("j :" + j + "    squares.Count/4:" + (squares.Count / 4));

                    int tlIndex = squares[(j * 4) + 0];                     // an index to be looked up in newVertices
                    int trIndex = squares[(j * 4) + 1];
                    int brIndex = squares[(j * 4) + 2];
                    int blIndex = squares[(j * 4) + 3];

                    Vector3 tlVert = newVertices[tlIndex];
                    Vector3 trVert = newVertices[trIndex];
                    Vector3 brVert = newVertices[brIndex];
                    Vector3 blVert = newVertices[blIndex];

                    int centerVertX = ((int)(tlVert.x + brVert.x)) / 2;
                    int centerVertY = ((int)(tlVert.y + brVert.y)) / 2;
                    print("centerVertX: " + centerVertX + "   centerVertY: " + centerVertY);

                    int centerIndex = this.verticesHelper[centerVertX, centerVertY];
                    newVertices[centerIndex].z = 1;
                }
            }
            else
            {
                // square step => find edges
                int j     = 0;
                int count = squares.Count / 4;
                for (; j < count; j++)
                {
                    print(j);
                    int tlIndex = squares[(j * 4) + 0];                     // an index to be looked up in newVertices
                    int trIndex = squares[(j * 4) + 1];
                    int brIndex = squares[(j * 4) + 2];
                    int blIndex = squares[(j * 4) + 3];

                    Vector3 tlVert = newVertices[tlIndex];
                    Vector3 trVert = newVertices[trIndex];
                    Vector3 brVert = newVertices[brIndex];
                    Vector3 blVert = newVertices[blIndex];

                    int centerVertX = ((int)(tlVert.x + brVert.x)) / 2;
                    int centerVertY = ((int)(tlVert.y + brVert.y)) / 2;

                    // Find top center index
                    int topCenterIndex = this.verticesHelper[centerVertX, (int)tlVert.y];
                    newVertices[topCenterIndex].z = 1;

                    int rightCenterIndex = this.verticesHelper[(int)trVert.x, centerVertY];
                    newVertices[rightCenterIndex].z = 1;

                    int botCenterIndex = this.verticesHelper[centerVertX, (int)blVert.y];
                    newVertices[botCenterIndex].z = 1;

                    int leftCenterIndex = this.verticesHelper[(int)tlVert.x, centerVertY];
                    newVertices[leftCenterIndex].z = 1;

                    // Might as well set the center on too for good measure
                    int centerIndex = this.verticesHelper[centerVertX, centerVertY];
                    newVertices[centerIndex].z = 1;

                    squares.Add(tlIndex);
                    squares.Add(topCenterIndex);
                    squares.Add(centerIndex);
                    squares.Add(leftCenterIndex);

                    squares.Add(topCenterIndex);
                    squares.Add(trIndex);
                    squares.Add(rightCenterIndex);
                    squares.Add(centerIndex);

                    squares.Add(centerIndex);
                    squares.Add(rightCenterIndex);
                    squares.Add(brIndex);
                    squares.Add(botCenterIndex);

                    squares.Add(leftCenterIndex);
                    squares.Add(centerIndex);
                    squares.Add(botCenterIndex);
                    squares.Add(blIndex);
                }

                squares.RemoveRange(0, (j * 4));
            }
        }



        this.mesh.vertices = newVertices;
    }
Example #36
0
    void generateTerrain()
    {
        Vector3[] newVertices  = this.mesh.vertices;
        int[]     newTriangles = this.mesh.triangles;     // 128 * 3 = 384


        List <int> squares = new List <int>();       // A list of the corners of the newest squares
        // Each element is an index from verticesHelper

        // Initialize corrner values
        int tempIndex = this.verticesHelper[0, 0];

        newVertices[tempIndex].z = Random.Range(0.0f, 1.0f);
        squares.Add(tempIndex);

        tempIndex = this.verticesHelper[8, 0];
        newVertices[tempIndex].z = Random.Range(0.0f, 1.0f);
        squares.Add(tempIndex);

        tempIndex = this.verticesHelper[8, 8];
        newVertices[tempIndex].z = Random.Range(0.0f, 1.0f);
        squares.Add(tempIndex);

        tempIndex = this.verticesHelper[0, 8];
        newVertices[tempIndex].z = Random.Range(0.0f, 1.0f);
        squares.Add(tempIndex);

        for (int i = 0; i < 8; i++)
        {
            // dimond step => find center
            print(squares.Count / 4);
            for (int jj = 0; jj < (squares.Count / 4); jj++)
            {
                int tlIndex = squares[(jj * 4) + 0];                 // an index to be looked up in newVertices
                int trIndex = squares[(jj * 4) + 1];
                int brIndex = squares[(jj * 4) + 2];
                int blIndex = squares[(jj * 4) + 3];

                Vector3 tlVert = newVertices[tlIndex];
                Vector3 trVert = newVertices[trIndex];
                Vector3 brVert = newVertices[brIndex];
                Vector3 blVert = newVertices[blIndex];

                int centerVertX = ((int)(tlVert.x + brVert.x)) / 2;
                int centerVertY = ((int)(tlVert.y + brVert.y)) / 2;

                float average = (tlVert.z + trVert.z + brVert.z + blVert.z) / 4;
                float bump    = Random.Range(-1.0f, 1.0f) / ((i * 3) + 1);

                int centerIndex = this.verticesHelper[centerVertX, centerVertY];
                newVertices[centerIndex].z = average + bump;
            }

            // square step => find edges
            int j     = 0;
            int count = squares.Count / 4;
            for (; j < count; j++)
            {
                int tlIndex = squares[(j * 4) + 0];                 // an index to be looked up in newVertices
                int trIndex = squares[(j * 4) + 1];
                int brIndex = squares[(j * 4) + 2];
                int blIndex = squares[(j * 4) + 3];

                Vector3 tlVert = newVertices[tlIndex];
                Vector3 trVert = newVertices[trIndex];
                Vector3 brVert = newVertices[brIndex];
                Vector3 blVert = newVertices[blIndex];

                int     centerVertX = ((int)(tlVert.x + brVert.x)) / 2;
                int     centerVertY = ((int)(tlVert.y + brVert.y)) / 2;
                Vector3 cVert       = newVertices[this.verticesHelper[centerVertX, centerVertY]];

                float average;
                float bump;

                // Find top center index
                int topCenterIndex = this.verticesHelper[centerVertX, (int)tlVert.y];
                average = (tlVert.z + cVert.z + trVert.z) / 3;
                bump    = Random.Range(-1.0f, 1.0f) / ((i * 3) + 2);
                newVertices[topCenterIndex].z = average + bump;

                int rightCenterIndex = this.verticesHelper[(int)trVert.x, centerVertY];
                average = (trVert.z + cVert.z + brVert.z) / 3;
                bump    = Random.Range(-1.0f, 1.0f) / ((i * 3) + 2);
                newVertices[rightCenterIndex].z = average + bump;

                int botCenterIndex = this.verticesHelper[centerVertX, (int)blVert.y];
                average = (blVert.z + cVert.z + brVert.z) / 3;
                bump    = Random.Range(-1.0f, 1.0f) / ((i * 3) + 2);
                newVertices[botCenterIndex].z = average + bump;

                int leftCenterIndex = this.verticesHelper[(int)tlVert.x, centerVertY];
                average = (tlVert.z + blVert.z + cVert.z) / 3;
                bump    = Random.Range(-1.0f, 1.0f) / ((i * 3) + 2);
                newVertices[leftCenterIndex].z = average + bump;

                // Might as well set the center on too for good measure
                int centerIndex = this.verticesHelper[centerVertX, centerVertY];
                //newVertices[centerIndex].z = 1;

                squares.Add(tlIndex);
                squares.Add(topCenterIndex);
                squares.Add(centerIndex);
                squares.Add(leftCenterIndex);

                squares.Add(topCenterIndex);
                squares.Add(trIndex);
                squares.Add(rightCenterIndex);
                squares.Add(centerIndex);

                squares.Add(centerIndex);
                squares.Add(rightCenterIndex);
                squares.Add(brIndex);
                squares.Add(botCenterIndex);

                squares.Add(leftCenterIndex);
                squares.Add(centerIndex);
                squares.Add(botCenterIndex);
                squares.Add(blIndex);
            }

            squares.RemoveRange(0, (j * 4));



            this.mesh.vertices = newVertices;
        }
    }
Example #37
0
        private void _Rebuild()
        {
            log.Debug("Rebuilding alertList: Starting background thread");
            Program.AssertOffEventThread();
            lock (GridViewAlerts)
            {
                if (inAlertBuild)
                {
                    // queue up a rebuild after the current one has completed
                    log.Debug("Rebuilding alertList: In build already, exiting");
                    retryAlertBuild = true;
                    return;
                }
                inAlertBuild = true;
                log.Debug("Rebuilding alertList: taking inAlertBuild lock");
            }
            try
            {
                // 1) Add all the alerts that have not been filtered out to an array
                // 2) Create rows for each of these
                // 3) Sort them
                // 4) Take the top n as set by the filters
                // 5) Add them to the control using the optimized AddRange()

                Program.Invoke(Program.MainWindow, SetFilterLabel);

                List <Alert> alerts = Alert.NonDismissingAlerts;
                alerts.RemoveAll(FilterAlert);

                log.DebugFormat("Rebuilding alertList: there are {0} alerts in total. After filtering we have {1}",
                                Alert.AlertCount,
                                alerts.Count);

                if (GridViewAlerts.SortedColumn != null)
                {
                    if (GridViewAlerts.SortedColumn.Index == ColumnMessage.Index)
                    {
                        alerts.Sort(Alert.CompareOnTitle);
                    }
                    else if (GridViewAlerts.SortedColumn.Index == ColumnDate.Index)
                    {
                        alerts.Sort(Alert.CompareOnDate);
                    }
                    else if (GridViewAlerts.SortedColumn.Index == ColumnLocation.Index)
                    {
                        alerts.Sort(Alert.CompareOnAppliesTo);
                    }
                    else if (GridViewAlerts.SortedColumn.Index == ColumnSeverity.Index)
                    {
                        alerts.Sort(Alert.CompareOnPriority);
                    }
                    if (GridViewAlerts.SortOrder == SortOrder.Descending)
                    {
                        alerts.Reverse();
                    }
                }
                int alertsFound = alerts.Count;

                if (ALERT_CAP < alerts.Count)
                {
                    log.DebugFormat("Rebuilding alertList: hit alert cap, hiding {0} alerts", alerts.Count - ALERT_CAP);
                    alerts.RemoveRange(ALERT_CAP, alerts.Count - ALERT_CAP);
                }

                Program.Invoke(Program.MainWindow, delegate
                {
                    List <DataGridViewRow> gridRows = new List <DataGridViewRow>();
                    log.Debug("Rebuilding alertList: Adding alert rows");
                    foreach (Alert alert in alerts)
                    {
                        gridRows.Add(NewAlertRow(alert));
                    }
                    log.DebugFormat("Rebuilding alertList: Added {0} rows", gridRows.Count);

                    List <string> selection = (GridViewAlerts.SelectedRows.Cast <DataGridViewRow>().Select(
                                                   selectedRow => ((Alert)selectedRow.Tag).uuid)).ToList();

                    GridViewAlerts.Rows.Clear();
                    log.Debug("Rebuilding alertList: Cleared rows");
                    GridViewAlerts.Rows.AddRange(gridRows.ToArray());
                    log.DebugFormat("Rebuilding alertList: Added {0} rows to the grid", GridViewAlerts.Rows.Count);
                    tableLayoutPanel3.Visible = alertsFound > ALERT_CAP;

                    //restore selection
                    if (selection.Count > 0)
                    {
                        log.Debug("Rebuilding alertList: Restoring alert selection");
                        foreach (DataGridViewRow alertRow in GridViewAlerts.Rows)
                        {
                            alertRow.Selected = selection.Contains(((Alert)alertRow.Tag).uuid);
                        }
                        if (GridViewAlerts.SelectedRows.Count == 0 && GridViewAlerts.Rows.Count > 0)
                        {
                            GridViewAlerts.Rows[0].Selected = true;
                        }
                        log.DebugFormat("Rebuilding alertList: Selected {0} alerts", selection.Count);
                    }

                    UpdateActionEnablement();
                });
            }
            catch (Exception e)
            {
                log.ErrorFormat("Encountered exception when building list: {0}", e);
            }
            finally
            {
                log.Debug("Rebuilding alertList: Waiting for lock to clear inAlertBuild");
                lock (GridViewAlerts)
                {
                    inAlertBuild = false;
                    log.Debug("Rebuilding alertList: cleared inAlertBuild");
                    if (retryAlertBuild)
                    {
                        // we received a request to build while we were building, rebuild in case we missed something
                        retryAlertBuild = false;
                        log.Debug("Rebuilding alertList: we received a request to build while we were building, rebuild in case we missed something");
                        _Rebuild();
                    }
                }
            }
        }
Example #38
0
        public MarkdownReader(string originText)
        {
            StringReader reader = new StringReader(originText);
            string       line;
            List <char>  list = new List <char>();

            while ((line = reader.ReadLine()) != null)
            {
                if (line.StartsWith("# "))
                {
                    AddText(GetText(list));
                    // 一级标题
                    AddTitle(line.Substring(2), 26, FontWeights.Normal);
                    AddLine();
                    AddText("\n");
                }
                else if (line.StartsWith("## "))
                {
                    AddText(GetText(list));
                    // 二级标题
                    AddTitle(line.Substring(3), 22, FontWeights.Normal);
                }
                else if (line.StartsWith("### "))
                {
                    AddText(GetText(list));
                    // 三级标题
                    AddTitle(line.Substring(4), 18, FontWeights.Normal);
                }
                else if (line.StartsWith("#### "))
                {
                    AddText(GetText(list));
                    // 四级标题
                    AddTitle(line.Substring(5), 15, FontWeights.Bold);
                }
                else if (line.StartsWith("##### "))
                {
                    AddText(GetText(list));
                    // 五级标题
                    AddTitle(line.Substring(6), 13, FontWeights.Bold);
                }
                else if (line.StartsWith("###### "))
                {
                    AddText(GetText(list));
                    // 六级标题
                    AddTitle(line.Substring(7), 11, FontWeights.Bold);
                }
                else if ((line.Contains("---") && line.Replace("-", "").Length == 0) || (line.Contains("***") && line.Replace("*", "").Length == 0))
                {
                    AddText(GetText(list));
                    // 横线
                    AddLine();
                    AddText("\n");
                }
                else if (line.StartsWith("```"))
                {
                    AddText(GetText(list));
                    // 代码块(伪,无语法高亮,且只能单独复制)
                    string temp = string.Empty;
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (line.Contains("```") && line.Replace("`", "").Length == 0)
                        {
                            break;
                        }
                        temp += line + "\n";
                    }
                    TextBox textBox = new TextBox
                    {
                        Text            = temp.Remove(temp.Length - 1),
                        Background      = new SolidColorBrush(Colors.Gainsboro),
                        BorderThickness = new Thickness(0),
                        Padding         = new Thickness(15),
                        IsReadOnly      = true,
                        TextWrapping    = TextWrapping.Wrap,
                    };
                    paragraph.Inlines.Add(textBox);
                    AddText("\n");
                }
                else
                {
                    line += "\n";
                    string   content = string.Empty;
                    TextType type    = TextType.Unknown;
                    for (int i = 0; i < line.Length; i++)
                    {
                        if (line[i] == '[' || line[i] == '!' || line[i] == '(' || line[i] == '`' || line[i] == '*' || line[i] == '~' || line[i] == '=')
                        {
                            if (i < line.Length - 1)
                            {
                                if (line[i] == '!' && line[i + 1] == '[')
                                {
                                    continue;
                                }
                            }
                            if (list.Count > 0 && type == TextType.Unknown)
                            {
                                AddText(GetText(list));
                            }
                            if (type == TextType.Unknown)
                            {
                                switch (line[i])
                                {
                                case '[':
                                    type = TextType.HyperLinkText;
                                    if (i > 0)
                                    {
                                        if (line[i - 1] == '!')
                                        {
                                            list.Insert(0, line[i - 1]);
                                        }
                                    }
                                    break;

                                case '(':
                                    if (content != string.Empty)
                                    {
                                        type = TextType.HyperLink;
                                    }
                                    break;

                                case '`':
                                    type = TextType.Code;
                                    break;

                                case '*':
                                    if (type == TextType.Unknown)
                                    {
                                        type = TextType.Oblique;
                                        while (line[++i] == '*')
                                        {
                                            list.Add(line[i]);
                                            type++;
                                        }
                                    }
                                    break;

                                case '~':
                                    type = TextType.Strikethrough;
                                    break;

                                case '=':
                                    type = TextType.Highlight;
                                    break;
                                }
                                list.Add(line[i]);
                                continue;
                            }
                        }
                        list.Add(line[i]);
                        if (type != TextType.Unknown)
                        {
                            if (line[i] == ']' && type == TextType.HyperLinkText)
                            {
                                string temp = GetText(list);
                                if (i < line.Length - 1)
                                {
                                    if (line[i + 1] == '(')
                                    {
                                        content = temp;
                                        type    = TextType.Unknown;
                                        continue;
                                    }
                                }
                                content = string.Empty;
                                AddText(temp);
                                type = TextType.Unknown;
                            }
                            else if (line[i] == ')' && type == TextType.HyperLink)
                            {
                                List <char> head = list.FindAll(delegate(char s) {
                                    return(s == '(');
                                });
                                List <char> tail = list.FindAll(delegate(char s) {
                                    return(s == ')');
                                });
                                if (head.Count != tail.Count)
                                {
                                    continue;
                                }
                                if (content.Length > 0)
                                {
                                    list.RemoveAt(0);
                                    list.RemoveAt(list.Count - 1);
                                    string temp = GetText(list);
                                    if (content[0] == '!')
                                    {
                                        AddImage(content.Remove(content.Length - 1).Remove(0, 2), temp);
                                    }
                                    else
                                    {
                                        AddLink(content.Remove(content.Length - 1).Remove(0, 1), temp);
                                    }
                                }
                                else
                                {
                                    AddText(GetText(list));
                                }
                                type = TextType.Unknown;
                            }
                            else if (line[i] == '`' && type == TextType.Code)
                            {
                                list.RemoveAt(0);
                                string temp = GetText(list);
                                AddText(temp.Remove(temp.Length - 1), Colors.Red);
                                type = TextType.Unknown;
                            }
                            else if (line[i] == '~' && type == TextType.Strikethrough && list.Count > 2)
                            {
                                list.RemoveAt(0);
                                if (list[0] == '~')
                                {
                                    continue;
                                }
                                list.RemoveRange(list.Count - 2, 2);
                                string temp = GetText(list);
                                AddText(temp, type);
                                type = TextType.Unknown;
                            }
                            else if (line[i] == '*')
                            {
                                if (list[0] == '*')
                                {
                                    list.RemoveAt(0);
                                    continue;
                                }
                                string temp = GetText(list);
                                AddText(temp.Remove(temp.IndexOf('*')), type);
                                type = TextType.Unknown;
                            }
                            else if (line[i] == '=' && type == TextType.Highlight)
                            {
                                if (list[0] == '=')
                                {
                                    list.RemoveAt(0);
                                    continue;
                                }
                                string temp = GetText(list);
                                AddTextWithBackground(temp.Remove(temp.IndexOf('=')), Colors.Yellow);
                                type = TextType.Unknown;
                            }
                        }
                    }
                }
            }
            AddText(GetText(list));
            reader.Close();
        }
Example #39
0
    static void Main()
    {
        List <int> numbers = Console.ReadLine().Split().Select(int.Parse).ToList();

        string command;

        while ((command = Console.ReadLine()) != "end")
        {
            string[] commands = command.Split(' ');

            if (commands[0] == "exchange")
            {
                int index = int.Parse(commands[1]);

                if (index < 1 || index > numbers.Count)
                {
                    Console.WriteLine("Invalid index");
                }

                var elementsToMove = numbers
                                     .Skip(index + 1)
                                     .ToArray();

                numbers.InsertRange(0, elementsToMove);
                numbers.RemoveRange(numbers.Count - elementsToMove.Length, elementsToMove.Length);
            }
            else if (commands[0] == "max")
            {
                if (commands[1] == "odd")
                {
                    int number = numbers.Where((k, v) => k % 2 != 0).OrderByDescending(x => x).First();

                    try
                    {
                        Console.WriteLine(numbers.LastIndexOf(number));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("No matches");
                    }
                }
                else if (commands[1] == "even")
                {
                    int number = numbers.Where((k, v) => k % 2 == 0).OrderByDescending(x => x).First();

                    try
                    {
                        Console.WriteLine(numbers.LastIndexOf(number));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("No matches");
                    }
                }
            }
            else if (commands[0] == "min")
            {
                if (commands[1] == "odd")
                {
                    int number = numbers.Where((k, v) => k % 2 != 0).OrderBy(x => x).First();

                    try
                    {
                        Console.WriteLine(numbers.LastIndexOf(number));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("No matches");
                    }
                }
                else if (commands[1] == "even")
                {
                    try
                    {
                        int number = numbers.Where((k, v) => k % 2 == 0).OrderBy(x => x).First();
                        Console.WriteLine(numbers.LastIndexOf(number));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("No matches");
                    }
                }
            }
            else if (commands[0] == "first")
            {
                int elementsCount = int.Parse(commands[1]);

                if (elementsCount < 1 || elementsCount > numbers.Count)
                {
                    Console.WriteLine("Invalid count");
                    continue;
                }

                if (commands[2] == "odd")
                {
                    var found = numbers.Where((k, v) => k % 2 != 0).Take(elementsCount);
                    Console.WriteLine("[{0}]", string.Join(", ", found));
                }
                else if (commands[2] == "even")
                {
                    var found = numbers.Where((k, v) => k % 2 == 0).Take(elementsCount);
                    Console.WriteLine("[{0}]", string.Join(", ", found));
                }
            }
            else if (commands[0] == "last")
            {
                int elementsCount = int.Parse(commands[1]);

                if (elementsCount < 1 || elementsCount > numbers.Count)
                {
                    Console.WriteLine("Invalid count");
                    continue;
                }

                if (commands[2] == "odd")
                {
                    var found = numbers.Where((k, v) => k % 2 != 0).TakeLast(elementsCount);
                    Console.WriteLine("[{0}]", string.Join(", ", found));
                }
                else if (commands[2] == "even")
                {
                    var found = numbers.Where((k, v) => k % 2 == 0).TakeLast(elementsCount);
                    Console.WriteLine("[{0}]", string.Join(", ", found));
                }
            }
        }

        Console.WriteLine("[{0}]", string.Join(", ", numbers));
    }
Example #40
0
 public void Initialize()
 {
     FTextStyles.RemoveRange(1, FTextStyles.Count - 1);
     FParaStyles.RemoveRange(1, FParaStyles.Count - 1);
 }
        public static void FixDataContextVB(string path, string model, string nameSpace, string sdfFileName, IRepository repository)
        {
            string debugWriter = @"
#Region ""DebugWriter""
Public Class DebugWriter
    Inherits TextWriter
    Private Const DefaultBufferSize As Integer = 256
    Private _buffer As System.Text.StringBuilder

    Public Sub New()
        BufferSize = 256
        _buffer = New System.Text.StringBuilder(BufferSize)
    End Sub

    Public Property BufferSize() As Integer
        Get
            Return m_BufferSize
        End Get
        Private Set(value As Integer)
            m_BufferSize = value
        End Set
    End Property
    Private m_BufferSize As Integer

    Public Overrides ReadOnly Property Encoding() As System.Text.Encoding
        Get
            Return System.Text.Encoding.UTF8
        End Get
    End Property

#Region ""StreamWriter Overrides""
    Public Overrides Sub Write(value As Char)
        _buffer.Append(value)
        If _buffer.Length >= BufferSize Then
            Flush()
        End If
    End Sub

    Public Overrides Sub WriteLine(value As String)
        Flush()

        Using reader = New StringReader(value)
            Dim line As String
            ' Read and display lines from the file until the end of
            ' the file is reached.
            Do
                line = reader.ReadLine()
                If Not (line Is Nothing) Then
                    System.Diagnostics.Debug.WriteLine(line)
                End If
            Loop Until line Is Nothing
        End Using
    End Sub

    Protected Overrides Sub Dispose(disposing As Boolean)
        If disposing Then
            Flush()
        End If
    End Sub

    Public Overrides Sub Flush()
        If _buffer.Length > 0 Then
            System.Diagnostics.Debug.WriteLine(_buffer)
            _buffer.Clear()
        End If
    End Sub
    Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
        target = value
        Return value
    End Function
#End Region
End Class
#End Region
";

            string createIfNotExists = @"
    Public Function CreateIfNotExists() As Boolean
        Dim created As Boolean = False
        Using db = New {0}({0}.ConnectionString)
            If Not db.DatabaseExists() Then
                Dim names As String() = Me.[GetType]().Assembly.GetManifestResourceNames()
                Dim name As String = names.Where(Function(n) n.EndsWith(FileName)).FirstOrDefault()
                If name IsNot Nothing Then
                    Using resourceStream As Stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name)
                        If resourceStream IsNot Nothing Then
                            Using myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
                                Using fileStream As New IsolatedStorageFileStream(FileName, FileMode.Create, myIsolatedStorage)
                                    Using writer As New BinaryWriter(fileStream)
                                        Dim length As Long = resourceStream.Length
                                        Dim buffer As Byte() = New Byte(32) {}
                                        Dim readCount As Integer = 0
                                        Using reader As New BinaryReader(resourceStream)
                                            ' read file in chunks in order to reduce memory consumption and increase performance
                                            While readCount < length
                                                Dim actual As Integer = reader.Read(buffer, 0, buffer.Length)
                                                readCount += actual
                                                writer.Write(buffer, 0, actual)
                                            End While
                                        End Using
                                    End Using
                                End Using
                            End Using
                            created = True
                        Else
                            db.CreateDatabase()
                            created = True
                        End If
                    End Using
                Else
                    db.CreateDatabase()
                    created = True
                End If
            End If
        End Using
        Return created
    End Function

	Public WriteOnly Property LogDebug() As Boolean
        Set(value As Boolean)
            If value Then
                Me.Log = New DebugWriter()
            End If
        End Set
    End Property
";

            List <string> dcLines = System.IO.File.ReadAllLines(path).ToList();
            var           n       = string.Empty;

            if (!string.IsNullOrEmpty(nameSpace))
            {
                n += "\t";
            }
            var t = "\t";

            int i = dcLines.IndexOf("Imports System.Reflection");

            if (i > -1)
            {
                dcLines.Insert(i++, "Imports Microsoft.Phone.Data.Linq");
                dcLines.Insert(i++, "Imports Microsoft.Phone.Data.Linq.Mapping");
                dcLines.Insert(i++, "Imports System.IO.IsolatedStorage");
                dcLines.Insert(i++, "Imports System.IO");
            }

            i = dcLines.IndexOf(n + "Partial Public Class " + model);
            if (i > -1)
            {
                dcLines.Insert(i - 2, debugWriter);
                dcLines.Insert(i - 2, "");
            }

            i = dcLines.IndexOf(n + t + "Public Sub New(ByVal connection As String)");
            if (i > -1)
            {
                dcLines.RemoveRange(i, 4);
            }

            i = dcLines.IndexOf(n + t + "Public Sub New(ByVal connection As System.Data.IDbConnection)");
            if (i > -1)
            {
                dcLines.RemoveRange(i, 4);
            }

            i = dcLines.IndexOf(n + t + "Public Sub New(ByVal connection As String, ByVal mappingSource As System.Data.Linq.Mapping.MappingSource)");
            if (i > -1)
            {
                dcLines.RemoveRange(i, 4);
            }

            i = dcLines.IndexOf(n + t + "Public Sub New(ByVal connection As System.Data.IDbConnection, ByVal mappingSource As System.Data.Linq.Mapping.MappingSource)");
            if (i > -1)
            {
                dcLines.RemoveRange(i, 4);
            }

            i = dcLines.IndexOf(n + "Partial Public Class " + model);
            if (i > -1)
            {
                dcLines.RemoveAt(i - 1);
                dcLines.RemoveAt(i - 2);
                i++;
                i++;
                i++;

                dcLines.Insert(i++, n + t + "Public Shared ConnectionString As String = \"Data Source=isostore:/" + sdfFileName + ";\"");
                dcLines.Insert(i++, "");
                dcLines.Insert(i++, n + t + "Public Shared ConnectionStringReadOnly As String = \"Data Source=appdata:/" + sdfFileName + ";File Mode=Read Only;\"");
                dcLines.Insert(i++, "");
                dcLines.Insert(i++, n + t + "Public Shared FileName As String = \"" + sdfFileName + "\"");
                dcLines.Insert(i++, "");
                dcLines.Insert(i++, n + t + "Public Sub New(ByVal connection As String)");
                dcLines.Insert(i++, n + t + t + "MyBase.New(connection)");
                dcLines.Insert(i++, n + t + t + "OnCreated()");
                dcLines.Insert(i++, n + t + "End Sub");
            }

            i = dcLines.IndexOf(n + t + "Private Shared mappingSource As System.Data.Linq.Mapping.MappingSource = New AttributeMappingSource()");
            if (i > -1)
            {
                dcLines.RemoveAt(i);
                createIfNotExists = createIfNotExists.Replace("{0}", model);
                dcLines.Insert(i++, n + t + createIfNotExists);
            }

            AddIndexes(repository, dcLines, n, false);
            FixSerialisation(dcLines, n + t, false);

            System.IO.File.WriteAllLines(path, dcLines.ToArray());
        }
Example #42
0
        public override void Start2()
        {
            List <Vector2> deck = ShuffleDeck();

            cards_field[0] = new List <Vector2>(); cards_field[0].AddRange(deck.GetRange(0, 1)); deck.RemoveRange(0, 1);
            cards_field[1] = new List <Vector2>(); cards_field[1].AddRange(deck.GetRange(0, 2)); deck.RemoveRange(0, 2);
            cards_field[2] = new List <Vector2>(); cards_field[2].AddRange(deck.GetRange(0, 3)); deck.RemoveRange(0, 3);
            cards_field[3] = new List <Vector2>(); cards_field[3].AddRange(deck.GetRange(0, 4)); deck.RemoveRange(0, 4);
            cards_field[4] = new List <Vector2>(); cards_field[4].AddRange(deck.GetRange(0, 5)); deck.RemoveRange(0, 5);
            cards_field[5] = new List <Vector2>(); cards_field[5].AddRange(deck.GetRange(0, 6)); deck.RemoveRange(0, 6);
            cards_field[6] = new List <Vector2>(); cards_field[6].AddRange(deck.GetRange(0, 7)); deck.RemoveRange(0, 7);

            cards_reserve.Clear();
            cards_reserve.AddRange(deck);
            cards_stack.Clear();


            cards_finish[0] = new List <Vector2>();
            cards_finish[1] = new List <Vector2>();
            cards_finish[2] = new List <Vector2>();
            cards_finish[3] = new List <Vector2>();

            selector_card = new Vector2(-1, -1);
            selector_pos  = new Vector2(1, 1);
        }
Example #43
0
        public override object Execute(List <string> args)
        {
            if (args.Count < 1)
            {
                return(false);
            }

            var fieldName      = args[0];
            var fieldNameLow   = fieldName.ToLower();
            var fieldNameSnake = fieldName.ToSnakeCase();

            var previousContext   = ContextStack.Context;
            var previousOwner     = Owner;
            var previousStructure = Structure;

            var blockName = "";

            if (fieldName.Contains("."))
            {
                var lastIndex = fieldName.LastIndexOf('.');
                blockName      = fieldName.Substring(0, lastIndex);
                fieldName      = fieldName.Substring(lastIndex + 1, (fieldName.Length - lastIndex) - 1);
                fieldNameLow   = fieldName.ToLower();
                fieldNameSnake = fieldName.ToSnakeCase();

                var command = new EditBlockCommand(ContextStack, CacheContext, Tag, Owner);

                if (command.Execute(new List <string> {
                    blockName
                }).Equals(false))
                {
                    while (ContextStack.Context != previousContext)
                    {
                        ContextStack.Pop();
                    }
                    Owner     = previousOwner;
                    Structure = previousStructure;
                    return(false);
                }

                command = (ContextStack.Context.GetCommand("EditBlock") as EditBlockCommand);

                Owner     = command.Owner;
                Structure = command.Structure;

                if (Owner == null)
                {
                    while (ContextStack.Context != previousContext)
                    {
                        ContextStack.Pop();
                    }
                    Owner     = previousOwner;
                    Structure = previousStructure;
                    return(false);
                }
            }

            var field = TagStructure.GetTagFieldEnumerable(Structure)
                        .Find(f =>
                              f.Name == fieldName ||
                              f.Name.ToLower() == fieldNameLow ||
                              f.Name.ToSnakeCase() == fieldNameSnake);

            var ownerType = Owner.GetType();

            if (field == null)
            {
                Console.WriteLine("{0} does not contain a block named \"{1}\"", ownerType.Name, fieldName);
                return(false);
            }

            IList fieldValue = null;

            if (field.FieldType.GetInterface("IList") == null || (fieldValue = (IList)field.GetValue(Owner)) == null)
            {
                Console.WriteLine("{0} does not contain a block named \"{1}\"", ownerType.Name, fieldName);
                return(false);
            }

            string fromName = null;
            int?   from     = null;

            string toName = null;
            int?   to     = null;

            while (true)
            {
                var found = false;

                switch (args[1].ToLower())
                {
                case "from:":
                    if (char.IsNumber(args[2][0]))
                    {
                        from = int.Parse(args[2]);
                    }
                    else
                    {
                        fromName = args[2];
                        from     = FindLabelIndex(fieldValue, fromName);
                    }
                    args.RemoveRange(1, 2);
                    found = true;
                    break;

                case "to:":
                    if (char.IsNumber(args[2][0]))
                    {
                        to = int.Parse(args[2]);
                    }
                    else
                    {
                        toName = args[2];
                        to     = FindLabelIndex(fieldValue, toName);
                    }
                    args.RemoveRange(1, 2);
                    found = true;
                    break;
                }

                if (!found)
                {
                    break;
                }
            }

            blockName = args[0];
            args      = args.Skip(1).ToList();

            for (var i = (from.HasValue ? from.Value : 0);
                 i < (to.HasValue ? to.Value + 1 : fieldValue.Count);
                 i++)
            {
                while (ContextStack.Context != previousContext)
                {
                    ContextStack.Pop();
                }

                Owner     = previousOwner;
                Structure = previousStructure;

                if (blockName != "" && new EditBlockCommand(ContextStack, CacheContext, Tag, Owner)
                    .Execute(new List <string> {
                    $"{blockName}[{i}]"
                })
                    .Equals(false))
                {
                    return(false);
                }

                var label = GetLabel(fieldValue, i);

                Console.Write(label == null ? $"[{i}] " : $"[{label} ({i})] ");
                ContextStack.Context.GetCommand(args[0]).Execute(args.Skip(1).ToList());
            }

            while (ContextStack.Context != previousContext)
            {
                ContextStack.Pop();
            }

            Owner     = previousOwner;
            Structure = previousStructure;

            return(true);
        }
Example #44
0
        private void  位机_Paint(object sender, PaintEventArgs e)
        {
            Bitmap I_bmp        = new Bitmap(I_plot.Size.Width, I_plot.Size.Height);
            Bitmap speed_bmp    = new Bitmap(speed_plot.Size.Width, speed_plot.Size.Height);
            Bitmap location_map = new Bitmap(location_plot.Size.Width, location_plot.Size.Height);

            Graphics gp          = Graphics.FromImage(I_bmp);
            Graphics gp_speed    = Graphics.FromImage(speed_bmp);
            Graphics gp_location = Graphics.FromImage(location_map);

            //纵向轴绘制
            for (int i = 0; i < I_plot.Size.Width / unit_length; i++)
            {
                //I_map
                Y_max = I_plot.Size.Height - 20;
                gp.DrawLine(tablepen, startprint_x + i * unit_length, startprint_y, startprint_x + i * unit_length, startprint_y + Y_max);
                gp.DrawString((i * (unit_length / drawstep)).ToString(), tabControl1.Font, Brushes.Black, new RectangleF(startprint_x + i * unit_length - 5, startprint_y + Y_max + 4, 50, 50), null);
                //speed_bmp
                Y_max = speed_plot.Size.Height - 20;
                gp_speed.DrawLine(tablepen, startprint_x + i * unit_length, startprint_y, startprint_x + i * unit_length, startprint_y + Y_max);
                gp_speed.DrawString((i * (unit_length / drawstep)).ToString(), tabControl1.Font, Brushes.Black, new RectangleF(startprint_x + i * unit_length - 5, startprint_y + Y_max + 4, 50, 50), null);
                //location_map
                Y_max = location_plot.Size.Height - 20;
                gp_location.DrawLine(tablepen, startprint_x + i * unit_length, startprint_y, startprint_x + i * unit_length, startprint_y + Y_max);
                gp_location.DrawString((i * (unit_length / drawstep)).ToString(), tabControl1.Font, Brushes.Black, new RectangleF(startprint_x + i * unit_length - 5, startprint_y + Y_max + 4, 50, 50), null);
            }

            //横向轴绘制
            //I_map
            Y_max = I_plot.Size.Height - 20;
            for (int i = 0; i <= Y_max / unit_length; i++)
            {
                gp.DrawLine(tablepen, startprint_x, startprint_y + i * unit_length, I_plot.Size.Width, startprint_y + i * unit_length);
                if (i == 0)
                {
                    gp.DrawString("1.00", tabControl1.Font, Brushes.Black, new RectangleF(0, startprint_y - 4, 40, 50), null);
                }
                if ((i + 1) > Y_max / unit_length)
                {
                    gp.DrawString("0.00", tabControl1.Font, Brushes.Black, new RectangleF(0, i * unit_length + startprint_y - 4, 40, 50), null);
                }
            }
            //speed_bmp
            Y_max = speed_plot.Size.Height - 20;
            for (int i = 0; i <= Y_max / unit_length; i++)
            {
                gp_speed.DrawLine(tablepen, startprint_x, startprint_y + i * unit_length, speed_plot.Size.Width, startprint_y + i * unit_length);
                if (i == 0)
                {
                    gp_speed.DrawString("1.00", tabControl1.Font, Brushes.Black, new RectangleF(0, startprint_y - 4, 40, 50), null);
                }
                if ((i + 1) > Y_max / unit_length)
                {
                    gp_speed.DrawString("0.00", tabControl1.Font, Brushes.Black, new RectangleF(0, i * unit_length + startprint_y - 4, 40, 50), null);
                }
            }
            //location_map
            Y_max = location_plot.Size.Height - 20;
            for (int i = 0; i <= Y_max / unit_length; i++)
            {
                gp_location.DrawLine(tablepen, startprint_x, startprint_y + i * unit_length, location_plot.Size.Width, startprint_y + i * unit_length);
                if (i == 0)
                {
                    gp_location.DrawString("1.00", tabControl1.Font, Brushes.Black, new RectangleF(0, startprint_y - 4, 40, 50), null);
                }
                if ((i + 1) > Y_max / unit_length)
                {
                    gp_location.DrawString("0.00", tabControl1.Font, Brushes.Black, new RectangleF(0, i * unit_length + startprint_y - 4, 40, 50), null);
                }
            }

            //绘制曲线
            List <byte> datalist_I        = new List <byte>(); //电流值数据结构——线性链表
            List <byte> datalist_speed    = new List <byte>(); //速度值数据结构——线性链表
            List <byte> datalist_location = new List <byte>(); //位置值数据结构——线性链表

            if (is_motor1.Checked)
            {
                datalist_I        = datalist_I_basemotor1;
                datalist_speed    = datalist_speed_basemotor1;
                datalist_location = datalist_power_basemotor1;
            }
            else if (is_motor2.Checked)
            {
                datalist_I        = datalist_I_basemotor2;
                datalist_speed    = datalist_speed_basemotor2;
                datalist_location = datalist_power_basemotor2;
            }
            else if (is_motor3.Checked)
            {
                datalist_I        = datalist_I_basemotor3;
                datalist_speed    = datalist_speed_basemotor3;
                datalist_location = datalist_power_basemotor3;
            }
            else if (is_motor4.Checked)
            {
                datalist_I        = datalist_I_basemotor4;
                datalist_speed    = datalist_speed_basemotor4;
                datalist_location = datalist_power_basemotor4;
            }
            else if (is_motor_ytyaw.Checked)
            {
                datalist_I        = datalist_I_ytmotoryaw;
                datalist_speed    = datalist_speed_ytmotoryaw;
                datalist_location = datalist_location_ytmotoryaw;
            }
            else if (is_motor_ytpitch.Checked)
            {
                datalist_I        = datalist_I_ytmotorpitch;
                datalist_speed    = datalist_speed_ytmotorpitch;
                datalist_location = datalist_location_ytmotorpitch;
            }
            else if (is_bdmotor.Checked)
            {
                datalist_I        = datalist_I_bdmotor;
                datalist_speed    = datalist_speed_bdmotor;
                datalist_location = datalist_location_bdmotor;
            }
            else if (is_mclmotor1.Checked)
            {
                datalist_I     = datalist_I_mclmotor1;
                datalist_speed = datalist_speed_mclmotor1;
            }
            else if (is_mclmotor2.Checked)
            {
                datalist_I     = datalist_I_mclmotor2;
                datalist_speed = datalist_speed_mclmotor2;
            }

            //I_map
            Y_max = I_plot.Size.Height - 20;
            if (datalist_I.Count - 1 >= (I_plot.Size.Width - startprint_x) / drawstep)
            {
                datalist_I.RemoveRange(0, datalist_I.Count - 1 - (I_plot.Size.Width - startprint_x) / drawstep);
            }
            for (int i = 0; i < datalist_I.Count - 1; i++)
            {
                gp.DrawLine(linespen, startprint_x + i * drawstep, startprint_y + Y_max - datalist_I[i] * Y_max / 0xFF, startprint_x + (i + 1) * drawstep, startprint_y + Y_max - datalist_I[i + 1] * Y_max / 0xFF);
            }
            //speed_bmp
            Y_max = speed_plot.Size.Height - 20;
            if (datalist_speed.Count - 1 >= (speed_plot.Size.Width - startprint_x) / drawstep)
            {
                datalist_speed.RemoveRange(0, datalist_speed.Count - 1 - (speed_plot.Size.Width - startprint_x) / drawstep);
            }
            for (int i = 0; i < datalist_speed.Count - 1; i++)
            {
                gp_speed.DrawLine(linespen, startprint_x + i * drawstep, startprint_y + Y_max - datalist_speed[i] * Y_max / 0xFF, startprint_x + (i + 1) * drawstep, startprint_y + Y_max - datalist_speed[i + 1] * Y_max / 0xFF);
            }
            //location_map
            Y_max = location_plot.Size.Height - 20;
            if (datalist_location.Count - 1 >= (location_plot.Size.Width - startprint_x) / drawstep)
            {
                datalist_location.RemoveRange(0, datalist_location.Count - 1 - (location_plot.Size.Width - startprint_x) / drawstep);
            }
            for (int i = 0; i < datalist_location.Count - 1; i++)
            {
                gp_location.DrawLine(linespen, startprint_x + i * drawstep, startprint_y + Y_max - datalist_location[i] * Y_max / 0xFF, startprint_x + (i + 1) * drawstep, startprint_y + Y_max - datalist_location[i + 1] * Y_max / 0xFF);
            }

            //显示曲线
            I_plot.Image        = I_bmp;
            speed_plot.Image    = speed_bmp;
            location_plot.Image = location_map;
        }
Example #45
0
        static void Main(string[] args)
        {
            List <int> nums  = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
            string     input = Console.ReadLine();

            while (input != "end")
            {
                string[] inputs  = input.Split(' ');
                string   command = inputs[0];
                if (command == "exchange")
                {
                    int index = int.Parse(inputs[1]);
                    if (index < 0 || index >= nums.Count)
                    {
                        Console.WriteLine("Invalid index");
                        input = Console.ReadLine();
                        continue;
                    }
                    var split = nums.Skip(index + 1).ToList();
                    nums.RemoveRange(index + 1, nums.Count - index - 1);
                    nums.InsertRange(0, split);
                }
                else if (command == "max")
                {
                    string type = inputs[1];
                    if (type == "even" && nums.Where(x => x % 2 == 0).Count() != 0)
                    {
                        Console.WriteLine(nums.LastIndexOf(nums.Where(x => x % 2 == 0).Max()));
                    }
                    else if (type == "odd" && nums.Where(x => x % 2 != 0).Count() != 0)
                    {
                        Console.WriteLine(nums.LastIndexOf(nums.Where(x => x % 2 != 0).Max()));
                    }
                    else
                    {
                        Console.WriteLine("No matches");
                    }
                }
                else if (command == "min")
                {
                    string type = inputs[1];
                    if (type == "even" && nums.Where(x => x % 2 == 0).Count() != 0)
                    {
                        Console.WriteLine(nums.LastIndexOf(nums.Where(x => x % 2 == 0).Min()));
                    }
                    else if (type == "odd" && nums.Where(x => x % 2 != 0).Count() != 0)
                    {
                        Console.WriteLine(nums.LastIndexOf(nums.Where(x => x % 2 != 0).Min()));
                    }
                    else
                    {
                        Console.WriteLine("No matches");
                    }
                }
                else if (command == "first")
                {
                    int count = int.Parse(inputs[1]);
                    if (count < 0 || count > nums.Count)
                    {
                        Console.WriteLine("Invalid count");
                        input = Console.ReadLine();
                        continue;
                    }
                    string type = inputs[2];
                    if (type == "even")
                    {
                        Console.WriteLine("[{0}]", String.Join(", ", nums.Where(x => x % 2 == 0).Take(count)));
                    }
                    else if (type == "odd")
                    {
                        Console.WriteLine("[{0}]", String.Join(", ", nums.Where(x => x % 2 != 0).Take(count)));
                    }
                }
                else if (command == "last")
                {
                    int count = int.Parse(inputs[1]);
                    if (count < 0 || count > nums.Count)
                    {
                        Console.WriteLine("Invalid count");
                        input = Console.ReadLine();
                        continue;
                    }
                    string type = inputs[2];
                    if (type == "even")
                    {
                        Console.WriteLine("[{0}]", String.Join(", ", nums
                                                               .Where(x => x % 2 == 0)
                                                               .Skip(nums.Where(x => x % 2 == 0).Count() - count)));
                    }
                    else if (type == "odd")
                    {
                        Console.WriteLine("[{0}]", String.Join(", ", nums
                                                               .Where(x => x % 2 != 0)
                                                               .Skip(nums.Where(x => x % 2 != 0).Count() - count)));
                    }
                }
                input = Console.ReadLine();
            }
            Console.WriteLine("[{0}]", String.Join(", ", nums));
        }
Example #46
0
        public List <byte> GetResponse(int ms, bool throwError = true)
        {
            List <byte> tmpBuff = new List <byte>();

            if (!packetReady.WaitOne(ms, false))
            {
                if (throwError == true)
                {
                    throw (new DMSSException("ReceiveTimeout"));
                }
                else
                {
                    return(tmpBuff);
                }
            }
            lock (locker)
            {
                while (RxBuff.Count > 0)
                {
                    byte tmp = RxBuff.Dequeue();
                    if (tmp == 0x7e)
                    {
                        break;
                    }
                    tmpBuff.Add(tmp);
                }
            }
            if (tmpBuff.Count == 0)
            {
                throw (new DMSSException("ReceiveTimeout NoData"));
            }
            tmpBuff = DecodePacket(tmpBuff);
            if (!Crc16.TestChecksum(tmpBuff.ToArray()))
            {
                throw new DMSSException("CRC Error");
            }
            if (tmpBuff[0] == 0x13)
            {
                throw (new DMSSException("BadCommand"));
            }
            if (tmpBuff[0] == 0x14)
            {
                throw (new DMSSException("Bad Parameters Response"));
            }
            if (tmpBuff[0] == 0x15)
            {
                throw (new DMSSException("Bad Length Response"));
            }
            if (tmpBuff[0] == 0x18)
            {
                throw (new DMSSException("Bad Mode Response"));
            }
            if (tmpBuff[0] == 0x47)
            {
                throw (new DMSSException("Bad Security mode"));
            }
            if (tmpBuff[0] == 0x79)
            {
                //diagnostic messages
                return(GetResponse(ms, false));
            }
            tmpBuff.RemoveRange(tmpBuff.Count - 2, 2);
            return(tmpBuff);
        }
Example #47
0
        /// <summary>
        /// Removes any unusable connections from the pool, and if the pool
        /// is then empty and stale, disposes of it.
        /// </summary>
        /// <returns>
        /// true if the pool disposes of itself; otherwise, false.
        /// </returns>
        public bool CleanCacheAndDisposeIfUnused()
        {
            TimeSpan pooledConnectionLifetime    = _poolManager.Settings._pooledConnectionLifetime;
            TimeSpan pooledConnectionIdleTimeout = _poolManager.Settings._pooledConnectionIdleTimeout;

            List <CachedConnection> list      = _idleConnections;
            List <HttpConnection>   toDispose = null;
            bool tookLock = false;

            try
            {
                if (NetEventSource.IsEnabled)
                {
                    Trace("Cleaning pool.");
                }
                Monitor.Enter(SyncObj, ref tookLock);

                // Get the current time.  This is compared against each connection's last returned
                // time to determine whether a connection is too old and should be closed.
                DateTimeOffset now = DateTimeOffset.Now;

                // Find the first item which needs to be removed.
                int freeIndex = 0;
                while (freeIndex < list.Count && list[freeIndex].IsUsable(now, pooledConnectionLifetime, pooledConnectionIdleTimeout))
                {
                    freeIndex++;
                }

                // If freeIndex == list.Count, nothing needs to be removed.
                // But if it's < list.Count, at least one connection needs to be purged.
                if (freeIndex < list.Count)
                {
                    // We know the connection at freeIndex is unusable, so dispose of it.
                    toDispose = new List <HttpConnection> {
                        list[freeIndex]._connection
                    };

                    // Find the first item after the one to be removed that should be kept.
                    int current = freeIndex + 1;
                    while (current < list.Count)
                    {
                        // Look for the first item to be kept.  Along the way, any
                        // that shouldn't be kept are disposed of.
                        while (current < list.Count && !list[current].IsUsable(now, pooledConnectionLifetime, pooledConnectionIdleTimeout))
                        {
                            toDispose.Add(list[current]._connection);
                            current++;
                        }

                        // If we found something to keep, copy it down to the known free slot.
                        if (current < list.Count)
                        {
                            // copy item to the free slot
                            list[freeIndex++] = list[current++];
                        }

                        // Keep going until there are no more good items.
                    }

                    // At this point, good connections have been moved below freeIndex, and garbage connections have
                    // been added to the dispose list, so clear the end of the list past freeIndex.
                    list.RemoveRange(freeIndex, list.Count - freeIndex);

                    // If there are now no connections associated with this pool, we can dispose of it. We
                    // avoid aggressively cleaning up pools that have recently been used but currently aren't;
                    // if a pool was used since the last time we cleaned up, give it another chance. New pools
                    // start out saying they've recently been used, to give them a bit of breathing room and time
                    // for the initial collection to be added to it.
                    if (_associatedConnectionCount == 0 && !_usedSinceLastCleanup)
                    {
                        Debug.Assert(list.Count == 0, $"Expected {nameof(list)}.{nameof(list.Count)} == 0");
                        _disposed = true;
                        return(true); // Pool is disposed of.  It should be removed.
                    }
                }

                // Reset the cleanup flag.  Any pools that are empty and not used since the last cleanup
                // will be purged next time around.
                _usedSinceLastCleanup = false;
            }
            finally
            {
                if (tookLock)
                {
                    Monitor.Exit(SyncObj);
                }

                // Dispose the stale connections outside the pool lock.
                toDispose?.ForEach(c => c.Dispose());
            }

            // Pool is active.  Should not be removed.
            return(false);
        }
Example #48
0
 public override void Execute(List <string> _params, CommandSenderInfo _senderInfo)
 {
     try
     {
         if (_params[0] == "new")
         {
             if (_params.Count < 3)
             {
                 SdtdConsole.Instance.Output(string.Format("Wrong number of arguments, expected at least 3, found {0}", _params.Count));
                 return;
             }
             else
             {
                 int _hours;
                 if (!int.TryParse(_params[1], out _hours))
                 {
                     SdtdConsole.Instance.Output(string.Format("Invalid integer {0}", _params[1]));
                     return;
                 }
                 _params.RemoveRange(0, 2);
                 string    _message = string.Join(" ", _params.ToArray());
                 string    _sql     = "SELECT pollTime, pollHours, pollMessage FROM Polls WHERE pollOpen = 'true'";
                 DataTable _result  = SQL.TQuery(_sql);
                 if (_result.Rows.Count > 0)
                 {
                     DateTime _pollTime;
                     DateTime.TryParse(_result.Rows[0].ItemArray.GetValue(0).ToString(), out _pollTime);
                     int _pollHours;
                     int.TryParse(_result.Rows[0].ItemArray.GetValue(1).ToString(), out _pollHours);
                     string   _pollMessage    = _result.Rows[0].ItemArray.GetValue(2).ToString();
                     TimeSpan varTime         = DateTime.Now - _pollTime;
                     double   fractionalHours = varTime.TotalHours;
                     int      _timepassed     = (int)fractionalHours;
                     if (_timepassed >= _pollHours)
                     {
                         SdtdConsole.Instance.Output("There is a poll open but the time has expired.");
                         SdtdConsole.Instance.Output(string.Format("Poll: {0}", _pollMessage));
                         SdtdConsole.Instance.Output("You need to close the above poll before making a new one.");
                     }
                     else
                     {
                         int _timeleft = _pollHours - _timepassed;
                         SdtdConsole.Instance.Output("There is a poll open. Let it finish or close it");
                         SdtdConsole.Instance.Output(string.Format("Poll: {0}", _pollMessage));
                         SdtdConsole.Instance.Output(string.Format("Time Remaining: {0} hours", _timeleft));
                     }
                 }
                 else
                 {
                     _sql = string.Format("INSERT INTO Polls (pollOpen, pollTime, pollHours, pollMessage) VALUES ('true', '{0}', {1}, '{2}')", DateTime.Now, _hours, _message);
                     SQL.FastQuery(_sql, "PollConsole");
                     string _phrase926;
                     if (!Phrases.Dict.TryGetValue(926, out _phrase926))
                     {
                         _phrase926 = "Poll: {Message}";
                     }
                     _phrase926 = _phrase926.Replace("{Message}", _message);
                     string _phrase927;
                     if (!Phrases.Dict.TryGetValue(927, out _phrase927))
                     {
                         _phrase927 = "Type {CommandPrivate}{Command91} or {CommandPrivate}{Command92} to vote.";
                     }
                     _phrase927 = _phrase927.Replace("{CommandPrivate}", ChatHook.Command_Private);
                     _phrase927 = _phrase927.Replace("{Command91}", Command91);
                     _phrase927 = _phrase927.Replace("{Command92}", Command92);
                     ChatHook.ChatMessage(null, LoadConfig.Chat_Response_Color + _phrase926, -1, LoadConfig.Server_Response_Name, EChatType.Global, null);
                     ChatHook.ChatMessage(null, LoadConfig.Chat_Response_Color + _phrase927, -1, LoadConfig.Server_Response_Name, EChatType.Global, null);
                     SdtdConsole.Instance.Output(string.Format("Opened a new poll for {0} hours.", _hours));
                     using (StreamWriter sw = new StreamWriter(_filepath, true))
                     {
                         sw.WriteLine(string.Format("{0}  New poll {1} ... The poll will be open for {2} hours", DateTime.Now, _message, _hours));
                         sw.WriteLine();
                         sw.Flush();
                         sw.Close();
                     }
                 }
                 _result.Dispose();
             }
         }
         else if (_params[0] == "close")
         {
             if (_params.Count != 2)
             {
                 SdtdConsole.Instance.Output(string.Format("Wrong number of arguments, expected 2, found {0}", _params.Count));
                 return;
             }
             bool _announce = false;
             if (!bool.TryParse(_params[1], out _announce))
             {
                 SdtdConsole.Instance.Output(string.Format("Invalid true/false argument: {0}", _params[1]));
                 return;
             }
             else
             {
                 string    _sql    = "SELECT pollMessage, pollYes, pollNo FROM Polls WHERE pollOpen = 'true'";
                 DataTable _result = SQL.TQuery(_sql);
                 if (_result.Rows.Count > 0)
                 {
                     int _pollYes;
                     int.TryParse(_result.Rows[0].ItemArray.GetValue(1).ToString(), out _pollYes);
                     int _pollNo;
                     int.TryParse(_result.Rows[0].ItemArray.GetValue(2).ToString(), out _pollNo);
                     if (_announce)
                     {
                         string _phrase925;
                         if (!Phrases.Dict.TryGetValue(925, out _phrase925))
                         {
                             _phrase925 = "Poll results: Yes {YesVote} / No {NoVote}";
                         }
                         _phrase925 = _phrase925.Replace("{YesVote}", _pollYes.ToString());
                         _phrase925 = _phrase925.Replace("{NoVote}", _pollNo.ToString());
                         ChatHook.ChatMessage(null, LoadConfig.Chat_Response_Color + _phrase925, -1, LoadConfig.Server_Response_Name, EChatType.Global, null);
                     }
                     using (StreamWriter sw = new StreamWriter(_filepath, true))
                     {
                         string _pollMessage = _result.Rows[0].ItemArray.GetValue(0).ToString();
                         sw.WriteLine(string.Format("{0}  Poll {1} ... has completed. The final results were yes {2} / no {3}", DateTime.Now, _pollMessage, _pollYes, _pollNo));
                         sw.WriteLine();
                         sw.Flush();
                         sw.Close();
                     }
                     _sql = "SELECT pollMessage, pollYes, pollNo FROM Polls WHERE pollOpen = 'false'";
                     DataTable _result1 = SQL.TQuery(_sql);
                     if (_result1.Rows.Count > 0)
                     {
                         _sql = "DELETE FROM Polls WHERE pollOpen = 'false'";
                         SQL.FastQuery(_sql, "PollConsole");
                     }
                     _result1.Dispose();
                     _sql = "UPDATE Polls SET pollOpen = 'false' WHERE pollOpen = 'true'";
                     SQL.FastQuery(_sql, "PollConsole");
                     PolledYes.Clear();
                     PolledNo.Clear();
                     SdtdConsole.Instance.Output("Closed the open poll.");
                 }
                 else
                 {
                     SdtdConsole.Instance.Output("No poll is open");
                 }
                 _result.Dispose();
             }
         }
         else if (_params[0] == "last")
         {
             if (_params.Count != 1)
             {
                 SdtdConsole.Instance.Output(string.Format("Wrong number of arguments, expected 1, found {0}", _params.Count));
                 return;
             }
             else
             {
                 string    _sql    = "SELECT pollHours, pollMessage, pollYes, pollNo FROM Polls WHERE pollOpen = 'false'";
                 DataTable _result = SQL.TQuery(_sql);
                 if (_result.Rows.Count > 0)
                 {
                     int _pollHours;
                     int.TryParse(_result.Rows[0].ItemArray.GetValue(0).ToString(), out _pollHours);
                     string _pollMessage = _result.Rows[0].ItemArray.GetValue(1).ToString();
                     int    _pollYes;
                     int.TryParse(_result.Rows[0].ItemArray.GetValue(2).ToString(), out _pollYes);
                     int _pollNo;
                     int.TryParse(_result.Rows[0].ItemArray.GetValue(3).ToString(), out _pollNo);
                     SdtdConsole.Instance.Output(string.Format("The last poll message: {0}", _pollMessage));
                     SdtdConsole.Instance.Output(string.Format("Last poll results: Yes {0} / No {1}", _pollYes, _pollNo));
                     SdtdConsole.Instance.Output(string.Format("Poll was open for {0} hours", _pollHours));
                 }
                 else
                 {
                     SdtdConsole.Instance.Output("There are no saved prior poll results");
                 }
                 _result.Dispose();
             }
         }
         else if (_params[0] == "reopen")
         {
             if (_params.Count != 2)
             {
                 SdtdConsole.Instance.Output(string.Format("Wrong number of arguments, expected 2, found {0}", _params.Count));
                 return;
             }
             string    _sql    = "SELECT pollTime, pollHours, pollMessage FROM Polls WHERE pollOpen = 'true'";
             DataTable _result = SQL.TQuery(_sql);
             if (_result.Rows.Count > 0)
             {
                 SdtdConsole.Instance.Output("A poll is open. Can not open a new poll until it is closed");
             }
             else
             {
                 _sql = "SELECT pollTime, pollHours, pollMessage FROM Polls WHERE pollOpen = 'false'";
                 DataTable _result1 = SQL.TQuery(_sql);
                 if (_result1.Rows.Count > 0)
                 {
                     int _hours;
                     int.TryParse(_params[1], out _hours);
                     _sql = string.Format("UPDATE Polls SET pollOpen = 'true', pollTime = '{0}', pollHours = {1} WHERE pollOpen = 'false'", DateTime.Now, _hours);
                     SQL.FastQuery(_sql, "PollConsole");
                 }
                 else
                 {
                     SdtdConsole.Instance.Output("You have no previous poll");
                 }
                 _result1.Dispose();
             }
             _result.Dispose();
         }
         else if (_params[0] == "check")
         {
             if (_params.Count != 1)
             {
                 SdtdConsole.Instance.Output(string.Format("Wrong number of arguments, expected 1, found {0}", _params.Count));
                 return;
             }
             string    _sql    = "SELECT pollTime, pollHours, pollMessage, pollYes, pollNo FROM Polls WHERE pollOpen = 'true'";
             DataTable _result = SQL.TQuery(_sql);
             if (_result.Rows.Count > 0)
             {
                 DateTime _pollTime;
                 DateTime.TryParse(_result.Rows[0].ItemArray.GetValue(0).ToString(), out _pollTime);
                 int _pollHours;
                 int.TryParse(_result.Rows[0].ItemArray.GetValue(1).ToString(), out _pollHours);
                 string _pollMessage = _result.Rows[0].ItemArray.GetValue(2).ToString();
                 int    _pollYes;
                 int.TryParse(_result.Rows[0].ItemArray.GetValue(3).ToString(), out _pollYes);
                 int _pollNo;
                 int.TryParse(_result.Rows[0].ItemArray.GetValue(4).ToString(), out _pollNo);
                 TimeSpan varTime         = DateTime.Now - _pollTime;
                 double   fractionalHours = varTime.TotalHours;
                 int      _timepassed     = (int)fractionalHours;
                 if (_timepassed >= _pollHours)
                 {
                     SdtdConsole.Instance.Output("There is a poll open but the time has expired.");
                     SdtdConsole.Instance.Output(string.Format("Poll: {0}", _pollMessage));
                     SdtdConsole.Instance.Output(string.Format("Current poll results: Yes votes {0} / No votes {1}", _pollYes, _pollNo));
                 }
                 else
                 {
                     SdtdConsole.Instance.Output(string.Format("Poll: {0}", _pollMessage));
                     SdtdConsole.Instance.Output(string.Format("Current poll results: Yes votes {0} / No votes {1}", _pollYes, _pollNo));
                 }
             }
             else
             {
                 SdtdConsole.Instance.Output("No poll is open");
             }
             _result.Dispose();
         }
     }
     catch (Exception e)
     {
         Log.Out(string.Format("[SERVERTOOLS] Error in PollConsole.Run: {0}.", e));
     }
 }
        public InputModelState(string outputPath, string filename, ModelGrid ecosystemModelGrid, List <uint[]> cellList)
        {
            //Set the input state flag to be true
            _InputState = true;

            // Construct the string required to access the file using Scientific Dataset
            string _ReadFileString = "msds:nc?file=input/ModelStates/" + filename + ".nc&openMode=readOnly";

            // Open the data file using Scientific Dataset
            DataSet StateDataSet = DataSet.Open(_ReadFileString);


            float[] Latitude              = StateDataSet.GetData <float[]>("Latitude");
            float[] Longitude             = StateDataSet.GetData <float[]>("Longitude");
            float[] CohortFunctionalGroup = StateDataSet.GetData <float[]>("Cohort Functional Group");
            float[] Cohort = StateDataSet.GetData <float[]>("Cohort");

            float[] StockFunctionalGroup = StateDataSet.GetData <float[]>("Stock Functional Group");
            float[] Stock = StateDataSet.GetData <float[]>("Stock");


            // Check that the longitudes and latitudes in the input state match the cell environment
            for (int la = 0; la < Latitude.Length; la++)
            {
                Debug.Assert(ecosystemModelGrid.GetCellEnvironment((uint)la, 0)["Latitude"][0] == Latitude[la],
                             "Error: input-state grid doesn't match current model grid");
            }
            for (int lo = 0; lo < Longitude.Length; lo++)
            {
                Debug.Assert(ecosystemModelGrid.GetCellEnvironment(0, (uint)lo)["Longitude"][0] == Longitude[lo],
                             "Error: input-state grid doesn't match current model grid");
            }

            List <double[, , ]> CohortJuvenileMass                = new List <double[, , ]>();
            List <double[, , ]> CohortAdultMass                   = new List <double[, , ]>();
            List <double[, , ]> CohortIndividualBodyMass          = new List <double[, , ]>();
            List <double[, , ]> CohortCohortAbundance             = new List <double[, , ]>();
            List <double[, , ]> CohortLogOptimalPreyBodySizeRatio = new List <double[, , ]>();
            List <double[, , ]> CohortBirthTimeStep               = new List <double[, , ]>();
            List <double[, , ]> CohortProportionTimeActive        = new List <double[, , ]>();
            List <double[, , ]> CohortTrophicIndex                = new List <double[, , ]>();

            double[,,,] tempData = new double[Latitude.Length, Longitude.Length,
                                              CohortFunctionalGroup.Length, Cohort.Length];

            tempData = StateDataSet.GetData <double[, , , ]>("CohortJuvenileMass");


            for (int la = 0; la < Latitude.Length; la++)
            {
                CohortJuvenileMass.Add(new double[Longitude.Length, CohortFunctionalGroup.Length, Cohort.Length]);
            }

            foreach (uint[] cell in cellList)
            {
                for (int fg = 0; fg < CohortFunctionalGroup.Length; fg++)
                {
                    for (int c = 0; c < Cohort.Length; c++)
                    {
                        CohortJuvenileMass[(int)cell[0]][cell[1], fg, c] = tempData[
                            cell[0], cell[1], fg, c];
                    }
                }
            }


            tempData = StateDataSet.GetData <double[, , , ]>("CohortAdultMass");

            for (int la = 0; la < Latitude.Length; la++)
            {
                CohortAdultMass.Add(new double[Longitude.Length, CohortFunctionalGroup.Length, Cohort.Length]);
            }

            foreach (uint[] cell in cellList)
            {
                for (int fg = 0; fg < CohortFunctionalGroup.Length; fg++)
                {
                    for (int c = 0; c < Cohort.Length; c++)
                    {
                        CohortAdultMass[(int)cell[0]][cell[1], fg, c] = tempData[
                            cell[0], cell[1], fg, c];
                    }
                }
            }

            tempData = StateDataSet.GetData <double[, , , ]>("CohortIndividualBodyMass");

            for (int la = 0; la < Latitude.Length; la++)
            {
                CohortIndividualBodyMass.Add(new double[Longitude.Length, CohortFunctionalGroup.Length, Cohort.Length]);
            }

            foreach (uint[] cell in cellList)
            {
                for (int fg = 0; fg < CohortFunctionalGroup.Length; fg++)
                {
                    for (int c = 0; c < Cohort.Length; c++)
                    {
                        CohortIndividualBodyMass[(int)cell[0]][cell[1], fg, c] = tempData[
                            cell[0], cell[1], fg, c];
                    }
                }
            }

            tempData = StateDataSet.GetData <double[, , , ]>("CohortCohortAbundance");

            for (int la = 0; la < Latitude.Length; la++)
            {
                CohortCohortAbundance.Add(new double[Longitude.Length, CohortFunctionalGroup.Length, Cohort.Length]);
            }

            foreach (uint[] cell in cellList)
            {
                for (int fg = 0; fg < CohortFunctionalGroup.Length; fg++)
                {
                    for (int c = 0; c < Cohort.Length; c++)
                    {
                        CohortCohortAbundance[(int)cell[0]][cell[1], fg, c] = tempData[
                            cell[0], cell[1], fg, c];
                    }
                }
            }

            tempData = StateDataSet.GetData <double[, , , ]>("CohortLogOptimalPreyBodySizeRatio");

            for (int la = 0; la < Latitude.Length; la++)
            {
                CohortLogOptimalPreyBodySizeRatio.Add(new double[Longitude.Length, CohortFunctionalGroup.Length, Cohort.Length]);
            }

            foreach (uint[] cell in cellList)
            {
                for (int fg = 0; fg < CohortFunctionalGroup.Length; fg++)
                {
                    for (int c = 0; c < Cohort.Length; c++)
                    {
                        CohortLogOptimalPreyBodySizeRatio[(int)cell[0]][cell[1], fg, c] = tempData[
                            cell[0], cell[1], fg, c];
                    }
                }
            }

            tempData = StateDataSet.GetData <double[, , , ]>("CohortBirthTimeStep");

            for (int la = 0; la < Latitude.Length; la++)
            {
                CohortBirthTimeStep.Add(new double[Longitude.Length, CohortFunctionalGroup.Length, Cohort.Length]);
            }

            foreach (uint[] cell in cellList)
            {
                for (int fg = 0; fg < CohortFunctionalGroup.Length; fg++)
                {
                    for (int c = 0; c < Cohort.Length; c++)
                    {
                        CohortBirthTimeStep[(int)cell[0]][cell[1], fg, c] = tempData[
                            cell[0], cell[1], fg, c];
                    }
                }
            }

            tempData = StateDataSet.GetData <double[, , , ]>("CohortProportionTimeActive");

            for (int la = 0; la < Latitude.Length; la++)
            {
                CohortProportionTimeActive.Add(new double[Longitude.Length, CohortFunctionalGroup.Length, Cohort.Length]);
            }

            foreach (uint[] cell in cellList)
            {
                for (int fg = 0; fg < CohortFunctionalGroup.Length; fg++)
                {
                    for (int c = 0; c < Cohort.Length; c++)
                    {
                        CohortProportionTimeActive[(int)cell[0]][cell[1], fg, c] = tempData[
                            cell[0], cell[1], fg, c];
                    }
                }
            }

            tempData = StateDataSet.GetData <double[, , , ]>("CohortTrophicIndex");

            for (int la = 0; la < Latitude.Length; la++)
            {
                CohortTrophicIndex.Add(new double[Longitude.Length, CohortFunctionalGroup.Length, Cohort.Length]);
            }

            foreach (uint[] cell in cellList)
            {
                for (int fg = 0; fg < CohortFunctionalGroup.Length; fg++)
                {
                    for (int c = 0; c < Cohort.Length; c++)
                    {
                        CohortTrophicIndex[(int)cell[0]][cell[1], fg, c] = tempData[
                            cell[0], cell[1], fg, c];
                    }
                }
            }

            _GridCellCohorts = new GridCellCohortHandler[Latitude.Length, Longitude.Length];

            long temp = 0;

            for (int cell = 0; cell < cellList.Count; cell++)
            {
                _GridCellCohorts[cellList[cell][0], cellList[cell][1]] = new GridCellCohortHandler(CohortFunctionalGroup.Length);

                for (int fg = 0; fg < CohortFunctionalGroup.Length; fg++)
                {
                    _GridCellCohorts[cellList[cell][0], cellList[cell][1]][fg] = new List <Cohort>();
                    for (int c = 0; c < Cohort.Length; c++)
                    {
                        if (CohortCohortAbundance[(int)cellList[cell][0]][cellList[cell][1], fg, c] > 0.0)
                        {
                            Cohort TempCohort = new Cohort(
                                (byte)fg,
                                CohortJuvenileMass[(int)cellList[cell][0]][cellList[cell][1], fg, c],
                                CohortAdultMass[(int)cellList[cell][0]][cellList[cell][1], fg, c],
                                CohortIndividualBodyMass[(int)cellList[cell][0]][cellList[cell][1], fg, c],
                                CohortCohortAbundance[(int)cellList[cell][0]][cellList[cell][1], fg, c],
                                Math.Exp(CohortLogOptimalPreyBodySizeRatio[(int)cellList[cell][0]][cellList[cell][1], fg, c]),
                                Convert.ToUInt16(CohortBirthTimeStep[(int)cellList[cell][0]][cellList[cell][1], fg, c]),
                                CohortProportionTimeActive[(int)cellList[cell][0]][cellList[cell][1], fg, c], ref temp,
                                CohortTrophicIndex[(int)cellList[cell][0]][cellList[cell][1], fg, c],
                                false);

                            _GridCellCohorts[cellList[cell][0], cellList[cell][1]][fg].Add(TempCohort);
                        }
                    }
                }
            }

            CohortJuvenileMass.RemoveRange(0, CohortJuvenileMass.Count);
            CohortAdultMass.RemoveRange(0, CohortAdultMass.Count);
            CohortIndividualBodyMass.RemoveRange(0, CohortIndividualBodyMass.Count);
            CohortCohortAbundance.RemoveRange(0, CohortCohortAbundance.Count);
            CohortLogOptimalPreyBodySizeRatio.RemoveRange(0, CohortLogOptimalPreyBodySizeRatio.Count);
            CohortBirthTimeStep.RemoveRange(0, CohortBirthTimeStep.Count);
            CohortProportionTimeActive.RemoveRange(0, CohortProportionTimeActive.Count);
            CohortTrophicIndex.RemoveRange(0, CohortTrophicIndex.Count);

            List <double[, , ]> StockIndividualBodyMass = new List <double[, , ]>();
            List <double[, , ]> StockTotalBiomass       = new List <double[, , ]>();

            double[,,,] tempData2 = new double[Latitude.Length, Longitude.Length,
                                               StockFunctionalGroup.Length, Stock.Length];

            tempData2 = StateDataSet.GetData <double[, , , ]>("StockIndividualBodyMass");

            for (int la = 0; la < Latitude.Length; la++)
            {
                StockIndividualBodyMass.Add(new double[Longitude.Length, StockFunctionalGroup.Length, Stock.Length]);
            }

            foreach (uint[] cell in cellList)
            {
                for (int fg = 0; fg < StockFunctionalGroup.Length; fg++)
                {
                    for (int c = 0; c < Stock.Length; c++)
                    {
                        StockIndividualBodyMass[(int)cell[0]][cell[1], fg, c] = tempData2[
                            cell[0], cell[1], fg, c];
                    }
                }
            }

            tempData2 = StateDataSet.GetData <double[, , , ]>("StockTotalBiomass");

            for (int la = 0; la < Latitude.Length; la++)
            {
                StockTotalBiomass.Add(new double[Longitude.Length, StockFunctionalGroup.Length, Stock.Length]);
            }

            foreach (uint[] cell in cellList)
            {
                for (int fg = 0; fg < StockFunctionalGroup.Length; fg++)
                {
                    for (int c = 0; c < Stock.Length; c++)
                    {
                        StockTotalBiomass[(int)cell[0]][cell[1], fg, c] = tempData2[
                            cell[0], cell[1], fg, c];
                    }
                }
            }

            _GridCellStocks = new GridCellStockHandler[Latitude.Length, Longitude.Length];

            for (int cell = 0; cell < cellList.Count; cell++)
            {
                _GridCellStocks[cellList[cell][0], cellList[cell][1]] = new GridCellStockHandler(StockFunctionalGroup.Length);

                for (int fg = 0; fg < StockFunctionalGroup.Length; fg++)
                {
                    _GridCellStocks[cellList[cell][0], cellList[cell][1]][fg] = new List <Stock>();
                    for (int c = 0; c < Stock.Length; c++)
                    {
                        if (StockTotalBiomass[(int)cellList[cell][0]][cellList[cell][1], fg, c] > 0.0)
                        {
                            Stock TempStock = new Stock(
                                (byte)fg,
                                StockIndividualBodyMass[(int)cellList[cell][0]][cellList[cell][1], fg, c],
                                StockTotalBiomass[(int)cellList[cell][0]][cellList[cell][1], fg, c]);

                            _GridCellStocks[cellList[cell][0], cellList[cell][1]][fg].Add(TempStock);
                        }
                    }
                }
            }
        }
Example #50
0
        /// <summary>
        /// Context: "&lt;"
        /// </summary>
        void ReadTag()
        {
            AssertHasMoreData();

            int         tagStart = this.CurrentLocation;
            InternalTag tag      = new InternalTag();
            var         frame    = BeginInternalObject(tag);

            // Read the opening bracket
            // It identifies the type of tag and parsing behavior for the rest of it
            tag.OpeningBracket = ReadOpeningBracket();

            if (tag.IsUnknownBang && !TryPeekWhiteSpace())
            {
                OnSyntaxError(tagStart, this.CurrentLocation, "Unknown tag");
            }

            if (tag.IsStartOrEmptyTag || tag.IsEndTag || tag.IsProcessingInstruction)
            {
                // Read the name
                TryMoveToNonWhiteSpace();
                tag.RelativeNameStart = this.CurrentRelativeLocation;
                string name;
                if (TryReadName(out name))
                {
                    if (!IsValidName(name))
                    {
                        OnSyntaxError(this.CurrentLocation - name.Length, this.CurrentLocation, "The name '{0}' is invalid", name);
                    }
                }
                else
                {
                    OnSyntaxError("Element name expected");
                }
                tag.Name = name;
            }
            else
            {
                tag.Name = string.Empty;
            }

            bool isXmlDeclr     = tag.Name == "xml" && tag.IsProcessingInstruction;
            int  oldObjectCount = objects.Count;

            if (tag.IsStartOrEmptyTag || tag.IsEndTag || isXmlDeclr)
            {
                // Read attributes for the tag
                while (HasMoreData())
                {
                    // Chech for all forbiden 'name' characters first - see ReadName
                    TryMoveToNonWhiteSpace();
                    if (TryPeek('<'))
                    {
                        break;
                    }
                    string endBr;
                    int    endBrStart = this.CurrentLocation;                  // Just peek
                    if (TryReadClosingBracket(out endBr))                      // End tag
                    {
                        GoBack(endBrStart);
                        break;
                    }

                    // We have "=\'\"" or name - read attribute
                    int attrStartOffset = this.CurrentLocation;
                    ReadAttribute();
                    if (tag.IsEndTag)
                    {
                        OnSyntaxError(attrStartOffset, this.CurrentLocation, "Attribute not allowed in end tag.");
                    }
                }
            }
            else if (tag.IsDocumentType)
            {
                ReadContentOfDTD();
            }
            else
            {
                int start = this.CurrentLocation;
                if (tag.IsComment)
                {
                    ReadText(TextType.Comment);
                }
                else if (tag.IsCData)
                {
                    ReadText(TextType.CData);
                }
                else if (tag.IsProcessingInstruction)
                {
                    ReadText(TextType.ProcessingInstruction);
                }
                else if (tag.IsUnknownBang)
                {
                    ReadText(TextType.UnknownBang);
                }
                else
                {
                    throw new InternalException(string.Format(CultureInfo.InvariantCulture, "Unknown opening bracket '{0}'", tag.OpeningBracket));
                }
                // Backtrack at complete start
                if (IsEndOfFile() || (tag.IsUnknownBang && TryPeek('<')))
                {
                    GoBack(start);
                    objects.RemoveRange(oldObjectCount, objects.Count - oldObjectCount);
                }
            }

            // Read closing bracket
            string bracket;

            TryReadClosingBracket(out bracket);
            tag.ClosingBracket = bracket;

            // Error check
            int brStart = this.CurrentLocation - (tag.ClosingBracket ?? string.Empty).Length;
            int brEnd   = this.CurrentLocation;

            if (tag.Name == null)
            {
                // One error was reported already
            }
            else if (tag.IsStartOrEmptyTag)
            {
                if (tag.ClosingBracket != ">" && tag.ClosingBracket != "/>")
                {
                    OnSyntaxError(brStart, brEnd, "'>' or '/>' expected");
                }
            }
            else if (tag.IsEndTag)
            {
                if (tag.ClosingBracket != ">")
                {
                    OnSyntaxError(brStart, brEnd, "'>' expected");
                }
            }
            else if (tag.IsComment)
            {
                if (tag.ClosingBracket != "-->")
                {
                    OnSyntaxError(brStart, brEnd, "'-->' expected");
                }
            }
            else if (tag.IsCData)
            {
                if (tag.ClosingBracket != "]]>")
                {
                    OnSyntaxError(brStart, brEnd, "']]>' expected");
                }
            }
            else if (tag.IsProcessingInstruction)
            {
                if (tag.ClosingBracket != "?>")
                {
                    OnSyntaxError(brStart, brEnd, "'?>' expected");
                }
            }
            else if (tag.IsUnknownBang)
            {
                if (tag.ClosingBracket != ">")
                {
                    OnSyntaxError(brStart, brEnd, "'>' expected");
                }
            }
            else if (tag.IsDocumentType)
            {
                if (tag.ClosingBracket != ">")
                {
                    OnSyntaxError(brStart, brEnd, "'>' expected");
                }
            }
            else
            {
                throw new InternalException(string.Format(CultureInfo.InvariantCulture, "Unknown opening bracket '{0}'", tag.OpeningBracket));
            }

            // Attribute name may not apper multiple times
            if (objects.Count > oldObjectCount)
            {
                // Move nested objects into tag.NestedObjects:
                tag.NestedObjects = new InternalObject[objects.Count - oldObjectCount];
                objects.CopyTo(oldObjectCount, tag.NestedObjects, 0, tag.NestedObjects.Length);
                objects.RemoveRange(oldObjectCount, objects.Count - oldObjectCount);

                // Look for duplicate attributes:
                HashSet <string> attributeNames = new HashSet <string>();
                foreach (var obj in tag.NestedObjects)
                {
                    InternalAttribute attr = obj as InternalAttribute;
                    if (attr != null && !attributeNames.Add(attr.Name))
                    {
                        int attrStart = tagStart + attr.StartRelativeToParent;
                        OnSyntaxError(attrStart, attrStart + attr.Name.Length, "Attribute with name '{0}' already exists", attr.Name);
                    }
                }
            }

            EndInternalObject(frame);
        }
        public static void FixDataContextCS(string path, string model, string nameSpace, string sdfFileName, IRepository repository)
        {
            string debugWriter = @"
public class DebugWriter : TextWriter
{
    private const int DefaultBufferSize = 256;
    private System.Text.StringBuilder _buffer;

    public DebugWriter()
    {
        BufferSize = 256;
        _buffer = new System.Text.StringBuilder(BufferSize);
    }

    public int BufferSize
    {
        get;
        private set;
    }

    public override System.Text.Encoding Encoding
    {
        get { return System.Text.Encoding.UTF8; }
    }

    #region StreamWriter Overrides
    public override void Write(char value)
    {
        _buffer.Append(value);
        if (_buffer.Length >= BufferSize)
            Flush();
    }

    public override void WriteLine(string value)
    {
        Flush();

        using(var reader = new StringReader(value))
        {
            string line; 
            while( null != (line = reader.ReadLine()))
                System.Diagnostics.Debug.WriteLine(line);
        }
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
            Flush();
    }

    public override void Flush()
    {
        if (_buffer.Length > 0)
        {
            System.Diagnostics.Debug.WriteLine(_buffer);
            _buffer.Clear();
        }
    }
    #endregion
}

";

            List <string> dcLines = System.IO.File.ReadAllLines(path).ToList();
            var           n       = string.Empty;

            if (!string.IsNullOrEmpty(nameSpace))
            {
                n += "\t";
            }
            var t = "\t";

            int i = dcLines.IndexOf(n + "public partial class " + model + " : System.Data.Linq.DataContext");

            if (i > -1)
            {
                dcLines.Insert(i - 2, debugWriter);
                dcLines.Insert(i - 2, "");
                dcLines.Insert(i - 2, "using Microsoft.Phone.Data.Linq;");
                dcLines.Insert(i - 2, "using Microsoft.Phone.Data.Linq.Mapping;");
                dcLines.Insert(i - 2, "using System.IO.IsolatedStorage;");
                dcLines.Insert(i - 2, "using System.IO;");
            }

            i = dcLines.IndexOf(n + "public partial class " + model + " : System.Data.Linq.DataContext");
            if (i > -1)
            {
                dcLines.RemoveAt(i - 1);
                dcLines.RemoveAt(i - 2);
                i++;
                i++;
                dcLines.Insert(i++, n + t + "public static string ConnectionString = \"Data Source=isostore:/" + sdfFileName + "\";");
                dcLines.Insert(i++, "");
                dcLines.Insert(i++, n + t + "public static string ConnectionStringReadOnly = \"Data Source=appdata:/" + sdfFileName + ";File Mode=Read Only;\";");
                dcLines.Insert(i++, "");
                dcLines.Insert(i++, n + t + "public static string FileName = \"" + sdfFileName + "\";");
                dcLines.Insert(i++, "");
                dcLines.Insert(i++, n + t + "public " + model + "(string connectionString) : base(connectionString)");
                dcLines.Insert(i++, n + t + "{");
                dcLines.Insert(i++, n + t + t + "OnCreated();");
                dcLines.Insert(i++, n + t + "}");
            }

            i = dcLines.IndexOf(n + t + "public " + model + "(string connection) : ");
            if (i > -1)
            {
                dcLines.RemoveRange(i, 6);
            }

            i = dcLines.IndexOf(n + t + "public " + model + "(System.Data.IDbConnection connection) : ");
            if (i > -1)
            {
                dcLines.RemoveRange(i, 6);
            }

            i = dcLines.IndexOf(n + t + "public " + model + "(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : ");
            if (i > -1)
            {
                dcLines.RemoveRange(i, 6);
            }

            i = dcLines.IndexOf(n + t + "public " + model + "(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : ");
            if (i > -1)
            {
                dcLines.RemoveRange(i, 6);
            }

            i = dcLines.IndexOf(n + t + "private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();");
            if (i > -1)
            {
                dcLines.RemoveAt(i);

                dcLines.Insert(i++, n + t + "public bool CreateIfNotExists()");
                dcLines.Insert(i++, n + t + "{");
                dcLines.Insert(i++, n + T(2) + "bool created = false;");
                dcLines.Insert(i++, n + T(2) + "if (!this.DatabaseExists())");
                dcLines.Insert(i++, n + T(2) + "{");
                dcLines.Insert(i++, n + T(3) + "string[] names = this.GetType().Assembly.GetManifestResourceNames();");
                dcLines.Insert(i++, n + T(3) + "string name = names.Where(n => n.EndsWith(FileName)).FirstOrDefault();");
                dcLines.Insert(i++, n + T(3) + "if (name != null)");
                dcLines.Insert(i++, n + T(3) + "{");
                dcLines.Insert(i++, n + T(4) + "using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name))");
                dcLines.Insert(i++, n + T(4) + "{");
                dcLines.Insert(i++, n + T(5) + "if (resourceStream != null)");
                dcLines.Insert(i++, n + T(5) + "{");
                dcLines.Insert(i++, n + T(6) + "using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())");
                dcLines.Insert(i++, n + T(6) + "{");
                dcLines.Insert(i++, n + T(7) + "using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(FileName, FileMode.Create, myIsolatedStorage))");
                dcLines.Insert(i++, n + T(7) + "{");
                dcLines.Insert(i++, n + T(8) + "using (BinaryWriter writer = new BinaryWriter(fileStream))");
                dcLines.Insert(i++, n + T(8) + "{");
                dcLines.Insert(i++, n + T(9) + "long length = resourceStream.Length;");
                dcLines.Insert(i++, n + T(9) + "byte[] buffer = new byte[32];");
                dcLines.Insert(i++, n + T(9) + "int readCount = 0;");
                dcLines.Insert(i++, n + T(9) + "using (BinaryReader reader = new BinaryReader(resourceStream))");
                dcLines.Insert(i++, n + T(9) + "{");
                dcLines.Insert(i++, n + T(10) + "// read file in chunks in order to reduce memory consumption and increase performance");
                dcLines.Insert(i++, n + T(10) + "while (readCount < length)");
                dcLines.Insert(i++, n + T(10) + "{");
                dcLines.Insert(i++, n + T(11) + "int actual = reader.Read(buffer, 0, buffer.Length);");
                dcLines.Insert(i++, n + T(11) + "readCount += actual;");
                dcLines.Insert(i++, n + T(11) + "writer.Write(buffer, 0, actual);");
                dcLines.Insert(i++, n + T(10) + "}");
                dcLines.Insert(i++, n + T(9) + "}");
                dcLines.Insert(i++, n + T(8) + "}");
                dcLines.Insert(i++, n + T(7) + "}");
                dcLines.Insert(i++, n + T(6) + "}");
                dcLines.Insert(i++, n + T(6) + "created = true;");
                dcLines.Insert(i++, n + T(5) + "}");
                dcLines.Insert(i++, n + T(5) + "else");
                dcLines.Insert(i++, n + T(5) + "{");
                dcLines.Insert(i++, n + T(6) + "this.CreateDatabase();");
                dcLines.Insert(i++, n + T(6) + "created = true;");
                dcLines.Insert(i++, n + T(5) + "}");
                dcLines.Insert(i++, n + T(4) + "}");
                dcLines.Insert(i++, n + T(3) + "}");
                dcLines.Insert(i++, n + T(3) + "else");
                dcLines.Insert(i++, n + T(3) + "{");
                dcLines.Insert(i++, n + T(4) + "this.CreateDatabase();");
                dcLines.Insert(i++, n + T(4) + "created = true;");
                dcLines.Insert(i++, n + T(3) + "}");
                dcLines.Insert(i++, n + T(2) + "}");
                dcLines.Insert(i++, n + T(2) + "return created;");
                dcLines.Insert(i++, n + t + "}");

                dcLines.Insert(i++, n + t + "");
                dcLines.Insert(i++, n + t + "public bool LogDebug");
                dcLines.Insert(i++, n + t + "{");
                dcLines.Insert(i++, n + T(2) + "set");
                dcLines.Insert(i++, n + T(2) + "{");
                dcLines.Insert(i++, n + T(3) + "if (value)");
                dcLines.Insert(i++, n + T(3) + "{");
                dcLines.Insert(i++, n + T(4) + "this.Log = new DebugWriter();");
                dcLines.Insert(i++, n + T(3) + "}");
                dcLines.Insert(i++, n + T(2) + "}");
                dcLines.Insert(i++, n + t + "}");
                dcLines.Insert(i++, n + t + "");
            }

            AddIndexes(repository, dcLines, n, true);
            FixSerialisation(dcLines, n + t, true);

            System.IO.File.WriteAllLines(path, dcLines.ToArray());
        }
Example #52
0
        public static void ModifyCSharpFile(string cs_fullpath, string json_fullpath)
        {
            var name       = Path.GetFileNameWithoutExtension(cs_fullpath);
            var json_asset = GetPathRelatedToProject(json_fullpath).Replace(@"\", "/");
            var lines      = new List <string>(File.ReadAllLines(cs_fullpath));

            lines.RemoveRange(0, 8);
            lines.RemoveRange(lines.Count - 3, 3);
            List <string> types = new List <string>();

            for (int i = 0; i < lines.Count; i++)
            {
                lines[i] = "  " + lines[i];
                if (lines[i].StartsWith("  public class"))
                {
                    var words = lines[i].Split(' ');
                    types.Add(words[words.Length - 1]);
                    lines[i + 1] = lines[i] + " {";
                    lines[i]     = "  [Serializable]";
                    i++;
                }
            }
            lines.Insert(0,
                         "namespace Messiah.JsonData {\n" +
                         "  using System;\n" +
                         "  using System.Threading.Tasks;\n" +
                         "  using System.Collections.Generic;\n" +
                         "  using UnityEngine;\n" +
                         "  using UnityEngine.AddressableAssets;\n");
            lines.Add(
                "\n" +
                "  [Serializable]\n" +
                "  public class " + name + " {"
                );
            foreach (var type in types)
            {
                lines.Add($"    public {type}[] {type};");
            }
            lines.Add(
                "  }\n" +
                "\n" +
                "  public static class " + name + "JsonData {\n" +
                "    static " + name + " " + name + ";\n" +
                "\n" +
                "    public static async Task Load() {\n" +
                "      var textAsset = await Addressables.LoadAssetAsync<TextAsset>(\"" + json_asset + "\").Task;\n" +
                "      " + name + " = JsonUtility.FromJson<" + name + ">(textAsset.text);\n");
            foreach (var type in types)
            {
                lines.Add(
                    $"      {type}Dic = new Dictionary<int, {type}>();\n" +
                    $"      foreach (var entry in {name}.{type})\n" +
                    $"        {type}Dic[entry.ID] = entry;\n"
                    );
            }
            lines.Add(
                $"      {name} = null;\n" +
                "    }\n" +
                "\n" +
                "    public static void UnLoad() {");
            foreach (var type in types)
            {
                lines.Add($"      {type}Dic = null;");
            }
            lines.Add("    }");

            foreach (var type in types)
            {
                lines.Add(
                    $"\n    static Dictionary<int, {type}> {type}Dic;\n" +
                    $"    public static {type} Get{type}(int ID) {{ return {type}Dic[ID]; }}"
                    );
            }

            lines.Add(
                "  }\n" +
                "}");
            File.WriteAllLines(cs_fullpath, lines);
        }
Example #53
0
        public void Update()
        {
            if (!Valid)
            {
                return;
            }

            if (nextUpdate < Interface.Oxide.Now)
            {
                RedrawInputLine();
                nextUpdate = Interface.Oxide.Now + 0.5f;
            }
            try
            {
                if (!Console.KeyAvailable)
                {
                    return;
                }
            }
            catch (Exception)
            {
                return;
            }
            ConsoleKeyInfo consoleKeyInfo = Console.ReadKey();

            if (consoleKeyInfo.Key != ConsoleKey.DownArrow && consoleKeyInfo.Key != ConsoleKey.UpArrow)
            {
                inputHistoryIndex = 0;
            }

            switch (consoleKeyInfo.Key)
            {
            case ConsoleKey.Enter:
                ClearLine(Interface.Oxide.Config.Console.ShowStatusBar ? StatusTextLeft.Length : 1);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(string.Concat("> ", inputString));
                inputHistory.Insert(0, inputString);
                if (inputHistory.Count > 50)
                {
                    inputHistory.RemoveRange(50, inputHistory.Count - 50);
                }

                string str = inputString;
                inputString = string.Empty;
                OnInputText?.Invoke(str);
                RedrawInputLine();
                return;

            case ConsoleKey.Backspace:
                if (inputString.Length < 1)
                {
                    return;
                }

                inputString = inputString.Substring(0, inputString.Length - 1);
                RedrawInputLine();
                return;

            case ConsoleKey.Escape:
                inputString = string.Empty;
                RedrawInputLine();
                return;

            case ConsoleKey.UpArrow:
                if (inputHistory.Count == 0)
                {
                    return;
                }

                if (inputHistoryIndex < 0)
                {
                    inputHistoryIndex = 0;
                }

                if (inputHistoryIndex >= inputHistory.Count - 1)
                {
                    inputHistoryIndex = inputHistory.Count - 1;
                    inputString       = inputHistory[inputHistoryIndex];
                    RedrawInputLine();
                    return;
                }
                inputString = inputHistory[inputHistoryIndex++];
                RedrawInputLine();
                return;

            case ConsoleKey.DownArrow:
                if (inputHistory.Count == 0)
                {
                    return;
                }

                if (inputHistoryIndex >= inputHistory.Count - 1)
                {
                    inputHistoryIndex = inputHistory.Count - 2;
                }

                inputString = inputHistoryIndex < 0 ? string.Empty : inputHistory[inputHistoryIndex--];
                RedrawInputLine();
                return;

            case ConsoleKey.Tab:
                string[] results = Completion?.Invoke(inputString);
                if (results == null || results.Length == 0)
                {
                    return;
                }

                if (results.Length > 1)
                {
                    ClearLine(Interface.Oxide.Config.Console.ShowStatusBar ? StatusTextLeft.Length + 1 : 1);
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    int lowestDiff = results.Max(r => r.Length);
                    for (int index = 0; index < results.Length; index++)
                    {
                        string result = results[index];
                        if (index > 0)
                        {
                            int diff = GetFirstDiffIndex(results[0], result);
                            if (diff > 0 && diff < lowestDiff)
                            {
                                lowestDiff = diff;
                            }
                        }
                        Console.WriteLine(result);
                    }
                    if (lowestDiff > 0)
                    {
                        inputString = results[0].Substring(0, lowestDiff);
                    }

                    RedrawInputLine();
                    return;
                }
                inputString = results[0];
                RedrawInputLine();
                return;
            }
            if (consoleKeyInfo.KeyChar == 0)
            {
                return;
            }

            inputString = string.Concat(inputString, consoleKeyInfo.KeyChar);
            RedrawInputLine();
        }
Example #54
0
        /// <summary>
        /// The token list will be edited in-place as handlers are able to deal with the content, so the input list should expect to be mutated
        /// </summary>
        public override ICodeBlock Process(List <IToken> tokens)
        {
            if (tokens == null)
            {
                throw new ArgumentNullException("tokens");
            }

            bool includesCallKeyword;
            int  numberOfKeywordTokens;

            if (base.checkAtomTokenPattern(tokens, new[] { "CALL", "ERASE" }, false))
            {
                includesCallKeyword   = true;
                numberOfKeywordTokens = 2;
            }
            else if (base.checkAtomTokenPattern(tokens, new[] { "ERASE" }, false))
            {
                includesCallKeyword   = false;
                numberOfKeywordTokens = 1;
            }
            else
            {
                return(null);
            }

            // Note: getEntryList will return a list of lists of tokens, where there will be multiple lists if there are multiple comma-separated expressions. Each
            // of these token sets needs to be wrapped in an Expression to initialise an EraseStatement. VBScript only works with a single target that is an array,
            // if there are zero or multiple targets then it will fail at runtime (but it's not a compile error so it's not an error case here).
            // - If the CALL keyword is present, then valid VBScript will have wrapped the argument(s) in brackets which will need stripping and then the arguments
            //   re-parsing. The getEntryList function will throw an exception if arguments are mismatched, indicating invalid VBScript. The translation process
            //   relies upon the source code not having any VBScript compile errors (in some places it tries to be helpful with explaining where there would be
            //   compile failures in the VBScript interpreter and in other places - like here - it pretty much just assume valid content.
            int numberOfTokensConsumedInStatement;
            IEnumerable <Tuple <EraseStatement.TargetDetails, int> > targetDetails;

            if (tokens.Count == numberOfKeywordTokens)
            {
                // It's a runtime error if there is an ERASE statement with no targets. But if it's the last statement then there may not be any more tokens to
                // consume - if so, don't try to look ahead!
                numberOfTokensConsumedInStatement = numberOfKeywordTokens;
                targetDetails = new Tuple <EraseStatement.TargetDetails, int> [0];
            }
            else
            {
                var targetExpressionsTokenSets = base.getEntryList(tokens, offset: numberOfKeywordTokens, endMarker: new EndOfStatementNewLineToken(tokens.First().LineIndex));
                if (includesCallKeyword)
                {
                    if (targetExpressionsTokenSets.Count != 1)
                    {
                        throw new Exception("Expected only a single argument token set to have been extracted when CALL is present, since brackets should have wrapped all argument(s) in valid VBScript");
                    }
                    var argumentTokens = targetExpressionsTokenSets[0];
                    var terminator     = new EndOfStatementNewLineToken(argumentTokens.Last().LineIndex);
                    targetExpressionsTokenSets = base.getEntryList(
                        argumentTokens.Skip(1).Take(argumentTokens.Count - 2).Concat(new[] { terminator }),
                        0,
                        terminator
                        );
                }
                targetDetails = targetExpressionsTokenSets.Select(targetTokens => GetTargetExpressionDetailsWithNumberOfTokensConsumed(targetTokens));
                numberOfTokensConsumedInStatement =
                    /* The keyword token(s) */ numberOfKeywordTokens +
                    /* The individual target expressions tokens */ targetDetails.Sum(tokenSet => tokenSet.Item2) +
                    /* Any argument separaters between target expressions */ (targetExpressionsTokenSets.Count - 1) +
                    /* Any extra brackets we removed due to CALL being present */ (includesCallKeyword ? 2 : 0);
            }
            var keywordLineIndex = tokens[0].LineIndex;

            tokens.RemoveRange(0, numberOfTokensConsumedInStatement);
            if (tokens.Any())
            {
                // When getEntryList was first called, it may have returned content when it hit an end-of-statement or when there were no more tokens to consume
                // (so long as the tokens it DID consume were valid and no brackets were mismatched - otherwise it would have thrown an exception). If it was the
                // end of the content then there will be nothing to remove after the tokens occupied by this statement. If it was an end-of-statement token then
                // we need to remove that too since we've effectively processed it.
                tokens.RemoveAt(0);
            }
            return(new EraseStatement(
                       targetDetails.Select(t => t.Item1),
                       keywordLineIndex
                       ));
        }
 public ArrayOfPoints splice(int startIndex, int deleteCount)
 {
     values.RemoveRange(startIndex, deleteCount);
     return(this);
 }
Example #56
0
        /* OMG THIS CODE IS COMPLICATED
         *
         * Here's the core idea. We want to create a ReadAsync function that
         * reads from our list of byte arrays **until it gets to the end of
         * our current list**.
         *
         * If we're not there yet, we keep returning data, serializing access
         * to the underlying position pointer (i.e. we definitely don't want
         * people concurrently moving position along). If we try to read past
         * the end, we return the section of data we could read and complete
         * it.
         *
         * Here's where the tricky part comes in. If we're not Completed (i.e.
         * the caller still wants to add more byte arrays in the future) and
         * we're at the end of the current stream, we want to *block* the read
         * (not blocking, but async blocking whatever you know what I mean),
         * until somebody adds another byte[] to chew through, or if someone
         * rewinds the position.
         *
         * If we *are* completed, we should return zero to simply complete the
         * read, signalling we're at the end of the stream */
        public override async Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
retry:
            int bytesRead = 0;
            int buffersToRemove = 0;

            if (isCompleted && position == maxLength)
            {
                return(0);
            }

            if (exception != null)
            {
                throw exception;
            }

            using (await readStreamLock.LockAsync().ConfigureAwait(false)) {
                lock (bytes) {
                    foreach (var buf in bytes)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        if (exception != null)
                        {
                            throw exception;
                        }

                        int toCopy = Math.Min(count, buf.Length - offsetInCurrentBuffer);
                        Array.ConstrainedCopy(buf, offsetInCurrentBuffer, buffer, offset, toCopy);

                        count     -= toCopy;
                        offset    += toCopy;
                        bytesRead += toCopy;

                        offsetInCurrentBuffer += toCopy;

                        if (offsetInCurrentBuffer >= buf.Length)
                        {
                            offsetInCurrentBuffer = 0;
                            buffersToRemove++;
                        }

                        if (count <= 0)
                        {
                            break;
                        }
                    }

                    // Remove buffers that we read in this operation
                    bytes.RemoveRange(0, buffersToRemove);

                    position += bytesRead;
                }
            }

            // If we're at the end of the stream and it's not done, prepare
            // the next read to park itself unless AddByteArray or Complete
            // posts
            if (position >= maxLength && !isCompleted)
            {
                lockRelease = await readStreamLock.LockAsync().ConfigureAwait(false);
            }

            if (bytesRead == 0 && !isCompleted)
            {
                // NB: There are certain race conditions where we somehow acquire
                // the lock yet are at the end of the stream, and we're not completed
                // yet. We should try again so that we can get stuck in the lock.
                goto retry;
            }

            if (cancellationToken.IsCancellationRequested)
            {
                Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose();
                cancellationToken.ThrowIfCancellationRequested();
            }

            if (exception != null)
            {
                Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose();
                throw exception;
            }

            if (isCompleted && position < maxLength)
            {
                // NB: This solves a rare deadlock
                //
                // 1. ReadAsync called (waiting for lock release)
                // 2. AddByteArray called (release lock)
                // 3. AddByteArray called (release lock)
                // 4. Complete called (release lock the last time)
                // 5. ReadAsync called (lock released at this point, the method completed successfully)
                // 6. ReadAsync called (deadlock on LockAsync(), because the lock is block, and there is no way to release it)
                //
                // Current condition forces the lock to be released in the end of 5th point

                Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose();
            }

            return(bytesRead);
        }
Example #57
0
        /// commands that can be automatically dispatched look like this:
        /// COMMANDNAME OBJECTNAME <param> <param> <param> ...

        /** We can dispatch this command if:
         * 1. it has at least 2 words
         * 2. the second word is the name of an object
         * 3. that object has components that have methods with the YarnCommand attribute that have the correct commandString set
         */
        public IEnumerator DispatchCommand(string command, System.Action <bool> hasValidCommand)
        {
            var words = command.Split(' ');

            // need 2 parameters in order to have both a command name
            // and the name of an object to find
            if (words.Length < 2)
            {
                hasValidCommand(false);
                yield break;
            }

            var commandName = words[0];

            var objectName = words[1];

            var sceneObject = GameObject.Find(objectName);

            // If we can't find an object, we can't dispatch a command
            if (sceneObject == null)
            {
                hasValidCommand(false);
                yield break;
            }

            int             numberOfMethodsFound = 0;
            List <string[]> errorValues          = new List <string[]>();

            List <string> parameters;

            if (words.Length > 2)
            {
                parameters = new List <string>(words);
                parameters.RemoveRange(0, 2);
            }
            else
            {
                parameters = new List <string>();
            }

            // Find every MonoBehaviour (or subclass) on the object
            foreach (var component in sceneObject.GetComponents <MonoBehaviour>())
            {
                var type = component.GetType();

                // Find every method in this component
                foreach (var method in type.GetMethods())
                {
                    // Find the YarnCommand attributes on this method
                    var attributes = (YarnCommandAttribute[])method.GetCustomAttributes(typeof(YarnCommandAttribute), true);

                    // Find the YarnCommand whose commandString is equal to the command name
                    foreach (var attribute in attributes)
                    {
                        if (attribute.commandString == commandName)
                        {
                            var  methodParameters = method.GetParameters();
                            bool paramsMatch      = false;
                            // Check if this is a params array
                            if (methodParameters.Length == 1 && methodParameters[0].ParameterType.IsAssignableFrom(typeof(string[])))
                            {
                                // Cool, we can send the command!
                                // Yield if this is a Coroutine
                                string[][] paramWrapper = new string[1][];
                                paramWrapper[0] = parameters.ToArray();
                                if (method.ReturnType == typeof(IEnumerator))
                                {
                                    yield return(StartCoroutine((IEnumerator)method.Invoke(component, paramWrapper)));
                                }
                                else
                                {
                                    method.Invoke(component, paramWrapper);
                                }
                                numberOfMethodsFound++;
                                paramsMatch = true;
                            }
                            // Otherwise, verify that this method has the right number of parameters
                            else if (methodParameters.Length == parameters.Count)
                            {
                                paramsMatch = true;
                                foreach (var paramInfo in methodParameters)
                                {
                                    if (!paramInfo.ParameterType.IsAssignableFrom(typeof(string)))
                                    {
                                        Debug.LogErrorFormat(sceneObject, "Method \"{0}\" wants to respond to Yarn command \"{1}\", but not all of its parameters are strings!", method.Name, commandName);
                                        paramsMatch = false;
                                        break;
                                    }
                                }
                                if (paramsMatch)
                                {
                                    // Cool, we can send the command!
                                    // Yield if this is a Coroutine
                                    if (method.ReturnType == typeof(IEnumerator))
                                    {
                                        yield return(StartCoroutine((IEnumerator)method.Invoke(component, parameters.ToArray())));
                                    }
                                    else
                                    {
                                        method.Invoke(component, parameters.ToArray());
                                    }
                                    numberOfMethodsFound++;
                                }
                            }
                            //parameters are invalid, but name matches.
                            if (!paramsMatch)
                            {
                                //save this error in case a matching command is never found.
                                errorValues.Add(new string[] { method.Name, commandName, methodParameters.Length.ToString(), parameters.Count.ToString() });
                            }
                        }
                    }
                }
            }

            // Warn if we found multiple things that could respond
            // to this command.
            if (numberOfMethodsFound > 1)
            {
                Debug.LogWarningFormat(sceneObject, "The command \"{0}\" found {1} targets. " +
                                       "You should only have one - check your scripts.", command, numberOfMethodsFound);
            }
            else if (numberOfMethodsFound == 0)
            {
                //list all of the near-miss methods only if a proper match is not found, but correctly-named methods are.
                foreach (string[] errorVal in errorValues)
                {
                    Debug.LogErrorFormat(sceneObject, "Method \"{0}\" wants to respond to Yarn command \"{1}\", but it has a different number of parameters ({2}) to those provided ({3}), or is not a string array!", errorVal[0], errorVal[1], errorVal[2], errorVal[3]);
                }
            }

            hasValidCommand(numberOfMethodsFound > 0);
        }
 public static List <T> removeRange <T>(this List <T> list, int start, int end)
 {
     list.RemoveRange(start, end);
     return(list);
 }
Example #59
0
        public static List <T>[] PartitionsBySize <T>(List <T> list, int size, bool shift = false)
        {
            if (list == null)
            {
                throw new ArgumentNullException("list");
            }

            if (size < 1)
            {
                throw new ArgumentOutOfRangeException("totalPartitions");
            }


            if (shift)
            {
                int half = (int)(size * 0.5);

                var start = list.GetRange(0, half).ToList();
                list.RemoveRange(0, half);

                int        count      = (int)Math.Ceiling(list.Count / (double)size);
                List <T>[] partitions = new List <T> [count + 1];
                partitions[0] = start;

                int k = 0;
                for (int i = 0; i < partitions.Length - 1; i++)
                {
                    partitions[i + 1] = new List <T>(size);
                    for (int j = k; j < k + size; j++)
                    {
                        if (j >= list.Count)
                        {
                            break;
                        }
                        partitions[i + 1].Add(list[j]);
                    }
                    k += size;
                }

                return(partitions);
            }
            else
            {
                int        count      = (int)Math.Ceiling(list.Count / (double)size);
                List <T>[] partitions = new List <T> [count];

                int k = 0;
                for (int i = 0; i < partitions.Length; i++)
                {
                    partitions[i] = new List <T>(size);
                    for (int j = k; j < k + size; j++)
                    {
                        if (j >= list.Count)
                        {
                            break;
                        }
                        partitions[i].Add(list[j]);
                    }
                    k += size;
                }

                return(partitions);
            }
        }
Example #60
0
 /// <summary>
 /// Trims the pool to a maximum number of objects.
 /// </summary>
 /// <param name="max">Max objects.</param>
 public void Trim(int max)
 {
     m_free.RemoveRange(0, Mathf.Min(m_free.Count, max));
 }