Example #1
0
 public static string Get(Dictionary<string, string> dict, FormatType formatType, string code)
 {
     if (formatType == FormatType.GetKey)
         return dict.FirstOrDefault(d => d.Value == code).Key;
     else
         return dict.FirstOrDefault(d => d.Key == code).Value;
 }
 public static void oldestYoungest(Dictionary<string, int> friendList)
 {
     Console.WriteLine("{0} is the oldest friend,\n{1} is the youngest friend.",
     friendList.FirstOrDefault(x => x.Value == friendList.Values.Max()).Key,
     friendList.FirstOrDefault(x => x.Value == friendList.Values.Min()).Key
     );
 }
		public static bool IsPlayersTurn(Dictionary<int, Entity> entities)
		{
			var firstPlayer = entities.FirstOrDefault(e => e.Value.HasTag(FIRST_PLAYER)).Value;
			if(firstPlayer != null)
			{
				var offset = firstPlayer.IsPlayer ? 0 : 1;
				var gameRoot = entities.FirstOrDefault(e => e.Value != null && e.Value.Name == "GameEntity").Value;
				if(gameRoot != null)
					return (gameRoot.Tags[TURN] + offset) % 2 == 1;
			}
			return false;
		}
    //working tests
    public ICollection<string> TopSort()
    {
        Dictionary<string, int> predecessors = new Dictionary<string, int>();

        foreach (var vertexEdgesPair in this.graph)
        {
            if (!predecessors.ContainsKey(vertexEdgesPair.Key))
            {
                predecessors[vertexEdgesPair.Key] = 0;
            }

            foreach (string child in vertexEdgesPair.Value)
            {
                if (!predecessors.ContainsKey(child))
                {
                    predecessors[child] = 0;
                }

                predecessors[child]++;
            }
        }

        var result = new List<string>();

        string nextNode = predecessors.FirstOrDefault(vertexEdgesPair => vertexEdgesPair.Value == 0).Key;
        while (nextNode != null)
        {
            result.Add(nextNode);

            if (this.graph.ContainsKey(nextNode))
            {
                foreach (string child in this.graph[nextNode])
                {
                    predecessors[child]--;
                }
            }

            predecessors.Remove(nextNode);
            nextNode = predecessors.FirstOrDefault(vertexEdgesPair => vertexEdgesPair.Value == 0).Key;
        }

        bool graphIsCyclic = predecessors.Count > 0;
        if (graphIsCyclic)
        {
            throw new InvalidOperationException("A cycle detected in the graph");
        }

        return result;
    }
        /// <summary>
        /// Gets the hierarcchical row that describes the selected feature
        /// </summary>
        /// <param name="selectedFeatures"></param>
        /// <returns></returns>
        public async Task<List<PopupContent>> GetPopupContent(Dictionary<BasicFeatureLayer, List<long>> selectedFeatures)
        {
            //_layersInMapFeatureClassMap = GetMapLayersFeatureClassMap(); //gets all the feature layers from the map and add it to the dictionary with the Feature class as its key         
            var popupContents = new List<PopupContent>();
            try
            {
                var objectIDS = _selection.GetObjectIDs();

                if (_geodatabase == null)
                    _geodatabase = await GetGDBFromLyrAsync(_featureLayer);

                var kvpMapMember = selectedFeatures.FirstOrDefault(s => s.Key.GetTable().GetName().Equals(_featureClassName));
                
                foreach (var objectID in objectIDS)
                {
                    //List<HierarchyRow> hrows = new List<HierarchyRow>(); //this makes the custom popup show only one record.
                    //var newRow = await GetRelationshipChildren(_featureClassName, objectID);
                    //hrows.Add(newRow);
                    popupContents.Add(new DynamicPopupContent(kvpMapMember.Key, objectID, _featureClassName, this));
                }
            }
            catch (Exception)
            {

            }
            return popupContents;
        }
        /// <summary>
        ///     Validates the category path.
        ///     Should allow categories to match in same order.
        ///     Can only allow some missings segments
        /// </summary>
        /// <param name="outline">The outline containing ids and semantic url mappings.</param>
        /// <param name="requestedPath">The requested path. Containing category codes code1/code2/.../codeN</param>
        /// <returns></returns>
        protected virtual bool ValidateCategoryPath(Dictionary<string, string> outline, string requestedPath)
        {
            var prevCatIndex = -1;
            var outlineIds = outline.Keys.ToList();
            foreach (
                var segment in requestedPath.Split(this.Separator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
            {
                var category =
                    outline.FirstOrDefault(
                        x =>
                            x.Key.Equals(segment, StringComparison.InvariantCultureIgnoreCase)
                            || x.Value.Equals(segment, StringComparison.InvariantCultureIgnoreCase));

                //Category must exist
                if (category.Equals(default(KeyValuePair<string, string>)))
                {
                    return false;
                }

                var currentCatIndex = outlineIds.IndexOf(category.Key);

                //Segments order must match outline order
                if (prevCatIndex > 0 && prevCatIndex > currentCatIndex)
                {
                    return false;
                }

                prevCatIndex = currentCatIndex;
            }

            return true;
        }
Example #7
0
        private static HashSet<FinancialReport> GenerateReportData(
            List<string> vendors,
            Dictionary<string, decimal> vendorsIncomes,
            Dictionary<string, decimal> vendorsExpenses,
            Dictionary<string, decimal> vendorsTaxes)
        {
            var vendorsReport = new HashSet<FinancialReport>();

            foreach (var vendor in vendors)
            {
                var incomes = vendorsIncomes.FirstOrDefault(v => v.Key == vendor);
                var expenses = vendorsExpenses.FirstOrDefault(v => v.Key == vendor);
                var taxes = vendorsTaxes.FirstOrDefault(v => v.Key == vendor);
                var vendorReport = new FinancialReport
                {
                    Vendor = vendor,
                    Incomes = incomes.Value,
                    Expenses = expenses.Value,
                    TotalTaxes = taxes.Value
                };

                vendorsReport.Add(vendorReport);
            }
            return vendorsReport;
        }
Example #8
0
        static void Main()
        {
            var inputList = new List<int>() { 2, 2, 3, 3, 2, 3, 4, 3, 3 };
            var occurs = new Dictionary<int, int>();

            for (int i = 0; i < inputList.Count; i++)
            {
                if (!occurs.ContainsKey(inputList[i]))
                {
                    occurs.Add(inputList[i], 1);
                }
                else
                {
                    occurs[inputList[i]]++;
                }
            }

            int maxOccurs = 0;

            foreach (KeyValuePair<int, int> pair in occurs)
            {
                if (pair.Value > maxOccurs)
                {
                    maxOccurs = pair.Value;
                }
            }

            var myValue = occurs.FirstOrDefault(x => x.Value == maxOccurs).Key;
            Console.WriteLine("Result: ");
            Console.WriteLine(myValue);
        }
 public ActionResult PostByMonthName(short year, string month, short day, string title)
 {
     month = month.ToLower();
     var months = new Dictionary<int, string>();
     months.Add(1, "jan");
     months.Add(2, "feb");
     months.Add(3, "mar");
     months.Add(4, "apr");
     months.Add(5, "may");
     months.Add(6, "jun");
     months.Add(7, "jul");
     months.Add(8, "aug");
     months.Add(9, "sep");
     months.Add(10, "oct");
     months.Add(11, "nov");
     months.Add(12, "dec");
     var nowMonth = from m in months
                    where m.Value == "January"
                    select m;
     foreach(var entry in nowMonth) {
         Console.WriteLine(entry.Value);
     }
     Func<int, int> square = x => x * x;
     var squaredValue = square(25);
     var currentMonth = months.FirstOrDefault(m => month.Contains(m.Value));
     if (currentMonth.Value != null)
     {
         var currentDate = new DateTime(year, currentMonth.Key, day);
         var post = title == null ?
             BlogPosts.FirstOrDefault(p => p.PublishDate == currentDate) :
             BlogPosts.FirstOrDefault(p => p.PublishDate == currentDate && p.Title == title);
         return View("Post", post);
     }
     return View("Post");
 }
        public void StateActionMapping(double[, ,] R, List<string> _States, int dim, int FinalStateIndex)
        {
            Dictionary<int, string> dctStates = new Dictionary<int, string>();
            List<string> nextStepStates = new List<string>();
            List<int> nextStepIndeces = new List<int>();

            for (int i = 0; i < _States.Count; i++)
                dctStates.Add(i, _States[i]);

            for (int i = 0; i < dctStates.Count; i++)
            {
                GetNextStates(nextStepStates, dctStates[i], false);

                for (int j = 0; j < nextStepStates.Count; j++)
                {
                    nextStepIndeces.Add(dctStates.FirstOrDefault(state => state.Value == nextStepStates[j]).Key);
                }

                for (int j = 0; j < nextStepIndeces.Count; j++)
                {
                    R[i, j, 1] = nextStepIndeces[j];
                    R[i, j, 0] = nextStepIndeces[j] == FinalStateIndex ? 100 : 0;
                }

                nextStepStates.Clear();
                nextStepIndeces.Clear();
            }

            R[FinalStateIndex, 2, 1] = FinalStateIndex;
            R[FinalStateIndex, 2, 0] = 100;
        }
Example #11
0
        private static double GetThrottle(double rpm_factor, double throttle)
        {
            var map1 = new Dictionary<double, double>();
            var map2 = new Dictionary<double, double>();
            var prevmap = ThrottleMap.FirstOrDefault();
            double duty_y = 0;
            foreach(var d in ThrottleMap)
            {

                if (d.Key >= rpm_factor && prevmap.Key <= rpm_factor)
                {
                    duty_y = (rpm_factor - prevmap.Key) / (d.Key - prevmap.Key);
                    map1 = d.Value;
                    map2 = prevmap.Value;
                    break;
                }
                prevmap = d;
            }

            // Interpolate curves
            var prevthrottle = map1.FirstOrDefault();
            var percents1 = new double[2] {0, 0};
            var percents2 = new double[2] {0, 0};
            double duty_x = 0;
            foreach(var d in map1)
            {
                if (prevthrottle.Key <= throttle && throttle <= d.Key && prevthrottle.Key != 0)
                {
                    duty_x = (throttle - prevthrottle.Key)/(d.Key - prevthrottle.Key);
                    percents1[0] = prevthrottle.Value;
                    percents1[1] = d.Value;
                    break;
                }
                prevthrottle = d;
            }
            foreach(var d in map2)
            {
                if (prevthrottle.Key <= throttle && throttle <= d.Key && prevthrottle.Key != 0)
                {
                    percents2[0] = prevthrottle.Value;
                    percents2[1] = d.Value;
                    break;
                }
                prevthrottle = d;
            }

            // The magic happens here
            double factor = duty_y*(duty_x*percents1[1] + (1 - duty_x)*percents1[0])
                            + (1 - duty_y)*(duty_x*percents2[1] + (1 - duty_x)*percents2[0]);

            if (throttle*factor >= 2)
                factor = throttle;
            if(factor<=0)
                factor = throttle;
            if (double.IsNaN(factor) || double.IsInfinity(factor))
                factor = throttle;
            Console.WriteLine(String.Format("{0:0.0000} -> {1:0.0000}", throttle, factor));
            throttle = factor;
            return throttle;
        }
Example #12
0
        public bool Subscribe(NguiBaseBinding binding, NotifyPropertyChanged handler) {
            var context = binding.GetContext(Text);
            if (context == null) {
                return false;
            }

            var properties = new Dictionary<Type, Property>() {
                {typeof(bool), context.FindProperty<bool>(Text, binding)},
                {typeof(int), context.FindProperty<int>(Text, binding)},
                {typeof(float), context.FindProperty<float>(Text, binding)},
                {typeof(double), context.FindProperty<double>(Text, binding)}
            };
            var pair = properties.FirstOrDefault(x => x.Value != null);
            if (pair.Equals(default(KeyValuePair<Type, Property>))) {
                return false;
            }

            type = pair.Key;
            property = pair.Value;

            //Предотвращеие двойной подписи
            property.OnChange -= handler;
            property.OnChange += handler;

            return true;
        }
Example #13
0
        static void Main(string[] args)
        {
            Dictionary<string, int> data = new Dictionary<string, int>();
            string input;

            Console.Write("Enter count of numbers:");
            int count = int.Parse(Console.ReadLine());

            for (int index = 0; index < count; index++)
            {
                Console.Write("Element = ");
                input = Console.ReadLine();

                if (!data.ContainsKey(input))
                {
                    data.Add(input, 1);
                }
                else
                {
                    data[input] = data[input] + 1;
                }
            }

            int majorant = count / 2 + 1;

            if (data.Values.Contains(majorant))
            {
                Console.WriteLine("Majorant is " + data.FirstOrDefault(x => x.Value == majorant).Key);
            }
            else
            {
                Console.WriteLine("No majorant founded!");
            }
        }
Example #14
0
        static string BinaryToHexadecimal(string bin)
        {
            string hex = "";
            Dictionary<string, string> matrixBinHex = new Dictionary<string, string>{
                                                                                        {"0", "0000"},
                                                                                        {"1", "0001"},
                                                                                        {"2", "0010"},
                                                                                        {"3", "0011"},
                                                                                        {"4", "0100"},
                                                                                        {"5", "0101"},
                                                                                        {"6", "0110"},
                                                                                        {"7", "0111"},
                                                                                        {"8", "1000"},
                                                                                        {"9", "1001"},
                                                                                        {"A", "1010"},
                                                                                        {"B", "1011"},
                                                                                        {"C", "1100"},
                                                                                        {"D", "1101"},
                                                                                        {"E", "1110"},
                                                                                        {"F", "1111"},
                                                                                    };

            // 0111 1001
            for (int i = 0; i < bin.Length; i += 4)
            {
                string temp = "";
                string digit = bin.Substring(i, 4);
                temp = matrixBinHex.FirstOrDefault(x => x.Value.Contains(digit)).Key;
                hex += temp;
            }

            return hex;
        }
Example #15
0
    void Start()
    {
        if (gManager == this)
        {
            isPaused = false;
            iManager = new InputManager(0.1f, 0.2f); // It could be helpful, I guess.
            tagged_objects = GameObject.FindGameObjectsWithTag("Scene_Object");
            scene_objects = new ISceneObject[tagged_objects.Length];
            iManager.Initialize();
            // Initialize the list of scene objects, all of which have ONE ISceneObject component.
            for (int i = 0; i < tagged_objects.Length; i++)
            {
                scene_objects[i] = tagged_objects[i].GetComponent<ISceneObject>(); // Grab all of those scene objects!
            }

            // Initialize all scene objects.
            for (int j = 0; j < scene_objects.Length; j++)
            {
                scene_objects[j].Initialize();
            }
            levelDictionary = new Dictionary<GameState, string>() { { GameState.TLEVELONE, "GMLevel1" },
                                                                    { GameState.TLEVELTWO, "GMLevel2" },
                {GameState.LEVELONE, "Level1" },
                {GameState.LEVELTWO, "Level2" },
                { GameState.LEVELTHREE, "Level3"},
                {GameState.LEVELFOUR, "Level4" } };
            // This will break on regular levels, handle regular levels separately.
            GameManager.gState = levelDictionary.FirstOrDefault(x => x.Value == _testLevelPrefix + SceneManager.GetActiveScene().name).Key;
            if(GameManager.m_Camera != null)
            {
                transform.Find("PauseScreen").gameObject.GetComponent<Canvas>().worldCamera = GameManager.m_Camera;
            }
        }
    }
Example #16
0
        static void FindMajorantNumber(List<int> sequence)
        {
            var occurenceOfNumbers = new Dictionary<int, int>();

            foreach (var number in sequence)
            {
                if (occurenceOfNumbers.ContainsKey(number))
                {
                    occurenceOfNumbers[number]++;
                }
                else
                {
                    occurenceOfNumbers[number] = 1;
                }
            }

            var maxOccurence = occurenceOfNumbers.Values.Max();
            var keyForMaxOccurence = occurenceOfNumbers.FirstOrDefault(d => d.Value == maxOccurence);

            if (maxOccurence > sequence.Count / 2)
            {
                Console.WriteLine("Majorant is {0} it occurs {1} times", keyForMaxOccurence.Key, maxOccurence);
            }
            else
            {
                Console.WriteLine("Majorant doesn't exist");
            }
        }
Example #17
0
		// http://bugzilla.xamarin.com/show_bug.cgi?id=300
		// http://stackoverflow.com/questions/6517736/monotouch-crash-dictionary-firstordefault-type-initializer-predicateof
		public void Bug300_Linker_PredicateOf ()
		{
			Dictionary<string, DateTime> queued = new Dictionary<string, DateTime> ();
			KeyValuePair<string, DateTime> valuePair = queued.FirstOrDefault ();
			// above should not crash with System.ExecutionEngineException
			Assert.NotNull (valuePair);
		}
Example #18
0
 // обнуление возможности контратаки
 public void ResetCounterAttack(Dictionary<int, Units> team)
 {
     foreach (var i in team.Keys)
     {
         double value = team.FirstOrDefault(x => x.Key == i).Value.GetStat(Stats.CounterAttack);
         team[i].CounterAttackLeft = value;
     }
 }
        public void Start()
        {
            var countries = new Dictionary<string, string>
            {
                {"cz", "prague"},
                {"de", "berlin"},
                {"us", "new york"}
            };

            var existingCountry = countries.FirstOrDefault(x => x.Key == "cz");
            Console.WriteLine("Real -> Exists?: {0}", !existingCountry.IsNull());

            var fictionalCountry = countries.FirstOrDefault(x => x.Key == "xx");
            Console.WriteLine("Fictional -> Exists?: {0}", !fictionalCountry.IsNull());

            Console.WriteLine();
        }
Example #20
0
 public static void PopulateGrid(IEnumerable<IObstacle> obstacles, ref Dictionary<int[], IObstacle> grid)
 {
     foreach (var o in obstacles)
     {
         if (!grid.Any(g => g.Key.SequenceEqual(o.Position))) continue;
         var gridEntry = grid.FirstOrDefault(g => g.Key.SequenceEqual(o.Position));
         grid[gridEntry.Key] = grid[gridEntry.Key] ?? o;
     }
 }
Example #21
0
	private static CategoryType ExtractCategory(string title)
	{
		var categories = new Dictionary<string, CategoryType>
		{
			{ "[Easy]", CategoryType.Easy },
			{ "[Intermediate]", CategoryType.Intermediate },
			{ "[Hard]", CategoryType.Hard }
		};
		return categories.FirstOrDefault(x => title.Contains(x.Key)).Value;	
	}
        public override bool SetValues(Dictionary<string, string> values)
        {
            Value = values.FirstOrDefault().Value;
            Outputs[0].Value = Value;

            UpdateMeOnDashboard();
            UpdateMeInDb();

            return true;
        }
Example #23
0
    ArrayList DetectTileMove()
    {
        #region Detect Best Moves
        List<Transform> moves = new List<Transform>();
        TakeMoves(ref moves, true);
        if (moves.Count == 0)
        {
            TakeMoves(ref moves);
            if (moves.Count == 0)
            {
                return null;
            }
        }
        moves = moves.Distinct().ToList();
        float maxAsim =  moves.Max(a => GetAsimilationCount(a.position));
        moves = moves.Where(a => GetAsimilationCount(a.position) == maxAsim).ToList();
        #endregion
        #region Create Dictionary Move/Unit
        Dictionary<Transform, Transform> targetTiles = new Dictionary<Transform, Transform>();
        float nearUnitCost;
        foreach (var move in moves)
        {
            nearUnitCost = myUnits.Min(a =>Vector3.Distance(move.position, a.transform.parent.position));
            Transform bestUnit=myUnits.First(a=>Vector3.Distance(a.transform.parent.position,move.position)==nearUnitCost).transform.parent;
            targetTiles.Add(move, bestUnit);
        }
        #endregion
        #region Best Unit/Best Move
        Transform resumeTarget=null;
        switch (level)//принятие решения соответственно уровню
        {
            case AiLevel.Easy:{
                resumeTarget = targetTiles.FirstOrDefault(a=>Vector3.Distance(a.Key.position, a.Value.position)<1.6f).Key;
                if (resumeTarget == null)
                {
                    resumeTarget = targetTiles.First().Key;
                }
                }break;

            case AiLevel.Middle: {
                nearUnitCost = targetTiles.Min(a => Vector3.Distance(a.Key.position, a.Value.position));
                resumeTarget = targetTiles.First(a => Vector3.Distance(a.Key.position, a.Value.position) == nearUnitCost).Key;
            } break;

            case AiLevel.Hard:{
                nearUnitCost = targetTiles.Min(a => Vector3.Distance(a.Key.position, a.Value.position));
                int minAroundUnit = targetTiles.Where(a => Vector3.Distance(a.Key.position, a.Value.position) == nearUnitCost)
                    .Min(a => AroundUnitCount(a.Value));
                resumeTarget = targetTiles.First(a => Vector3.Distance(a.Key.position, a.Value.position) == nearUnitCost
                    && AroundUnitCount(a.Value) == minAroundUnit).Key;
            } break;
        }
        return new ArrayList(){targetTiles[resumeTarget], resumeTarget};
        #endregion
    }
 public Contour GetSingleContour()
 {
     if (Contours.Count == 0){
         throw new Exception("Контуры отсутствуют");
     }
     if (!AllContoursAreCompleted){
         throw new Exception("Все контуры должны быть замкнуты!");
     }
     var boundingBoxes = new Dictionary<int, BoundingBox>();
     for (int i=0; i<Contours.Count; i++){
         boundingBoxes.Add(i, Contours[i].GetBoundingBox());
     }
     var largestBox = boundingBoxes.FirstOrDefault(x => boundingBoxes.Where(y => y.Key != x.Key).All(y => x.Value.Contains(y.Value)));
     var restBoxes = boundingBoxes.Where(x => x.Key != largestBox.Key).ToArray();
     if (largestBox.Value == null) {
         throw new Exception("Контуры не образуют единой области. Дальнейшие вычисления невозможны");
     }
     if (restBoxes.Any(x => restBoxes.Where(y => y.Key != x.Key).Any(y => x.Value.Contains(y.Value)))){
         throw new Exception("Вложенность дырок недопустима. Дальнейшие вычисления невозможны");
     }
     var largestContour = Contours[largestBox.Key];
     largestContour.OrientCounterclockwise();
     for (int i = 0; i < Contours.Count; i++ ){
         if (i != largestBox.Key){
             var contour = Contours[i];
             contour.OrientClockwise();
             var nearestPoints = largestContour.ToDictionary(x => x,
                 x => contour.ToDictionary(y => y, y => Math.Sqrt(Math.Pow(x.X - y.X, 2) + Math.Pow(x.Y - y.Y, 2))).OrderBy(r => r.Value).First()).
                 OrderBy(r => r.Value.Value).First();
             int largeContourPointIndex = nearestPoints.Key.Index;
             int contourPointIndex = nearestPoints.Value.Key.Index;
             for (int j = 0; j < contour.Count - contourPointIndex + 1; j++){
                 Point pt = contour[contourPointIndex - 1 + j].Clone();
                 pt.Index = largeContourPointIndex + 1 + j;
                 largestContour.Insert(pt.Index - 1, pt);
             }
             for (int j = 0; j < contourPointIndex; j++){
                 Point pt = contour[j].Clone();
                 pt.Index = largeContourPointIndex + contour.Count - contourPointIndex + j + 2;
                 largestContour.Insert(pt.Index - 1, pt);
             }
             Point self = largestContour[largeContourPointIndex - 1].Clone();
             int offset = self.Index + contour.Count + 2;
             self.Index = offset;
             largestContour.Insert(self.Index - 1, self);
             for (int j = offset; j < largestContour.Count; j++){
                 largestContour[j].Index = j + 1;
             }
         }
     }
     largestContour.Index = 1;
     Contours.Clear();
     Contours.Add(largestContour);
     return largestContour;
 }
Example #25
0
File: Form.cs Project: epam/JDI
 public void Fill(Dictionary<string, string> map)
 {
     this.GetFields(typeof(ISetValue)).ForEach(element =>
     {
         var fieldValue = map.FirstOrDefault(pair =>
             GetElementClass.NamesEqual(pair.Key, NameAttribute.GetElementName(element))).Value;
         if (fieldValue == null) return;
         var setValueElement = (ISetValue)element.GetValue(this);
         DoActionRule(fieldValue, val => SetFieldValueAction(this, val, setValueElement));
     });
 }
        /// <summary>
        /// Processes the work item. pushes give document files for tagging
        /// </summary>
        /// <param name="message">The message.</param>
        protected override void ProcessMessage(PipeMessageEnvelope message)
        {
            Send(message);
            var documentCollection = message.Body as DocumentCollection;
            documentCollection.ShouldNotBe(null);
            documentCollection.documents.ShouldNotBe(null);
            documentCollection.documents.ShouldNotBeEmpty();
            var nativeSet =
                    documentCollection.documents.FindAll(
                        d => (d.docType == DocumentsetType.NativeSet));
            
            try
            {
                IDictionary<int, List<BulkDocumentInfoBEO>> tags = new Dictionary<int, List<BulkDocumentInfoBEO>>();
                IDictionary<int, string> tagKeys = new Dictionary<int, string>();
                //Converting to RVWDocument from Document detail object
                var documents = ToDocumentBeoList(nativeSet);
                foreach (var document in documents)
                {
                    var bulkDocumentInfoBEO = new BulkDocumentInfoBEO
                    {
                        DocumentId = document.DocumentId,
                        DuplicateId = document.DuplicateId,
                        FromOriginalQuery = true,
                        CreatedBy = _jobParams.CreatedBy,
                        FamilyId = document.FamilyId
                    };

                    foreach (var tag in document.Tags)
                    {
                        if (tags.ContainsKey(tag.TagId))
                        {
                            var bulkDocumentInfoBeOs = tags.FirstOrDefault(t => t.Key == tag.TagId).Value;
                            bulkDocumentInfoBeOs.Add(bulkDocumentInfoBEO);
                        }
                        else
                        {
                            var bulkDocumentInfoBeOs = new List<BulkDocumentInfoBEO> {bulkDocumentInfoBEO};
                            tags.Add(tag.TagId, bulkDocumentInfoBeOs);
                            tagKeys.Add(tag.TagId, tag.TagName);
                        }
                    }
                }

                BulkTagging(tags, tagKeys);
                LogTaggingMessage(nativeSet, true, TagSuccesMessage);
            }
            catch (Exception ex)
            {
                LogTaggingMessage(nativeSet, false, TagFailureMessage);
                ReportToDirector(ex.ToUserString());
                ex.Trace().Swallow();
            }
        }
Example #27
0
File: Noe.cs Project: jotem/SPOJ
 public static String getMissingAnimalNumber(Dictionary<String,int> data)
 {
     if (data.ContainsValue(1))
     {
         return data.FirstOrDefault(value => value.Value == 1).Key;
     }
     else
     {
         return "No missing animal has been found";
     }
 }
Example #28
0
        public Robot UpdatePosition(int[] positionUpdate, Dictionary<int[], IObstacle> grid)
        {
            var updatedPosition = new[] { Position[0] + positionUpdate[0], Position[1] + positionUpdate[1] };
            if (!grid.Keys.Any(g => g.SequenceEqual(updatedPosition))) return this; // new position is out of bounds

            var obstacle = grid.FirstOrDefault(g => g.Key.SequenceEqual(updatedPosition)).Value;
            if (obstacle != null) return obstacle.TakeAction(this); // return the obstacle action if encountered obstacle

            Position = updatedPosition;
            return this;
        }
Example #29
0
 public static string GetSurprise()
 {
      Dictionary<int,string> IdToSite = new Dictionary<int,string>(){
     {1,"http://wired.com"},
     {2,"http://www.nationalgeographic.com/"},
     {3,"https://www.ted.com/"},
     {4,"https://www.padi.com/scuba-diving/"}
 };
     Random rnd = new Random();
     int rndKey = rnd.Next(1, 5);
     return IdToSite.FirstOrDefault(x => x.Key == rndKey).Value;
 }
Example #30
0
 // получение юнита, который должен походить, сейчас
 public void GetCurrentUnit(Model mod, Dictionary<int, Units> red, Dictionary<int, Units> green)
 {
     RoundTurn(mod, red, green);
     mod.CurrentTeam = mod.TurnList.FirstOrDefault().team;
     var NameUnit = mod.TurnList.FirstOrDefault().name;
     if (mod.CurrentTeam == "Red")
     {
         var xxx = red.FirstOrDefault(x => x.Value.Name == NameUnit && x.Value.Live == true && x.Value.OnAction == true);
         mod.CurrentUnitAttak = xxx.Key;
     }
     else { mod.CurrentUnitAttak = green.Where(x => x.Value.Name == NameUnit && x.Value.Live == true && x.Value.OnAction == true).FirstOrDefault().Key; }
 }