コード例 #1
1
 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
     );
 }
コード例 #2
0
ファイル: DictionaryHelper.cs プロジェクト: Cold1986/MZZ
 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;
 }
コード例 #3
0
		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;
		}
コード例 #4
0
    //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;
    }
コード例 #5
0
        public static SimpleMaterial CreateMaterial(TwoDimensionDrawContext drawContext, BrushWidget widget)
        {
            SimpleMaterial simpleMaterial = drawContext.CreateSimpleMaterial();
            Brush          brush          = widget.Brush;
            StyleLayer     styleLayer;

            if (brush == null)
            {
                styleLayer = null;
            }
            else
            {
                Dictionary <string, StyleLayer> .ValueCollection layers = brush.GetStyleOrDefault(widget.CurrentState).Layers;
                styleLayer = layers?.FirstOrDefault();
            }
            simpleMaterial.OverlayEnabled         = false;
            simpleMaterial.CircularMaskingEnabled = false;
            simpleMaterial.AlphaFactor            = (styleLayer?.AlphaFactor ?? 1f) * widget.Brush.GlobalAlphaFactor * widget.Context.ContextAlpha;
            simpleMaterial.ColorFactor            = (styleLayer?.ColorFactor ?? 1f) * widget.Brush.GlobalColorFactor;
            simpleMaterial.HueFactor        = styleLayer?.HueFactor ?? 0.0f;
            simpleMaterial.SaturationFactor = styleLayer?.SaturationFactor ?? 0.0f;
            simpleMaterial.ValueFactor      = styleLayer?.ValueFactor ?? 0.0f;
            simpleMaterial.Color            = (styleLayer?.Color ?? Color.White) * widget.Brush.GlobalColor;
            return(simpleMaterial);
        }
コード例 #6
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;
            }
        }
    }
コード例 #7
0
        public void OnSelection(MaterialDialog p0, View p1, int itemId, ICharSequence itemString)
        {
            try
            {
                var subCategory = SubCategories?.FirstOrDefault(a => a.Value.Contains(itemString.ToString())).Key;
                if (subCategory != null)
                {
                    IdSubCategory = subCategory;
                }

                ToolBar.Title = itemString.ToString();

                //Get Data Api
                MAdapter.VideoList.Clear();
                MAdapter.NotifyDataSetChanged();

                SwipeRefreshLayout.Refreshing = true;
                SwipeRefreshLayout.Enabled    = true;
                SwipeRefreshLayout.SetProgressBackgroundColorSchemeColor(AppSettings.SetTabDarkTheme ? Color.ParseColor("#424242") : Color.ParseColor("#f7f7f7"));

                StartApiService();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
コード例 #8
0
        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;
        }
コード例 #9
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);
		}
コード例 #10
0
ファイル: startup.cs プロジェクト: shtilyanov/HomeworkDSA
        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");
            }
        }
コード例 #11
0
        /// <summary>
        /// This function tries to convert a given string into a Color in the following order:
        ///    1. If the string starts with '#' the function tries to get the color from the hex-code
        ///    2. else the function tries to find the color in the color names Dictionary
        ///    3. If 1. + 2. were not successful the function adds a '#' sign and tries 1. + 2. again
        /// </summary>
        /// <param name="colorName">The localized name of the color, the hex-code of the color or the internal color name</param>
        /// <param name="colorNamesDictionary">Optional: The dictionary where the ColorName should be looked up</param>
        /// <returns>the Color if successful, else null</returns>
        public static Color?ColorFromString(string colorName, Dictionary <Color?, string> colorNamesDictionary)
        {
            Color?result = null;

            try
            {
                // if we don't have a string, we cannot have any Color
                if (string.IsNullOrWhiteSpace(colorName))
                {
                    return(null);
                }

                colorNamesDictionary ??= ColorNamesDictionary;

                if (!colorName.StartsWith("#"))
                {
                    result = colorNamesDictionary?.FirstOrDefault(x => string.Equals(x.Value, colorName, StringComparison.OrdinalIgnoreCase)).Key;
                }

                result ??= ColorConverter.ConvertFromString(colorName) as Color?;
            }
            catch (FormatException)
            {
                if (colorName != null && !result.HasValue && !colorName.StartsWith("#"))
                {
                    result = ColorFromString("#" + colorName);
                }
            }

            return(result);
        }
コード例 #12
0
        /// <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;
        }
コード例 #13
0
ファイル: BinToHex.cs プロジェクト: Hri100v/Telerik-Academy
        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;
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: vaster/Telerik.vasko
        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!");
            }
        }
コード例 #15
0
ファイル: MySqlManager.cs プロジェクト: Okiana/Team-Diosma
        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;
        }
コード例 #16
0
 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");
 }
コード例 #17
0
ファイル: Program.cs プロジェクト: nlhans/TorqueMapping
        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;
        }
コード例 #18
0
        /// <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;
        }
コード例 #19
0
ファイル: Evaluator.cs プロジェクト: Niller/LastStand
        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;
        }
コード例 #20
0
ファイル: StartUp.cs プロジェクト: Moiraines/TelerikAcademy
        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);
        }
コード例 #21
0
        public override void OnResponse(int buttonID, int[] switches, Dictionary <int, string> textEntries = null)
        {
            if (buttonID == SEARCH_BUTTON)
            {
                string searchText = textEntries?.FirstOrDefault(i => i.Key == SEARCH_ENTRY_ID).Value ?? "";

                HttpClient httpClient = new HttpClient();

                httpClient.GetAsync($"{API_URL}/searchFull/{Uri.EscapeUriString( searchText )}").ContinueWith(
                    async t =>
                {
                    try
                    {
                        string response = await t.Result.Content.ReadAsStringAsync();

                        if (!t.Result.IsSuccessStatusCode)
                        {
                            throw new Exception("An error occurred.");
                        }

                        VendorItem[] results = JsonConvert.DeserializeObject <VendorItem[]>(response);

                        if (results?.Length == 0)
                        {
                            DemiseSearchGump gump = new DemiseSearchGump("No results found for search.");
                            gump.SendGump();
                        }
                        else
                        {
                            DemiseSearchGump gump =
                                new DemiseSearchGump($"{results?.Length} result(s) for search term.", searchText,
                                                     results);
                            gump.SendGump();
                        }
                    }
                    catch (Exception e)
                    {
                        DemiseSearchGump gump = new DemiseSearchGump(e.Message);
                        gump.SendGump();
                    }
                });
            }
            else if (buttonID >= 0x40000000)
            {
                DemiseSearchGump gump = new DemiseSearchGump(_message, _searchTerm, _results);
                gump.SendGump();

                VendorItem item = _results.FirstOrDefault(i => i.Serial == buttonID);

                if (item == null)
                {
                    return;
                }

                SendMap(item.Serial, item.X, item.Y, item.Map);
            }

            Engine.RemoveSendPostFilter(_pfi);
        }
コード例 #22
0
        private void UpdateIncludeCount()
        {
            var count = rbIncludeSelected.Checked ? crmGridView1.SelectedCellRecords?.Entities?.Count : records?.Entities?.Count;

            lblIncludedRecords.Text = $"{count} records";
            lblDeleteHeader.Text    = $"Delete {count} {entities?.FirstOrDefault(e => e.Key == records?.EntityName).Value?.DisplayCollectionName?.UserLocalizedLabel?.Label}";
            txtDeleteWarning.Text   = deleteWarningText.Replace("[nn]", rbIncludeSelected.Checked ? count.ToString() : "ALL");
        }
コード例 #23
0
ファイル: Logic.cs プロジェクト: rickSanches/game
 // обнуление возможности контратаки
 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;
     }
 }
コード例 #24
0
        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();
        }
コード例 #25
0
ファイル: PriceJob.cs プロジェクト: blocksentinel/periscope
        private static decimal GetCoinPropertyByKey(SimplePriceResponse response, string coin, string property)
        {
            Dictionary <string, double?> t = response.FirstOrDefault(r => r.Key == coin).Value;

            double?value = t?.FirstOrDefault(p => p.Key == property).Value;

            return(value != null ? (decimal)value : 0);
        }
コード例 #26
0
        protected override bool ShouldComponentUpdate(Dictionary <string, object> nextProps, Dictionary <string, object> nextState)
        {
            if (nextProps?.FirstOrDefault(x => x.Key == "name").Value != props?.FirstOrDefault(x => x.Key == "name").Value)
            {
                return(false);
            }

            return(true);
        }
コード例 #27
0
        /// <summary>
        /// 开始导出
        /// </summary>
        /// <param name="uidoc"></param>
        /// <param name="view"></param>
        /// <param name="localConfig"></param>
        /// <param name="exportType"></param>
        /// <param name="outputStream"></param>
        /// <param name="features"></param>
        /// <param name="useShareTexture"></param>
        /// <param name="progressCallback"></param>
        /// <param name="cancellationToken"></param>
        private void StartExport(UIDocument uidoc, View3D view, AppLocalConfig localConfig, ExportType exportType, Stream outputStream, Dictionary <FeatureType, bool> features, bool useShareTexture, Action <int> progressCallback, CancellationToken cancellationToken)
        {
            using (var log = new RuntimeLog())
            {
                var config = new ExportConfig();
                config.TargetPath      = localConfig.LastTargetPath;
                config.ExportType      = exportType;
                config.UseShareTexture = useShareTexture;
                config.OutputStream    = outputStream;
                config.Features        = features ?? new Dictionary <FeatureType, bool>();
                config.Trace           = log.Log;
                config.ElementIds      = (features?.FirstOrDefault(x => x.Key == FeatureType.OnlySelected).Value ?? false)
                    ? _ElementIds
                    : null;
                config.LevelOfDetail = localConfig.LevelOfDetail;

                #region Add Plugin - CreatePropDb
                {
                    var cliPath = Path.Combine(
                        App.GetHomePath(),
                        @"Tools",
                        @"CreatePropDb",
                        @"CreatePropDbCLI.exe");

                    if (File.Exists(cliPath))
                    {
                        config.Addins.Add(new ExportPlugin(
                                              FeatureType.GenerateModelsDb,
                                              cliPath,
                                              new[] { @"-i", config.TargetPath }
                                              ));
                    }
                }
                #endregion

                #region Add Plugin - CreateThumbnail
                {
                    var cliPath = Path.Combine(
                        App.GetHomePath(),
                        @"Tools",
                        @"CreateThumbnail",
                        @"CreateThumbnailCLI.exe");

                    if (File.Exists(cliPath))
                    {
                        config.Addins.Add(new ExportPlugin(
                                              FeatureType.GenerateThumbnail,
                                              cliPath,
                                              new[] { @"-i", config.TargetPath }
                                              ));
                    }
                }
                #endregion

                Exporter.ExportToSvf(uidoc, view, config, x => progressCallback?.Invoke((int)x), cancellationToken);
            }
        }
コード例 #28
0
ファイル: Program.cs プロジェクト: jpmartin43/RobotController
 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;
     }
 }
コード例 #29
0
ファイル: DailyScraper.cs プロジェクト: aloisdg/DailyScraper
	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;	
	}
コード例 #30
0
        public override bool SetValues(Dictionary<string, string> values)
        {
            Value = values.FirstOrDefault().Value;
            Outputs[0].Value = Value;

            UpdateMeOnDashboard();
            UpdateMeInDb();

            return true;
        }
コード例 #31
0
        public async Task <IEnumerable <T> > GetItemsFromLocalDatabaseAsync <T>() where T : EntityData
        {
            IMobileServiceSyncTable <T> table = null;

            await Initialize <T>();

            table = _localDataTableDictionary?.FirstOrDefault(x => x.Key == typeof(T)).Value as IMobileServiceSyncTable <T>;

            return(await table?.ReadAsync());
        }
コード例 #32
0
 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;
 }
コード例 #33
0
ファイル: AI.cs プロジェクト: maxCdev/GardenBattle
    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
    }
コード例 #34
0
 /// <summary>
 /// Gets the <see cref="ConfigSection"/> with the specified section name.
 /// </summary>
 /// <value>
 /// The <see cref="ConfigSection"/>.
 /// </value>
 /// <param name="sectionName">Name of the section.</param>
 /// <returns></returns>
 public ConfigSection this[string sectionName]
 {
     get
     {
         return((null == sectionName)
             ? null
             : sections
                ?.FirstOrDefault(s => sectionName.Equals(s.Key, StringComparison.InvariantCultureIgnoreCase))
                .Value ?? new ConfigSection(sectionName));
     }
 }
コード例 #35
0
ファイル: Form.cs プロジェクト: 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));
     });
 }
コード例 #36
0
ファイル: Robot.cs プロジェクト: jpmartin43/RobotController
        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;
        }
コード例 #37
0
        /// <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();
            }
        }
コード例 #38
0
ファイル: Noe.cs プロジェクト: 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";
     }
 }
コード例 #39
0
ファイル: Logic.cs プロジェクト: rickSanches/game
 // получение юнита, который должен походить, сейчас
 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; }
 }
コード例 #40
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;
 }
        internal KEntity GetKEntityFromEntityName(string entityName)
        {
            try
            {
                if (!String.IsNullOrEmpty(entityName))
                {
                    return(entities.Where(x => x.Value?.EntityName.ToLower() == entityName.ToLower()).FirstOrDefault().Value);
                }
            }
            catch { }

            return(entities?.FirstOrDefault().Value);
        }
コード例 #42
0
ファイル: BDU.cs プロジェクト: lminhlam/BulkDataUpdater
 private void InitializeTab()
 {
     if (tabControl1.SelectedTab == tabUpdate)
     {
         btnExecute.Text = "Update records";
     }
     else if (tabControl1.SelectedTab == tabAssign)
     {
         btnExecute.Text = "Assign records";
         LoadOwners();
     }
     else if (tabControl1.SelectedTab == tabSetState)
     {
         btnExecute.Text = "Update records";
         LoadStates(entities?.FirstOrDefault(ent => ent.Key == records?.EntityName).Value);
     }
     else if (tabControl1.SelectedTab == tabDelete)
     {
         btnExecute.Text = "Delete records";
     }
     panWaitBetween.Visible = tabControl1.SelectedTab == tabUpdate;
     EnableControls(true);
 }
コード例 #43
0
        private DataWrapper GetCurrentGrid()
        {
            if (_gridAndData == null || _gridAndData.Count == 0)
            {
                return(null);
            }

            if (_currentTab.SelectedTab?.Tag?.ToString() == null)
            {
                return(_gridAndData?.FirstOrDefault().Value);
            }

            _gridAndData.TryGetValue(_currentTab.SelectedTab?.Tag?.ToString(), out DataWrapper selected);
            return(selected);
        }
コード例 #44
0
        /// <summary>
        /// Ermittelt die ID-Information aus der Informationssammlung
        /// </summary>
        /// <param name="information">Informationssammlung</param>
        /// <returns>ID-Information</returns>
        public static string GetInformationId(this Dictionary <string, IEnumerable <object> > information)
        {
            var id = default(string);

            var idexpressions = new[] { ".id", "id" };
            var ids           =
                information != null?
                information?.FirstOrDefault(entry => idexpressions.Any(expression => entry.Key.ToLower().EndsWith(expression))) :
                    default(KeyValuePair <string, IEnumerable <object> >)
            ;

            id = (ids?.Value?.FirstOrDefault() ?? new object()).ToString();

            return(id);
        }
コード例 #45
0
        /// <summary>
        /// 开始导出
        /// </summary>
        /// <param name="view"></param>
        /// <param name="targetPath"></param>
        /// <param name="exportType"></param>
        /// <param name="outputStream"></param>
        /// <param name="features"></param>
        /// <param name="useShareTexture"></param>
        private void StartExport(View3D view, string targetPath, ExportType exportType, Stream outputStream, Dictionary <FeatureType, bool> features, bool useShareTexture)
        {
            using (var log = new RuntimeLog())
            {
                var config = new ExportConfig();
                config.TargetPath      = targetPath;
                config.ExportType      = exportType;
                config.UseShareTexture = useShareTexture;
                config.OutputStream    = outputStream;
                config.Features        = features ?? new Dictionary <FeatureType, bool>();
                config.Trace           = log.Log;
                config.ElementIds      = (features?.FirstOrDefault(x => x.Key == FeatureType.OnlySelected).Value ?? false)
                    ?  _ElementIds
                    : null;

                Exporter.ExportToSvf(view, config);
            }
        }
コード例 #46
0
 public void GenerateMidLowResEnergySeries(DateTime start, DateTime end)
 {
     foreach (var day in new TimeSeriesSpan(start, end, 1).IncludedDates())
     {
         Dictionary <DateTime, TimeSeriesStreamCollection <Dsuid, int> >?timeseriesCollections = null;
         try
         {
             timeseriesCollections = ReadHighResEnergyValuesFromDb(new List <DateTime>()
             {
                 day
             });
             SaveMidResEnergyValuesToDb(timeseriesCollections);
             SaveLowResEnergyValuesToDb(timeseriesCollections);
             _dbContext.SaveChanges();
         }
         catch { throw; }
         finally { timeseriesCollections?.FirstOrDefault().Value?.Dispose(); }
     }
 }
コード例 #47
0
ファイル: ExcelWriter.cs プロジェクト: wkxuan/code
        /// <summary>
        /// 设置循环项
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Infos"></param>
        /// <param name="name"></param>
        /// <param name="funcs">对每个项有额外的处理方式</param>
        public void SetInfos <T>(IList <T> Infos, string name = "table", Dictionary <string, Func <T, string> > funcs = null) where T : class
        {
            List <PropertyInfo> PropertyList = Infos[0].GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
            DataTable           dt           = new DataTable(name);

            foreach (PropertyInfo item in PropertyList)
            {
                dt.Columns.Add(item.Name);
            }
            if (funcs != null)
            {
                foreach (var v in funcs)
                {
                    if (!dt.Columns.Contains(v.Key))
                    {
                        dt.Columns.Add(v.Key);
                    }
                }
            }
            foreach (var info in Infos)
            {
                DataRow dr = dt.NewRow();
                foreach (DataColumn dc in dt.Columns)
                {
                    PropertyInfo     item = PropertyList.FirstOrDefault(a => a.Name == dc.ColumnName);
                    Func <T, string> f    = funcs?.FirstOrDefault(a => a.Key == dc.ColumnName).Value;
                    if (item != null)
                    {
                        var obj = item.GetValue(info, null);
                        if (obj != null)
                        {
                            dr[dc.ColumnName] = obj.ToString();
                        }
                    }
                    if (f != null)
                    {
                        dr[dc.ColumnName] = f(info);
                    }
                }
                dt.Rows.Add(dr);
            }
            SetTable(dt);
        }
コード例 #48
0
        protected override void OnRender(TwoDimensionContext twoDimensionContext, TwoDimensionDrawContext drawContext)
        {
            base.OnRender(twoDimensionContext, drawContext);


            SimpleMaterial simpleMaterial = drawContext.CreateSimpleMaterial();
            Brush          brush          = Brush;
            StyleLayer     styleLayer;

            if (brush == null)
            {
                styleLayer = null;
            }
            else
            {
                Dictionary <string, StyleLayer> .ValueCollection layers = brush.GetStyleOrDefault(CurrentState).Layers;
                styleLayer = layers?.FirstOrDefault();
            }
            simpleMaterial.OverlayEnabled         = false;
            simpleMaterial.CircularMaskingEnabled = false;
            simpleMaterial.Texture          = Texture;
            simpleMaterial.AlphaFactor      = (styleLayer?.AlphaFactor ?? 1f) * Brush.GlobalAlphaFactor * Context.ContextAlpha;
            simpleMaterial.ColorFactor      = (styleLayer?.ColorFactor ?? 1f) * Brush.GlobalColorFactor;
            simpleMaterial.HueFactor        = styleLayer?.HueFactor ?? 0.0f;
            simpleMaterial.SaturationFactor = styleLayer?.SaturationFactor ?? 0.0f;
            simpleMaterial.ValueFactor      = styleLayer?.ValueFactor ?? 0.0f;
            simpleMaterial.Color            = (styleLayer?.Color ?? Color.White) * Brush.GlobalColor;
            if (CachedMesh == null || Math.Abs(CachedMesh.Width - Size.X) > 0.01f && Math.Abs(CachedMesh.Height - Size.Y) > 0.01f)
            {
                UpdateDrawObject2D();
            }
            if (drawContext.CircularMaskEnabled)
            {
                simpleMaterial.CircularMaskingEnabled         = true;
                simpleMaterial.CircularMaskingCenter          = drawContext.CircularMaskCenter;
                simpleMaterial.CircularMaskingRadius          = drawContext.CircularMaskRadius;
                simpleMaterial.CircularMaskingSmoothingRadius = drawContext.CircularMaskSmoothingRadius;
            }
            //drawContext.Draw(GlobalPosition.X, GlobalPosition.Y, simpleMaterial, CachedMesh, Size.X, Size.Y);
            twoDimensionContext.Draw(GlobalPosition.X, GlobalPosition.Y, simpleMaterial, CachedMesh, Layer);
        }
コード例 #49
0
        public virtual void ConfigureWindows <T>(
            Dictionary <string, string> displayItemList,
            Dictionary <string, dynamic> dataItemList,
            bool configureLeftPane = true,
            bool configureHostPane = true)
        {
            _dataItemList = dataItemList;

            if (configureLeftPane)
            {
                ConfigureLeftPane(GetName());
            }
            if (configureHostPane)
            {
                ConfigureHostPane("");
            }

            ConfigureStatusBar();

            MenuBar menubar = null;

            if (displayItemList?.Count > 0)
            {
                var itemListView = GetClassListView <T>(displayItemList);
                LeftPane.Add(itemListView);

                string typeName = dataItemList.FirstOrDefault().Value.GetType().Name;
                switch ((T)dataItemList.FirstOrDefault().Value)
                {
                case Device d:
                case InstalledApp app:
                case SceneSummary s:
                case Subscription sub:
                case CapabilitySummary cs:
                    menubar = MenuHelper.GetStandardMenuBar(Top.ColorScheme, typeName, ExportItem, null);
                    break;

                default:
                    menubar = MenuHelper.GetStandardMenuBar(Top.ColorScheme, typeName, ExportItem, ImportItem);
                    break;
                }
            }
            else
            {
                menubar = MenuHelper.GetStandardMenuBar(Top.ColorScheme);
            }

            if (menubar != null)
            {
                Top.Add(menubar);
            }
            Top.Add(LeftPane);
            if (SettingsPane != null)
            {
                Top.Add(SettingsPane);
            }
            Top.Add(HostPane);
            Top.Add(StatusBar);

            if (displayItemList?.Count > 0)
            {
                dynamic itemToSelect = SelectedItem ?? dataItemList?.FirstOrDefault().Value;
                UpdateJsonView(itemToSelect.ToJson());
                if (SettingsPane != null)
                {
                    UpdateSettings <T>(itemToSelect);
                }
            }
        }
コード例 #50
0
        public override void Setup()
        {
            var statusBar = new StatusBar(new StatusItem[] {
                //new StatusItem(Key.ControlR, "~CTRL-R~ Refresh Data", () => RefreshScreen()),
                new StatusItem(Key.ControlQ, "~CTRL-Q~ Back/Quit", () => Quit())
            });

            LeftPane = new Window("Devices")
            {
                X           = 0,
                Y           = 0, // for menu
                Width       = 40,
                Height      = Dim.Fill(),
                CanFocus    = false,
                ColorScheme = Colors.TopLevel,
            };

            try
            {
                if (STClient.GetAllDevices().Items?.Count > 0)
                {
                    _viewDevices = STClient.GetAllDevices().Items
                                   .OrderBy(t => t.Name)
                                   .Select(t => new KeyValuePair <string, Device>(t.Label, t))
                                   .ToDictionary(t => t.Key, t => t.Value);
                }
                else
                {
                    SetErrorView($"You have no devices configured");
                }
            }
            catch (SmartThingsNet.Client.ApiException exp)
            {
                SetErrorView($"Error calling API: {exp.Source} {exp.ErrorCode} {exp.Message}");
            }
            catch (System.Exception exp)
            {
                SetErrorView($"Unknown error calling API: {exp.Message}");
            }

            ClassListView = new ListView(_viewDevices?.Keys?.ToList())
            {
                X             = 0,
                Y             = 0,
                Width         = Dim.Fill(0),
                Height        = Dim.Fill(), // for status bar
                AllowsMarking = false,
                ColorScheme   = Colors.TopLevel
            };

            if (_viewDevices?.Keys?.Count > 0)
            {
                ClassListView.OpenSelectedItem += (a) =>
                {
                    Top.SetFocus(SettingsPane);
                };
                ClassListView.SelectedItemChanged += (args) =>
                {
                    ClearClass(CurrentView);

                    var    selectedDevice = _viewDevices.Values.ToArray()[ClassListView.SelectedItem];
                    string json           = selectedDevice.ToJson();
                    CurrentView = CreateJsonView(json);
                    UpdateSettings(selectedDevice);
                };
            }
            LeftPane.Add(ClassListView);

            SettingsPane = new FrameView("Settings")
            {
                X           = Pos.Right(LeftPane),
                Y           = 0, // for menu
                Width       = Dim.Fill(),
                Height      = 8,
                CanFocus    = false,
                ColorScheme = Colors.TopLevel,
            };

            _deviceDetailsFrame = new FrameView("Device Details")
            {
                X      = 0,
                Y      = 0,
                Height = 6,
                Width  = 50,
            };
            SettingsPane.Add(_deviceDetailsFrame);

            _deviceLocationFrame = new FrameView("Device Location")
            {
                X      = Pos.Right(_deviceDetailsFrame),
                Y      = Pos.Y(_deviceDetailsFrame),
                Height = 6,
                Width  = 40,
            };

            SettingsPane.Add(_deviceLocationFrame);

            HostPane = new FrameView("")
            {
                X           = Pos.Right(LeftPane),
                Y           = Pos.Bottom(SettingsPane),
                Width       = Dim.Fill(),
                Height      = Dim.Fill(1), // + 1 for status bar
                ColorScheme = Colors.Dialog,
            };

            Top.Add(LeftPane, SettingsPane, HostPane);
            Top.Add(statusBar);

            if (_viewDevices?.Count > 0)
            {
                var firstItem = _viewDevices?.FirstOrDefault().Value;
                if (firstItem != null)
                {
                    CurrentView = CreateJsonView(firstItem.ToJson());
                    UpdateSettings(firstItem);
                }
            }
        }
コード例 #51
0
 public static Languages?GetLang(string value)
 {
     return(Map?.FirstOrDefault(kv => kv.Value == value).Key);
 }
コード例 #52
0
        bool IsDataTypeInitialized <T>() where T : EntityData
        {
            var isDataTypeInitalized = _isInitializedDictionary?.FirstOrDefault(x => x.Key.Equals(typeof(T))).Value;

            return(isDataTypeInitalized == true);
        }
コード例 #53
0
 private Item FindItemById(string id, Dictionary <Item, int> items)
 {
     return(items?.FirstOrDefault(i => i.Key.Id == id).Key);
 }
コード例 #54
0
 public string GetFirstError()
 {
     return(_propErrors?.FirstOrDefault().Value.FirstOrDefault());
 }
コード例 #55
0
        public virtual List <Expression> GeneratePropertyAssignExpression(ParameterExpression sourcePar, ParameterExpression targetPar, ParameterExpression checkerPar, bool isCopy = false, Dictionary <MemberInfo, Expression> excludeProperties = null)
        {
            Type sType = typeof(TSource);
            Type tType = typeof(TTarget);
            List <PropertyInfo> spis = sType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static).ToList();
            List <PropertyInfo> tpis = tType.GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();
            // target property --> source property
            // Dictionary<PropertyInfo, PropertyInfo> propertyMap = new Dictionary<PropertyInfo, PropertyInfo>(tpis.Select(p => new KeyValuePair<PropertyInfo, PropertyInfo>(p, null)));

            Dictionary <PropertyInfo, List <string> > sourceNamesMap
                = new Dictionary <PropertyInfo, List <string> >(spis.Select(x => new KeyValuePair <PropertyInfo, List <string> >(x, new List <string>()
            {
                x.Name
            })));

            sourceNamesMap.All(x =>
            {
                // [MapperPropertyName(Name="",SourceType=xxx)]
                var sAttrs = x.Key.GetCustomAttributes <MapperPropertyNameAttribute>();
                if (sAttrs != null)
                {
                    foreach (var attr in sAttrs)
                    {
                        if ((attr.TargetType == null ||
                             (attr.TargetType != null && attr.TargetType.IsAssignableFrom(tType))) &&
                            !x.Value.Contains(attr.Name))
                        {
                            x.Value.Add(attr.Name);
                        }
                    }
                }
                return(true);
            });

            // [MapperPropertyName(Name="",SourceType=xxx)]
            tpis.All(x =>
            {
                var tAttrs = x.GetCustomAttributes <MapperPropertyNameAttribute>();
                if (tAttrs != null)
                {
                    foreach (var attr in tAttrs)
                    {
                        if (attr.SourceType == null ||
                            (attr.SourceType != null && attr.SourceType.IsAssignableFrom(sType)))
                        {
                            var sp = sourceNamesMap.FirstOrDefault(x => x.Key.Name == attr.Name);
                            if (sp.Value != null && !sp.Value.Contains(x.Name))
                            {
                                sp.Value.Add(x.Name);
                            }
                        }
                    }
                }

                return(true);
            });


            List <Expression> expList = new List <Expression>()
            {
            };


            foreach (var pi in spis)
            {
                Expression excludeExpression = excludeProperties?.FirstOrDefault(p => p.Key == pi || (p.Key.DeclaringType == pi.DeclaringType && p.Key.Name == pi.Name)).Value;
                if (excludeExpression == null && excludeProperties != null && excludeProperties.Count > 0)
                {
                    excludeExpression = excludeProperties.FirstOrDefault(x => x.Value is MemberExpression me && me.Member == pi).Value;
                }
                if (excludeExpression?.NodeType == ExpressionType.MemberAccess ||
                    excludeExpression?.NodeType == ExpressionType.Constant)
                {
                    continue;
                }

                MemberInitExpression _dic = null;
                if (excludeExpression is MemberInitExpression mie)
                {
                    _dic = mie;
                }

                var names = sourceNamesMap[pi];

                // 获取targetProperty
                var targetList = tpis.Where(x => names.Any(y => y == x.Name)).ToList();
                if (targetList == null || targetList.Count == 0)
                {
                    targetList = tpis.Where(x => names.Any(y => y.Equals(x.Name, StringComparison.OrdinalIgnoreCase))).ToList();
                }
                if (targetList == null || targetList.Count == 0)
                {
                    continue;
                }

                foreach (var property in targetList)
                {
                    if (!property.CanWrite)
                    {
                        continue;
                    }
                    var exp = ConvertProperty(sourcePar, checkerPar, pi, targetPar, property, isCopy, _dic);
                    if (exp != null)
                    {
                        expList.Add(exp);
                    }
                }
            }
            return(expList);
        }
コード例 #56
0
 /// <summary>
 /// Gets the unknown associated with the specified index.
 /// </summary>
 /// <param name="index">The index.</param>
 /// <returns>The unknown.</returns>
 public Unknown Reverse(int index)
 {
     return(_unknowns.FirstOrDefault(p => p.Value == index).Key);
 }
コード例 #57
0
 public string GetTopLowellReference()
 {
     return(_mappings?.FirstOrDefault().Value);
 }
コード例 #58
0
        public override void Setup()
        {
            var statusBar = new StatusBar(new StatusItem[] {
                //new StatusItem(Key.ControlR, "~CTRL-R~ Refresh Data", () => RefreshScreen()),
                new StatusItem(Key.ControlQ, "~CTRL-Q~ Back/Quit", () => Quit())
            });

            LeftPane = new Window("Installed Apps")
            {
                X           = 0,
                Y           = 0, // for menu
                Width       = 40,
                Height      = Dim.Fill(),
                CanFocus    = false,
                ColorScheme = Colors.TopLevel,
            };

            try
            {
                if (STClient.GetAllInstalledApps().Items?.Count > 0)
                {
                    _viewInstalledApps = STClient.GetAllInstalledApps().Items
                                         .OrderBy(t => t.DisplayName)
                                         .Select(t => new KeyValuePair <string, InstalledApp>(t.DisplayName, t))
                                         .ToDictionary(t => t.Key, t => t.Value);
                }
                else
                {
                    SetErrorView($"You have no installed apps");
                }
            }
            catch (SmartThingsNet.Client.ApiException exp)
            {
                SetErrorView($"Error calling API: {exp.Source} {exp.ErrorCode} {exp.Message}");
            }
            catch (System.Exception exp)
            {
                SetErrorView($"Unknown error calling API: {exp.Message}");
            }

            ClassListView = new ListView(_viewInstalledApps?.Keys?.ToList())
            {
                X             = 0,
                Y             = 0,
                Width         = Dim.Fill(0),
                Height        = Dim.Fill(), // for status bar
                AllowsMarking = false,
                ColorScheme   = Colors.TopLevel,
            };

            if (_viewInstalledApps?.Keys?.Count > 0)
            {
                ClassListView.SelectedItemChanged += (args) =>
                {
                    ClearClass(CurrentView);
                    var selectedItem = _viewInstalledApps.Values.ToArray()[ClassListView.SelectedItem];
                    CurrentView = CreateJsonView(selectedItem.ToJson());
                };
            }
            LeftPane.Add(ClassListView);

            HostPane = new FrameView("")
            {
                X = Pos.Right(LeftPane),
                //Y = Pos.Bottom(_settingsPane),
                Width       = Dim.Fill(),
                Height      = Dim.Fill(1), // + 1 for status bar
                ColorScheme = Colors.Dialog,
            };

            Top.Add(LeftPane, HostPane);
            Top.Add(statusBar);

            if (_viewInstalledApps?.Count > 0)
            {
                CurrentView = CreateJsonView(_viewInstalledApps?.FirstOrDefault().Value?.ToJson());
            }

            DisplayErrorView();
        }
コード例 #59
0
 public AgeVerification FindAgeOverVerification(int age)
 {
     return(_ageOverVerificationsDict?.FirstOrDefault(
                x => x.Key == $"{Constants.UserProfile.AgeOverAttribute}:{age}")
            .Value);
 }
コード例 #60
0
 public static string GetHeaderValue(Dictionary <string, string> headers, string name)
 {
     return(headers?.FirstOrDefault(f => f.Key.ToLower() == name.ToLower()).Value);
 }