Exemplo n.º 1
0
 public void FiltrateFighters()
 {
     var pretendents = new Dictionary<string, int>();
     foreach (var e in Fighters)
         if (!pretendents.ContainsKey(e.Item1))
             pretendents[e.Item1] = 0;
     var temp = pretendents.ToDictionary(x => x.Key, y => y.Value);
     foreach (var e in temp)
     {
         try
         {
             var process = new Process();
             process.StartInfo.FileName = "Checkers.Tournament.exe";
             process.StartInfo.Arguments = e.Key + " " + "testPlayer.dll";
             process.StartInfo.UseShellExecute = false;
             process.StartInfo.RedirectStandardInput = true;
             process.StartInfo.RedirectStandardOutput = true;
             process.StartInfo.CreateNoWindow = true;
             process.Start();
             var winner = process.StandardOutput.ReadLine()[0];
             if (winner == 'W')
                 pretendents[e.Key]++;
         }
         catch
         {
             pretendents[e.Key] = -10;
         }
     }
     Fighters = Fighters.Where(x => pretendents.ContainsKey(x.Item1) && pretendents.ContainsKey(x.Item2))
                        .ToList();
     //добавить ограничение по победам
     // фильтруем некорректные дллс
 }
Exemplo n.º 2
0
 public void ConvertFromDic(ref Dictionary<string, string> dic)
 {
     if (dic.ContainsKey("MinBpm"))
         double.TryParse(dic["MinBpm"], out _minBpm);
     if (dic.ContainsKey("MaxBpm"))
         double.TryParse(dic["MaxBpm"], out _maxBpm);
 }
Exemplo n.º 3
0
 protected void BatchAdd(Item item1, Item item2, Item item3, Item item4, Item item5, Section[] sectionList)
 {
     var itemList = new[] {item1, item2, item3, item4, item5};
     var itemDictionary = new Dictionary<ItemCategory, Item>();
     foreach (var item in itemList)
     {
         if (item != null) itemDictionary.Add(item.Category, item);
     }
     var topList = new List<Section>();
     var bottomList = new List<Section>();
     var leftList = new List<Section>();
     var rightList = new List<Section>();
     foreach (var section in sectionList)
     {
         topList.Add(Section.Line(section.GridX, section.GridY + section.Row, section.Column, section.OffsetX,
             section.OffsetY));
         bottomList.Add(Section.Line(section.GridX, section.GridY - 1, section.Column, section.OffsetX,
             section.OffsetY));
         leftList.Add(Section.Tower(section.GridX - 1, section.GridY, section.Row, section.OffsetX,
             section.OffsetY));
         rightList.Add(Section.Line(section.GridX + section.Column, section.GridY, section.Row, section.OffsetX,
             section.OffsetY));
     }
     ObjectData.Add(itemDictionary[ItemCategory.Body].Clone, sectionList);
     if (itemDictionary.ContainsKey(ItemCategory.TopCap))
         ObjectData.Add(itemDictionary[ItemCategory.TopCap].Clone, topList.ToArray());
     if (itemDictionary.ContainsKey(ItemCategory.BottomCap))
         ObjectData.Add(itemDictionary[ItemCategory.BottomCap].Clone, bottomList.ToArray());
     if (itemDictionary.ContainsKey(ItemCategory.LeftCap))
         ObjectData.Add(itemDictionary[ItemCategory.LeftCap].Clone, leftList.ToArray());
     if (itemDictionary.ContainsKey(ItemCategory.RightCap))
         ObjectData.Add(itemDictionary[ItemCategory.RightCap].Clone, rightList.ToArray());
 }
Exemplo n.º 4
0
	public override bool CheckAccept()
	{
		Dictionary<int, int> dicHaveItem = new Dictionary<int, int>();
		InvenSlot[] invens = ItemMgr.HadItemManagement.Inven.invenSlots;
		foreach( InvenSlot inven in invens)
		{
			if( inven != null && inven.realItem != null)
			{
				int itemID = inven.realItem.item.ItemID;

				if( dicHaveItem.ContainsKey( itemID))
					dicHaveItem[itemID] += 1;
				else
					dicHaveItem.Add( itemID, 1);
			}
		}

		// 아이템 소유 & 수량 체크
		if( !dicHaveItem.ContainsKey( ItemID))
			return false;

		int count = dicHaveItem[ItemID];
		if( ItemCount > count)
			return false;

		return true;
	}
        public IDictionary<Person, ExchangeCheckSum> PickListToValidateWithPeopleList(PersonCollection personList, XMasPickList pickList)
        {
            IDictionary<Person, ExchangeCheckSum> checkList = new Dictionary<Person, ExchangeCheckSum>();

            foreach (Person person in personList)
            {
                checkList.Add(person, new ExchangeCheckSum());
            }

            foreach (XMasPick pick in pickList)
            {
                if (checkList.ContainsKey(pick.Recipient))
                {
                    checkList[pick.Recipient].updatePresentsIn();
                }
                else
                {
                    throw new Exception(string.Format("The recipient {0} is not found in adult list", pick.Recipient));
                }

                if (checkList.ContainsKey(pick.Subject))
                {
                    checkList[pick.Subject].updatePresentsOut();
                }
                else
                {
                    throw new Exception(string.Format("The subject {0} is not found in adult list", pick.Subject));
                }
            }

            return checkList;
        }
Exemplo n.º 6
0
        public int[] Intersect(int[] nums1, int[] nums2)
        {
            //Solution can be:(this one is slower than below)
            //var map1 = nums1.GroupBy(n => n).ToDictionary(g => g.Key, g => g.Count());
            //return nums2.Where(n => map1.ContainsKey(n) && map1[n]-- > 0).ToArray();
            //Or:

            Dictionary<int, int> numbCount=new Dictionary<int, int>();
            foreach (int i in nums1)
            {
                if (!numbCount.ContainsKey(i))
                {
                    numbCount.Add(i,0);
                }
                numbCount[i]++;
            }

            List<int> ls = new List<int>();
            foreach (int j in nums2)
            {
                if (numbCount.ContainsKey(j) && numbCount[j] > 0)
                {
                    ls.Add(j);
                    numbCount[j]--;
                }
            }

            return ls.ToArray();
        }
Exemplo n.º 7
0
        public static Person Import(String input)
        {
            var parameters = new Dictionary<string, string>();
            var data = input.Split(';');
            foreach (string item in data)
            {
                var specyficData = item.Split(':');
                parameters[specyficData[0]] = specyficData[1];
            }

            var person = new Person();
            person.NameSurname = parameters["NS"];

            IFormatProvider culture = new System.Globalization.CultureInfo("pl-PL", true);
            if (parameters.ContainsKey("BD"))
            {
                person.Birthdate = DateTime.Parse(parameters["BD"], culture);
            }

            if (parameters.ContainsKey("DD"))
            {
                person.Deathdate = DateTime.Parse(parameters["DD"], culture);
            }

            if (parameters.ContainsKey("S"))
            {
                switch (parameters["S"])
                {
                    case "M": person.Sex = PersonSex.Male; break;
                    case "F": person.Sex = PersonSex.Female; break;
                }
            }

            return person;
        }
Exemplo n.º 8
0
        public static void CsvLoadTripRoutes(string filename, bool lngFirst)
        {
            // load trip routes
            Dictionary<string, LinkedList<Waypoint>> routes = new Dictionary<string, LinkedList<Waypoint>>();
            using (CsvFileReader reader = new CsvFileReader(filename))
            {
                CsvRow row = new CsvRow();
                while (reader.ReadRow(row, ','))
                {
                    string routeID = row[0];
                    double distance = 0;
                    double lat = Convert.ToDouble(lngFirst ? row[2] : row[1]);
                    double lng = Convert.ToDouble(lngFirst ? row[1] : row[2]);
                    if (routes.ContainsKey(routeID))
                        distance = routes[routeID].First.Value.GetDistance(new Location(lat, lng, "null"));
                    Waypoint waypoint = new Waypoint(lat, lng, TimeSpan.Parse(row[3]), distance, row[4].Replace("\"", ""));

                    // Scenario #1
                    if (!routes.ContainsKey(routeID))
                        routes[routeID] = new LinkedList<Waypoint>();
                    routes[routeID].AddLast(waypoint);

                }
            }
            foreach (LinkedList<Waypoint> w in routes.Values)
            {
                Route r = new Route(w.ToArray());
                string key = Route.GetKey(r.start, r.end);
                MapTools.routes.Add(key, r);
            }
        }
Exemplo n.º 9
0
        private static void AddPortal(XmlNode portal)
        {
            Dictionary<string, string> data = new Dictionary<string, string>();
            XmlNodeList childList = portal.ChildNodes;
            for (int i = 0; i < childList.Count; i++)
                data.Add(childList.Item(i).Name, childList.Item(i).InnerText);

            if (!data.ContainsKey("toid")) return;
            try
            {
                Dictionary<byte,PortalInfo> tmpdic;
                System.Globalization.CultureInfo culture;
                culture = System.Globalization.CultureInfo.GetCultureInfo("en-US");
                PortalInfo nPortal = new PortalInfo(int.Parse(data["toid"]), float.Parse(data["x"],culture), float.Parse(data["y"],culture), float.Parse(data["z"],culture));
                if (data.ContainsKey("mapid"))
                    nPortal.m_mapID = byte.Parse(data["mapid"]);
                if (!portals.ContainsKey(byte.Parse(data["toid"])))
                {
                    tmpdic = new Dictionary<byte, PortalInfo>();
                    tmpdic.Add(byte.Parse(data["fromid"]), nPortal);
                    portals.Add(byte.Parse(data["toid"]), tmpdic);
                }
                else
                {
                    tmpdic = portals[byte.Parse(data["toid"])];
                    tmpdic.Add(byte.Parse(data["fromid"]), nPortal);
                }

            }
            catch (Exception e) { Logger.ShowError("cannot parse: " + data["toid"],null); Logger.ShowError(e,null); return; }
        }
Exemplo n.º 10
0
        public AmzCD(string url, Dictionary<string, string> options)
        {
            var uri = new Utility.Uri(url);

            m_path = uri.HostAndPath;
            if (!m_path.EndsWith("/"))
                m_path += "/";

            string authid = null;
            if (options.ContainsKey(AUTHID_OPTION))
                authid = options[AUTHID_OPTION];

            string labels = DEFAULT_LABELS;
            if (options.ContainsKey(LABELS_OPTION))
                labels = options[LABELS_OPTION];

            string delay = DEFAULT_DELAY;
            if (options.ContainsKey(DELAY_OPTION))
                delay = options[DELAY_OPTION];
            
            if (!string.IsNullOrWhiteSpace(labels))
                m_labels = labels.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

            if (string.IsNullOrWhiteSpace(delay))
                m_delayTimeSpan = new TimeSpan(0);
            else
                m_delayTimeSpan = Library.Utility.Timeparser.ParseTimeSpan(delay);

            m_oauth = new OAuthHelper(authid, this.ProtocolKey) { AutoAuthHeader = true };
            m_userid = authid.Split(new string[] {":"}, StringSplitOptions.RemoveEmptyEntries).First();
        }
Exemplo n.º 11
0
        public Portal(World world, int actorSNO, Vector3D position, Dictionary<int, TagMapEntry> tags)
            : base(world, world.NewActorID, position, tags)
        {
            this.SNOId = actorSNO;
            this.Destination = new ResolvedPortalDestination
            {
                WorldSNO = tags[(int)MarkerTagTypes.DestinationWorld].Int2,
            };

            if (tags.ContainsKey((int)MarkerTagTypes.DestinationLevelArea))
                this.Destination.DestLevelAreaSNO = tags[(int)MarkerTagTypes.DestinationLevelArea].Int2;

            if (tags.ContainsKey((int)MarkerTagTypes.DestinationActorTag))
                this.Destination.StartingPointActorTag = tags[(int)MarkerTagTypes.DestinationActorTag].Int2;
            else
                Logger.Warn("Found portal {0}without target location actor", this.SNOId);

            this.Field8 = this.SNOId;
            this.Field2 = 16;
            this.Field3 = 0;
            this.CollFlags = 0x00000001;

            // FIXME: Hardcoded crap; probably don't need to set most of these. /komiga
            this.Attributes[GameAttribute.MinimapActive] = true;
            this.Attributes[GameAttribute.Hitpoints_Max_Total] = 1f;
            this.Attributes[GameAttribute.Hitpoints_Max] = 0.0009994507f;
            this.Attributes[GameAttribute.Hitpoints_Total_From_Level] = 3.051758E-05f;
            this.Attributes[GameAttribute.Hitpoints_Cur] = 0.0009994507f;
            this.Attributes[GameAttribute.TeamID] = 1;
            this.Attributes[GameAttribute.Level] = 1;
        }
Exemplo n.º 12
0
        private static bool EvaluateChain(string chain)
        {
            var nodes = new Dictionary<string, string>();

            // Build LinkedList
            foreach (string pair in chain.Split(';'))
            {
                // Node value: node[0]
                // Next node:  node[1]
                var node = pair.Split('-');
                if (nodes.ContainsKey(node[0])) { return false; }   // Duplicate
                if (node[0].Equals(node[1])) { return false; }      // Cycle
                nodes.Add(node[0], node[1]);
            }

            // Evaluate LinkedList
            // 500 pairs, maximum therefore it is more effective to just iterate at max 500 instead of doing cycle detection.
            // The counter will also make sure that we fail, if we have unconnected nodes :)
            // BEGIN-3;3-4;4-2;2-END --> GOOD
            // BEGIN-3;3-4;4-2;2-3   --> BAD
            string transitionTo = "BEGIN";
            for (int i = 0; i < nodes.Count; i++)
            {
                if (!nodes.ContainsKey(transitionTo)) { return false; }
                transitionTo = nodes[transitionTo];
            }

            // At the end, transitionTo should be Pointing to END
            return transitionTo.Equals("END");
        }
Exemplo n.º 13
0
        private IList<Vocabulary> CalcUserVocabulary(IList<string> newWords, IDictionary<int, int> histories)
        {
            var result = new Dictionary<string, Vocabulary>();

            //var histories = dbOperator.GetAll<User_LearnHistory>();
            foreach (var history in histories)
            {
                //读取已经背诵的单元
                var items = dbOperator.GetBookItemsBelowMaxUnitId(history.Key, history.Value);
                foreach (var item in items)
                {
                    if (!result.ContainsKey(item.Word))
                        result.Add(item.Word, new Vocabulary() { Word = item.Word, IsKnown = true });
                }
            }
            foreach (var newword in newWords)
            {
                if (result.ContainsKey(newword))
                {
                    result[newword].IsKnown = false;
                }
                else
                {
                    result.Add(newword, new Vocabulary() { Word = newword, IsKnown = false });
                }
            }
            return new List<Vocabulary>(result.Values);
        }
        public Dictionary<string, object> Fill(WebInterface webInterface, string filename, OSHttpRequest httpRequest,
                                               OSHttpResponse httpResponse, Dictionary<string, object> requestParameters,
                                               ITranslator translator, out string response)
        {
            response = null;
            var vars = new Dictionary<string, object>();

            if (requestParameters.ContainsKey("ResetMenu"))
            {
                PagesMigrator.ResetToDefaults();
                response = "Menu: "+ translator.GetTranslatedString("ChangesSavedSuccessfully");
                return null;
            }
            if (requestParameters.ContainsKey("ResetSettings"))
            {
                SettingsMigrator.ResetToDefaults(webInterface);
                response = "WebUI: "+ translator.GetTranslatedString("ChangesSavedSuccessfully");
                return null;
            }

            vars.Add("FactoryReset", translator.GetTranslatedString("FactoryReset"));
            vars.Add("ResetMenuText", translator.GetTranslatedString("ResetMenuText"));
            vars.Add("ResetSettingsText", translator.GetTranslatedString("ResetSettingsText"));
            vars.Add("ResetMenuInfoText", translator.GetTranslatedString("ResetMenuText"));
            vars.Add("ResetSettingsInfoText", translator.GetTranslatedString("ResetSettingsInfoText"));
            vars.Add("Reset", translator.GetTranslatedString("Reset"));

            return vars;
        }
Exemplo n.º 15
0
 public override void FillFromDictionary(Dictionary<string, object> dict)
 {
     if(dict.ContainsKey("status")) {
         if(dict["status"] != null) {
             status = DataType.Instance.FillString(dict["status"]);
         }
     }
     if(dict.ContainsKey("date_created")) {
         if(dict["date_created"] != null) {
             date_created = DataType.Instance.FillDateTime(dict["date_created"]);
         }
     }
     if(dict.ContainsKey("active")) {
         if(dict["active"] != null) {
             active = DataType.Instance.FillBool(dict["active"]);
         }
     }
     if(dict.ContainsKey("uuid")) {
         if(dict["uuid"] != null) {
             uuid = DataType.Instance.FillString(dict["uuid"]);
         }
     }
     if(dict.ContainsKey("date_modified")) {
         if(dict["date_modified"] != null) {
             date_modified = DataType.Instance.FillDateTime(dict["date_modified"]);
         }
     }
 }
Exemplo n.º 16
0
        public static bool IsPermutationByCharacterCount(string s, string t)
        {
            if (s.Length != t.Length) return false;

            var counts = new Dictionary<char, int>();

            foreach (var c in s)
            {
                if (!counts.ContainsKey(c)) counts[c] = 0;

                counts[c]++;
            }

            foreach (var c in t)
            {
                if (!counts.ContainsKey(c)) counts[c] = 0;

                if (--counts[c] < 0)
                {
                    return false;
                }
            }

            return true;
        }
Exemplo n.º 17
0
 public void Parse1CssFileAndValidate() {
     p.Parse(new StringReader(HTML1));
     Dictionary<String, String> props = new Dictionary<String, String>();
     cssFiles.PopulateCss(props, "body");
     Assert.IsTrue(props.ContainsKey("font-size"));
     Assert.IsTrue(props.ContainsKey("color"));
 }
Exemplo n.º 18
0
        public void TestMap()
        {
            foreach (var file in Directory.GetFiles(FilesDirectory))
            {
                DexReader dexreader;
                DexWriter dexwriter;
                TestReadWrite(file, out dexreader, out dexwriter);

                var checklist = new Dictionary<TypeCodes, string>();

                foreach (var tc in dexwriter.Map.Keys.Where(tc => dexreader.Map.ContainsKey(tc)))
                {
                    if (dexreader.Map[tc].Size != dexwriter.Map[tc].Size)
                    {
                        TestContext.WriteLine("{0} Size differs expected={1}, actual={2}", tc, dexreader.Map[tc].Size, dexwriter.Map[tc].Size);
                        if (!checklist.ContainsKey(tc))
                            checklist.Add(tc, tc.ToString());
                    }
                    if (dexreader.Map[tc].Offset != dexwriter.Map[tc].Offset)
                    {
                        TestContext.WriteLine("{0} Offset differs : expected={1}, actual={2}", tc, dexreader.Map[tc].Offset, dexwriter.Map[tc].Offset);
                        if (!checklist.ContainsKey(tc))
                            checklist.Add(tc, tc.ToString());
                    }
                }

                Assert.IsTrue(checklist.Count == 0, string.Concat("Check test report : ", string.Join(", ", checklist.Values)));
            }
        }
Exemplo n.º 19
0
        public void CreateModels(IEnumerable<OvhApi> apis)
        {
            Dictionary<string,ModelType> modelsByNamespace = new Dictionary<string, ModelType>();
            foreach (var ovhApi in apis)
            {
                foreach (var model in ovhApi.Models)
                {
                    string fullTypeName = Util.GetType(model.Key);

                    if (modelsByNamespace.ContainsKey(fullTypeName))
                        continue;

                    modelsByNamespace.Add(fullTypeName, new ModelType(model.Value));
                }
            }

            foreach (var st in modelsByNamespace)
            {
                string modelNamespace = Util.GetNamespace(st.Value.Model);

                if (modelsByNamespace.ContainsKey(modelNamespace))
                {
                    modelsByNamespace[modelNamespace].AddChild(st.Value);
                }
            }

            foreach (var type in modelsByNamespace.Where(x => x.Value.Parent == null))
            {
                CodeNamespace ns = new CodeNamespace(Util.GetNamespace(type.Value.Model));
                ns.Types.Add(CreateType(type.Value));
                _code.Namespaces.Add(ns);
            }
        }
Exemplo n.º 20
0
 public RulerGivenSkillContainerSkill(IRulerGivenSkill InnerSkill, Allegiance al)
 {
     innerSkillType = InnerSkill.GetType();
     Allegiance = al;
     masterList = new Dictionary<Player, IRulerGivenSkill>();
     var trigger = new AutoNotifyPassiveSkillTrigger(
         this,
         DistributeSkills,
         TriggerCondition.OwnerIsSource
     ) { IsAutoNotify = false, AskForConfirmation = false };
     var trigger2 = new AutoNotifyPassiveSkillTrigger(
         this,
         (p, e, a) =>
         {
             if (a.Source.Allegiance == Allegiance && !masterList.ContainsKey(a.Source))
             {
                 DistributeSkills(Owner, null, null);
             }
             if (a.Source.Allegiance != Allegiance && masterList.ContainsKey(a.Source))
             {
                 ISkill skill = masterList[a.Source];
                 masterList.Remove(a.Source);
                 Game.CurrentGame.PlayerLoseAdditionalSkill(a.Source, skill, true);
             }
         },
         TriggerCondition.Global
     ) { IsAutoNotify = false, AskForConfirmation = false };
     Triggers.Add(GameEvent.PlayerGameStartAction, trigger);
     Triggers.Add(GameEvent.PlayerChangedAllegiance, trigger2);
     IsAutoInvoked = null;
     IsRulerOnly = true;
 }
Exemplo n.º 21
0
            public string Correct(string word)
            {
                if (string.IsNullOrEmpty(word))
                    return word;

                word = word.ToLower();

                // known()
                if (_dictionary.ContainsKey(word))
                    return word;

                List<String> list = Edits(word);
                Dictionary<string, int> candidates = new Dictionary<string, int>();

                foreach (string wordVariation in list)
                {
                    if (_dictionary.ContainsKey(wordVariation) && !candidates.ContainsKey(wordVariation))
                        candidates.Add(wordVariation, _dictionary[wordVariation]);
                }

                if (candidates.Count > 0)
                    return candidates.OrderByDescending(x => x.Value).First().Key;

                // known_edits2()
                foreach (string item in list)
                {
                    foreach (string wordVariation in Edits(item))
                    {
                        if (_dictionary.ContainsKey(wordVariation) && !candidates.ContainsKey(wordVariation))
                            candidates.Add(wordVariation, _dictionary[wordVariation]);
                    }
                }

                return (candidates.Count > 0) ? candidates.OrderByDescending(x => x.Value).First().Key : word;
            }
Exemplo n.º 22
0
 public object StartMethod(object parent = null, Dictionary<string, object> parameters = null)
 {
     if (!parameters.ContainsKey("Tag")) throw new ArgumentNullException("Tag");
     if (!parameters.ContainsKey("ClassName")) throw new ArgumentNullException("ClassName");
     List<string> resultListUrl = new List<string>();
     mshtml.IHTMLDocument2 doc2 = parent as mshtml.IHTMLDocument2;
     Common.WaitForPageReady(doc2);
     string url = doc2.url;
     for (int i = 0; i < 1; i++)
     {
         mshtml.IHTMLDocument2 document2 = parent as mshtml.IHTMLDocument2;
         mshtml.IHTMLDocument3 document3 = parent as mshtml.IHTMLDocument3;
         Common.WaitForPageReady(document2);
         document2.url = string.Format("{0}{1}{2}", url, "&startindex=", i * 20);
         if (document3 != null)
         {
             mshtml.IHTMLElementCollection elements = document3.getElementsByTagName(parameters["Tag"] as string);
             foreach (mshtml.IHTMLElement element in elements)
             {
                 if (element.className == parameters["ClassName"] as string)
                 {
                     mshtml.IHTMLElementCollection elementChildren = element.children as mshtml.IHTMLElementCollection;
                     foreach (mshtml.IHTMLElement firstChild in elementChildren)
                     {
                         resultListUrl.Add(firstChild.getAttribute("href") as string);
                         break;
                     }
                 }
             }
         }
     }
     return resultListUrl;
 }
Exemplo n.º 23
0
 public IMMDModelPart Create(int triangleCount, MMDVertexNm[] Vertices, Dictionary<string, object> OpaqueData)
 {
     IndexBuffer indexBuffer = null;
     if (OpaqueData.ContainsKey("IndexBuffer"))
         indexBuffer = OpaqueData["IndexBuffer"] as IndexBuffer;
     Vector2[] extVert = null;
     if (OpaqueData.ContainsKey("VerticesExtention"))
         extVert = OpaqueData["VerticesExtention"] as Vector2[];
     if (indexBuffer == null)
         throw new ArgumentException("MMDModelPartXBoxFactoryのOpaqueDataには\"IndexBuffer\"キーとIndexBufferオブジェクトが必要です。", "OpaqueData");
     if (extVert == null)
         throw new ArgumentException("MMDModelPartXboxFactoryのOpaqueDataには\"VerticesExtention\"キーが必要です。", "OpaqueData");
     if (Vertices is MMDVertexNmTx[])
     {
         if (Vertices is MMDVertexNmTxVc[])
             return new MMDXBoxModelPartPNmTxVc(triangleCount, (MMDVertexNmTxVc[])Vertices, extVert, indexBuffer);
         else
             return new MMDXBoxModelPartPNmTx(triangleCount, (MMDVertexNmTx[])Vertices, extVert, indexBuffer);
     }
     else
     {
         if (Vertices is MMDVertexNmVc[])
             return new MMDXBoxModelPartPNmVc(triangleCount, (MMDVertexNmVc[])Vertices, extVert, indexBuffer);
         else
             return new MMDXBoxModelPartPNm(triangleCount, (MMDVertexNm[])Vertices, extVert, indexBuffer);
     }
 }
        public virtual FacebookOAuthResult ParseOAuthCallbackUrl(Uri uri)
        {
            var parameters = new Dictionary<string, object>();

            bool found = false;
            if (!string.IsNullOrEmpty(uri.Fragment))
            {
                // #access_token and expries_in are in fragment
                var fragment = uri.Fragment.Substring(1);
                ParseUrlQueryString("?" + fragment, parameters, true);

                if (parameters.ContainsKey("access_token"))
                    found = true;
            }

            // code, state, error_reason, error and error_description are in query
            // ?error_reason=user_denied&error=access_denied&error_description=The+user+denied+your+request.
            var queryPart = new Dictionary<string, object>();
            ParseUrlQueryString(uri.Query, queryPart, true);

            if (queryPart.ContainsKey("code") || (queryPart.ContainsKey("error") && queryPart.ContainsKey("error_description")))
                found = true;

            foreach (var kvp in queryPart)
                parameters[kvp.Key] = kvp.Value;

            if (found)
                return new FacebookOAuthResult(parameters);

            throw new InvalidOperationException("Could not parse Facebook OAuth url.");
        }
Exemplo n.º 25
0
        public Diff GetDiff(Dictionary<string, PriceItem> newProds, Dictionary<string, PriceItem> oldProds)
        {
            oldProds = oldProds ?? new Dictionary<string, PriceItem>();

            var diff = new Diff 
            { 
                NewItems = newProds.Where(kvp => !oldProds.ContainsKey(kvp.Key)).ToDictionary(key => key.Key, value => value.Value),
                DeletedItems = oldProds.Where(kvp => !newProds.ContainsKey(kvp.Key)).ToDictionary(key => key.Key, value => value.Value),
                UpdatedItems = newProds.Where(kvp => oldProds.ContainsKey(kvp.Key)).ToDictionary(key => key.Key, value => value.Value)
            };

            var toRemove = new List<string>();
            foreach (var item in diff.UpdatedItems.Values)
            {
                var oldItem = oldProds[item.Reference];
                if (item.WholesalePrice == oldItem.WholesalePrice && item.Active == oldItem.Active && !SameBalance(item, oldItem))
                {
                    toRemove.Add(item.Reference);
                }
            }

            foreach (var reference in toRemove)
            {
                diff.UpdatedItems.Remove(reference);
            }

            return diff;
        }
Exemplo n.º 26
0
 public override void FillFromDictionary(Dictionary<string, object> dict)
 {
     if(dict.ContainsKey("path")) {
         if(dict["path"] != null) {
             path = DataType.Instance.FillString(dict["path"]);
         }
     }
     if(dict.ContainsKey("date_end")) {
         if(dict["date_end"] != null) {
             date_end = DataType.Instance.FillDateTime(dict["date_end"]);
         }
     }
     if(dict.ContainsKey("date_start")) {
         if(dict["date_start"] != null) {
             date_start = DataType.Instance.FillDateTime(dict["date_start"]);
         }
     }
     if(dict.ContainsKey("data")) {
         if(dict["data"] != null) {
             data = DataType.Instance.FillString(dict["data"]);
         }
     }
     if(dict.ContainsKey("type_id")) {
         if(dict["type_id"] != null) {
             type_id = DataType.Instance.FillString(dict["type_id"]);
         }
     }
 }
        protected virtual Dictionary<string, KeyValuePair<string, string>> GetEntityDataFromType(Type type)
        {
            Dictionary<string, KeyValuePair<string, string>> res = new Dictionary<string, KeyValuePair<string, string>>();
            foreach (Attribute attr in type.GetCustomAttributes())
            {
                if (attr is SemanticEntityAttribute)
                {
                    SemanticEntityAttribute semantics = (SemanticEntityAttribute)attr;
                    // we can only support mapping to a single semantic entity, the derived type is set first, so that is what we use
                    if (!res.ContainsKey(semantics.Prefix))
                    {
                        res.Add(semantics.Prefix, new KeyValuePair<string, string>(semantics.Vocab, semantics.EntityName));
                    }
                }
                if (attr is SemanticDefaultsAttribute)
                {
                    SemanticDefaultsAttribute semantics = (SemanticDefaultsAttribute)attr;
                    res.Add(semantics.Prefix, new KeyValuePair<string, string>(semantics.Vocab, String.Empty));
                }
            }

            //Add default mapping if none was specified on entity
            if (!res.ContainsKey(string.Empty))
            {
                res.Add(string.Empty, new KeyValuePair<string, string>(ViewModel.CoreVocabulary, string.Empty));
            }

            return res;
        }
Exemplo n.º 28
0
        static void Main()
        {
            var graph = new Dictionary<int, List<int>>();
            int f = int.Parse(Console.ReadLine());
            int k = int.Parse(Console.ReadLine());

            for (int i = 0; i < f; i++)
            {
                int[] edge = new int[2];
                edge =
                    Console.ReadLine()
                        .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(int.Parse)
                        .ToArray();
                if (!graph.ContainsKey(edge[0]))
                {
                    graph[edge[0]] = new List<int>();
                }

                graph[edge[0]].Add(edge[1]);

                if (!graph.ContainsKey(edge[1]))
                {
                    graph[edge[1]] = new List<int>();
                }

                graph[edge[1]].Add(edge[0]);
            }

            var currentNode = k;
            int count = FindLongestDance(graph, k);
            Console.WriteLine(count);
        }
        private string MinWindow(string s, string t)
        {
            if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(t)) return "";

            int tLen = t.Length, sLen = s.Length, start = -1, end = -1;
            var dicNoCounted = new Dictionary<char, int>();

            for (int index = 0; index < tLen; index++)
                if (!dicNoCounted.ContainsKey(t[index]))
                    dicNoCounted.Add(t[index], 1);
                else
                    dicNoCounted[t[index]]++;

            for (int index = 0; index < sLen && dicNoCounted.Count > 0; index++)
            {
                if (dicNoCounted.ContainsKey(s[index]))
                {
                    if (dicNoCounted[s[index]] > 1)
                        dicNoCounted[s[index]]--;
                    else
                        dicNoCounted.Remove(s[index]);

                    if (start < 0)
                        end = start = index;
                    else
                        end = index;
                }
            }

            if (dicNoCounted.Count > 0 || start < 0 || end < 0) return "";
            return s.Substring(start, end - start + 1);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StackTraceElement"/> class using the given property values.
        /// </summary>
        /// <param name="elementAttributes">A <see cref="Dictionary{K, V}"/> containing the names and values for the properties of this <see cref="StackTraceElement"/>.</param>
        public StackTraceElement(Dictionary<string, object> elementAttributes)
        {
            if (elementAttributes != null)
            {
                if (elementAttributes.ContainsKey("className") && elementAttributes["className"] != null)
                {
                    this.className = elementAttributes["className"].ToString();
                }

                if (elementAttributes.ContainsKey("methodName") && elementAttributes["methodName"] != null)
                {
                    this.methodName = elementAttributes["methodName"].ToString();
                }

                if (elementAttributes.ContainsKey("lineNumber"))
                {
                    this.lineNumber = Convert.ToInt32(elementAttributes["lineNumber"], CultureInfo.InvariantCulture);
                }

                if (elementAttributes.ContainsKey("fileName") && elementAttributes["fileName"] != null)
                {
                    this.fileName = elementAttributes["fileName"].ToString();
                }
            }
        }
 private static Dictionary<string, ControlData> OptionCollection(
     Context context,
     Dictionary<string, ControlData> optionCollection = null,
     string selectedValue = null,
     bool multiple = false,
     bool addSelectedValue = true,
     bool insertBlank = false,
     Column column = null)
 {
     if (insertBlank)
     {
         optionCollection = InsertBlank(optionCollection);
     }
     if (selectedValue == null ||
         selectedValue == string.Empty ||
         optionCollection?.ContainsKey(selectedValue) == true ||
         selectedValue == "0" ||
         multiple ||
         !addSelectedValue)
     {
         return optionCollection;
     }
     else
     {
         var selectedId = selectedValue.ToInt();
         optionCollection?.Add(
             selectedValue,
             column != null && column.Type != Column.Types.Normal
                 ? new ControlData(SiteInfo.Name(
                     context: context,
                     id: selectedId,
                     type: column.Type))
                 : new ControlData("? " + selectedValue));
         return optionCollection;
     }
 }
Exemplo n.º 32
0
        internal static string ConvertToQueryString(this object option, Dictionary <string, string> replacements = null)
        {
            List <string> options = new List <string>();

            PropertyInfo[] properties = option.GetType().GetProperties();
            foreach (PropertyInfo property in properties)
            {
                var value = property.GetValue(option, null);
                if (value != null && !string.IsNullOrWhiteSpace(value.ToString()))
                {
                    string val = value.ToString().Trim();
                    if (value is bool)
                    {
                        val = (bool)value ? "1" : "0";
                    }
                    else if (value is DateTime dt)
                    {
                        val = dt.ToString("yyyy-MM-dd");
                    }
                    else if (value is List <int> ints)
                    {
                        val = string.Join(",", ints);
                    }
                    else if (value is List <ThingType> types)
                    {
                        val = string.Join(",", types);
                    }
                    string queryValue = HttpUtility.UrlEncode(val);
                    string propName   = property.Name.ToLower();
                    propName = replacements?.ContainsKey(propName) ?? false ? replacements[propName] : propName;
                    options.Add(string.Join("=", propName, queryValue));
                }
            }

            return(string.Join("&", options));
        }
Exemplo n.º 33
0
        /// <summary> Connects to Player.IO using as the given user </summary>
        /// <param name="gameId"> The game ID of the game you wish to connect to. This value can be found in the admin panel </param>
        /// <param name="connectionId"> The ID of the connection, as given in the settings section of the admin panel. 'public' should be used as the default </param>
        /// <param name="authenticationArguments"> A dictionary of arguments for the given connection. </param>
        /// <param name="playerInsightSegments"> Custom segments for the user in PlayerInsight. </param>
        public static Client Authenticate(string gameId, string connectionId, Dictionary <string, string> authenticationArguments = null, string[] playerInsightSegments = null)
        {
            if (authenticationArguments?.ContainsKey("secureSimpleUserPasswordsOverHttp") == true && authenticationArguments["secureSimpleUserPasswordsOverHttp"] == "true")
            {
                var secureLoginInfo = SimpleUserGetSecureLoginInfo();
                authenticationArguments["password"] = PlayerIO.SimpleUserPasswordEncrypt(secureLoginInfo.PublicKey, authenticationArguments["password"]);
                authenticationArguments["nonce"]    = secureLoginInfo.Nonce;
            }

            var authenticationOutput = Authenticate(gameId, connectionId, authenticationArguments ?? null, playerInsightSegments?.ToList() ?? null, GetClientAPI(), GetClientInfo(), GetPlayCodes());

            PlayerIO.ServerApiEndpoints = authenticationOutput.ApiServerHosts;
            PlayerIO.ServerApiSecurity  = authenticationOutput.ApiSecurity;

            // TODO: Don't want to overwrite any custom user-set endpoint...
            PlayerIO.SetAPIEndpoint(PlayerIO.ServerApiEndpoints[0]);

            return(new Client(Channel, gameId,
                              authenticationOutput.GameFSRedirectMap,
                              authenticationOutput.Token,
                              authenticationOutput.UserId,
                              authenticationOutput.ShowBranding,
                              authenticationOutput.IsSocialNetworkUser, null));
        }
Exemplo n.º 34
0
        private void GenerateSheet(AseImportContextWorker aseWorker, string sheetAssetPath, Dictionary <string, AnimationOptions> animationOptionsDictionary)
        {
            var sheetImporter = GetAtPath(sheetAssetPath) as TextureImporter;
            var texture       = AssetDatabase.LoadAssetAtPath <Texture2D>(sheetAssetPath);

            sheetImporter.wrapMode            = textureCreationOptions.textureWrapMode;
            sheetImporter.filterMode          = textureCreationOptions.filterMode;
            sheetImporter.alphaIsTransparency = textureCreationOptions.alphaIsTransparency;
            sheetImporter.spriteImportMode    = SpriteImportMode.Multiple;


            var sprites = AseImportContextWorker.EnumerateSprites(texture, sheetData, spriteImportOptions).ToArray();

            sheetImporter.spritesheet = sprites.Select(s => new SpriteMetaData
            {
                rect = s.rect,
                name = s.name,
            }).ToArray();

            sheetImporter.SaveAndReimport();


            foreach (var metaFrameTag in sheetData.meta.frameTags)
            {
                var anim = aseWorker.GenerateAnimation(metaFrameTag, sheetData.frames, sprites,
                                                       animationOptionsDictionary?.ContainsKey(metaFrameTag.name) == true
                ? animationOptionsDictionary[metaFrameTag.name]
                : AseImportContextWorker.GetDefaultAnimationOptions);


                if (anim != null)
                {
                    AssetDatabase.CreateAsset(anim, Path.GetDirectoryName(sheetAssetPath) + "/anim_" + metaFrameTag.name + ".anim");
                }
            }
        }
Exemplo n.º 35
0
 public void LaunchUri(string uri, Dictionary <string, object> options = null)
 {
     if ((uri.StartsWith("http://") || uri.StartsWith("https://")) &&
         Uri.TryCreate(uri, UriKind.Absolute, out var parsedUri))
     {
         try
         {
             Browser.OpenAsync(uri, BrowserLaunchMode.External);
         }
         catch (FeatureNotSupportedException) { }
     }
     else
     {
         var launched = false;
         if (GetDevice() == Core.Enums.DeviceType.Android && uri.StartsWith("androidapp://"))
         {
             launched = _deviceActionService.LaunchApp(uri);
         }
         if (!launched && (options?.ContainsKey("page") ?? false))
         {
             (options["page"] as Page).DisplayAlert(null, "", ""); // TODO
         }
     }
 }
Exemplo n.º 36
0
        public static IRecordManager GetRecordManager(Dictionary <ConfigKey, object> config = null)
        {
            if (recordManager == null)
            {
                Debug.WriteLine("Using default TextRecordManager");
                recordManager = new TextRecordManager();
            }

            if (config?.ContainsKey(ConfigKey.TextRecordManagerFilePath) ?? false)
            {
                Debug.WriteLine("ConfigKey.TextRecordManagerFilePath is provided");

                var filePath = config[ConfigKey.TextRecordManagerFilePath] as string;

                if (String.IsNullOrWhiteSpace(filePath))
                {
                    throw new Exception("TextRecordManagerFilePath is empty!");
                }

                (recordManager as TextRecordManager).SetFilePath(filePath);
            }

            return(recordManager);
        }
Exemplo n.º 37
0
 public SqlOrderBy.Types ColumnSorter(string columnName)
 {
     return(ColumnSorterHash?.ContainsKey(columnName) == true
         ? ColumnSorterHash[columnName]
         : SqlOrderBy.Types.release);
 }
Exemplo n.º 38
0
        public async Task <ServerStatusAllViewModel> Get()
        {
            var result = new ServerStatusAllViewModel();

            foreach (var context in _contextManager.Servers)
            {
                var serverContext = _contextManager.GetServer(context.Config.Key);
                var status        = serverContext.Steam.GetServerStatusCached();
                if (status == null || status.Item1 == null || status.Item2 == null)
                {
                    //Server status is currently unavailable
                }
                else
                {
                    var info        = status.Item1;
                    var rules       = status.Item2;
                    var playerinfos = status.Item3;

                    var m               = new Regex(@"^(?<name>.+?)\s+-\s+\(v(?<version>\d+\.\d+)\)$", RegexOptions.IgnoreCase | RegexOptions.Singleline).Match(info.Name);
                    var name            = m.Success ? m.Groups["name"].Value : info.Name;
                    var version         = m.Success ? m.Groups["version"] : null;
                    var currentTime     = rules.FirstOrDefault(x => x.Name == "DayTime_s")?.Value;
                    var tamedDinosCount = context.TamedCreatures?.Count();
                    //var uploadedDinosCount = _context.Cluster?.Creatures?.Count();
                    var wildDinosCount = context.WildCreatures?.Count();
                    //var tamedDinosMax = 6000; //todo: remove hardcoded value
                    var structuresCount = context.Structures?.Count();
                    var totalPlayers    = context.Players?.Count();
                    var totalTribes     = context.Tribes?.Count();

                    //server uptime
                    //DateTime? serverStarted = null;
                    //try
                    //{
                    //    serverStarted = Process.GetProcessesByName(_constants.ArkServerProcessName)?.FirstOrDefault()?.StartTime;

                    //}
                    //catch { /* ignore exceptions */ }

                    var nextUpdate       = context.ApproxTimeUntilNextUpdate;
                    var nextUpdateTmp    = nextUpdate?.ToStringCustom();
                    var nextUpdateString = (nextUpdate.HasValue ? (!string.IsNullOrWhiteSpace(nextUpdateTmp) ? $"~{nextUpdateTmp}" : "waiting for new update ...") : null);
                    var lastUpdate       = context.LastUpdate;
                    var lastUpdateString = lastUpdate.ToStringWithRelativeDay();

                    var sr = new ServerStatusViewModel
                    {
                        Key                = context.Config.Key,
                        Name               = name,
                        Address            = info.Address,
                        Version            = version.ToString(),
                        OnlinePlayerCount  = info.Players,
                        OnlinePlayerMax    = info.MaxPlayers,
                        MapName            = info.Map,
                        InGameTime         = currentTime,
                        TamedCreatureCount = tamedDinosCount ?? 0,
                        WildCreatureCount  = wildDinosCount ?? 0,
                        StructureCount     = structuresCount ?? 0,
                        PlayerCount        = totalPlayers ?? 0,
                        TribeCount         = totalTribes ?? 0,
                        LastUpdate         = lastUpdateString,
                        NextUpdate         = nextUpdateString
                    };

                    var players = playerinfos?.Where(x => !string.IsNullOrEmpty(x.Name)).ToArray() ?? new PlayerInfo[] { };
                    using (var db = _databaseContextFactory.Create())
                    {
                        Dictionary <string, Tuple <ArkPlayer, Database.Model.User, User, long?, TimeSpan, ArkTribe> > d = null;
                        if (context.Players != null)
                        {
                            var playerNames = players.Select(x => x.Name).ToArray();
                            d = context.Players.Where(x => playerNames.Contains(x.Name, StringComparer.Ordinal)).Select(x =>
                            {
                                long steamId;
                                return(new Tuple <ArkPlayer, Database.Model.User, User, long?, TimeSpan, ArkTribe>(
                                           x,
                                           null,
                                           null,
                                           long.TryParse(x.SteamId, out steamId) ? steamId : (long?)null,
                                           TimeSpan.Zero, null));
                            }).ToDictionary(x => x.Item1.Name, StringComparer.OrdinalIgnoreCase);

                            var ids      = new List <ulong>();
                            var steamIds = d.Values.Select(x => x.Item4).Where(x => x != null).ToArray();
                            foreach (var user in db.Users.Where(y => steamIds.Contains(y.SteamId)))
                            {
                                var item = d.Values.FirstOrDefault(x => x.Item4 == user.SteamId);
                                if (item == null)
                                {
                                    continue;
                                }

                                ids.Add(item.Item1.Id);

                                var discordUser         = (User)null;        //e.User?.Client?.Servers?.Select(x => x.GetUser((ulong)user.DiscordId)).FirstOrDefault();
                                var playedLastSevenDays = TimeSpan.MinValue; //TimeSpan.FromSeconds(user?.Played?.OrderByDescending(x => x.Date).Take(7).Sum(x => x.TimeInSeconds) ?? 0);

                                d[item.Item1.Name] = Tuple.Create(item.Item1, user, discordUser, item.Item4, playedLastSevenDays, item.Item1.TribeId.HasValue ? context.Tribes?.FirstOrDefault(x => x.Id == item.Item1.TribeId.Value) : null);
                            }

                            var remaining = d.Values.Where(x => !ids.Contains(x.Item1.Id)).Where(x => x.Item4 != null).Select(x => x.Item4.Value).ToArray();
                            foreach (var user in db.Played.Where(x => x.SteamId.HasValue && remaining.Contains(x.SteamId.Value))
                                     .GroupBy(x => x.SteamId)
                                     .Select(x => new { key = x.Key, items = x.OrderByDescending(y => y.Date).Take(7).ToList() })
                                     .ToArray())
                            {
                                var item = d.Values.FirstOrDefault(x => x.Item4 == user.key);
                                if (item == null)
                                {
                                    continue;
                                }

                                var playedLastSevenDays = TimeSpan.FromSeconds(user?.items?.Sum(x => x.TimeInSeconds) ?? 0);
                                d[item.Item1.Name] = Tuple.Create(item.Item1, item.Item2, item.Item3, item.Item4, playedLastSevenDays, item.Item1.TribeId.HasValue ? context.Tribes?.FirstOrDefault(x => x.Id == item.Item1.TribeId.Value) : null);
                            }
                        }

                        //var playerslist = players.Select(x => {
                        //    var extra = d.ContainsKey(x.Name) ? d[x.Name] : null;
                        //    return new
                        //    {
                        //        Steam = x.Name,
                        //        Name = extra?.Item1?.Name,
                        //        Tribe = extra?.Item1?.TribeName,
                        //        Discord = extra != null && extra.Item3 != null ? $"{extra.Item3.Name}#{extra.Item3.Discriminator}" : null,
                        //        TimeOnline = x.Time.ToStringCustom(),
                        //        PlayedLastSevenDays = extra != null && extra.Item5.TotalMinutes > 1 ? extra?.Item5.ToStringCustom() : null
                        //    };
                        //}).ToArray();

                        foreach (var player in players)
                        {
                            var extra = d?.ContainsKey(player.Name) == true ? d[player.Name] : null;
                            sr.OnlinePlayers.Add(new OnlinePlayerViewModel
                            {
                                SteamName         = player.Name,
                                CharacterName     = extra?.Item1?.Name,
                                TribeName         = extra?.Item6?.Name,
                                DiscordName       = extra != null && extra.Item3 != null ? $"{extra.Item3.Name}#{extra.Item3.Discriminator}" : null,
                                TimeOnline        = player.Time.ToStringCustom(),
                                TimeOnlineSeconds = (int)Math.Round(player.Time.TotalSeconds)
                            });
                        }
                    }

                    result.Servers.Add(sr);
                }
            }

            foreach (var context in _contextManager.Clusters)
            {
                var cc = new ClusterStatusViewModel
                {
                    Key        = context.Config.Key,
                    ServerKeys = _contextManager.Servers
                                 .Where(x => x.Config.Cluster.Equals(context.Config.Key, StringComparison.OrdinalIgnoreCase))
                                 .Select(x => x.Config.Key).ToArray()
                };
                result.Clusters.Add(cc);
            }

            return(result);
        }
Exemplo n.º 39
0
 public static TValue Get <TKey, TValue>(this Dictionary <TKey, TValue> dict, TKey key) =>
 dict?.ContainsKey(key) == true ? dict[key] : default(TValue);
Exemplo n.º 40
0
 public bool ContainSurface()
 {
     return(planes?.ContainsKey(Block.UP_FACE_INDEX) ?? false);
 }
Exemplo n.º 41
0
        private async Task <ValueTuple <AcmeDnsRegistration, bool> > Register(string settingsPath, string domainId)
        {
            var apiPrefix = "";

            if (_parameters["api"] != null)
            {
                _client.BaseAddress = new System.Uri(_parameters["api"]);

                // we prefix the settings file with the encoded API url as these settings are
                // only useful on the target API, changing the api should change all settings
                apiPrefix = ToUrlSafeBase64String(_client.BaseAddress.Host);
            }

            var registrationSettingsPath = Path.Combine(settingsPath, "acmedns");

            if (!System.IO.Directory.Exists(registrationSettingsPath))
            {
                System.IO.Directory.CreateDirectory(registrationSettingsPath);
            }

            var domainConfigFile = domainId.Replace("*.", "") + ".json";

            var filenameRegex = new Regex(
                $"[{Regex.Escape(new string(Path.GetInvalidFileNameChars()))}]",
                RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.CultureInvariant
                );

            domainConfigFile = filenameRegex.Replace(domainConfigFile, "_");

            registrationSettingsPath = Path.Combine(registrationSettingsPath, apiPrefix + "_" + domainConfigFile);

            if (System.IO.File.Exists(registrationSettingsPath))
            {
                // registration exists
                var reg = JsonConvert.DeserializeObject <AcmeDnsRegistration>(System.IO.File.ReadAllText(registrationSettingsPath));

                // is an existing registration
                return(reg, false);
            }

            var registration = new AcmeDnsRegistration();

            if (_parameters.ContainsKey("allowfrom") && _parameters["allowfrom"] != null)
            {
                var rules = _parameters["allowfrom"].Split(';');
                registration.allowfrom = new List <string>();
                foreach (var r in rules)
                {
                    registration.allowfrom.Add(r.Trim().ToLower());
                }
            }

            if (EnableExtensions)
            {
                registration.subject = domainId;
            }

            var json = JsonConvert.SerializeObject(registration, _serializerSettings);

            var req = new HttpRequestMessage(HttpMethod.Post, "/register");

            if (_credentials?.ContainsKey("user") == true && _credentials?.ContainsKey("key") == true)
            {
                var basicCredentials = "Basic " + ToUrlSafeBase64String(_credentials["user"] + ":" + _credentials["key"]);
                req.Headers.Add("Authorization", basicCredentials);
            }


            req.Content = new StringContent(json);

            var response = await _client.SendAsync(req);

            if (response.IsSuccessStatusCode)
            {
                // got new registration
                var responseJson = await response.Content.ReadAsStringAsync();

                registration = JsonConvert.DeserializeObject <AcmeDnsRegistration>(responseJson);

                // save these settings for later
                System.IO.File.WriteAllText(registrationSettingsPath, JsonConvert.SerializeObject(registration));

                // is a new registration
                return(registration, true);
            }
            else
            {
                // failed to register
                return(null, false);
            }
        }
Exemplo n.º 42
0
 public static bool TypeExists(string typeName) => m_types?.ContainsKey(typeName) ?? false;
Exemplo n.º 43
0
        public static async Task <List <ListedItem> > ListEntries(
            string path,
            string returnformat,
            IntPtr hFile,
            WIN32_FIND_DATA findData,
            NamedPipeAsAppServiceConnection connection,
            CancellationToken cancellationToken,
            int countLimit,
            Func <List <ListedItem>, Task> intermediateAction,
            Dictionary <string, BitmapImage> defaultIconPairs = null
            )
        {
            var sampler     = new IntervalSampler(500);
            var tempList    = new List <ListedItem>();
            var hasNextFile = false;
            var count       = 0;

            IUserSettingsService userSettingsService = Ioc.Default.GetService <IUserSettingsService>();
            bool showFolderSize = userSettingsService.PreferencesSettingsService.ShowFolderSize;

            do
            {
                var isSystem     = ((FileAttributes)findData.dwFileAttributes & FileAttributes.System) == FileAttributes.System;
                var isHidden     = ((FileAttributes)findData.dwFileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden;
                var startWithDot = findData.cFileName.StartsWith(".");
                if ((!isHidden ||
                     (userSettingsService.PreferencesSettingsService.AreHiddenItemsVisible &&
                      (!isSystem || !userSettingsService.PreferencesSettingsService.AreSystemItemsHidden))) &&
                    (!startWithDot || userSettingsService.PreferencesSettingsService.ShowDotFiles))
                {
                    if (((FileAttributes)findData.dwFileAttributes & FileAttributes.Directory) != FileAttributes.Directory)
                    {
                        var file = await GetFile(findData, path, returnformat, connection, cancellationToken);

                        if (file != null)
                        {
                            if (defaultIconPairs != null)
                            {
                                if (!string.IsNullOrEmpty(file.FileExtension))
                                {
                                    var lowercaseExtension = file.FileExtension.ToLowerInvariant();
                                    if (defaultIconPairs.ContainsKey(lowercaseExtension))
                                    {
                                        file.SetDefaultIcon(defaultIconPairs[lowercaseExtension]);
                                    }
                                }
                            }
                            tempList.Add(file);
                            ++count;
                        }
                    }
                    else if (((FileAttributes)findData.dwFileAttributes & FileAttributes.Directory) == FileAttributes.Directory)
                    {
                        if (findData.cFileName != "." && findData.cFileName != "..")
                        {
                            var folder = await GetFolder(findData, path, returnformat, cancellationToken);

                            if (folder != null)
                            {
                                if (defaultIconPairs?.ContainsKey(string.Empty) ?? false)
                                {
                                    // Set folder icon (found by empty extension string)
                                    folder.SetDefaultIcon(defaultIconPairs[string.Empty]);
                                }
                                tempList.Add(folder);
                                ++count;

                                if (showFolderSize)
                                {
                                    folderSizeProvider.UpdateFolder(folder, cancellationToken);
                                }
                            }
                        }
                    }
                }
                if (cancellationToken.IsCancellationRequested || count == countLimit)
                {
                    break;
                }

                hasNextFile = FindNextFile(hFile, out findData);
                if (intermediateAction != null && (count == 32 || sampler.CheckNow()))
                {
                    await intermediateAction(tempList);

                    // clear the temporary list every time we do an intermediate action
                    tempList.Clear();
                }
            } while (hasNextFile);

            FindClose(hFile);
            return(tempList);
        }
Exemplo n.º 44
0
        /// <inheritdoc />
        public override CodeGeneratorResult Generate()
        {
            var isDeleted = false;
            var file      = new FileInfo(Path.Combine(_writeDirectory.FullName, _name + ".cs"));

            if (file.Exists)
            {
                isDeleted = true;
                file.Delete();
            }

            using (var writer = file.CreateText())
            {
                var extraSpaces = "";

                writer.WriteLine("using System;");
                if (_descriptions?.Count > 0)
                {
                    writer.WriteLine("using System.ComponentModel;");
                }
                writer.WriteLine();

                if (!string.IsNullOrWhiteSpace(_ns))
                {
                    writer.WriteLine($"namespace {_ns}");
                    writer.WriteLine("{");
                    extraSpaces = "    ";
                }

                writer.WriteLine("#pragma warning disable 1591");
                writer.WriteLine($"{extraSpaces}public enum {_name} : {typeof(T).Name}");
                writer.WriteLine($"{extraSpaces}{{");

                var formattedValues = _values
                                      .ToDictionary(pair => pair.Key, pair => GetEnumValueAsString(pair.Value))
                                      .Where(pair => !string.IsNullOrWhiteSpace(pair.Value))
                                      .ToArray();

                for (var i = 0; i < formattedValues.Length; i++)
                {
                    var formattedValue = formattedValues[i];

                    if (_descriptions?.ContainsKey(formattedValue.Key) == true &&
                        !string.IsNullOrWhiteSpace(_descriptions[formattedValue.Key]))
                    {
                        var description = _descriptions[formattedValue.Key]
                                          .Trim()
                                          .Replace("\"", "\\\"")
                                          .Replace("\r", "\\r")
                                          .Replace("\n", "\\n");

                        writer.WriteLine($"{extraSpaces}    /// <summary>");
                        writer.WriteLine($"{extraSpaces}    ///      {description}");
                        writer.WriteLine($"{extraSpaces}    /// </summary>");
                        writer.WriteLine($"{extraSpaces}    [Description(\"{description}\")]");
                    }

                    var friendlyName = _nameRuleSet.Apply(formattedValue.Key);
                    if (!char.IsLetter(friendlyName[0]))
                    {
                        friendlyName = "_" + friendlyName;
                    }
                    writer.WriteLine(
                        $"{extraSpaces}    {friendlyName} = {formattedValue.Value}" +
                        (i == formattedValues.Length - 1 ? "" : ",\r\n")
                        );
                }

                writer.WriteLine($"{extraSpaces}}}");
                writer.WriteLine("#pragma warning restore 1591");

                if (!string.IsNullOrWhiteSpace(_ns))
                {
                    writer.WriteLine("}");
                }
            }

            return(new CodeGeneratorResult(
                       new[] { file },
                       isDeleted ? new[] { file } : new FileInfo[0],
                       _writeDirectory
                       ));
        }
Exemplo n.º 45
0
 public bool Has(ulong guid)
 {
     return(_allObject?.ContainsKey(guid) ?? false);
 }
Exemplo n.º 46
0
        private List <CloudFormationParameter> PromptModuleParameters(
            ModuleManifest manifest,
            CloudFormationStack existing           = null,
            Dictionary <string, string> parameters = null,
            bool promptAll = false
            )
        {
            var stackParameters = new Dictionary <string, CloudFormationParameter>();

            // tentatively indicate to reuse previous parameter values
            if (existing != null)
            {
                foreach (var parameter in manifest.ParameterSections
                         .SelectMany(section => section.Parameters)
                         .Where(moduleParameter => existing.Parameters.Any(existingParameter => existingParameter.ParameterKey == moduleParameter.Name))
                         )
                {
                    stackParameters[parameter.Name] = new CloudFormationParameter {
                        ParameterKey     = parameter.Name,
                        UsePreviousValue = true
                    };
                }
            }

            // deployment bucket must always be set to match deployment tier in case it changed because LambdaSharp.Core was recreated
            stackParameters["DeploymentBucketName"] = new CloudFormationParameter {
                ParameterKey   = "DeploymentBucketName",
                ParameterValue = Settings.DeploymentBucketName
            };

            // add all provided parameters
            if (parameters != null)
            {
                foreach (var parameter in parameters)
                {
                    stackParameters[parameter.Key] = new CloudFormationParameter {
                        ParameterKey   = parameter.Key,
                        ParameterValue = parameter.Value
                    };
                }
            }

            // check if module requires any prompts
            if (manifest.GetAllParameters().Any(RequiresPrompt))
            {
                Console.WriteLine();
                Console.WriteLine($"Configuration for {manifest.GetFullName()} (v{manifest.GetVersion()})");

                // only list parameter sections that contain a parameter that requires a prompt
                foreach (var parameterGroup in manifest.ParameterSections.Where(group => group.Parameters.Any(RequiresPrompt)))
                {
                    Console.WriteLine();
                    Settings.PromptLabel(parameterGroup.Title.ToUpper());

                    // only prompt for required parameters
                    foreach (var parameter in parameterGroup.Parameters.Where(RequiresPrompt))
                    {
                        // check if parameter is multiple choice
                        string enteredValue;
                        if (parameter.AllowedValues?.Any() ?? false)
                        {
                            var message = parameter.Name;
                            if (parameter.Label != null)
                            {
                                message += $": {parameter.Label}";
                            }
                            enteredValue = Settings.PromptChoice(message, parameter.AllowedValues);
                        }
                        else
                        {
                            var constraints = new StringBuilder();
                            if ((parameter.MinValue != null) || (parameter.MaxValue != null))
                            {
                                // append value constraints
                                constraints.Append(" (");
                                if ((parameter.MinValue != null) && (parameter.MaxValue != null))
                                {
                                    constraints.Append($"Range: {parameter.MinValue.Value}..{parameter.MaxValue.Value}");
                                }
                                else if (parameter.MinValue != null)
                                {
                                    constraints.Append($"Mininum: {parameter.MinValue.Value}");
                                }
                                else if (parameter.MaxValue != null)
                                {
                                    constraints.Append($"Maximum: {parameter.MaxValue.Value}");
                                }
                                constraints.Append(")");
                            }
                            else if ((parameter.MinLength != null) || (parameter.MaxLength != null))
                            {
                                // append length constraints
                                constraints.Append(" (");
                                if ((parameter.MinLength != null) || (parameter.MaxLength != null))
                                {
                                    constraints.Append($"Length: {parameter.MinValue.Value}..{parameter.MaxValue.Value}");
                                }
                                else if (parameter.MinLength != null)
                                {
                                    constraints.Append($"Mininum Length: {parameter.MinLength.Value}");
                                }
                                else if (parameter.MaxLength != null)
                                {
                                    constraints.Append($"Maximum Length: {parameter.MaxLength.Value}");
                                }
                                constraints.Append(")");
                            }
                            var message = $"{parameter.Name} [{parameter.Type}]{constraints}";
                            if (parameter.Label != null)
                            {
                                message += $": {parameter.Label}";
                            }
                            enteredValue = Settings.PromptString(message, parameter.Default, parameter.AllowedPattern, parameter.ConstraintDescription) ?? "";
                        }
                        stackParameters[parameter.Name] = new CloudFormationParameter {
                            ParameterKey   = parameter.Name,
                            ParameterValue = enteredValue
                        };
                    }
                }
            }

            // check if LambdaSharp.Core services should be enabled by default
            if (
                (Settings.CoreServices == CoreServices.Enabled) &&
                manifest.GetAllParameters().Any(p => p.Name == "LambdaSharpCoreServices") &&
                !stackParameters.Any(p => p.Value.ParameterKey == "LambdaSharpCoreServices")
                )
            {
                stackParameters.Add("LambdaSharpCoreServices", new CloudFormationParameter {
                    ParameterKey   = "LambdaSharpCoreServices",
                    ParameterValue = Settings.CoreServices.ToString()
                });
            }
            return(stackParameters.Values.ToList());

            // local functions
            bool RequiresPrompt(ModuleManifestParameter parameter)
            {
                if (parameters?.ContainsKey(parameter.Name) == true)
                {
                    // no prompt since parameter is provided explicitly
                    return(false);
                }
                if (existing?.Parameters.Any(p => p.ParameterKey == parameter.Name) == true)
                {
                    // no prompt since we can reuse the previous parameter value
                    return(false);
                }
                if (!promptAll && (parameter.Default != null))
                {
                    // no prompt since parameter has a default value
                    return(false);
                }
                if (Settings.PromptsAsErrors)
                {
                    LogError($"{manifest.GetFullName()} requires value for parameter '{parameter.Name}'");
                    return(false);
                }
                return(true);
            }
        }
Exemplo n.º 47
0
        private List <CloudFormationParameter> PromptModuleParameters(
            ModuleManifest manifest,
            CloudFormationStack existing           = null,
            Dictionary <string, string> parameters = null,
            bool promptAll       = false,
            bool promptsAsErrors = false
            )
        {
            var stackParameters = new Dictionary <string, CloudFormationParameter>();

            // tentatively indicate to reuse previous parameter values
            if (existing != null)
            {
                foreach (var parameter in manifest.ParameterSections
                         .SelectMany(section => section.Parameters)
                         .Where(moduleParameter => existing.Parameters.Any(existingParameter => existingParameter.ParameterKey == moduleParameter.Name))
                         )
                {
                    stackParameters[parameter.Name] = new CloudFormationParameter {
                        ParameterKey     = parameter.Name,
                        UsePreviousValue = true
                    };
                }
            }

            // add all provided parameters
            if (parameters != null)
            {
                foreach (var parameter in parameters)
                {
                    stackParameters[parameter.Key] = new CloudFormationParameter {
                        ParameterKey   = parameter.Key,
                        ParameterValue = parameter.Value
                    };
                }
            }

            // check if module requires any prompts
            if (manifest.GetAllParameters().Any(RequiresPrompt))
            {
                Console.WriteLine();
                Console.WriteLine($"Configuration for {manifest.GetFullName()} (v{manifest.GetVersion()})");

                // only list parameter sections that contain a parameter that requires a prompt
                foreach (var parameterGroup in manifest.ParameterSections.Where(group => group.Parameters.Any(RequiresPrompt)))
                {
                    Console.WriteLine();
                    Console.WriteLine($"*** {parameterGroup.Title.ToUpper()} ***");

                    // only prompt for required parameters
                    foreach (var parameter in parameterGroup.Parameters.Where(RequiresPrompt))
                    {
                        var enteredValue = PromptString(parameter, parameter.Default) ?? "";
                        stackParameters[parameter.Name] = new CloudFormationParameter {
                            ParameterKey   = parameter.Name,
                            ParameterValue = enteredValue
                        };
                    }
                }
            }
            return(stackParameters.Values.ToList());

            // local functions
            bool RequiresPrompt(ModuleManifestParameter parameter)
            {
                if (parameters?.ContainsKey(parameter.Name) == true)
                {
                    // no prompt since parameter is provided explicitly
                    return(false);
                }
                if (existing?.Parameters.Any(p => p.ParameterKey == parameter.Name) == true)
                {
                    // no prompt since we can reuse the previous parameter value
                    return(false);
                }
                if (!promptAll && (parameter.Default != null))
                {
                    // no prompt since parameter has a default value
                    return(false);
                }
                if (promptsAsErrors)
                {
                    LogError($"{manifest.GetFullName()} requires value for parameter '{parameter.Name}'");
                    return(false);
                }
                return(true);
            }

            string PromptString(ModuleManifestParameter parameter, string defaultValue = null)
            {
                var prompt = $"|=> {parameter.Name} [{parameter.Type}]:";

                if (parameter.Label != null)
                {
                    prompt += $" {parameter.Label}:";
                }
                if (!string.IsNullOrEmpty(defaultValue))
                {
                    prompt = $"{prompt} [{defaultValue}]";
                }
                Console.Write(prompt);
                Console.Write(' ');
                SetCursorVisible(true);
                var resp = Console.ReadLine();

                SetCursorVisible(false);
                if (!string.IsNullOrEmpty(resp))
                {
                    return(resp);
                }
                return(defaultValue);

                // local functions
                void SetCursorVisible(bool visible)
                {
                    try {
                        Console.CursorVisible = visible;
                    } catch { }
                }
            }
        }
Exemplo n.º 48
0
        public static async Task <List <ListedItem> > ListEntries(
            BaseStorageFolder rootFolder,
            StorageFolderWithPath currentStorageFolder,
            string returnformat,
            Type sourcePageType,
            CancellationToken cancellationToken,
            int countLimit,
            Func <List <ListedItem>, Task> intermediateAction,
            Dictionary <string, BitmapImage> defaultIconPairs = null
            )
        {
            var  sampler    = new IntervalSampler(500);
            var  tempList   = new List <ListedItem>();
            uint count      = 0;
            var  firstRound = true;

            while (true)
            {
                IReadOnlyList <IStorageItem> items;
                uint maxItemsToRetrieve = 300;

                if (intermediateAction == null)
                {
                    // without intermediate action increase batches significantly
                    maxItemsToRetrieve = 1000;
                }
                else if (firstRound)
                {
                    maxItemsToRetrieve = 32;
                    firstRound         = false;
                }
                try
                {
                    items = await rootFolder.GetItemsAsync(count, maxItemsToRetrieve);

                    if (items == null || items.Count == 0)
                    {
                        break;
                    }
                }
                catch (NotImplementedException)
                {
                    break;
                }
                catch (Exception ex) when(
                    ex is UnauthorizedAccessException ||
                    ex is FileNotFoundException ||
                    (uint)ex.HResult == 0x80070490)    // ERROR_NOT_FOUND
                {
                    // If some unexpected exception is thrown - enumerate this folder file by file - just to be sure
                    items = await EnumerateFileByFile(rootFolder, count, maxItemsToRetrieve);
                }
                foreach (var item in items)
                {
                    if (item.IsOfType(StorageItemTypes.Folder))
                    {
                        var folder = await AddFolderAsync(item.AsBaseStorageFolder(), currentStorageFolder, returnformat, cancellationToken);

                        if (folder != null)
                        {
                            if (defaultIconPairs?.ContainsKey(string.Empty) ?? false)
                            {
                                folder.SetDefaultIcon(defaultIconPairs[string.Empty]);
                            }
                            tempList.Add(folder);
                        }
                    }
                    else
                    {
                        var fileEntry = await AddFileAsync(item.AsBaseStorageFile(), currentStorageFolder, returnformat, cancellationToken);

                        if (fileEntry != null)
                        {
                            if (defaultIconPairs != null)
                            {
                                if (!string.IsNullOrEmpty(fileEntry.FileExtension))
                                {
                                    var lowercaseExtension = fileEntry.FileExtension.ToLowerInvariant();
                                    if (defaultIconPairs.ContainsKey(lowercaseExtension))
                                    {
                                        fileEntry.SetDefaultIcon(defaultIconPairs[lowercaseExtension]);
                                    }
                                }
                            }
                            tempList.Add(fileEntry);
                        }
                    }
                    if (cancellationToken.IsCancellationRequested)
                    {
                        break;
                    }
                }
                count += maxItemsToRetrieve;

                if (countLimit > -1 && count >= countLimit)
                {
                    break;
                }

                if (intermediateAction != null && (items.Count == maxItemsToRetrieve || sampler.CheckNow()))
                {
                    await intermediateAction(tempList);

                    // clear the temporary list every time we do an intermediate action
                    tempList.Clear();
                }
            }
            return(tempList);
        }
Exemplo n.º 49
0
        /// <summary>
        /// Create a remote control group listing shaders matching the specified tags.
        /// </summary>
        /// <param name="group">The group <see cref="Guid"/> (unique identifier).</param>
        /// <param name="tags">Shaders matching all tags will be added to the group.</param>
        /// <returns>Returns <c>true</c> if the group contains at least one shader, otherwise <c>false</c>.</returns>
        public bool AddRemoteGroup(Guid group, HashSet <string> tags)
        {
            if (managedAssets == null || tags == null || managedAssets.Count == 0 || tags.Count == 0 || remoteGroups?.ContainsKey(group) != false)
            {
                return(false);
            }

            var list = new List <ManagedAsset>(managedAssets.Count);

            foreach (var asset in managedAssets)
            {
                if (!asset.IsContainer && tags.IsSubsetOf(asset.HashTags))
                {
                    list.Add(asset);
                }
            }

            if (list.Count == 0)
            {
                return(false);
            }

            list.TrimExcess();
            remoteGroups.Add(group, list);
            return(true);
        }
Exemplo n.º 50
0
        public string ToString(Dictionary <string, string> values, RuleConditions conditions = null)
        {
            StringBuilder toReturn = new StringBuilder();

            foreach (Argument argument in Arguments)
            {
                switch (argument.Type)
                {
                case ArgumentType.SINGLE:
                    break;

                case ArgumentType.MULTIPLE:
                    if (!(argument is MultipleArgument multipleArgument))
                    {
                        break;
                    }

                    if (!multipleArgument.IsAllowed(conditions))
                    {
                        continue;
                    }

                    if (multipleArgument.HasMultipleArguments)
                    {
                        toReturn = multipleArgument.Values.Aggregate(toReturn,
                                                                     (current, value) =>
                                                                     toReturn.Append((value.ToString().Contains(' ')
                                                    ? "\"" + value + "\""
                                                    : value) + " "));
                        continue;
                    }

                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                toReturn.Append((argument.Value.ToString().Contains(' ')
                                                ? "\"" + argument.Value + "\""
                                                : argument.Value) + " ");
            }

            Regex re = new Regex(@"\$\{(\w+)\}", RegexOptions.IgnoreCase);

            if (toReturn.Length > 0)
            {
                toReturn.Length--;
            }

            foreach (Match match in re.Matches(toReturn.ToString()))
            {
                if (values?.ContainsKey(match.Groups[1].Value) == true && values[match.Groups[1].Value] != null)
                {
                    toReturn.Replace(match.Value, !values[match.Groups[1].Value].Contains(' ')
                        ? values[match.Groups[1].Value]
                        : $"\"{values[match.Groups[1].Value]}\"");
                }
                else
                {
                    toReturn.Replace(match.Value, match.Groups[1].Value);
                }
            }

            return(toReturn.ToString());
        }
Exemplo n.º 51
0
        public static string GetLocalName(Dictionary <string, string> locals, string localization = null)
        {
            string local = localization ?? Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            return(locals?.ContainsKey(local) ?? false ? locals[local] : null);
        }
Exemplo n.º 52
0
 public T GetInjected <T>()
 {
     return((T)(_injected?.ContainsKey(typeof(T)) ?? false ? _injected[typeof(T)] : null));
 }
Exemplo n.º 53
0
 public static bool EnumExists(string typeName) => m_enums?.ContainsKey(typeName) ?? false;
Exemplo n.º 54
0
 public override string ResolveReference(string path, string baseFilePath) =>
 _sources?.ContainsKey(path) == true ? path : null;
Exemplo n.º 55
0
 public string ColumnFilter(string columnName)
 {
     return(ColumnFilterHash?.ContainsKey(columnName) == true
         ? ColumnFilterHash[columnName]
         : null);
 }
        public IEnumerable ReadForeignKey(string tableName, string id = null, Dictionary <string, object> postedFilter = null)
        {
            var desc          = src.DescribeTable(tableName, true, out _);
            var idColumnCount = desc.Count(n => n.IsPrimaryKey);

            if (idColumnCount != 1)
            {
                throw new InvalidOperationException("No Primary-Key was found!");
            }

            var stringColumnCount = desc.Count(n => n.Type.ManagedType == typeof(string));

            if (stringColumnCount == 0)
            {
                throw new InvalidOperationException("Unable to select a proper foreignkey.");
            }

            var idColumn   = desc.First(n => n.IsPrimaryKey);
            var stringCol  = desc.First(n => n.Type.ManagedType == typeof(string));
            var t          = typeof(ForeignKeyData <>).MakeGenericType(idColumn.Type.ManagedType);
            var keyAlias   = src.SyntaxProvider.FormatObjectName("Key");
            var labelAlias = src.SyntaxProvider.FormatObjectName("Label");

            if (id != null)
            {
                return(src.SqlQuery($"Select {src.SyntaxProvider.FormatObjectName(idColumn.ColumnName)} {keyAlias}, {src.SyntaxProvider.FormatObjectName(stringCol.ColumnName)} {labelAlias} from {src.SyntaxProvider.FormatObjectName(tableName)} where {src.SyntaxProvider.FormatObjectName(idColumn.ColumnName)} = [->p0]", t, id));
            }

            var filterValue = (postedFilter?.ContainsKey("Filter") ?? false) ? postedFilter["Filter"] : null;

            if (filterValue != null)
            {
                List <object> values     = new List <object>();
                List <string> andFilters = new List <string>();
                List <string> orFilters  = new List <string>();
                string        linkOp;
                foreach (var col in desc)
                {
                    var target = orFilters;
                    linkOp = " AND ";
                    var pnNull = "is not null";
                    var cv     = filterValue;
                    if (postedFilter.ContainsKey(col.ColumnName))
                    {
                        cv     = postedFilter[col.ColumnName];
                        linkOp = " OR ";
                        pnNull = "is null";
                        target = andFilters;
                    }

                    var pn = $"[->p{values.Count}]";
                    var op = "=";
                    if (col.Type.ManagedType == typeof(string))
                    {
                        values.Add($"%{cv}%");
                        op = "like";
                    }
                    else
                    {
                        values.Add(TypeConverter.TryConvert(cv, col.Type.ManagedType) ?? DBNull.Value);
                    }

                    target.Add($"({pn} {pnNull}{linkOp}{src.SyntaxProvider.FormatObjectName(col.ColumnName)} {op} {pn})");
                }

                List <string> final = new List <string>();
                if (andFilters.Count != 0)
                {
                    final.Add($"({string.Join(" AND ", andFilters)})");
                }

                if (orFilters.Count != 0)
                {
                    final.Add($"({string.Join(" OR ", orFilters)})");
                }

                return(src.SqlQuery($"Select {src.SyntaxProvider.FormatObjectName(idColumn.ColumnName)} {keyAlias}, {src.SyntaxProvider.FormatObjectName(stringCol.ColumnName)} {labelAlias} from {src.SyntaxProvider.FormatObjectName(tableName)} {(final.Count != 0 ? $"where {string.Join(" AND ", final)}" : "")}", t, values.ToArray()));
            }

            return(src.SqlQuery($"Select {src.SyntaxProvider.FormatObjectName(idColumn.ColumnName)} {keyAlias}, {src.SyntaxProvider.FormatObjectName(stringCol.ColumnName)} {labelAlias} from {src.SyntaxProvider.FormatObjectName(tableName)}", t));
        }
Exemplo n.º 57
0
        private void Initialize(StreamingContext context)
        {
            // TODO: Base species are maybe not used in game and may only lead to confusion (e.g. Giganotosaurus).

            InitializeNames();

            stats = new CreatureStat[Values.STATS_COUNT];
            if (altBaseStatsRaw != null)
            {
                altStats = new CreatureStat[Values.STATS_COUNT];
            }

            usedStats = 0;
            double[][] completeRaws = new double[Values.STATS_COUNT][];
            for (int s = 0; s < Values.STATS_COUNT; s++)
            {
                stats[s] = new CreatureStat();
                if (altBaseStatsRaw?.ContainsKey(s) ?? false)
                {
                    altStats[s] = new CreatureStat();
                }

                completeRaws[s] = new double[] { 0, 0, 0, 0, 0 };
                if (fullStatsRaw.Length > s && fullStatsRaw[s] != null)
                {
                    for (int i = 0; i < 5; i++)
                    {
                        if (fullStatsRaw[s].Length > i)
                        {
                            completeRaws[s][i] = fullStatsRaw[s]?[i] ?? 0;
                            if (i == 0 && fullStatsRaw[s][0] > 0)
                            {
                                usedStats |= (1 << s);
                            }
                        }
                    }
                }
            }
            fullStatsRaw = completeRaws;
            if (TamedBaseHealthMultiplier == null)
            {
                TamedBaseHealthMultiplier = 1;
            }

            if (colors == null)
            {
                colors = new List <ColorRegion>(ColorRegionCount);
            }
            for (int ci = colors.Count; ci < ColorRegionCount; ci++)
            {
                colors.Add(null);
            }
            if (string.IsNullOrEmpty(blueprintPath))
            {
                blueprintPath = string.Empty;
            }

            if (boneDamageAdjusters != null && boneDamageAdjusters.Any())
            {
                // cleanup boneDamageMultipliers. Remove duplicates. Improve names.
                var   boneDamageAdjustersCleanedUp = new Dictionary <string, double>();
                Regex rCleanBoneDamage             = new Regex(@"(^r_|^l_|^c_|Cnt_|JNT|\d+|SKL)");
                foreach (KeyValuePair <string, double> bd in boneDamageAdjusters)
                {
                    string boneName = rCleanBoneDamage.Replace(bd.Key, "").Replace("_", "");
                    if (boneName.Length < 2)
                    {
                        continue;
                    }
                    boneName = boneName.Substring(0, 1).ToUpper() + boneName.Substring(1);
                    if (!boneDamageAdjustersCleanedUp.ContainsKey(boneName))
                    {
                        boneDamageAdjustersCleanedUp.Add(boneName, Math.Round(bd.Value, 2));
                    }
                }
                boneDamageAdjusters = boneDamageAdjustersCleanedUp;
            }

            IsDomesticable = (taming != null && (taming.nonViolent || taming.violent)) || breeding != null;

            if (statImprintMult == null)
            {
                statImprintMult = new double[] { 0.2, 0, 0.2, 0, 0.2, 0.2, 0, 0.2, 0.2, 0.2, 0, 0 }
            }
            ;                                                                                                                 // default values for the stat imprint multipliers
        }
Exemplo n.º 58
0
 internal bool ContainsTarget(LabelTarget target)
 {
     return(_labels?.ContainsKey(target) == true);
 }
Exemplo n.º 59
0
        public bool TryFilterSerializableProps(
            JsonSourceGenerationOptionsAttribute options,
            [NotNullWhen(true)] out Dictionary <string, PropertyGenerationSpec>?serializableProperties,
            out bool castingRequiredForProps)
        {
            serializableProperties = new Dictionary <string, PropertyGenerationSpec>();
            Dictionary <string, PropertyGenerationSpec>?ignoredMembers = null;

            for (int i = 0; i < PropertyGenSpecList.Count; i++)
            {
                PropertyGenerationSpec propGenSpec     = PropertyGenSpecList[i];
                JsonIgnoreCondition?   ignoreCondition = propGenSpec.DefaultIgnoreCondition;

                if (ignoreCondition == JsonIgnoreCondition.WhenWritingNull && !propGenSpec.TypeGenerationSpec.CanBeNull)
                {
                    goto ReturnFalse;
                }

                // In case of JsonInclude fail if either:
                // 1. the getter is not accessible by the source generator or
                // 2. neither getter or setter methods are public.
                if (propGenSpec.HasJsonInclude && (!propGenSpec.CanUseGetter || !propGenSpec.IsPublic))
                {
                    goto ReturnFalse;
                }

                // Discard any getters not accessible by the source generator.
                if (!propGenSpec.CanUseGetter)
                {
                    continue;
                }

                if (!propGenSpec.IsProperty && !propGenSpec.HasJsonInclude && !options.IncludeFields)
                {
                    continue;
                }

                string memberName = propGenSpec.ClrName !;

                // The JsonPropertyNameAttribute or naming policy resulted in a collision.
                if (!serializableProperties.TryAdd(propGenSpec.RuntimePropertyName, propGenSpec))
                {
                    PropertyGenerationSpec other = serializableProperties[propGenSpec.RuntimePropertyName] !;

                    if (other.DefaultIgnoreCondition == JsonIgnoreCondition.Always)
                    {
                        // Overwrite previously cached property since it has [JsonIgnore].
                        serializableProperties[propGenSpec.RuntimePropertyName] = propGenSpec;
                    }
                    else if (
                        // Does the current property have `JsonIgnoreAttribute`?
                        propGenSpec.DefaultIgnoreCondition != JsonIgnoreCondition.Always &&
                        // Is the current property hidden by the previously cached property
                        // (with `new` keyword, or by overriding)?
                        other.ClrName != memberName &&
                        // Was a property with the same CLR name was ignored? That property hid the current property,
                        // thus, if it was ignored, the current property should be ignored too.
                        ignoredMembers?.ContainsKey(memberName) != true)
                    {
                        // We throw if we have two public properties that have the same JSON property name, and neither have been ignored.
                        serializableProperties  = null;
                        castingRequiredForProps = false;
                        return(false);
                    }
                    // Ignore the current property.
                }

                if (propGenSpec.DefaultIgnoreCondition == JsonIgnoreCondition.Always)
                {
                    (ignoredMembers ??= new Dictionary <string, PropertyGenerationSpec>()).Add(memberName, propGenSpec);
                }
            }

            Debug.Assert(PropertyGenSpecList.Count >= serializableProperties.Count);
            castingRequiredForProps = PropertyGenSpecList.Count > serializableProperties.Count;
            return(true);

ReturnFalse:
            serializableProperties  = null;
            castingRequiredForProps = false;
            return(false);
        }
Exemplo n.º 60
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="options">Options</param>
        public SpectralFeaturesExtractor(MultiFeatureOptions options) : base(options)
        {
            var featureList = options.FeatureList;

            if (featureList == "all" || featureList == "full")
            {
                featureList = FeatureSet;
            }

            var features = featureList.Split(',', '+', '-', ';', ':')
                           .Select(f => f.Trim().ToLower())
                           .ToList();

            _parameters = options.Parameters;

            _extractors = features.Select <string, Func <float[], float[], float> >(feature =>
            {
                switch (feature)
                {
                case "sc":
                case "centroid":
                    return(Spectral.Centroid);

                case "ss":
                case "spread":
                    return(Spectral.Spread);

                case "sfm":
                case "flatness":
                    if (_parameters?.ContainsKey("minLevel") ?? false)
                    {
                        var minLevel = (float)_parameters["minLevel"];
                        return((spectrum, freqs) => Spectral.Flatness(spectrum, minLevel));
                    }
                    else
                    {
                        return((spectrum, freqs) => Spectral.Flatness(spectrum));
                    }

                case "sn":
                case "noiseness":
                    if (_parameters?.ContainsKey("noiseFrequency") ?? false)
                    {
                        var noiseFrequency = (float)_parameters["noiseFrequency"];
                        return((spectrum, freqs) => Spectral.Noiseness(spectrum, freqs, noiseFrequency));
                    }
                    else
                    {
                        return((spectrum, freqs) => Spectral.Noiseness(spectrum, freqs));
                    }

                case "rolloff":
                    if (_parameters?.ContainsKey("rolloffPercent") ?? false)
                    {
                        var rolloffPercent = (float)_parameters["rolloffPercent"];
                        return((spectrum, freqs) => Spectral.Rolloff(spectrum, freqs, rolloffPercent));
                    }
                    else
                    {
                        return((spectrum, freqs) => Spectral.Rolloff(spectrum, freqs));
                    }

                case "crest":
                    return((spectrum, freqs) => Spectral.Crest(spectrum));

                case "entropy":
                case "ent":
                    return((spectrum, freqs) => Spectral.Entropy(spectrum));

                case "sd":
                case "decrease":
                    return((spectrum, freqs) => Spectral.Decrease(spectrum));

                case "c1":
                case "c2":
                case "c3":
                case "c4":
                case "c5":
                case "c6":
                    return((spectrum, freqs) => Spectral.Contrast(spectrum, freqs, int.Parse(feature.Substring(1))));

                default:
                    return((spectrum, freqs) => 0);
                }
            }).ToList();

            FeatureCount        = features.Count;
            FeatureDescriptions = features;

            _blockSize = options.FftSize > FrameSize ? options.FftSize : MathUtils.NextPowerOfTwo(FrameSize);
            _fft       = new RealFft(_blockSize);

            var frequencies = options.Frequencies;
            var resolution  = (float)SamplingRate / _blockSize;

            if (frequencies == null)
            {
                _frequencies = Enumerable.Range(0, _blockSize / 2 + 1)
                               .Select(f => f * resolution)
                               .ToArray();
            }
            else if (frequencies.Length == _blockSize / 2 + 1)
            {
                _frequencies = frequencies;
            }
            else
            {
                _frequencies = new float[frequencies.Length + 1];
                frequencies.FastCopyTo(_frequencies, frequencies.Length, 0, 1);
                _mappedSpectrum     = new float[_frequencies.Length];
                _frequencyPositions = new int[_frequencies.Length];

                for (var i = 1; i < _frequencies.Length; i++)
                {
                    _frequencyPositions[i] = (int)(_frequencies[i] / resolution) + 1;
                }
            }

            _spectrum = new float[_blockSize / 2 + 1];  // buffer for magnitude spectrum
        }