Example #1
0
        static void Main()
        {
            int number = 10;
            Random rand = new Random();
            List<int> myList = new List<int>();
            List<int> resultList = new List<int>();
            for (int i = 0; i < number; i++)
            {
                myList.Add(rand.Next(1, number));
            }

            foreach (var item in myList)
            {
                Console.WriteLine(item);
            }

            myList.Sort();

            Console.WriteLine("Sorted List");
            foreach (var item in myList)
            {
                Console.WriteLine(item);
            }

            int index = 0;
            int curr = myList[index];
            int counter = 0;
            Console.WriteLine(myList.LastIndexOf(curr) + "{0}", 1 / 2);

            while (index < myList.Count)
            {
                curr = myList[index];
                counter = (myList.LastIndexOf(curr) - index) + 1;
                
                if (((counter % 2) == 0) && (counter != 1))
                {
                    Console.WriteLine("in");
                    for (int i = 1; i <= counter; i++)
                    {
                        resultList.Add(curr);

                    }
                }
                index = myList.LastIndexOf(curr) + 1;


            }

            foreach (var item in resultList)
            {
                Console.WriteLine(item);
            }

        }
        private List<String> ParseParentheses(List<String> tokens)
        {
            int openingParenthesesIndex = tokens.LastIndexOf(Operators.OPEN_PARENTHESES);

            while (openingParenthesesIndex >= 0)
            {
                int closingParenthesesIndex = tokens.IndexOf(Operators.CLOSE_PARENTHESES);

                tokens = Unwind(tokens, openingParenthesesIndex, closingParenthesesIndex);

                openingParenthesesIndex = tokens.LastIndexOf(Operators.OPEN_PARENTHESES);
            }

            return tokens;
        }
Example #3
0
        static void Main(string[] args)
        {
            //creating a list
            var numbers = new List<int>() { 1, 2, 3, 4 };
            numbers.Add(1);
            numbers.AddRange(new int[3] { 5, 6, 7 });

            foreach (var number in numbers)
                Console.WriteLine(number);

            Console.WriteLine();
            Console.WriteLine("Index of 1: " + numbers.IndexOf(1));
            Console.WriteLine("Last Index of 1: " + numbers.LastIndexOf(1));

            Console.WriteLine("Count: " + numbers.Count);

            for (int i = 0; i < numbers.Count; i++)
            {
                if (numbers[i] == 1)
                    numbers.Remove(numbers[i]);
            }

            foreach (var number in numbers)
                Console.WriteLine(number);

            numbers.Clear();
            Console.WriteLine("Count: " + numbers.Count);
        }
Example #4
0
 /// <summary>
 /// Beginning at the end, of the set, return all elements until the element after the element which satifies the condition [stopAt]
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="orderedSet"></param>
 /// <param name="stopAt"></param>
 /// <returns></returns>
 static IEnumerable<TestBuilder> Filter(List<TestBuilder> orderedSet, Func<TestBuilder, bool> stopAt)
 {
     var first = orderedSet.LastOrDefault(stopAt);
     return first == null ?
         orderedSet :
         orderedSet.Skip(orderedSet.LastIndexOf(first));
 }
Example #5
0
        static void Main(string[] args)
        {
            List<String> nomes = new List<String>() { "epaminondas", "eva", "chico", "tião", "eva" };

            List<String> outrosNomes = new List<String>() { "adão", "eva", "agnaldo" };

            Console.WriteLine("quantidade de elementos: {0}", nomes.Count);
            Console.WriteLine("posição da 1a. \"eva\" dentro da lista: {0}", nomes.IndexOf("eva"));
            Console.WriteLine("posição da última \"eva\" dentro da lista: {0}", nomes.LastIndexOf("eva"));

            Console.WriteLine();

            nomes.Remove("chico");

            nomes.RemoveAll(x => x.Contains('e'));

            nomes.AddRange(outrosNomes);

            foreach (var item in nomes)
            {
                Console.WriteLine(item);
            }

            nomes.Sort();

            nomes.ForEach(new Action<string>(Imprimir));

            Console.ReadKey();
        }
Example #6
0
    public bool PosTest2()
    {
        bool retVal = true;

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

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

        return retVal;
    }
        public static int SpanNumber(List<int> inputNumbers)
        {
            List<int> spanNumbers = new List<int>();
            for (int i = 0; i < inputNumbers.Count; i++)
            {
                if (inputNumbers.LastIndexOf(inputNumbers[i]) >= 0)
                {
                    int span = (inputNumbers.LastIndexOf(inputNumbers[i]) - i) + 1;
                    spanNumbers.Add(span);
                }
            }

            spanNumbers.Sort((a, b) => -1 * a.CompareTo(b));

            return spanNumbers[0];
        }
Example #8
0
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: The generic type is int");

        try
        {
            int[] iArray = new int[1000];
            for (int i = 0; i < 1000; i++)
            {
                iArray[i] = i;
            }
            List<int> listObject = new List<int>(iArray);
            int ob = this.GetInt32(0, 1000);
            int result = listObject.LastIndexOf(ob);
            if (result != ob)
            {
                TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,result is: " + result);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
        public string Eval()
        {
            decimal result = 0;
            int position;
            string resultString = "";

            foreach (string line in File.ReadLines("C:\\users\\skornish\\Desktop\\prefix.txt"))
            {
                List<string> list = new List<string>(line.Split(' '));
                while (list.Contains("+") ||
                       list.Contains("-") ||
                       list.Contains("/") ||
                       list.Contains("*"))
                {
                    position = 0;
                    foreach (string element in list)
                    {
                        if (element.Equals("+") ||
                            element.Equals("-") ||
                            element.Equals("/") ||
                            element.Equals("*"))
                        {
                            position = Math.Max(position, list.LastIndexOf(element));
                        }
                    }

                    if (list.ElementAt(position).Equals("+"))
                    {
                        result = decimal.Parse(list.ElementAt(position + 1)) +
                                 decimal.Parse(list.ElementAt(position + 2));
                    }
                    else if (list.ElementAt(position).Equals("-"))
                    {
                        result = decimal.Parse(list.ElementAt(position + 1)) -
                                 decimal.Parse(list.ElementAt(position + 2));
                    }
                    else if (list.ElementAt(position).Equals("/"))
                    {
                        result = decimal.Parse(list.ElementAt(position + 1)) /
                                 decimal.Parse(list.ElementAt(position + 2));
                    }
                    else if (list.ElementAt(position).Equals("*"))
                    {
                        result = decimal.Parse(list.ElementAt(position + 1)) *
                                 decimal.Parse(list.ElementAt(position + 2));
                    }
                    list.Insert(position, result.ToString());
                    list.RemoveAt(position + 3);
                    list.RemoveAt(position + 2);
                    list.RemoveAt(position + 1);
                }
                resultString = resultString + "," + result.ToString();
            }

            MessageBox.Show(resultString);
            return resultString;
        }
Example #10
0
        static void Main(string[] args)
        {
            List<int> MyList = new List<int>();

            string l = Console.ReadLine();

            while (l != string.Empty)
            {

                MyList.Add(int.Parse(l));

                l = Console.ReadLine();
            }

            MyList.Sort();

            int index = 0;

            int curr = 0;

            bool isMajorant = false;

            while (index < MyList.Count)
            {
                curr = MyList[index];

                int counter = MyList.LastIndexOf(curr) - index + 1;

                if (counter > (MyList.Count / 2))
                {
                    Console.WriteLine("The majorant is: {0} -> {1} times", curr, counter);

                    isMajorant = true;
                }

                index = MyList.LastIndexOf(curr) + 1;

            }

            if (!isMajorant)
            {
                Console.WriteLine("The majorant does't exist");
            }
        }
Example #11
0
        static void Main()
        {
            int number = 1000;

            Random rand = new Random();
            List<int> myList = new List<int>();
            int[] countingArr = new int[number];

            for (int i = 0; i < 30; i++)
            {
                myList.Add(rand.Next(0, 30));
            }

            myList.Sort();

            int index = 0;
            int curr = myList[index];

            while (index < myList.Count)
            {
                curr = myList[index];
                int counter = myList.LastIndexOf(curr) - index + 1;
                countingArr[index] = counter;

                index = myList.LastIndexOf(curr) + 1;

            }

            for (int i = 0; i < countingArr.Length; i++)
            {
                if (countingArr[i] > 0)
                {
                    Console.WriteLine("Number {0} -> {1}", i, countingArr[i]);
                }
            }

            //foreach (var item in countingArr)
            //{
            //    if (item > 0)
            //    {
            //        Console.WriteLine("Number {0} -> {1}", Array.IndexOf(countingArr, item), item);
            //    }
            //}
        }
Example #12
0
        public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
        {
            ValidateArguments(arguments, 2);
            var number = ArgToDecimal(arguments, 0);
            var refer = arguments.ElementAt(1);
            bool asc = false;
            if (arguments.Count() > 2)
            {
                asc = base.ArgToBool(arguments, 2);
            }
            var l = new List<double>();

            foreach (var c in refer.ValueAsRangeInfo)
            {
                var v = Utils.ConvertUtil.GetValueDouble(c.Value, false, true);
                if (!double.IsNaN(v))
                {
                    l.Add(v);
                }
            }
            l.Sort();
            double ix;
            if (asc)
            {
                ix = l.IndexOf(number)+1;
                if(_isAvg)
                {
                    int st = Convert.ToInt32(ix);
                    while (l.Count > st && l[st] == number) st++;
                    if (st > ix) ix = ix + ((st - ix) / 2D);
                }
            }
            else
            {
                ix = l.LastIndexOf(number);
                if (_isAvg)
                {
                    int st = Convert.ToInt32(ix)-1;
                    while (0 <= st && l[st] == number) st--;
                    if (st+1 < ix) ix = ix - ((ix - st - 1) / 2D);
                }
                ix = l.Count - ix;
            }
            if (ix <= 0 || ix>l.Count)
            {
                return new CompileResult(ExcelErrorValue.Create(eErrorType.NA), DataType.ExcelError);
            }
            else
            {
                return CreateResult(ix, DataType.Decimal);
            }
        }
Example #13
0
        static void Main()
        {
            int number = 10;

            Random rand = new Random();
            List<int> myList = new List<int>();
            List<int> resultList = new List<int>();
            for (int i = 0; i < number; i++)
            {
                myList.Add(rand.Next(1, number));
            }

            foreach (var item in myList)
            {
                Console.WriteLine(item);
            }

            myList.Sort();

            Console.WriteLine("Sorted List");
            foreach (var item in myList)
            {
                Console.WriteLine(item);
            }
            int index = 0;
            int curr = myList[index];

            while (index < myList.Count)
            {
                curr = myList[index];
                var newL = myList.FindAll(i => i.Equals(curr));
                if ((newL.Count % 2) == 0)
                {
                    foreach (var item1 in newL)
                    {
                        resultList.Add(item1);
                    }
                }

                newL.Clear();
                index = myList.LastIndexOf(curr) + 1;
            } 

            Console.WriteLine("Result list");
            foreach (var a in resultList)
            {
                Console.WriteLine(a);
            }


        }
Example #14
0
        static void Main()
        {
            List<int> myList = new List<int>();
            string line = Console.ReadLine();

            while (line != string.Empty)
            {

                myList.Add(int.Parse(line));
                line = Console.ReadLine();
            }

            myList.Sort();
            int index = 0;
            int curr = 0;
            bool isMajorant = false;

            while (index < myList.Count)
            {
                curr = myList[index];
                int counter = myList.LastIndexOf(curr) - index + 1;
                if (counter > (myList.Count /2))
                {
                    Console.WriteLine("The majorant is: {0} -> {1} times", curr, counter);
                    isMajorant = true;
                }
                

                index = myList.LastIndexOf(curr) + 1;

            }

            if (!isMajorant)
            {
                Console.WriteLine("The majorant does not exists!");
            }

        }
Example #15
0
        static void Main(string[] args)
        {
            int n = 1000;

            Random rand = new Random();
            List<int> List = new List<int>();
            int[] countingArr = new int[n];

            for (int i = 0; i < 30; i++)
            {
                List.Add(rand.Next(0, 30));
            }

            List.Sort();

            int index = 0;
            int curr = List[index];

            while (index < List.Count)
            {
                curr = List[index];
                int counter = List.LastIndexOf(curr) - index + 1;
                countingArr[index] = counter;

                index = List.LastIndexOf(curr) + 1;

            }

            for (int i = 0; i < countingArr.Length; i++)
            {
                if (countingArr[i] > 0)
                {
                    Console.WriteLine("Number {0} -> {1}", i, countingArr[i]);
                }
            }
        }
        /// <summary>
        /// Finds the biggest span between a leftmost and rightmost appearance of some value.
        /// </summary>
        /// <param name="numbers">List input.</param>
        /// <returns>Biggest span.</returns>
        public static int MaxSpan(List<int> numbers)
        {
            List<int> spanCounters = new List<int>();
            for (int i = 0; i < numbers.Count; i++)
            {
                int lastindexof = numbers.LastIndexOf(numbers[i]);
                if (lastindexof != -1)
                {
                    var spanCounter = (lastindexof - i) + 1;
                    spanCounters.Add(spanCounter);
                }
            }

            spanCounters.Sort((a, b) => -1 * a.CompareTo(b));
            return spanCounters[0];
        }
Example #17
0
    public static List<int> addJump(List<int> path, int n)
    {
        var position = path.LastIndexOf((int)Way.step);

        if (position < 0)
        {
            return null;
        }

        path[position] = (int)Way.jump;

        if (position > 0)
        {
            path.RemoveAt(position - 1);
        }

        return path.Sum() == n ? path : null;
    }
Example #18
0
        static List<string> Reorder(string[] words)
        {
            List<string> listOfWords = new List<string>(words);

            for (int i = 0; i < listOfWords.Count; i++)
            {
                string currentWord = listOfWords[i];
                int position = (currentWord.Length % (words.Length + 1));
                listOfWords.Insert(position, currentWord);
                if (position > i)
                {
                    listOfWords.RemoveAt(listOfWords.IndexOf(currentWord));
                }
                else
                {
                    listOfWords.RemoveAt(listOfWords.LastIndexOf(currentWord));
                }
            }
            return listOfWords;
        }
Example #19
0
 // this solution borrows heavily from solutions proposed by others
 public string Run()
 {
     int max = 0;
     int maxCycleLen = 0;
     List<int> remainders;
     for (int i = 983; i < 1000; i++)
     {
         int r = 10, count;
         remainders = new List<int>();
         for (count = 0; !remainders.Contains(r); count++)
         {
             remainders.Add(r);
             r = 10 * (r % i);
         }
         int cycleLen = count - remainders.LastIndexOf(r);
         if (cycleLen > maxCycleLen)
         {
             maxCycleLen = cycleLen;
             max = i;
         }
     }
     return max.ToString();
 }
Example #20
0
        private void tsmiCViewInCrawlResultView_Click(object sender, EventArgs e)
        {
            List<int> rowIndices = new List<int>();
            foreach (DataGridViewCell cell in this.dgvContent.SelectedCells) {
                int rowIndex = cell.RowIndex;
                if(rowIndices.LastIndexOf(rowIndex) < 0){
                    rowIndices.Add(rowIndex);
                }
            }
            rowIndices.Sort();

            List<GContentClass> conts = new List<GContentClass>();
            foreach (int idx in rowIndices) {
                DataGridViewRow dgvRow = this.dgvContent.Rows[idx];
                DataRowView drv = dgvRow.DataBoundItem as DataRowView;
                if(drv == null) continue;
                GDataSet.GContentRow row = drv.Row as GDataSet.GContentRow;
                GContentClass cont;
                if (Program.CacheController.TryFindContent(row.ContentKey, out cont)) {
                    conts.Add(cont);
                }
            }
            Program.AddVirtualGenre(new SimpleContentsVirtualGenre(conts, "キャッシュビューア", "キャッシュビューアからの書き出し" + Environment.NewLine + DateTime.Now.ToString()));
        }
        public HttpResponseMessage SpecBuild(int id,  JObject moveTaskParams)
        {
            dynamic json = moveTaskParams;
            string jsonString = Convert.ToString(json.data);
            var response = Request.CreateResponse();
            List<CategoryViewModel> jCategory = (List<CategoryViewModel>)javaScriptSerializ­er.Deserialize(jsonString, typeof(List<CategoryViewModel>));

            //Iterate through data list collection
            List <List <string>> propNames = new List<List<string>>();
            List<List<string>> propParamsVal = new List<List<string>>();
            List<string> propLabel = new List<string>();
            List<string> propValues = new List<string>();
            List<string> propParams = new List<string>();
            List<string> propMathsParams = new List<string>();
            List<string> propInputParams = new List<string>();
            int LoopCounter = 0;
            LoopCounter = 0;

            foreach (var item in jCategory)
            {
                //
                LoopCounter = 0;
                propValues.Add(item.Name);
                propValues.Add(item.Description);
                propNames.Add(propValues);
                propValues = new List<string>();

                foreach (var list in item.Functions)
                {
                    //Propoerties for the row
                    LoopCounter = LoopCounter + 1;
                    propValues.Add(Convert.ToString(list.ID));
                    propValues.Add(Convert.ToString(list.Name));
                    propValues.Add(Convert.ToString(list.Function));
                    propValues.Add(Convert.ToString(list.Type));

                    //Logic string
                    List<string> logicString = new List<string>();
                    foreach (var logicvar in list.Logic)
                    {
                        logicString.Add(Convert.ToString(logicvar.Bracket1 + " " + logicvar.Input1 + " "
                            + " " + logicvar.LogicInd + " " + logicvar.Input2 + " " + logicvar.Bracket2 + " " + logicvar.Operator));
                    }

                    StringBuilder builderLogic = new StringBuilder();
                    foreach (var logiclevel in logicString)
                    {
                        // Append each int to the StringBuilder overload.
                        builderLogic.Append(logiclevel).Append(" ");
                    }
                    //Add row
                    propValues.Add(Convert.ToString(builderLogic));

                    //Functions
                    if (list.Function != "Input")
                    {
                        if(list.Function == "Maths")
                        {
                            //Maths string builder
                            List<string> mathString = new List<string>();
                            foreach (var Mathvar in list.Parameter)
                            {
                                Maths MathsObject = new Maths();
                                foreach (var MathvarLevel in Mathvar)
                                {
                                    if(MathvarLevel.Key == "Bracket1")
                                    {
                                        MathsObject.Bracket1 = MathvarLevel.Value;
                                    }
                                    else if (MathvarLevel.Key == "Input1")
                                    {
                                        MathsObject.Input1 = MathvarLevel.Value;
                                    }
                                    else if (MathvarLevel.Key == "Logic")
                                    {
                                        MathsObject.Logic = MathvarLevel.Value;
                                    }
                                    else if (MathvarLevel.Key == "Input2")
                                    {
                                        MathsObject.Input2 = MathvarLevel.Value;
                                    }
                                    else if (MathvarLevel.Key == "Bracket2")
                                    {
                                        MathsObject.Bracket2 = MathvarLevel.Value;
                                    }
                                    else if (MathvarLevel.Key == "Rounding")
                                    {
                                        if(MathvarLevel.Value != null)
                                        {
                                            MathsObject.Rounding = Convert.ToInt16(MathvarLevel.Value);
                                        }
                                        else
                                        {
                                            MathsObject.Rounding = null;
                                        }
                                    }
                                    else if (MathvarLevel.Key == "RoundingType")
                                    {
                                        MathsObject.RoundingType = MathvarLevel.Value;
                                    }
                                    else if (MathvarLevel.Key == "Logic2")
                                    {
                                        MathsObject.Logic2 = MathvarLevel.Value;
                                    }
                                }
                                //Show maths formula with rounding
                                if(MathsObject.Rounding > 0)
                                {
                                    mathString.Add(Convert.ToString(MathsObject.Bracket1 + "" + MathsObject.Input1 + " "
                                   + MathsObject.Logic + " " + MathsObject.Input2 + "" + MathsObject.Bracket2 + " "
                                   + MathsObject.Rounding + "dp " + MathsObject.RoundingType + " " + MathsObject.Logic2));
                                }
                                else
                                {
                                    mathString.Add(Convert.ToString(MathsObject.Bracket1 + "" + MathsObject.Input1 + " "
                                   + MathsObject.Logic + " " + MathsObject.Input2 + "" + MathsObject.Bracket2 + " "
                                   + MathsObject.Rounding + "" + MathsObject.RoundingType + "" + MathsObject.Logic2));
                                }
                            }
                            StringBuilder MathStringbuilder = new StringBuilder();
                            foreach (var bitmathlevel in mathString)
                            {
                                // Append each int to the StringBuilder overload.
                                MathStringbuilder.Append(bitmathlevel).Append(" ");
                            }
                            //Add to List
                            propValues.Add(Convert.ToString(MathStringbuilder));
                            propMathsParams = new List<string>();
                        }
                        else
                        {
                            foreach (var bit in list.Parameter)
                            {
                                foreach (var bitlevel in bit)
                                {
                                    propParams.Add(Convert.ToString(bitlevel.Key));
                                    propParams.Add(":");
                                    propParams.Add(Convert.ToString(bitlevel.Value));
                                    propParams.Add("~");
                                }
                                propParams.RemoveAt(propParams.LastIndexOf("~"));
                                StringBuilder builder = new StringBuilder();
                                foreach (var bitlevel in propParams)
                                {
                                    // Append each int to the StringBuilder overload.
                                    builder.Append(bitlevel).Append(" ");
                                }
                                propValues.Add(Convert.ToString(builder));
                                propParams = new List<string>();
                            }
                        }
                    }
                    else
                    {
                        foreach(var InputVal in list.Parameter)
                        {
                            foreach(var InputVal1 in InputVal)
                            {
                                if(InputVal1.Key == "templateOptions")
                                {
                                    foreach(var InputVal2 in InputVal1.Value)
                                    {
                                        if(InputVal2.Key != "options")
                                        {
                                            propInputParams.Add(InputVal2.Key);
                                            propInputParams.Add(":");
                                            propInputParams.Add(Convert.ToString(InputVal2.Value));
                                            propInputParams.Add("~");
                                        }
                                    }
                                }
                            }
                        }
                        propInputParams.RemoveAt(propInputParams.LastIndexOf("~"));
                        StringBuilder inputbuilder = new StringBuilder();
                        foreach (var bitlevel2 in propInputParams)
                        {
                            // Append each int to the StringBuilder overload.
                            inputbuilder.Append(bitlevel2).Append(" ");
                        }
                        propValues.Add(Convert.ToString(inputbuilder));
                        propInputParams = new List<string>();
                    }
                    propNames.Add(propValues);
                    propValues = new List<string>();
                }
            }
            response.Content = new StringContent(JsonConvert.SerializeObject(propNames));
            response.StatusCode = HttpStatusCode.OK;
            return response;
        }
Example #22
0
        //Order the {@link #insertions} queue such that we group inserts
        //against the same entity together (without violating constraints).  The
        //original order is generated by cascade order, which in turn is based on
        //the directionality of foreign-keys. So even though we will be changing
        //the ordering here, we need to make absolutely certain that we do not
        //circumvent this FK ordering to the extent of causing constraint
        //violations
        private void SortInsertActions()
        {
            // IMPLEMENTATION NOTES:
            //
            // The main data structure in this ordering algorithm is the 'positionToAction'
            // map. Essentially this can be thought of as an put-ordered map (the problem with
            // actually implementing it that way and doing away with the 'nameList' is that
            // we'd end up having potential duplicate key values).  'positionToAction' maitains
            // a mapping from a position within the 'nameList' structure to a "partial queue"
            // of actions.

            Dictionary<int,List<EntityInsertAction>> positionToAction =
                new Dictionary<int, List<EntityInsertAction>>();
            List<string> nameList = new List<string>();

            while (!(insertions.Count == 0))
            {
                // todo-events : test behaviour
                // in Java they use an implicit cast to EntityInsertAction
                // but it may be not work because the insertions list may contain EntityIdentityInsertAction
                // (I don't like that "goto"too)
                object tempObject = insertions[0];
                insertions.RemoveAt(0);
                EntityInsertAction action = (EntityInsertAction)tempObject;
                string thisEntityName = action.EntityName;

                // see if we have already encountered this entity-name...
                if (!nameList.Contains(thisEntityName))
                {
                    // we have not, so create the proper entries in nameList and positionToAction
                    List<EntityInsertAction> segmentedActionQueue = new List<EntityInsertAction>();
                    segmentedActionQueue.Add(action);
                    nameList.Add(thisEntityName);
                    positionToAction[nameList.IndexOf(thisEntityName)] = segmentedActionQueue;
                }
                else
                {
                    // we have seen it before, so we need to determine if this insert action is
                    // is depenedent upon a previously processed action in terms of FK
                    // relationships (this FK checking is done against the entity's property-state
                    // associated with the action...)
                    int lastPos = nameList.LastIndexOf(thisEntityName);
                    object[] states = action.State;
                    for (int i = 0; i < states.Length; i++)
                    {
                        for (int j = 0; j < nameList.Count; j++)
                        {
                            List<EntityInsertAction> tmpList = positionToAction[j];
                            for (int k = 0; k < tmpList.Count; k++)
                            {
                                EntityInsertAction checkAction = tmpList[k];
                                if (checkAction.Instance == states[i] && j > lastPos)
                                {
                                    // 'checkAction' is inserting an entity upon which 'action' depends...
                                    // note: this is an assumption and may not be correct in the case of one-to-one
                                    List<EntityInsertAction> segmentedActionQueue = new List<EntityInsertAction>();
                                    segmentedActionQueue.Add(action);
                                    nameList.Add(thisEntityName);
                                    positionToAction[nameList.LastIndexOf(thisEntityName)] = segmentedActionQueue;
                                    goto loopInsertion;
                                }
                            }
                        }
                    }

                    List<EntityInsertAction> actionQueue = positionToAction[lastPos];
                    actionQueue.Add(action);
                }
            loopInsertion: ;
            }

            // now iterate back through positionToAction map and move entityInsertAction back to insertion list
            for (int p = 0; p < nameList.Count; p++)
            {
                List<EntityInsertAction> actionQueue = positionToAction[p];
                foreach (EntityInsertAction action in actionQueue)
                    insertions.Add(action);
            }
        }
Example #23
0
        private String GetParentFolderFromPath(String Path)
            {
            String Result =  String.Empty;
            List<Char> TempList = new List<Char>();
           
            foreach (Char Letter in Path)
            {
                TempList.Add(Letter);
            }

            TempList.RemoveRange(0, TempList.LastIndexOf('\\'));
            try
            {
                TempList.Remove('\\');
            }
            catch
            {

            }

            foreach (Char Letter in TempList)
            {
                Result = Result + Letter;
            }


            return Result;

            }
Example #24
0
 public static void CleanMusicList(ref CListView D)
 {
     List<String> Tracks = new List<string>();
     List<ListViewItem> itemsToRemove = new List<ListViewItem>();
     foreach(ListViewItem X in D.Items)
     {
         Song _Song = MainForm.ItemToSong(X);
         if(Tracks.LastIndexOf(_Song.Title.ToLower()+" - "+_Song.Artist.ToLower())>-1)
         {
             itemsToRemove.Add(X);
         }
         else
         {
             Tracks.Add(_Song.Title.ToLower() + " - "+_Song.Artist.ToLower());
         }
     }
     foreach(ListViewItem R in itemsToRemove)
     {
         D.Items.Remove(R);
     }
 }
        /// <summary>
        /// On Level Change
        /// </summary>
        void HandleGameSceneLevelChangeDetected(object sender, EventArgs e)
        {
            Reset ();
            List<string> variables = new List<string>();

            // IF A QUALITY IS IN THE LEVEL, AND IT HAS A VARIENT (E.G. FOR COLOR, AT LEAST 2 COLORS ARE USED)
            // THEN IT IS INCLUDED IN THE LEVEL TITLE AND WILL BE WORTH POINTS
            foreach (string key in QualityManager.Instance.qualityDict.Keys) {
                if ( key == "QOrientation") continue;
                var variations = QualityManager.Instance.qualityDict[key];
                if( variations[0] != null && variations[1] != null && variations[2] != null ) {
                    variables.Add(key.Substring(1));
                }
            }

            switch(GameScene.currentLevel) {
            case 0:
                levelTitle.Title = "crystallon tutorial";
                break;
            case 999:
                levelTitle.Title = "crystallon challenge mode";
                variables[variables.LastIndexOf("Particle")] = LoadingScene.GAME_SCENE_DATA.fourthQuality;
                if(GameScene.gameTimeLimit > 0.0f) {
                    float minutes = GameScene.gameTimeLimit/60.0f;
                    levelTitle.Title += ": " + minutes.ToString("#0.#") + " minute limit";
                }
                break;
            default:
                levelTitle.Title = "crystallon puzzle " + GameScene.currentLevel.ToString();
                break;
            }
            levelTitle.SetQualityNames( variables.ToArray() );
            levelTitle.SlideIn();
        }
Example #26
0
		/*
		 * Matches a method against its arguments in the Lua stack. Returns
		 * if the match was successful. It it was also returns the information
		 * necessary to invoke the method.
		 */
		internal bool MatchParameters (LuaState luaState, MethodBase method, ref MethodCache methodCache)
		{
			ExtractValue extractValue;
			bool isMethod = true;
			var paramInfo = method.GetParameters ();
			int currentLuaParam = 1;
			int nLuaParams = LuaLib.LuaGetTop (luaState);
			var paramList = new List<object> ();
			var outList = new List<int> ();
			var argTypes = new List<MethodArgs> ();

			foreach (var currentNetParam in paramInfo) {
#if !SILVERLIGHT
				if (!currentNetParam.IsIn && currentNetParam.IsOut)  // Skips out params 
#else
				if (currentNetParam.IsOut)  // Skips out params
#endif
				{					
					paramList.Add (null);
					outList.Add (paramList.LastIndexOf (null));
				}  else if (IsTypeCorrect (luaState, currentLuaParam, currentNetParam, out extractValue)) {  // Type checking
					var value = extractValue (luaState, currentLuaParam);
					paramList.Add (value);
					int index = paramList.LastIndexOf (value);
					var methodArg = new MethodArgs ();
					methodArg.index = index;
					methodArg.extractValue = extractValue;
					argTypes.Add (methodArg);

					if (currentNetParam.ParameterType.IsByRef)
						outList.Add (index);

					currentLuaParam++;
				}  // Type does not match, ignore if the parameter is optional
				else if (IsParamsArray (luaState, currentLuaParam, currentNetParam, out extractValue)) {

					var paramArrayType = currentNetParam.ParameterType.GetElementType ();

					Func<int, object> extractDelegate = (currentParam) => {
						currentLuaParam ++;
						return extractValue (luaState, currentParam);
					};
					int count = (nLuaParams - currentLuaParam) + 1;
					Array paramArray = TableToArray (extractDelegate, paramArrayType, currentLuaParam, count);

					paramList.Add (paramArray);
					int index = paramList.LastIndexOf (paramArray);
					var methodArg = new MethodArgs ();
					methodArg.index = index;
					methodArg.extractValue = extractValue;
					methodArg.isParamsArray = true;
					methodArg.paramsArrayType = paramArrayType;
					argTypes.Add (methodArg);

				} else if (currentLuaParam > nLuaParams) { // Adds optional parameters
					if (currentNetParam.IsOptional)
						paramList.Add (currentNetParam.DefaultValue);
					else {
						isMethod = false;
						break;
					}
				} else if (currentNetParam.IsOptional)
					paramList.Add (currentNetParam.DefaultValue);
				else {  // No match
					isMethod = false;
					break;
				}
			}

			if (currentLuaParam != nLuaParams + 1) // Number of parameters does not match
				isMethod = false;
			if (isMethod) {
				methodCache.args = paramList.ToArray ();
				methodCache.cachedMethod = method;
				methodCache.outList = outList.ToArray ();
				methodCache.argTypes = argTypes.ToArray ();
			}
			return isMethod;
		}
Example #27
0
        static void handleResult(IAsyncResult result)
        {
            //string outputFile = @"C:\dev\csharp\Stream_Data.txt";     //Uncomment and update if you want to write to a local file.
            HttpWebRequest request = (HttpWebRequest)result.AsyncState;

            using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
            using (Stream stream = response.GetResponseStream())
            using (MemoryStream memory = new MemoryStream())
            {
                byte[] compressedBuffer = new byte[8192];
                byte[] uncompressedBuffer = new byte[8192];
                List<byte> output = new List<byte>();

                while (stream.CanRead)
                {
                    AddToConsole(" +++ Reading Stream");

                    try
                    {
                        int readCount = stream.Read(compressedBuffer, 0, compressedBuffer.Length);

                        memory.Write(compressedBuffer.Take(readCount).ToArray(), 0, readCount);
                        memory.Position = 0;

                        int uncompressedLength = memory.Read(uncompressedBuffer, 0, uncompressedBuffer.Length);

                        output.AddRange(uncompressedBuffer.Take(uncompressedLength));

                        byte[] bytesToDecode = output.Take(output.LastIndexOf(0x0A) + 1).ToArray();
                        string outputString = Encoding.UTF8.GetString(bytesToDecode);
                        output.RemoveRange(0, bytesToDecode.Length);

                        string[] lines = outputString.Split(new[] { Environment.NewLine }, new StringSplitOptions());

                        for (int i = 0; i < (lines.Length - 1); i++)
                        {
                            string heartBeatCheck = lines[i];
                            if (heartBeatCheck.Trim().Length > 0)
                            {
                                AddToConsole(lines[i]);  //Just print out to console window...
                                //File.AppendAllText(outputFile, lines[i] + Environment.NewLine); //Write out to the file...
                            }
                            else
                            {
                                AddToConsole(" ♥♥♥ Heartbeat Received");
                            }
                        }
                    }
                    catch (Exception error)
                    {
                        AddToConsole(error.Message);
                        // Handle the error as needed here
                    }

                    memory.SetLength(0);    // Everything needs to reach this line otherwise you will end up with
                                            // merged activities and loads of errors. i.e. do not use "return", "continue" etc.
                                            // above this line without setting the memory length to ZERO first.
                }

                if (!stream.CanRead)
                {
                    AddToConsole(" --- Cannot Read Stream");
                    // Handle the situation as needed here. The stream is probably corrupted.
                }
            }
        }
Example #28
0
 private void keySet(string section, string key, bool useString, string sValue, double dValue)
 {
     List<string> sections = new List<string>();
     List<string> keys = new List<string>();
     List<string> comments = new List<string>();
     foreach (INILine line in iniContent) {
         sections.Add(line.section);
         keys.Add(line.iKey);
         comments.Add(line.comment);
     }
     bool isDef = useString ? isDefault(section, key, sValue) : isDefault(section, key, dValue);
     INIVariableDef vd = getVarDefn(section, key);
     string iSection = section.ToLower(Statics.Culture);
     string iKey = key.ToLower(Statics.Culture);
     int firstIndex = sections.IndexOf(iSection);
     int lastIndex = sections.LastIndexOf(iSection);
     int index = keys.IndexOf(iKey);
     INILine.setSection = section;
     INILine tmp = new INILine(key + "=");
     tmp.defVal = vd.defValue;
     tmp.varType = vd.type;
     tmp.varDict = vd.dict;
     tmp.varBool = vd.boolType;
     tmp.useMinMax = vd.useMinMax;
     tmp.min = vd.min;
     tmp.max = vd.max;
     if (useString) tmp.sValue = sValue;
     else {
         if (vd.precision != -1) dValue = double.Parse (dValue.ToString ("F" + vd.precision.ToString ()));
         tmp.dValue = dValue;
     }
     if (firstIndex == -1) {
         if (!saveDef && isDef) return;
         if (iniContent.Count > 0) {
             INILine line = iniContent[iniContent.Count - 1];
             if (line.entry != "" || line.comment != "") {
                 INILine.setSection = line.section;
                 iniContent.Add(new INILine(""));
                 firstIndex++;
             }
         }
         INILine.setSection = section;
         iniContent.Add(new INILine("[" + section + "]"));
         iniContent.Add(tmp);
         iniContent.Add(new INILine(""));
     } else if (index >= firstIndex && index <= lastIndex) {
         if (!saveDef && isDef && comments[index] == "") iniContent.RemoveAt(index);
         else if (useString && iniContent[index].value == sValue || !useString && iniContent[index].dValue == dValue) return;
         else if (useString) iniContent[index].sValue = sValue;
         else iniContent[index].dValue = dValue;
     } else {
         if (!saveDef && isDef) return;
         INILine line = iniContent[lastIndex++];
         if (line.entry != "" || line.comment != "") {
             iniContent.Insert(lastIndex, new INILine(""));
             iniContent.Insert(lastIndex, tmp);
         } else iniContent.Insert(lastIndex - 1, tmp);
     }
     modified = true;
 }
Example #29
0
 public void setSectOrderedList(string section, string[] tab)
 {
     List<string> sections = new List<string>();
     foreach (INILine line in iniContent) sections.Add(line.section);
     string iSection = section.ToLower(Statics.Culture);
     int firstIndex = sections.IndexOf(iSection);
     int lastIndex = sections.LastIndexOf(iSection);
     if (firstIndex == -1) {
         if (iniContent.Count > 0) {
             INILine line = iniContent[iniContent.Count - 1];
             if (line.entry != "" || line.comment != "") {
                 INILine.setSection = line.section;
                 iniContent.Add(new INILine(""));
                 firstIndex++;
             }
         }
         INILine.setSection = section;
         firstIndex = lastIndex = iniContent.Count;
         iniContent.Add(new INILine("[" + section + "]"));
     }
     int tabIndex = 0;
     int tabCount = tab.Length - 1;
     while (++firstIndex <= lastIndex && tabIndex <= tabCount) {
         INILine line = iniContent[firstIndex];
         if (line.entry != "" && line.comment != "") {
             line.entry = INIComment + line.entry;
         }
         else if (line.comment != "") continue;
         else {
             line.entry = tab[tabIndex++];
         }
     }
     while (firstIndex <= lastIndex) iniContent.RemoveAt(lastIndex--);
     iniContent.Insert(firstIndex, new INILine(""));
     INILine.setSection = section;
     while (tabCount >= tabIndex) {
         iniContent.Insert(firstIndex, new INILine(tab[tabCount--]));
     }
     modified = true;
 }
Example #30
0
 public void setSectList(string section, string[] tab)
 {
     List<string> sections = new List<string>();
     foreach (INILine line in iniContent) sections.Add(line.section);
     string iSection = section.ToLower(Statics.Culture);
     int firstIndex = sections.IndexOf(iSection);
     int lastIndex = sections.LastIndexOf(iSection);
     List<string> iTab = new List<string>();
     List<string> lTab = new List<string>();
     foreach (string tmpStr in tab) {
         iTab.Add(tmpStr.ToLower(Statics.Culture));
         lTab.Add(tmpStr);
     }
     if (firstIndex == -1) {
         if (iniContent.Count > 0) {
             INILine line = iniContent[iniContent.Count - 1];
             if (line.entry != "" || line.comment != "") {
                 INILine.setSection = line.section;
                 iniContent.Add(new INILine(""));
                 firstIndex++;
             }
         }
         INILine.setSection = section;
         firstIndex = lastIndex = iniContent.Count;
         iniContent.Add(new INILine("[" + section + "]"));
     }
     for (int i = lastIndex; i > firstIndex; i--) {
         INILine line = iniContent[i];
         int index = iTab.IndexOf(line.iEntry);
         if (index != -1) {
             iTab.RemoveAt(index);
             lTab.RemoveAt(index);
         } else if (line.comment != "") {
             line.entry = INIComment + line.entry;
             modified = true;
         } else {
             iniContent.RemoveAt(i);
             lastIndex--;
             modified = true;
         }
     }
     INILine.setSection = section;
     if (iniContent[lastIndex].entry != "" || iniContent[lastIndex].comment != "") iniContent.Insert(++lastIndex, new INILine(""));
     for (int i = lTab.Count - 1; i >= 0; i--) {
         iniContent.Insert(lastIndex, new INILine(lTab[i]));
         modified = true;
     }
 }