public bool PosTest1()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method IDictionaryContains when specified key existed.");

        try
        {
            IDictionary dictionary = new Dictionary<string, string>();

            dictionary.Add("txt", "notepad.exe");
            dictionary.Add("bmp", "paint.exe");
            dictionary.Add("dib", "paint.exe");
            dictionary.Add("rtf", "wordpad.exe");

            bool testVerify = dictionary.Contains("txt") && dictionary.Contains("bmp") &&
                              dictionary.Contains("dib") && dictionary.Contains("rtf");

            if (testVerify == false)
            {
                TestLibrary.TestFramework.LogError("001.1", "Method IDictionaryContains Err .");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Exemplo n.º 2
0
 public void Dictionary_kvp_Contains_checks_key_and_value()
 {
     IDictionary<int,string> dictionary = new Dictionary<int, string>();
     dictionary[1] = "foo";
     Assert.IsTrue(dictionary.Contains(new KeyValuePair<int, string>(1, "foo")));
     Assert.IsFalse(dictionary.Contains(new KeyValuePair<int, string>(1, "bar")));
 }
Exemplo n.º 3
0
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: The IDictionary contains the key");

        try
        {
            IDictionary iDictionary = new Dictionary<object,object>();
            Int32[] key = new Int32[1000];
            Byte[] value = new Byte[1000];
            for (int i = 0; i < 1000; i++)
            {
                key[i] = i;
            }
            TestLibrary.Generator.GetBytes(-55, value);
            for (int i = 0; i < 1000; i++)
            {
                iDictionary.Add(key[i], value[i]);
            }
            int keyValue = this.GetInt32(0, 1000);
            if (!iDictionary.Contains(keyValue))
            {
                TestLibrary.TestFramework.LogError("001", "The result is not the value as expected ");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
    public bool PosTest2()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method IDictionaryRemove when the specified key is not exist.");

        try
        {
            IDictionary dictionary = new Dictionary<string, string>();

            dictionary.Remove("txt");

            if (dictionary.Contains("txt") == true)
            {
                TestLibrary.TestFramework.LogError("002.1", "Method IDictionary.GetEnumerator Err .");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Exemplo n.º 5
0
    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2: The key to be remove is a custom class");

        try
        {
            IDictionary iDictionary = new Dictionary<object,object>();
            MyClass mc = new MyClass();
            int value = TestLibrary.Generator.GetInt32(-55);
            iDictionary.Add(mc, value);
            iDictionary.Remove(mc);
            if (iDictionary.Contains(mc))
            {
                TestLibrary.TestFramework.LogError("003", "The result is not the value as expected ");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
    public bool PosTest1()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method ICollectionContains when k/v existed.");

        try
        {
            ICollection<KeyValuePair<String, String>> dictionary = new Dictionary<String, String>();

            KeyValuePair<string, string> kvp1 = new KeyValuePair<String, String>("txt", "notepad.exe");
            KeyValuePair<string, string> kvp2 = new KeyValuePair<String, String>("bmp", "paint.exe");
            KeyValuePair<string, string> kvp3 = new KeyValuePair<String, String>("dib", "paint.exe");
            KeyValuePair<string, string> kvp4 = new KeyValuePair<String, String>("rtf", "wordpad.exe");

            dictionary.Add(kvp1);
            dictionary.Add(kvp2);
            dictionary.Add(kvp3);
            dictionary.Add(kvp4);

            bool actual  = dictionary.Contains(kvp1) &&
                           dictionary.Contains(kvp1) &&
                           dictionary.Contains(kvp1) &&
                           dictionary.Contains(kvp1);
            bool expected = true;

            if (actual != expected)
            {
                TestLibrary.TestFramework.LogError("001.1", "Method ICollectionContains Err.");
                TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
                retVal = false;
            }

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
        public void VersionSetsCorrectTagKeyAndValue()
        {
            IDictionary<string, string> tags = new Dictionary<string, string>();
            var component = new ComponentContext(tags);

            string componentVersion = "fakeVersion";
            component.Version = componentVersion;

            Assert.True(tags.Contains(new KeyValuePair<string, string>(ContextTagKeys.Keys.ApplicationVersion, componentVersion)));
        }
 public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
 {
     if (values.Length == 1)
     {
         if (Dictionary?.Contains(values[0]) == true)
         {
             return(Dictionary[values[0]]);
         }
     }
     else if (values.Length > 1 && values[0] != null && (values[1] is IDictionary dictionary) && (dictionary.Contains(values[0]) == true))
     {
         return(dictionary[values[0]]);
     }
     return(null);
 }
		public void CharHistogramTest()
		{
			Dictionary<char, int> expectedDictionary = new Dictionary<char, int>()
			{
			//	expected - 'P': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1, '!': 2
				{'P', 1},
				{'y', 1},
				{'t', 1},
				{'h', 1},
				{'o', 1},
				{'n', 1},
				{'!', 2},
			};
			/*Dictionary<char, int> resultDictionary = new Dictionary<char, int>() {
				{'P', 1},
				{'y', 1},
				{'t', 1},
				{'h', 1},
				{'o', 1},
				{'n', 1},
				{'!', 2},};
				*/
				Histogram rclass = new Histogram();
				var resultDictionary = rclass.CharHistogram("Phyton!!");
				Assert.AreEqual(true,resultDictionary.All(e => expectedDictionary.Contains(e)));
			/*Assert.AreEqual(resultDictionary,expectedDictionary);
			Histogram rclass = new Histogram();
			//var result = res.CharHistogram("Phyton!!");
			foreach (var exp in expectedDictionary)
			{
				foreach (var res in resultDictionary)
				{
					if (exp.Key == res.Key)
					{
						if (exp.Value != res.Value)
						{
							Assert.Fail("exp.Val= {0} res.Val = {1} ", exp.Value, res.Value);
						}
					}
					else
					{
						Assert.Fail("exp.Key= {0} res.Key = {1} ",exp.Key,res.Key);
					}
				}
			}
			*/
		}
Exemplo n.º 10
0
        public static bool IsEquals(Dictionary<BaseSi, int> d1, Dictionary<BaseSi, int> d2)
        {
            if(d1.Count == d2.Count)
            {
                foreach(var item in d1)
                {
                    if(!d2.Contains(item))
                    {
                        return false;
                    }
                }
            }
            else
            {
                return false;
            }

            return true;
        }
Exemplo n.º 11
0
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Using Dictionary<string,Byte> to implemented the clear method");

        try
        {
            IDictionary iDictionary = new Dictionary<string,Byte>();
            string[] key = new string[1000];
            Byte[] value = new Byte[1000];
            for (int i = 0; i < 1000; i++)
            {
                key[i] = TestLibrary.Generator.GetString(-55, false, 1, 100);
            }
            TestLibrary.Generator.GetBytes(-55, value);
            for (int i = 0; i < 1000; i++)
            {
                while (iDictionary.Contains(key[i]))
                {
                    key[i] = TestLibrary.Generator.GetString(false, 1, 100);
                }
                iDictionary.Add(key[i], value[i]);
            }
            iDictionary.Clear();
            if (iDictionary.Count != 0)
            {
                TestLibrary.TestFramework.LogError("001", "The result is not the value as expected ");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
        public void UnionDictionariesTest()
        {
            IDictionary<int, string> target = new Dictionary<int, string>();
            IDictionary<int, string> source = new Dictionary<int, string>();
            // simple add
            target.Add(1, "one");
            source.Add(2, "two");
            CollectionUtil.UnionDictionaries(target, source);
            Assert.IsTrue(target.ContainsKey(2));
            Assert.IsTrue(target.Contains(new KeyValuePair<int,string>(2, "two")));
            Assert.AreEqual(2, target.Count);

            // skip existing
            source.Add(3, "three");
            CollectionUtil.UnionDictionaries(target, source);
            Assert.AreEqual(3, target.Count);

            // replace
            source[3] = "new three";
            CollectionUtil.UnionDictionaries(target, source);
            Assert.AreEqual("new three", target[3]);

        }
Exemplo n.º 13
0
    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2: The key is a string of white space");

        try
        {
            IDictionary iDictionary = new Dictionary<object,object>();
            iDictionary.Add("  ", true);
            if (!iDictionary.Contains("  "))
            {
                TestLibrary.TestFramework.LogError("003", "The result is not the value as expected ");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
Exemplo n.º 14
0
        /// <summary>
        /// Removes the two objects at the top of the stack and subtracts the top most object on the stack from the other.
        /// Then, pushes the result on to the top of the stack.
        /// </summary>
        public override void PerformOperation()
        {
            base.PerformOperation();

            // If we have fewer than 2 objects on the stack we are el-bonerino-ed
            Debug.Assert(CelesteStack.StackSize >= 2, "Not enough elements on the stack for subtract operator");

            CelesteObject rhs = CelesteStack.Pop();
            CelesteObject lhs = CelesteStack.Pop();

            // The stack will wrap our subtraction result in a CelesteObject, so just push the actual value of the subtraction
            if (lhs.IsNumber() && rhs.IsNumber())
            {
                CelesteStack.Push(lhs.As <float>() - rhs.As <float>());
            }
            else if (lhs.IsString() && rhs.IsString())
            {
                string lhsAsString = lhs.As <string>();
                string rhsAsString = rhs.As <string>();

                if (lhsAsString.Contains(rhsAsString))
                {
                    // Push the lhs string having removed the rhs string
                    CelesteStack.Push(lhsAsString.Remove(lhsAsString.IndexOf(rhsAsString), rhsAsString.Length));
                }
                else
                {
                    // If our lhs does not contain our rhs, we just push the original unaltered lhs string
                    CelesteStack.Push(lhsAsString);
                }
            }
            else if (lhs.IsList() && rhs.IsList())
            {
                // The subtract operator for lists removes all elements in the first list who are equal to an element in the second, either by reference or value
                List <object> lhsList = lhs.AsList <object>();
                List <object> rhsList = rhs.AsList <object>();

                // Remove ALL occurrences in the list of any object in the rhs list - otherwise there is non-deterministic behaviour in which instance to remove
                lhsList.RemoveAll(x => rhsList.Exists(y => y.Equals(x) || y.ValueEquals(x)));
                CelesteStack.Push(lhs);
            }
            else if (lhs.IsTable() && rhs.IsList())
            {
                // Subtraction of tables does not make sense
                // What does make sense, is subtracting elements in a table using a list of keys
                // Subtracting a list from a table will remove any elements in the table with a matching key as an element in our list

                Dictionary <object, object> lhsTable = lhs.AsTable();
                List <object> rhsList = rhs.AsList <object>();

                foreach (object obj in rhsList)
                {
                    if (lhsTable.Contains(new KeyValuePair <object, object>(obj, null), new TableKeyComparer()))
                    {
                        lhsTable.Remove(lhsTable.First(x => x.Key.Equals(obj) || x.Key.ValueEquals(obj)));
                    }
                }

                CelesteStack.Push(lhs);
            }
            else
            {
                Debug.Fail("Invalid parameters to subtract operation.");
            }
        }
Exemplo n.º 15
0
 /// <summary>
 /// Test whether the dictionary contains an element equal to that given.
 /// </summary>
 public bool Contains(KeyValuePair <TKey, TValue> pair)
 {
     return(fDictionary.Contains(pair));
 }
Exemplo n.º 16
0
 public bool Contains(KeyValuePair <string, object> item)
 {
     return(_dict.Contains(item));
 }
        public void GetOrAddTestCase()
        {
            var dictionary = new Dictionary<String, String>();
            var key = RandomValueEx.GetRandomString();
            var value = RandomValueEx.GetRandomString();

            var actual = dictionary.GetOrAdd( key, value );
            Assert.AreEqual( value, actual );
            Assert.IsTrue( dictionary.Contains( new KeyValuePair<String, String>( key, value ) ) );
            Assert.AreEqual( 1, dictionary.Count );

            actual = dictionary.GetOrAdd( key, value );
            Assert.AreEqual( value, actual );
            Assert.IsTrue( dictionary.Contains( new KeyValuePair<String, String>( key, value ) ) );
            Assert.AreEqual( 1, dictionary.Count );
        }
Exemplo n.º 18
0
        public static FncFile Parse(string sourceFile)
        {
            var sourceText = File.ReadAllText(sourceFile);
            var boxes = new List<Box>();

            // Turn into array of characters
            var lines = (sourceText.Replace("\r", "") + "\n\n").Split('\n');
            var source = new SourceAsChars(lines);

            if (lines.Length == 0)
                return new FncFile { Boxes = boxes, Source = source };

            var visited = new Dictionary<int, HashSet<int>>();

            // Find boxes
            for (int y = 0; y < source.NumLines; y++)
            {
                for (int x = 0; x < source[y].Length; x++)
                {
                    // Go looking for a box only if this is a top-left corner of a box
                    if (source.TopLine(x, y) != LineType.None || source.LeftLine(x, y) != LineType.None || source.RightLine(x, y) == LineType.None || source.BottomLine(x, y) == LineType.None)
                        continue;

                    if (visited.Contains(x, y))
                        continue;

                    // Find width of box by walking along top edge
                    var top = source.RightLine(x, y);
                    var index = x + 1;
                    while (index < source[y].Length && source.RightLine(index, y) == top)
                        index++;
                    if (index == source[y].Length || source.BottomLine(index, y) == LineType.None || source.TopLine(index, y) != LineType.None || source.RightLine(index, y) != LineType.None)
                        continue;
                    var width = index - x;

                    // Find height of box by walking along left edge
                    var left = source.BottomLine(x, y);
                    index = y + 1;
                    while (index < source.NumLines && source.BottomLine(x, index) == left)
                        index++;
                    if (index == source.NumLines || source.RightLine(x, index) == LineType.None || source.LeftLine(x, index) != LineType.None || source.BottomLine(x, index) != LineType.None)
                        continue;
                    var height = index - y;

                    // Verify the bottom edge
                    var bottom = source.RightLine(x, y + height);
                    index = x + 1;
                    while (index < source[y].Length && source.RightLine(index, y + height) == bottom)
                        index++;
                    if (index == source[y].Length || source.TopLine(index, y + height) == LineType.None || source.BottomLine(index, y + height) != LineType.None || source.RightLine(index, y + height) != LineType.None)
                        continue;
                    if (index - x != width)
                        continue;

                    // Verify the right edge
                    var right = source.BottomLine(x + width, y);
                    index = y + 1;
                    while (index < source.NumLines && source.BottomLine(x + width, index) == right)
                        index++;
                    if (index == source.NumLines || source.LeftLine(x + width, index) == LineType.None || source.RightLine(x + width, index) != LineType.None || source.BottomLine(x + width, index) != LineType.None)
                        continue;
                    if (index - y != height)
                        continue;

                    // If all edges are single lines, this is not a box
                    if (top == LineType.Single && right == LineType.Single && bottom == LineType.Single && left == LineType.Single)
                        continue;

                    for (int xx = 0; xx <= width; xx++)
                    {
                        visited.AddSafe(x + xx, y);
                        visited.AddSafe(x + xx, y + height);
                    }
                    for (int yy = 0; yy <= height; yy++)
                    {
                        visited.AddSafe(x, y + yy);
                        visited.AddSafe(x + width, y + yy);
                    }

                    boxes.Add(new Box
                    {
                        X = x,
                        Y = y,
                        Width = width,
                        Height = height,
                        LineTypes = Helpers.MakeDictionary(top, right, bottom, left)
                    });
                }
            }

            // Determine the location of text lines within every box
            foreach (var box in boxes)
            {
                var curTextLines = new HashSet<TextLine>();
                for (int by = 1; by < box.Height; by++)
                {
                    var y = box.Y + by;
                    TextLine curTextLine = null;
                    var curLineText = new StringBuilder();
                    for (int bx = 1; bx < box.Width; bx++)
                    {
                        var x = box.X + bx;

                        if (source.AnyLine(x, y))
                        {
                            if (curTextLine != null)
                            {
                                curTextLine.Content = curLineText.ToString();
                                curTextLines.Add(curTextLine);
                                curTextLine = null;
                                curLineText.Clear();
                            }
                        }
                        else
                        {
                            if (curTextLine == null)
                                curTextLine = new TextLine { X = x, Y = y };
                            curLineText.Append(source[y][x]);
                        }
                    }
                    if (curTextLine != null)
                    {
                        curTextLine.Content = curLineText.ToString();
                        curTextLines.Add(curTextLine);
                    }
                }

                // Group text lines by vertical adjacency
                var textAreas = new List<TextLine[]>();
                while (curTextLines.Count > 0)
                {
                    var first = curTextLines.First();
                    curTextLines.Remove(first);
                    var curGroup = new List<TextLine> { first };
                    while (true)
                    {
                        var next = curTextLines.FirstOrDefault(one => curGroup.Any(two => (one.Y == two.Y + 1 || one.Y == two.Y - 1) && one.X + one.Content.Length > two.X && one.X < two.X + two.Content.Length));
                        if (next == null)
                            break;
                        curGroup.Add(next);
                        curTextLines.Remove(next);
                    }
                    curGroup.Sort(CustomComparer<TextLine>.By(l => l.Y).ThenBy(l => l.X));
                    textAreas.Add(curGroup.ToArray());
                }
                box.TextAreas = textAreas.ToArray();
            }

            return new FncFile { Boxes = boxes, Source = source };
        }
Exemplo n.º 19
0
 public bool Contains(KeyValuePair <string, DireccionPunto> item)
 {
     return(_d.Contains(item));
 }
        private void InitializeDataFeatureHash()
        {
            int macroActiveFeatureTotalCount = 0;
            int macroCondensedTotalCount     = 0;
            int macroDocPosCount             = 0;

            log.Info("initializing data feature hash, sup-data size: " + data.Length + ", unsup data size: " + (totalData.Length - data.Length));
            dataFeatureHash      = new List <IList <ICollection <int> > >(totalData.Length);
            condensedMap         = new List <IDictionary <int, IList <int> > >(totalData.Length);
            dataFeatureHashByDoc = new int[totalData.Length][];
            for (int m = 0; m < totalData.Length; m++)
            {
                IDictionary <int, int> occurPos = new Dictionary <int, int>();
                int[][][] aDoc = totalData[m];
                IList <ICollection <int> > aList         = new List <ICollection <int> >(aDoc.Length);
                ICollection <int>          setOfFeatures = new HashSet <int>();
                for (int i = 0; i < aDoc.Length; i++)
                {
                    // positions in docI
                    ICollection <int> aSet  = new HashSet <int>();
                    int[][]           dataI = aDoc[i];
                    for (int j = 0; j < dataI.Length; j++)
                    {
                        int[] dataJ = dataI[j];
                        foreach (int item in dataJ)
                        {
                            if (j == 0)
                            {
                                if (occurPos.Contains(item))
                                {
                                    occurPos[item] = -1;
                                }
                                else
                                {
                                    occurPos[item] = i;
                                }
                            }
                            aSet.Add(item);
                        }
                    }
                    aList.Add(aSet);
                    Sharpen.Collections.AddAll(setOfFeatures, aSet);
                }
                macroDocPosCount             += aDoc.Length;
                macroActiveFeatureTotalCount += setOfFeatures.Count;
                // examine all singletons, merge ones in the same position
                IDictionary <int, IList <int> > condensedFeaturesMap = new Dictionary <int, IList <int> >();
                int[] representFeatures = new int[aDoc.Length];
                Arrays.Fill(representFeatures, -1);
                foreach (KeyValuePair <int, int> entry in occurPos)
                {
                    int key = entry.Key;
                    int pos = entry.Value;
                    if (pos != -1)
                    {
                        if (representFeatures[pos] == -1)
                        {
                            // use this as representFeatures
                            representFeatures[pos]    = key;
                            condensedFeaturesMap[key] = new List <int>();
                        }
                        else
                        {
                            // condense this one
                            int rep = representFeatures[pos];
                            condensedFeaturesMap[rep].Add(key);
                            // remove key
                            aList[pos].Remove(key);
                            setOfFeatures.Remove(key);
                        }
                    }
                }
                int condensedCount = 0;
                for (IEnumerator <KeyValuePair <int, IList <int> > > it = condensedFeaturesMap.GetEnumerator(); it.MoveNext();)
                {
                    KeyValuePair <int, IList <int> > entry_1 = it.Current;
                    if (entry_1.Value.Count == 0)
                    {
                        it.Remove();
                    }
                }
                macroCondensedTotalCount += setOfFeatures.Count;
                condensedMap.Add(condensedFeaturesMap);
                dataFeatureHash.Add(aList);
                int[] arrOfIndex = new int[setOfFeatures.Count];
                int   pos2       = 0;
                foreach (int ind in setOfFeatures)
                {
                    arrOfIndex[pos2++] = ind;
                }
                dataFeatureHashByDoc[m] = arrOfIndex;
            }
            log.Info("Avg. active features per position: " + (macroActiveFeatureTotalCount / (macroDocPosCount + 0.0)));
            log.Info("Avg. condensed features per position: " + (macroCondensedTotalCount / (macroDocPosCount + 0.0)));
            log.Info("initializing data feature hash done!");
        }
        private static void VerifyEntry(
            Dictionary<string, object> expectedFullMetadataObject,
            ODataEntry entry,
            ODataNavigationLink[] userSpecifiedNavigationLinks,
            ODataProperty[] userSpecifiedMediaProperties,
            Dictionary<string, object> metadataNotYetVerified,
            string mimeType,
            bool autoComputePayloadMetadataInJson)
        {
            if (autoComputePayloadMetadataInJson && !mimeType.Contains(MimeTypes.ODataParameterMinimalMetadata))
            {
                // Verify fullmedata result against fullmetadata expected object, for nometadata, verify metadata does not exist in the result
                foreach (var pair in expectedFullMetadataObject)
                {
                    // whether the expected metadata is in the result
                    bool existInEntry = metadataNotYetVerified.Contains(pair);

                    bool isMetadata = pair.Key.Contains("odata.");

                    // special handling for actions since each action is a Dictionary<string, object> in the expect/actual with key value "#Namespace.ActionName"
                    if (pair.Key.StartsWith("#" + WritePayloadHelper.Model.EntityContainer.Namespace))
                    {
                        isMetadata = true;
                        var expectedActionObject = pair.Value as Dictionary<string, object>;
                        if (metadataNotYetVerified.ContainsKey(pair.Key))
                        {
                            var actualActionObject = metadataNotYetVerified[pair.Key] as Dictionary<string, object>;
                            existInEntry = true;
                            foreach (var item in expectedActionObject)
                            {
                                // verify action title/target
                                existInEntry = existInEntry && actualActionObject.Contains(item);
                            }
                        }
                    }

                    // whether expectedFullMetadataObject property is in the result
                    if (!isMetadata)
                    {
                        existInEntry = metadataNotYetVerified.ContainsKey(pair.Key);
                    }

                    if (mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
                    {
                        // nometadata result should contain properties but not metadata
                        Assert.IsTrue(isMetadata != existInEntry, "Unexpected " + pair.Key);
                    }
                    else if (mimeType.Contains(MimeTypes.ODataParameterFullMetadata))
                    {
                        // fullmetadata result should contain properties and metadata
                        Assert.IsTrue(existInEntry, "Expected item not found " + pair.Key);
                    }

                    metadataNotYetVerified.Remove(pair.Key);
                }
            }
            else
            {
                VerifyAgainstODataEntry(entry, userSpecifiedNavigationLinks, userSpecifiedMediaProperties, metadataNotYetVerified);
            }

            // additional verification for mimimalmetadata, only include odata.type in derived type instances
            if (!autoComputePayloadMetadataInJson || mimeType.Contains(MimeTypes.ODataParameterMinimalMetadata))
            {
                object value = null;
                bool typeAnnotationFound = metadataNotYetVerified.TryGetValue(JsonLightConstants.ODataTypeAnnotationName, out value);
                Assert.IsTrue(!typeAnnotationFound || (typeAnnotationFound && (value as string).Contains("Employee")));

                metadataNotYetVerified.Remove(JsonLightConstants.ODataTypeAnnotationName);
            }

            // make sure all metadata in the actual object is verified
            foreach (var pair in metadataNotYetVerified)
            {
                Assert.IsFalse(pair.Key.Contains("odata.") && !pair.Key.Contains("odata.associationLink"));
                Assert.IsFalse(pair.Key.StartsWith("#"));
            }
        }
Exemplo n.º 22
0
        private void gridViewTags_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            GridView view = gridViewTags;
            if (!IsLoaded) {
                if (!Cleared) {
                    if (view != null && view.SelectedRowsCount > 0) {
                        Cleared = true;
                        view.ClearSelection();
                    }
                }
                if (dictionarySelectedTags != null) {
                    KeyValuePair<string, int> kvTag;
                    questiontag qt;
                    for (int i = 0; i < view.RowCount; i++) {
                        qt = view.GetRow(i) as questiontag;
                        if (qt != null) {
                            kvTag = dictionarySelectedTags.FirstOrDefault(d => d.Value == qt.id);
                            if (kvTag.Key != null && kvTag.Value != 0) {
                                if (!view.IsRowSelected(i)) {
                                    view.SelectRow(i);
                                    view.FocusedRowHandle = i;
                                }
                            }
                        }
                    }
                    textEditSelectedTags.Text = string.Join(",", dictionarySelectedTags.Keys.ToArray());
                }
                IsLoaded = true;
                if (view.RowCount <= 0) {
                    btnEditTag.Enabled = false;
                    btnDeleteTag.Enabled = false;
                } else {
                    btnEditTag.Enabled = true;
                    btnDeleteTag.Enabled = true;
                }
                return;
            }

            if (view == null || view.SelectedRowsCount == 0) return;

            if (view.SelectedRowsCount > 1) btnEditTag.Enabled = false;
            else btnEditTag.Enabled = true;

            questiontag[] rows = new questiontag[view.SelectedRowsCount];
            for (int i = 0; i < view.SelectedRowsCount; i++) {
                rows[i] = view.GetRow(view.GetSelectedRows()[i]) as questiontag;
            }

            view.BeginSort();
            dictionarySelectedTags = new Dictionary<string, int>();
            try
            {
                //[@jeff 09.27.2011]: http://brightvision.jira.com/browse/PLATFORM-541
                KeyValuePair<string, int> iTag;
                foreach (questiontag row in rows)
                    if (row != null)
                    {
                        iTag = new KeyValuePair<string, int>(row.title, row.id);
                        if (!dictionarySelectedTags.Contains(iTag) && !dictionarySelectedTags.Keys.Contains(row.title))
                            dictionarySelectedTags.Add(row.title, row.id);
                    }
            }
            finally
            {
                view.EndSort();
            }
            textEditSelectedTags.Text = string.Join(",", dictionarySelectedTags.Keys.ToArray());
        }
Exemplo n.º 23
0
        private object MapDataInternal(Dictionary<string, object> row, DataSchemaKey key, Type type, Dictionary<DataSchemaIterator, int> interatorsIndexes)
        {
            Contract.Requires(type != null);

            object generetedObject = Activator.CreateInstance(type);
            var p = type.GetProperties();
            foreach (DataSchemaKey childKey in key.Childs)
            {
                PropertyInfo property = type.GetProperty("_" + childKey.Name);
                object value = new object();
                switch (childKey.Type)
                {
                    case DataSchemaKeyType.Container:
                        value = MapDataInternal(row, childKey, property.PropertyType, interatorsIndexes);
                        break;

                    case DataSchemaKeyType.Value:
                        DataSchemaValue v = (DataSchemaValue)childKey;
                        value = row[v.MappedColumn];
                        break;

                    case DataSchemaKeyType.Iterator:
                        DataSchemaIterator iterator = (DataSchemaIterator)childKey;
                        interatorsIndexes.Add(iterator, 0);
                        Array array = Array.CreateInstance(property.PropertyType.GetElementType(), iterator.MaxItemCount);

                        for (int i = 0; i < iterator.MaxItemCount; i++)
                        {
                            interatorsIndexes[iterator] = i;
                            object arrayValue = MapDataInternal(row, childKey, property.PropertyType.GetElementType(), interatorsIndexes);
                            array.SetValue(arrayValue, i);
                        }
                        value = array;
                        break;

                    case DataSchemaKeyType.IteratedValue:
                        DataSchemaIteratorValue va = (DataSchemaIteratorValue)childKey;
                        foreach (DataSchemaIteratorValueMappedColumn mc in va.MappedColumns)
                        {
                            bool match = true;
                            foreach (KeyValuePair<DataSchemaIterator, int> index in mc.IteratorIndexes)
                            {
                                if (!interatorsIndexes.Contains(index))
                                {
                                    match = false;
                                    break;
                                }
                            }
                            if (match)
                            {
                                value = row[mc.ColumnName];
                                break;
                            }
                        }
                        break;
                }

                property.SetValue(generetedObject, value, null);
            }
            return generetedObject;
        }
Exemplo n.º 24
0
        //选择乘客
        async void chkContact_Click(object sender, RoutedEventArgs e)
        {
            string val = "";
            CheckBox chk;
            foreach (var c in gContacts.Children)
            {
                if (c is CheckBox)
                {
                    chk = c as CheckBox;
                    if (chk.IsChecked == true)
                    {
                        val += chk.Tag + ",";
                    }
                }
            }
            string train = lblTicket.Content.ToString().Substring(lblTicket.Content.ToString().IndexOf("(") + 1, 1), trainType = "";
            trainType = !"DZTK".Contains(train) ? "QT" : train;
            trainType = "GC".Contains(train) ? "D" : "QT";
            Dictionary<string, string> seatType = await GetTickType(trainType);//席别
            IDictionary<string, string> seat_Type = new Dictionary<string, string>();
            var type = seatTypes.Split('@');
            for (int i = 0; i < type.Count(); i++)
            {
                if (type[i] != "")
                {
                    var _seatType = (from s in seatType
                                     where s.Value == type[i]
                                     select s).ToDictionary(t => t.Key, t => t.Value);
                    foreach (var t in _seatType)
                    {
                        if (!seat_Type.Contains(t))
                        {
                            seat_Type.Add(t);
                        }
                    }
                }
            }

            Dictionary<string, string> tickType = new Dictionary<string, string>();//票种
            tickType.Add("成人票", "1");
            tickType.Add("儿童票", "2");
            tickType.Add("学生票", "3");
            tickType.Add("残军票", "4");
            Dictionary<string, string> idType = new Dictionary<string, string>();//证件类型
            idType.Add("二代身份证", "1");
            idType.Add("一代身份证", "2");
            idType.Add("港澳通行证", "C");
            idType.Add("台湾通行证", "G");
            idType.Add("护照", "B");

            List<SubmitOrder> subOrder = new List<SubmitOrder>();
            if (val != "")
            {
                var selPassenger = val.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);//选中的乘客
                if (selPassenger.Count() > 5)
                {
                    MessageBox.Show("乘客数不能超过5个", "消息", MessageBoxButton.OK, MessageBoxImage.Warning);
                    CheckBox chkItem = e.Source as CheckBox;
                    chkItem.IsChecked = false;
                    return;
                }
                for (int j = 0; j < selPassenger.Count(); j++)
                {
                    if (selPassenger[j] != "")
                    {
                        var item = selPassenger[j].Split('#');
                        SubmitOrder subOrderModel = new SubmitOrder();
                        subOrderModel.SeatType = seat_Type.ToDictionary(m => m.Key, m => m.Value);
                        subOrderModel.SelSeatType = subOrderModel.SeatType.Keys.Last();
                        subOrderModel.TickType = (from t in tickType
                                                  where t.Key.Contains(item[0])
                                                  select t).ToDictionary(m => m.Key, m => m.Value);
                        subOrderModel.SelTickType = subOrderModel.TickType.Values.First();
                        subOrderModel.PassengerName = item[1];
                        subOrderModel.IDType = (from d in idType
                                                where d.Key.Contains(item[2])
                                                select d).ToDictionary(m => m.Key, m => m.Value);
                        subOrderModel.SelIDType = subOrderModel.IDType.Values.First();
                        subOrderModel.PassengerId = item[3];
                        subOrderModel.PassengerMobile = item[4];
                        subOrder.Add(subOrderModel);
                    }
                }
            }

            gridPassenger.ItemsSource = subOrder;
        }
Exemplo n.º 25
0
    public bool PosTest3()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest3: The key is a custom class");

        try
        {
            IDictionary iDictionary = new Dictionary<object,object>();
            MyClass mc = new MyClass();
            iDictionary.Add(mc, true);
            if (!iDictionary.Contains(mc))
            {
                TestLibrary.TestFramework.LogError("005", "The result is not the value as expected ");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
Exemplo n.º 26
0
 public bool Contains(KeyValuePair <HrbcField, object> item)
 {
     return(content.Contains(item));
 }
Exemplo n.º 27
0
 /// <summary>
 /// Determines whether a property already exists.
 /// </summary>
 /// <param name="name">The name of the property to check.</param>
 /// <returns>
 /// <see langword="true" /> if the specified property already exists;
 /// otherwise, <see langword="false" />.
 /// </returns>
 public bool Contains(string name)
 {
     return(Dictionary.Contains(name));
 }
    public bool NegTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException is not thrown.");

        try
        {
            IDictionary dictionary = new Dictionary<string, string>();

            dictionary.Add("txt", "notepad.exe");
            dictionary.Add("bmp", "paint.exe");
            dictionary.Add("dib", "paint.exe");
            dictionary.Add("rtf", "wordpad.exe");

            string key = null;

            dictionary.Contains(key);

            TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown.");
            retVal = false;
        }
        catch (ArgumentNullException) { }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Exemplo n.º 29
0
 public bool Contains(KeyValuePair <int, int> item)
 {
     return(_dictionary.Contains(item));
 }
Exemplo n.º 30
0
    public bool NegTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest1: The argument is a null reference");

        try
        {
            IDictionary iDictionary = new Dictionary<object,object>();
            iDictionary.Contains(null);
            TestLibrary.TestFramework.LogError("101", "The ArgumentNullException was not thrown as expected");
            retVal = false;
        }
        catch (ArgumentNullException)
        {
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
 public bool Contains(KeyValuePair <TKey, TValue> item)
 {
     return(Dictionary.Contains(item));
 }
        public void ShouldReportContainsCorrectly()
        {
            var bag = new Dictionary<string, object>();
            bag.Add(new Url("/2"));

            Assert.That(bag.Contains<Url>());
            Assert.That(bag.Contains(typeof(Url)));
        }
 private static void CheckMetadataSubset(Dictionary<string, string> expected, Dictionary<string, string> actual)
 {
     foreach (var pair in expected)
         Assert.IsTrue(actual.Contains(pair), "Expected metadata item {{ {0} : {1} }} not found.", pair.Key, pair.Value);
 }
Exemplo n.º 34
0
        /// <summary>
        /// Returns an alt present in the passed dictionary
        /// </summary>
        /// <param name="nick"></param>
        public string FindPlayerAlt(string nick, Dictionary<string,Player>.KeyCollection allNames)
        {
            try
            {
                StreamReader reader = new StreamReader(".//AlternateNames.txt");
                string input;
                string newNick;

                do
                {
                    // Get line of alts
                    input = reader.ReadLine();
                    input = input.ToUpper();

                    // See if the current line of alts contains the input nick
                    if (input.Contains(nick.ToUpper()))
                    {
                        int index = 0;
                        while (true)
                        {
                            // Parse a nick
                            int commaLocation = input.IndexOf(",", index);
                            if (commaLocation == -1)
                            {
                                // Get all remaining characters for a final match attempt
                                newNick = input.Substring(index, input.Length - index).Trim();
                                if (allNames.Contains(newNick))
                                {
                                    errorwriter.Write("Match found: " + newNick);
                                    reader.Close();
                                    return newNick;
                                }
                                break;
                            }
                            else
                            {
                                newNick = input.Substring(index, commaLocation - index);

                                // If the new nick is found in the collection of players, return the new nick
                                if (allNames.Contains(newNick))
                                {
                                    errorwriter.Write("Match found: " + newNick);
                                    reader.Close();
                                    return newNick;
                                }

                                // Advance past the comma
                                index = commaLocation + 1;
                            }
                        }
                    }
                } while (!reader.EndOfStream);

                // Search failed
                errorwriter.Write("No match found");
                reader.Close();
                return string.Empty;
            }
            catch (FileNotFoundException e)
            {
                errorwriter.Write("Could not find AlternateNames.txt (" + e.Message + ")");
                return string.Empty;
            }
            catch (Exception e)
            {
                errorwriter.Write("Error reading alternate name file (" + e.Message + ")");
                return string.Empty;
            }
        }
Exemplo n.º 35
0
        private Dictionary<int, string> GetPop3NewMessagesIDs(Pop3Client client)
        {
            var newMessages = new Dictionary<int, string>();

            var emailIds = client.GetUniqueIds();

            if (!emailIds.Any() || emailIds.Count == Account.MessagesCount)
                return newMessages;

            var i = 0;
            var chunk = tasksConfig.ChunkOfPop3Uidl;

            var emails = emailIds.Skip(i).Take(chunk).ToList();

            do
            {
                var checkList = emails.Select(e => e.UniqueId).Distinct().ToList();

                var existingUidls = mailBoxManager.CheckUidlExistance(Account.MailBoxId, checkList);

                if (!existingUidls.Any())
                {
                    foreach (
                        var item in
                            emails.Select(email => new KeyValuePair<int, string>(email.Index, email.UniqueId))
                                  .Where(item => !newMessages.Contains(item)))
                    {
                        newMessages.Add(item.Key, item.Value);
                    }
                }
                else if (existingUidls.Count != emails.Count)
                {
                    foreach (var item in (from email in emails
                                          where !existingUidls.Contains(email.UniqueId)
                                          select new KeyValuePair<int, string>(email.Index, email.UniqueId)).Where(
                                              item => !newMessages.Contains(item)))
                    {
                        newMessages.Add(item.Key, item.Value);
                    }
                }

                i += chunk;

                emails = emailIds.Skip(i).Take(chunk).ToList();

            } while (emails.Any());

            return newMessages;
        }
Exemplo n.º 36
0
 /// <summary>
 /// Check if the CommandArgument(s) contains a particular option.
 /// </summary>
 /// <param name="option">From CommandArgument.Option or of the form -[:alpha:].</param>
 /// <returns></returns>
 public bool Contains(string option)
 {
     return(Dictionary.Contains(option));
 }
Exemplo n.º 37
0
 public bool Contains(KeyValuePair <TKey, TValue> item) => dictionary.Contains(item);
Exemplo n.º 38
0
 public bool Contains(FooKey key) => Dictionary.Contains(key);
Exemplo n.º 39
0
 /// <summary>
 /// Determines if a byte with the given index exists.
 /// </summary>
 /// <param name="index">the index of the byte</param>
 /// <returns>true, if the is in the collection</returns>
 public bool Contains(long index)
 {
     return(Dictionary.Contains(index));
 }
Exemplo n.º 40
0
 public bool Contains(KeyValuePair <string, IndexField> item)
 {
     return(_underlyingStorage.Contains(item));
 }
Exemplo n.º 41
0
        static void Main(string[] args)
        {
            Trace.Write("START");

            Debuggers.LogError("error occured");
            Debuggers.LogError(new Exception("ex occured"));

            Dictionary <string, int> dict = new Dictionary <string, int>()
            {
                { "Marketing", 1 }, { "Sales", 2 }, { "IT", 3 }
            };

            var dictExists = dict.Contains(new KeyValuePair <string, int>("IT", 2));



            Formaters.DateAndTime(DateTime.Now, 10.23456D);
            Debuggers.Start();
            var customers = Linqers.CustomersWithOrdersByYear(2017);

            Linqers.GetProductsLongestNameByCategory();

            string asyncResult;

            Task.Run(async() =>
            {
                asyncResult = await Threads.StartAsync();
            }).GetAwaiter().GetResult();


            Threads.RunTimer();
            var publicTypes       = new Reflections().GetPublicTypes();
            var assemblyName      = new Reflections().GetAssemblyName();
            var isPositiveDecimal = Regexes.PositiveWithTwoDecimalPlaces(5.666M);

            Console.WriteLine("Available memory: " + new PerformanceCounter("Memory", "Available MBytes").NextValue());

            var assemblies = new Reflections().GetTypesFromCurrentDomain();

            Product productForSerialization = new Product()
            {
                CategoryId = 1, Id = 2, IsValid = true
            };

            Serializators.SerializeWithBinaryFormatter(productForSerialization, "bin.dat");
            Serializators.SerializeWithDataContractToFile(productForSerialization, "datacontract.dat");


            string userSerialized = Serializators.SerializeWithBinaryWriter(new Product {
                Id = 10
            });
            DateTime?nullableDateTime = null;
            bool     isDateNotNull    = nullableDateTime.HasValue;

            RateCollection rateCollection = new RateCollection(new Rate[] { new Rate {
                                                                                Value = 1
                                                                            } });

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

            var currentAssembly = Assembly.GetExecutingAssembly();

            var sb = new StringBuilder();

            sb.Append("First");
            sb.AppendLine();
            sb.Append("Second");
            Console.WriteLine(sb);

            SortedList <string, string> sortedList = new SortedList <string, string>()
            {
                { "asd", "dsa" }
            };

            Debug.Assert(false, "stop");
            float  amount    = 1.6F;
            object amountObj = amount;
            int    amountInt = (int)(float)amountObj;

            new Product().Add("book1");

            User newUser = new User()
            {
                UserGroup = Group.Supervisors | Group.Users
            };
            bool isTrue    = newUser.UserGroup < Group.Administrator;
            var  userGroup = newUser.UserGroup;

            Console.WriteLine(userGroup);

            string stringNull    = null;
            string stringNotNull = "asd";

            Comparers.AreEqual(stringNull, stringNotNull);

            Rate rate1 = new Rate()
            {
                Value = 1, Category = "cat"
            };
            string xml  = Serializators.SerializeWithDataContract(rate1);
            string json = Serializators.SerializeWithDataContractJson(rate1);

            Console.WriteLine("xml:\r\n" + xml);
            Console.WriteLine("json:\r\n" + json);

            Subscriber sub = new Subscriber();

            sub.Subscribe();
            sub.Execute();


            Console.Read();
            return;


            DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Rate));

            Console.WriteLine(string.Format("{0} asdasd {1:000#} asd", 4, 159));
            Console.WriteLine(123.ToString("000#"));

            Rate ratenull = null;
            int  wynik;

            int.TryParse(ratenull.Category, out wynik);

            Console.Read();

            BaseLogger logger = new Logger();

            logger.Log("Log started");
            logger.Log("Base: Log contiuniug");
            ((Logger)logger).LogCompleted();


            Console.Read();
            return;


            Reflections.SetPropertiesOnObject(new Rate()
            {
                MyInt = 10
            }, "MyInt", "MyIntSpecified");
            float  mojfloat = 1.6F;
            double dable    = (double)mojfloat;
            var    hashed   = Hashers.HashByAlgName(@"C:\windows-version.txt", "SHA");

            Threads.ConcurrentDict();
            var x = from i in new List <int> {
                1, 2
            }
            group i by i into grouped
            where grouped.Key > 1
            select grouped.Key;


            string xmlInput = "<xml><RateSheet><rate category=\"boutou\" date=\"2012-12-12\"><value>0.03</value></rate><rate category=\"druga\" date=\"2011-11-11\"><value>0.04</value></rate></RateSheet></xml>";

            var result = Serializators.ReadFromXml(xmlInput);

            SHA1Managed SHhash = new SHA1Managed();

            //new Class2().Method1();
            Class1        class1 = new Class1();
            INewInterface interf = class1;

            interf.Method1();

            IEnumerable <Person> people = new List <Person>()
            {
                new Person {
                    PhoneNumbers = new List <PhoneNumber> {
                        new PhoneNumber {
                            Number = "1"
                        }, new PhoneNumber {
                            Number = "2"
                        }
                    }
                },
                new Person {
                    PhoneNumbers = new List <PhoneNumber> {
                        new PhoneNumber {
                            Number = "2"
                        }, new PhoneNumber {
                            Number = "3"
                        }
                    }
                },
            };

            IEnumerable <IEnumerable <PhoneNumber> > phoneLists = people.Select(p => p.PhoneNumbers);
            IEnumerable <PhoneNumber> phoneNumbers = people.SelectMany(p => p.PhoneNumbers);
        }
Exemplo n.º 42
0
        /// <summary>
        /// 跳转设置单价参数
        /// </summary>
        /// <returns></returns>
        public ActionResult SetParameters()
        {
            var priceDic   = _systemProfileRepos.GetAllPrice().ToDictionary(x => x.SP_ID);
            var timeDic    = _systemProfileRepos.GetByStartStr("time").ToDictionary(x => x.SP_ID);
            var timeHigh   = timeDic["time_high"].SP_Value;
            var timeNormal = timeDic["time_normal"].SP_Value;
            var timeLow    = timeDic["time_low"].SP_Value;

            IDictionary timeFlagDic    = new Dictionary <int, string>();
            var         timeBlocks     = timeHigh.Split(new char[] { ',' });
            string      timeTipStr     = "";
            string      highTimeTipStr = "";

            foreach (var timeStr in timeBlocks)
            {
                var times = timeStr.Split(new char[] { '-' });
                if (times != null && times.Length > 1)
                {
                    if (string.IsNullOrWhiteSpace(highTimeTipStr))
                    {
                        highTimeTipStr += times[0] + "点-" + times[1] + "点";
                    }
                    else
                    {
                        highTimeTipStr += "," + times[0] + "点-" + times[1] + "点";
                    }
                    int startTime = Int32.Parse(times[0]);
                    int endTime   = Int32.Parse(times[1]);
                    for (int i = startTime; i < endTime; i++)
                    {
                        if (!timeFlagDic.Contains(i))
                        {
                            timeFlagDic.Add(i, "high");
                        }
                    }
                }
            }
            if (!string.IsNullOrWhiteSpace(highTimeTipStr))
            {
                timeTipStr += "【峰时:" + highTimeTipStr + "】";
            }
            string normalTimeTipStr = "";

            timeBlocks = timeNormal.Split(new char[] { ',' });
            foreach (var timeStr in timeBlocks)
            {
                var times = timeStr.Split(new char[] { '-' });
                if (times != null && times.Length > 1)
                {
                    if (string.IsNullOrWhiteSpace(normalTimeTipStr))
                    {
                        normalTimeTipStr += times[0] + "点-" + times[1] + "点";
                    }
                    else
                    {
                        normalTimeTipStr += "," + times[0] + "点-" + times[1] + "点";
                    }
                    int startTime = Int32.Parse(times[0]);
                    int endTime   = Int32.Parse(times[1]);
                    for (int i = startTime; i < endTime; i++)
                    {
                        if (!timeFlagDic.Contains(i))
                        {
                            timeFlagDic.Add(i, "normal");
                        }
                    }
                }
            }
            if (!string.IsNullOrWhiteSpace(normalTimeTipStr))
            {
                timeTipStr += "【平时:" + normalTimeTipStr + "】";
            }
            string lowTimeTipStr = "";

            timeBlocks = timeLow.Split(new char[] { ',' });
            foreach (var timeStr in timeBlocks)
            {
                var times = timeStr.Split(new char[] { '-' });
                if (times != null && times.Length > 1)
                {
                    if (string.IsNullOrWhiteSpace(lowTimeTipStr))
                    {
                        lowTimeTipStr += times[0] + "点-" + times[1] + "点";
                    }
                    else
                    {
                        lowTimeTipStr += "," + times[0] + "点-" + times[1] + "点";
                    }
                    int startTime = Int32.Parse(times[0]);
                    int endTime   = Int32.Parse(times[1]);
                    for (int i = startTime; i < endTime; i++)
                    {
                        if (!timeFlagDic.Contains(i))
                        {
                            timeFlagDic.Add(i, "low");
                        }
                    }
                }
            }
            if (!string.IsNullOrWhiteSpace(lowTimeTipStr))
            {
                timeTipStr += "【谷时:" + lowTimeTipStr + "】";
            }
            ViewBag.timeDic     = timeDic;
            ViewBag.timeFlagDic = timeFlagDic;
            ViewBag.timeTipStr  = timeTipStr;

            return(View(priceDic));
        }
Exemplo n.º 43
0
 public bool Contains(KeyValuePair <NdiffFlag, string> Item)
 {
     return(_ndiffOptions.Contains(new KeyValuePair <string, string>(_ndiffFlagToOption[Item.Key], Item.Value)));
 }
Exemplo n.º 44
0
        public bool Contains(string propertyName)
        {
            object objectName = propertyName.ToLower(CultureInfo.InvariantCulture);

            return(Dictionary.Contains(objectName));
        }
Exemplo n.º 45
0
        private static bool?FindInList(string searchTerm, int value)
        {
            Dictionary <string, int> data = CreateTestData();

            return(data.Contains(new KeyValuePair <string, int>(searchTerm, value)));
        }
Exemplo n.º 46
0
        void ReadMessage()
        {
            NetIncomingMessage inMsg;

            if ((inMsg = peer.ReadMessage()) != null)
            {
#if DEBUG
                Console.WriteLine($"msg: {inMsg.MessageType}");
#endif
                switch (inMsg.MessageType)
                {
                case NetIncomingMessageType.Data:
                    // Handle custom messages
                    Process(inMsg);
                    break;

                case NetIncomingMessageType.DiscoveryResponse:
                    try
                    {
                        // Parse game data
                        FoundGame fg = ByteSerializer.ByteArrayToObject <FoundGame>(inMsg.Data);
                        // skip if game is already discovered / up to date
                        if (DiscoveredHosts.Contains(new KeyValuePair <IPEndPoint, FoundGame>(inMsg.SenderEndPoint, fg)))
                        {
                            break;
                        }
                        // Add server to list
                        DiscoveredHosts.Add(inMsg.SenderEndPoint, fg);
                        Console.WriteLine($"Discovered host at: {inMsg.SenderEndPoint}");
                    }
                    catch { }

                    break;

                case NetIncomingMessageType.DiscoveryRequest:
                    if (isHost && !gameActive)
                    {
                        peer.SendDiscoveryResponse(PacketFactory.CreateFoundGameMessage(peer, FoundGame.CreateFromGrid(grid, peer.ConnectionsCount + 1)), inMsg.SenderEndPoint);
                    }
                    break;

                case NetIncomingMessageType.StatusChanged:
                    // handle connection status messages
                    if (isHost)
                    {
                        switch (inMsg.SenderConnection.Status)
                        {
                        case NetConnectionStatus.Connected:
                            if (isHost)
                            {
                                PlayerConnection np = new PlayerConnection(Player.GetRandomisedPlayer(), inMsg.SenderConnection.RemoteEndPoint);
                                peers.Add(np);
                                players.Add(np.player);
                            }

                            Console.WriteLine($"{inMsg.SenderConnection.RemoteEndPoint} {inMsg.SenderConnection.Status}");
                            Console.WriteLine($"{peers.Count + 1} players currently connected");
                            break;

                        case NetConnectionStatus.Disconnected:
                            if (isHost)
                            {
                                PlayerConnection p = (from peer in peers where Equals(inMsg.SenderConnection.RemoteEndPoint, peer.ipEndPoint) select peer).Single();
                                peers.Remove(p);
                                players.Remove(p.player);
                            }

                            Console.WriteLine($"{inMsg.SenderConnection.RemoteEndPoint} {inMsg.SenderConnection.Status}");
                            Console.WriteLine($"{peers.Count + 1} players currently connected");
                            break;
                        }
                    }
                    else
                    {
                        switch (inMsg.SenderConnection.Status)
                        {
                        case NetConnectionStatus.Connected:
                        case NetConnectionStatus.Disconnected:
                            Console.WriteLine($"{inMsg.SenderConnection.RemoteEndPoint} {inMsg.SenderConnection.Status}");
                            Console.WriteLine($"{peer.Connections.Count + 1} players currently connected");
                            break;
                        }
                    }

                    break;

                case NetIncomingMessageType.ConnectionApproval:
                    if (isHost)
                    {
                        if (gameActive)
                        {
                            inMsg.SenderConnection.Deny("Game already started");
                            break;
                        }

                        // not max players
                        if (grid.maxPlayers >= peer.ConnectionsCount + 1)
                        {
                            inMsg.SenderConnection.Approve();
                        }
                        else
                        {
                            inMsg.SenderConnection.Deny("Game is full");
                        }
                    }
                    else
                    {
                        inMsg.SenderConnection.Approve();      // TODO: Validate with gameID
                    }
                    break;

                case NetIncomingMessageType.DebugMessage:
                case NetIncomingMessageType.WarningMessage:
                    Console.WriteLine(inMsg.ReadString());
                    break;

                default: throw new ArgumentOutOfRangeException();
                }

                peer.Recycle(inMsg);
            }
        }
        public bool Contains(string attributeName)
        {
            string tempName = attributeName.ToLowerInvariant();

            return(Dictionary.Contains(tempName));
        }
 public bool Contains(KeyValuePair <A, B> item)
 {
     lock (_lock)
         return(_dict.Contains(item));
 }
Exemplo n.º 49
0
        // GET: api/Flights
        public JsonResult Get(string relative_to)
        {
            bool sync_all = false;

            if (Request != null)
            {
                sync_all = Request.Query.ContainsKey("sync_all");
            }

            if (sync_all)
            {
                string[] tmp = relative_to.Split('&');
                relative_to = tmp[0];
            }
            DateTime parsedDate;

            parsedDate = DateTime.Parse(relative_to);
            IEnumerable <FlightDetails> allFlightsDetails = flightManager.GetAllEllements();
            List <Flight> allFlights = new List <Flight>();

            /*try
             * {
             *  allFlights = new Flight[allFlightsDetails.Count()];
             * }
             * catch (Exception)
             * {
             *  throw new Exception("Container is empty");
             * }*/
            int i = 0;

            foreach (FlightDetails iterator in allFlightsDetails)
            {
                if (!sync_all & iterator.Flight.Is_external)
                {
                    continue;
                }

                if ((DateTime.Compare(iterator.Flight.Date_time, parsedDate) < 0) &&
                    (DateTime.Compare(iterator.Landing_time, parsedDate) >= 0))
                {
                    TimeSpan timeSpan  = parsedDate.Subtract(iterator.Flight.Date_time);
                    string   s         = timeSpan.TotalSeconds.ToString();
                    double   time_span = 0;
                    try
                    {
                        time_span = Double.Parse(s);//.Parse(s);
                        time_span++;
                    }catch (Exception)
                    {
                        Console.WriteLine("TimeSpan not a number\n");
                    }
                    int j = 0;
                    while (true)
                    {
                        if ((time_span - iterator.FlightPlan.Segments[j].Timespan_seconds) >= 0 && j < iterator.FlightPlan.Segments.Length)
                        {
                            time_span = time_span - iterator.FlightPlan.Segments[j].Timespan_seconds;
                            j++;
                            if (j == iterator.FlightPlan.Segments.Length - 1)
                            {
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                    double relative_location = time_span / iterator.FlightPlan.Segments[j].Timespan_seconds;
                    if (j <= 1)
                    {
                        iterator.Flight.Longitude = iterator.Flight.Longitude +
                                                    relative_location * (iterator.FlightPlan.Segments[j].Longitude
                                                                         - iterator.Flight.Longitude);

                        iterator.Flight.Latitude = iterator.Flight.Latitude +
                                                   relative_location * (iterator.FlightPlan.Segments[j].Latitude
                                                                        - iterator.Flight.Latitude);
                    }
                    else
                    {
                        iterator.Flight.Longitude = iterator.FlightPlan.Segments[j - 1].Longitude +
                                                    relative_location * (iterator.FlightPlan.Segments[j].Longitude
                                                                         - iterator.FlightPlan.Segments[j - 1].Longitude);

                        iterator.Flight.Latitude = iterator.FlightPlan.Segments[j - 1].Latitude +
                                                   relative_location * (iterator.FlightPlan.Segments[j].Latitude
                                                                        - iterator.FlightPlan.Segments[j - 1].Latitude);
                    }
                    allFlights.Add(iterator.Flight);
                    i++;
                }
            }
            if (sync_all)
            {
                Dictionary <string, Server> dic = ServerManager.dictionary;
                ServerManager manger            = ServerManager.getServerManger();
                foreach (Server index in manger.GetAllEllements())
                {
                    string         strResult;
                    string         url     = index.ServerURL + "/api/Flights?relative_to=" + relative_to;
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                        using (Stream stream = response.GetResponseStream())
                            using (StreamReader reader = new StreamReader(stream))
                            {
                                strResult = reader.ReadToEnd();
                                reader.Close();
                            }
                    List <Flight> flights = JsonConvert.DeserializeObject <List <Flight> >(strResult);
                    foreach (Flight one in flights)
                    {
                        if (!dic.Contains(new KeyValuePair <string, Server>(one.Flight_id, index)))
                        {
                            dic.Add(one.Flight_id, index);
                        }
                        one.Is_external = true;
                        allFlights.Add(one);
                    }
                }
            }
            JsonResult jr = new JsonResult(allFlights);

            return(jr);
        }
Exemplo n.º 50
0
 public bool Contains(KeyValuePair <string, PropertyValueCollection> item) => _valueTable.Contains(item);
Exemplo n.º 51
0
 public bool Contains(KeyValuePair <TKey, TValue> item)
 {
     return(_dict.Contains(item));
 }
 public bool Contains(KeyValuePair <TKey, TValue> item)
 {
     return(backing.Contains(item));
 }
Exemplo n.º 53
0
 public bool Contains(KeyValuePair <string, object> item)
 {
     return(viewData.Contains(item));
 }
Exemplo n.º 54
0
 private bool AssertCorrectParameters(Dictionary<string, string> expected, Dictionary<string, string> paramsToCheck)
 {
     return paramsToCheck.Count == expected.Count && paramsToCheck.All(p => expected.Contains(p));
 }
Exemplo n.º 55
0
        private List<string> CompareDictionaries(Dictionary<string, object> publishedValues, Dictionary<string, string> editedValues)
        {
            var notMatchingFields = new List<string>();

            // Check if values match JUST by checking values from PUBLISHED values which is containing just data from coupled table (no document specific data)
            foreach (var publishedItem in publishedValues)
            {
                // Check if the column is present in both published and edited dictionaries
                // Kentico does not store field in CMS_Version history if its value is set null
                if (!editedValues.ContainsKey(publishedItem.Key))
                {
                    // Check if published value is also empty
                    if (!string.IsNullOrEmpty(publishedItem.Value.ToString()))
                    {
                        // Published value is not empty, but Edited value is
                        notMatchingFields.Add(publishedItem.Key);
                    }
                    continue;
                }

                // Handle different types of values
                if (publishedItem.Value is DateTime)
                {
                    // Compare dates
                    DateTime publishedDate;
                    DateTime editedDate;

                    DateTime.TryParse(publishedItem.Value.ToString(), out publishedDate);
                    DateTime.TryParse(editedValues[publishedItem.Key], out editedDate);

                    bool datesMatch = publishedDate.CompareTo(editedDate) == 0;

                    if (!datesMatch)
                    {
                        notMatchingFields.Add(publishedItem.Key);
                    }

                }
                else if (publishedItem.Value is bool)
                {
                    bool publishedBool;
                    bool editedBool;

                    bool.TryParse(publishedItem.Value.ToString(), out publishedBool);
                    bool.TryParse(editedValues[publishedItem.Key], out editedBool);

                    bool boolsMatch = publishedBool.CompareTo(editedBool) == 0;

                    if (!boolsMatch)
                    {
                        notMatchingFields.Add(publishedItem.Key);
                    }
                }
                else
                {
                    // Check if the column has the same value as edited value
                    if (!editedValues.Contains(new KeyValuePair<string, string>(publishedItem.Key, publishedItem.Value.ToString())))
                    {
                        notMatchingFields.Add(publishedItem.Key);
                    }
                }
            }

            return notMatchingFields;
        }
Exemplo n.º 56
0
 public bool Contains(KeyValuePair <Date, T> item)
 {
     return(backingDictionary_.Contains(item));
 }
        public void GetOrAddTestCase1()
        {
            var dictionary = new Dictionary<String, String>();
            var keyValuePair = new KeyValuePair<String, String>( RandomValueEx.GetRandomString(),
                                                                 RandomValueEx.GetRandomString() );

            var actual = dictionary.GetOrAdd( keyValuePair );
            Assert.AreEqual( keyValuePair.Value, actual );
            Assert.IsTrue( dictionary.Contains( keyValuePair ) );
            Assert.AreEqual( 1, dictionary.Count );

            actual = dictionary.GetOrAdd( keyValuePair );
            Assert.AreEqual( keyValuePair.Value, actual );
            Assert.IsTrue( dictionary.Contains( keyValuePair ) );
            Assert.AreEqual( 1, dictionary.Count );
        }
Exemplo n.º 58
0
 public bool Contains(KeyValuePair <K, V> item) => _dictionary.Contains(item);
Exemplo n.º 59
0
 private void RemoveSendStatuses(Dictionary<int, int> temp_statuses)
 {
     Dictionary<int, int> temp_statuses2 = new Dictionary<int, int>();
     try
     {
         lock (statuses)
         {
             foreach (KeyValuePair<int, int> o in statuses)
                 if (!temp_statuses.Contains(o))
                     temp_statuses2.Add(o.Key, o.Value);
             statuses.Clear();
             foreach (KeyValuePair<int, int> o in temp_statuses2)
                 statuses.Add(o.Key, o.Value);
         }
     }
     catch (Exception ex) { Console.WriteLine("Произошла ошибка при очистке статусов "+ex.Message); }
     finally
     {
         if (temp_statuses2 != null) { temp_statuses2.Clear(); GC.SuppressFinalize(temp_statuses2); }
     }
 }
Exemplo n.º 60
0
 public void TestDictionary()
 {
     var dict = new Dictionary<YamlNode, int>();
     var key = (YamlScalar)"abc";
     dict[key] = 4;
     Assert.Throws<ArgumentException>(() => dict.Add(key, 5));
     key.Value = "def";
     Assert.IsFalse(dict.ContainsKey(key));
     Assert.IsFalse(dict.Remove(key));
     Assert.IsFalse(dict.Contains(new KeyValuePair<YamlNode, int>(key, 4)));
     var entry = dict.First(e => e.Key == key);
     Assert.IsFalse(dict.Contains(entry));
     Assert.IsFalse(((ICollection<KeyValuePair<YamlNode,int>>)dict).Remove(entry));
     Assert.IsTrue(( (ICollection<YamlNode>)dict.Keys ).IsReadOnly);
 }