Esempio n. 1
0
        public void TestContains()
        {
            var jArray = new JArray();

            jArray.Add(alice);

            jArray.Contains(alice).Should().BeTrue();
            jArray.Contains(bob).Should().BeFalse();
        }
Esempio n. 2
0
    public void Contains()
    {
      JValue v = new JValue(1);

      JArray a = new JArray {v};

      Assert.AreEqual(false, a.Contains(new JValue(2)));
      Assert.AreEqual(false, a.Contains(new JValue(1)));
      Assert.AreEqual(false, a.Contains(null));
      Assert.AreEqual(true, a.Contains(v));
    }
Esempio n. 3
0
    public void Contains()
    {
      JValue v = new JValue(1);

      JArray a = new JArray { v };

      Assert.AreEqual(false, a.Contains(new JValue(2)));
      Assert.AreEqual(false, a.Contains(new JValue(1)));
      Assert.AreEqual(false, a.Contains(null));
      Assert.AreEqual(true, a.Contains(v));
    }
Esempio n. 4
0
        private JArray ArrayRelativePatch(JArray left, JObject patch)
        {
            var addList    = patch.SelectToken("add");
            var removeList = patch.SelectToken("remove");

            foreach (var toAdd in addList.Children())
            {
                if (left.Contains(toAdd, JTokenDeepEqualEqualityComparer.Instance))
                {
                    continue;
                }

                left.Add(toAdd);
            }

            foreach (var toRemove in removeList.Children())
            {
                foreach (var inLeft in left.Children())
                {
                    if (JToken.DeepEquals(inLeft, toRemove))
                    {
                        inLeft.Remove();
                        break;
                    }
                }
            }

            return(left);
        }
Esempio n. 5
0
        private static void _cookieInDomainToJArray(ref JArray store, string strDomain, CookieContainer cookies)
        {
            Uri domain;

            if (!Uri.TryCreate(strDomain, UriKind.RelativeOrAbsolute, out domain))
            {
                return;
            }

            if (cookies.GetCookies(domain).Count > 0)
            {
                foreach (Cookie cookie in cookies.GetCookies(domain))
                {
                    var jCookie = new JObject();
                    jCookie.Add("name", cookie.Name);
                    jCookie.Add("domain", cookie.Domain);
                    jCookie.Add("path", cookie.Path);
                    jCookie.Add("value", cookie.Value);

                    if (store.Contains(jCookie))
                    {
                        continue;
                    }

                    store.Add(jCookie);
                }
            }
        }
Esempio n. 6
0
        private JObject ArrayRelativeDiff(JArray left, JArray right)
        {
            if (JToken.DeepEquals(left, right))
            {
                return(null);
            }

            var result = new RelativeArrayDiff();

            foreach (var child in right.Children())
            {
                if (left.Contains(child, JTokenDeepEqualEqualityComparer.Instance))
                {
                    continue;
                }

                result.ToAdd.Add(child);
            }

            foreach (var child in left.Children())
            {
                if (right.Contains(child, JTokenDeepEqualEqualityComparer.Instance))
                {
                    continue;
                }

                result.ToRemove.Add(child);
            }

            return(result.Object);
        }
        /// <summary>
        /// Computes as array.
        /// </summary>
        /// <param name="item1">The item1.</param>
        /// <param name="item2">The item2.</param>
        /// <param name="computeOperator">The compute operator.</param>
        /// <returns><c>true</c> if compute as true, <c>false</c> otherwise.</returns>
        private static bool ComputeAsArray(JArray item1, string item2, ComputeOperator computeOperator)
        {
            switch (computeOperator)
            {
            case ComputeOperator.Contains:
                return(item1.Contains <JToken, string>(item2, x => x.ToObject <string>(), (x, y) => x.Equals(y, StringComparison.OrdinalIgnoreCase)));

            case ComputeOperator.NotContains:
                return(!item1.Contains <JToken, string>(item2, x => x.ToObject <string>(), (x, y) => x.Equals(y, StringComparison.OrdinalIgnoreCase)));

            default:
                throw ExceptionFactory.CreateInvalidObjectException(nameof(computeOperator), new
                {
                    ComputeOperator = computeOperator.EnumToString()
                });
            }
        }
 private void IncludeInArray(JArray existingArray, JArray includeValues)
 {
     foreach (var val in includeValues)
     {
         if (!existingArray.Contains(val))
         {
             existingArray.Add(val);
         }
     }
 }
Esempio n. 9
0
 internal static bool Contains(this JArray jArray, object item, bool useExtension)
 {
     if (useExtension)
     {
         return(jArray.ToObject <List <object> >().Contains(item));
     }
     else
     {
         return(jArray.Contains(item));
     }
 }
Esempio n. 10
0
        public void SplitContactDetailsArrayTest()
        {
            //arrange
            string s = "[{\"id\":30075066,\"href\":\"https://api.intelliflo.com/v2/clients/30944834/contactdetails/30075066\",\"type\":\"Telephone\",\"value\":\"0117 9452500\",\"isDefault\":true},{\"id\":30075067,\"href\":\"https://api.intelliflo.com/v2/clients/30944834/contactdetails/30075067\",\"type\":\"Mobile\",\"value\":\"07971 123456\",\"isDefault\":true},{\"id\":30075068,\"href\":\"https://api.intelliflo.com/v2/clients/30944834/contactdetails/30075068\",\"type\":\"Email\",\"value\":\"[email protected]\",\"isDefault\":true}]";
            JArray a = JArray.Parse(s);

            //act
            JArray result = Tools.SplitContactDetails(a, true);

            //assert
            Assert.AreEqual(true, result[0]["type"].ToString() == "Email", "Array doesn't include Email");
            Assert.AreEqual(false, result.Contains("Telephone"), "Array includes Telephone in emails");
        }
        public void RemoveAt()
        {
            JValue v1 = new JValue(1);
            JValue v2 = new JValue(1);
            JValue v3 = new JValue(1);

            JArray j = new JArray();

            j.Add(v1);
            j.Add(v2);
            j.Add(v3);

            Assert.AreEqual(true, j.Contains(v1));
            j.RemoveAt(0);
            Assert.AreEqual(false, j.Contains(v1));

            Assert.AreEqual(true, j.Contains(v3));
            j.RemoveAt(1);
            Assert.AreEqual(false, j.Contains(v3));

            Assert.AreEqual(1, j.Count);
        }
Esempio n. 12
0
        private static void mostrarDiferencias(JArray provinciasSegunUnaApi, JArray provinciasSegunOtraApi)
        {
            JArray provinciasDiferentes = new JArray();

            foreach (object nombreProvinciaML in provinciasSegunUnaApi)
            {
                if (!provinciasSegunOtraApi.Contains(nombreProvinciaML))
                {
                    provinciasDiferentes.Add(nombreProvinciaML);
                }
            }
            Console.Out.WriteLine(provinciasDiferentes);
        }
Esempio n. 13
0
        public void TestRemoveAt()
        {
            var jArray = new JArray
            {
                alice,
                bob,
                alice
            };

            jArray.RemoveAt(1);
            jArray.Count().Should().Be(2);
            jArray.Contains(bob).Should().BeFalse();
        }
Esempio n. 14
0
        private void SaveRecentFile(string path)
        {
            JObject json         = JsonManager.GetJson();
            JArray  recentlyUsed = json["recentlyUsed"] as JArray;

            if (recentlyUsed.Contains(path))
            {
                return;
            }
            recentlyUsed.Insert(recentlyUsed.Count >= 1 ? recentlyUsed.Count - 1 : 0, path);

            json["recentlyUsed"].Parent.Remove();
            json.Add(new JProperty("recentlyUsed", recentlyUsed));

            JsonManager.SaveJson(json.ToString());
            LoadRecentList();
        }
        private bool EvaluateOperation(string op, object operand, AuthorizationRequest request)
        {
            var normalizedOp = op.ToLower();
            var opDictionary = JsonConvert.DeserializeObject <Dictionary <string, object> >(operand.ToString());
            var leftOperand  = opDictionary.Keys.FirstOrDefault <string>();
            var rightOperand = opDictionary.GetValueOrDefault(leftOperand);

            switch (normalizedOp)
            {
            case "stringequals":
                var valueOfLeftOperand = request.AllAttributes.GetValueOrDefault(leftOperand);
                if (rightOperand.GetType() == typeof(Newtonsoft.Json.Linq.JArray))
                {
                    JArray arr = JArray.Parse(rightOperand.ToString());
                    if (arr.Contains(valueOfLeftOperand))
                    {
                        return(true);
                    }
                }
                else
                {
                    if (string.Equals(valueOfLeftOperand, rightOperand.ToString(), StringComparison.OrdinalIgnoreCase))
                    {
                        return(true);
                    }
                }

                break;

            case "bool":
                valueOfLeftOperand = request.AllAttributes.GetValueOrDefault(leftOperand);
                var valueOfRightOperant = rightOperand.ToString();
                if (valueOfLeftOperand != null && valueOfLeftOperand == valueOfRightOperant)
                {
                    return(true);
                }
                break;
            }

            return(false);
        }
        private void status_information_is_returned()
        {
            var     statusNode      = this.nodes[FirstPowNode].FullNode;
            JObject jObjectResponse = JObject.Parse(this.responseText);

            jObjectResponse["agent"].Value <string>().Should().Contain(statusNode.Settings.Agent);
            jObjectResponse["version"].Value <string>().Should().Be(statusNode.Version.ToString());
            jObjectResponse["network"].Value <string>().Should().Be(statusNode.Network.Name);
            jObjectResponse["consensusHeight"].Value <int>().Should().Be(0);
            jObjectResponse["blockStoreHeight"].Value <int>().Should().Be(0);
            jObjectResponse["protocolVersion"].Value <uint>().Should().Be((uint)(statusNode.Settings.ProtocolVersion));
            jObjectResponse["relayFee"].Value <decimal>().Should().Be(statusNode.Settings.MinRelayTxFeeRate.FeePerK.ToUnit(MoneyUnit.BTC));
            jObjectResponse["dataDirectoryPath"].Value <string>().Should().Be(statusNode.Settings.DataDir);
            JArray jArrayFeatures = jObjectResponse["enabledFeatures"].Value <JArray>();

            jArrayFeatures.Contains("Stratis.Bitcoin.Base.BaseFeature");
            jArrayFeatures.Contains("Stratis.Bitcoin.Features.Api.ApiFeature");
            jArrayFeatures.Contains("Stratis.Bitcoin.Features.BlockStore.BlockStoreFeature");
            jArrayFeatures.Contains("Stratis.Bitcoin.Features.Consensus.ConsensusFeature");
            jArrayFeatures.Contains("Stratis.Bitcoin.Features.MemoryPool.MempoolFeature");
            jArrayFeatures.Contains("Stratis.Bitcoin.Features.Miner.MiningFeature");
            jArrayFeatures.Contains("Stratis.Bitcoin.Features.RPC.RPCFeature");
            jArrayFeatures.Contains("Stratis.Bitcoin.Features.Wallet.WalletFeature");
        }
Esempio n. 17
0
        /// <summary>Parses RDF in the form of N-Quads.</summary>
        /// <remarks>Parses RDF in the form of N-Quads.</remarks>
        /// <param name="input">the N-Quads input to parse.</param>
        /// <returns>an RDF dataset.</returns>
        /// <exception cref="JsonLD.Core.JsonLdError"></exception>
        public static RDFDataset ParseNQuads(string input)
        {
            // build RDF dataset
            RDFDataset dataset = new RDFDataset();

            // split N-Quad input into lines
            string[] lines      = RDFDatasetUtils.Regex.Eoln.Split(input);
            int      lineNumber = 0;

            foreach (string line in lines)
            {
                lineNumber++;
                // skip empty lines
                if (RDFDatasetUtils.Regex.Empty.Matcher(line).Matches())
                {
                    continue;
                }
                // parse quad
                Matcher match = RDFDatasetUtils.Regex.Quad.Matcher(line);
                if (!match.Matches())
                {
                    throw new JsonLdError(JsonLdError.Error.SyntaxError, "Error while parsing N-Quads; invalid quad. line:"
                                          + lineNumber);
                }
                // get subject
                RDFDataset.Node subject;
                if (match.Group(1) != null)
                {
                    subject = new RDFDataset.IRI(Unescape(match.Group(1)));
                }
                else
                {
                    subject = new RDFDataset.BlankNode(Unescape(match.Group(2)));
                }
                // get predicate
                RDFDataset.Node predicate = new RDFDataset.IRI(Unescape(match.Group(3)));
                // get object
                RDFDataset.Node @object;
                if (match.Group(4) != null)
                {
                    @object = new RDFDataset.IRI(Unescape(match.Group(4)));
                }
                else
                {
                    if (match.Group(5) != null)
                    {
                        @object = new RDFDataset.BlankNode(Unescape(match.Group(5)));
                    }
                    else
                    {
                        string language = Unescape(match.Group(8));
                        string datatype = match.Group(7) != null?Unescape(match.Group(7)) : match.Group
                                                  (8) != null ? JSONLDConsts.RdfLangstring : JSONLDConsts.XsdString;

                        string unescaped = Unescape(match.Group(6));
                        @object = new RDFDataset.Literal(unescaped, datatype, language);
                    }
                }
                // get graph name ('@default' is used for the default graph)
                string name = "@default";
                if (match.Group(9) != null)
                {
                    name = Unescape(match.Group(9));
                }
                else
                {
                    if (match.Group(10) != null)
                    {
                        name = Unescape(match.Group(10));
                    }
                }
                RDFDataset.Quad triple = new RDFDataset.Quad(subject, predicate, @object, name);
                // initialise graph in dataset
                if (!dataset.ContainsKey(name))
                {
                    JArray tmp = new JArray();
                    tmp.Add(triple);
                    dataset[name] = (JToken)tmp;
                }
                else
                {
                    // add triple if unique to its graph
                    JArray triples = (JArray)dataset[name];
                    if (!triples.Contains(triple))
                    {
                        triples.Add(triple);
                    }
                }
            }
            return(dataset);
        }
Esempio n. 18
0
        void BuildItems()
        {
            var libraIndex = _builder.Libra.Table <Libra.Item>()
                             .ToArray()
                             .ToDictionary(i => i.Key);

            foreach (var sItem in _builder.ItemsToImport)
            {
                var item = _builder.CreateItem(sItem.Key);
                _builder.Localize.Strings(item, sItem, "Name");
                _builder.Localize.HtmlStrings(item, sItem, "Description");
                _builder.Db.ItemsByName[(string)item.en.name] = item;
                item.patch         = PatchDatabase.Get("item", sItem.Key);
                item.patchCategory = PatchDatabase.GetPatchCategory(sItem);
                item.price         = sItem.Ask;
                item.ilvl          = sItem.ItemLevel.Key;
                item.category      = sItem.ItemUICategory.Key;

                if (sItem.IsUnique)
                {
                    item.unique = 1;
                }

                if (sItem.IsDyeable)
                {
                    item.dyeable = 1;
                }

                if (!sItem.IsUntradable)
                {
                    item.tradeable = 1;
                }

                if (sItem.Bid > 0)
                {
                    item.sell_price = sItem.Bid;
                }

                var rarity = sItem.As <byte>("Rarity");
                if (rarity > 0)
                {
                    item.rarity = rarity;
                }

                if (sItem.IsConvertable)
                {
                    item.convertable = 1;
                }

                if (sItem.IsAetherialReducible)
                {
                    item.reducible = 1;
                }

                if (sItem.ItemSearchCategory.Key == 0)
                {
                    item.unlistable = 1;
                }

                if (sItem.IsCollectable)
                {
                    item.collectable = 1;
                }

                // Mark applicable materia for advanced melding.
                if (sItem.ItemUICategory.Key == 58 && !sItem.IsAdvancedMeldingPermitted)
                {
                    item.advancedMeldingForbidden = 1;
                }

                item.stackSize = sItem.StackSize;

                if (sItem.RepairClassJob.Key != 0)
                {
                    item.repair = sItem.RepairClassJob.Key;
                }

                BuildAttributes(item, sItem);

                item.icon = ItemIconDatabase.EnsureIcon(sItem);

                // Additional data
                var additionalData = sItem.AdditionalData;
                if (additionalData != null)
                {
                    if (additionalData.Sheet.Name == "GardeningSeed")
                    {
                        _gardeningSeeds.Add(sItem);
                    }
                }

                #region Libra Supplement
                libraIndex.TryGetValue(sItem.Key, out var lItem);

                if (lItem != null && lItem.data != null)
                {
                    dynamic extraLibraData = JsonConvert.DeserializeObject(lItem.data);

                    // Mob drops
                    if (extraLibraData.bnpc != null && extraLibraData.bnpc.Count > 0)
                    {
                        var mobIds = new JArray();
                        foreach (long mob in extraLibraData.bnpc)
                        {
                            mobIds.Add(mob);

                            if (!_builder.ItemDropsByMobId.TryGetValue(mob, out var itemIds))
                            {
                                itemIds = new List <int>();
                                _builder.ItemDropsByMobId[mob] = itemIds;
                            }
                            itemIds.Add(sItem.Key);
                        }

                        // References are added by Mobs module.
                        item.drops = mobIds;
                    }

                    // Instances
                    if (extraLibraData.instance_content != null)
                    {
                        foreach (int instanceId in extraLibraData.instance_content)
                        {
                            if (!_builder.Db.ItemsByInstanceId.TryGetValue(instanceId, out var instanceItems))
                            {
                                _builder.Db.ItemsByInstanceId[instanceId] = instanceItems = new List <dynamic>();
                            }

                            instanceItems.Add(item);

                            if (item.instances == null)
                            {
                                item.instances = new JArray();
                            }

                            JArray itemInstances = item.instances;
                            if (!itemInstances.Contains(instanceId))
                            {
                                itemInstances.Add(instanceId);
                                _builder.Db.AddReference(item, "instance", instanceId, true);
                            }
                        }
                    }
                }
                #endregion

                //todo: item.repair_price = ? Not important

                // Mark embedded categories
                if (sItem.ItemUICategory.Key == 59)
                {
                    // Crystals
                    _builder.Db.EmbeddedIngredientItems.Add(item);
                    _builder.Db.EmbeddedPartialItemIds.Add(sItem.Key);
                }
                if (sItem.ItemUICategory.Key == 60 && sItem.ItemSearchCategory.Key == 59)
                {
                    _builder.Db.EmbeddedPartialItemIds.Add(sItem.Key); // Catalysts with a matching search category.
                }
            }

            // Needs another pass once all items are processed.
            BuildAdditionalItemData();
        }
Esempio n. 19
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!555555555555");
            string str1      = "[{\"Name\":\"qd\",\"ProUrl\":\"123\"}]";
            var    file_objs = new JArray();

            try
            {
                file_objs = JArray.Parse(str1);
            }
            catch (Exception ex)
            {
                return;
            }

            string name;
            string url;
            // string hh = "[{\"mid\": \"123456\",\"nid\": \"321\",\"data\": [{\"mid\": \"1\",\"name\": \"111\" },{\"mid\": \"2\",\"name\": \"222\"}, {\"mid\": \"3\",\"name\": \"333\" },{\"mid\": \"4\",\"name\": \"444\"},{\"mid\": \"5\",\"name\": \"555\" }    ]},{\"mid\": \"123456\",\"nid\": \"321\",\"data\": [ {\"mid\": \"1\",\"name\": \"111\" }, {\"mid\": \"2\",\"name\": \"222\" }, {\"mid\": \"3\",\"name\": \"333\"},{\"mid\": \"4\",\"name\": \"444\" }, {\"mid\": \"5\", \"name\": \"555\" } ]}\r\n]";

            // string hh = "[{\"mid\": \"123456\",\"nid\": \"321\",\"data\": [{\"mid\": \"1\",\"name\": \"111\" },{\"mid\": \"2\",\"name\": \"222\"}, {\"mid\": \"3\",\"name\": \"333\" },{\"mid\": \"4\",\"name\": \"444\"},{\"mid\": \"5\",\"name\": \"555\" }    ]},{\"mid\": \"123456\",\"nid\": \"321\",\"data\": [ {\"mid\": \"1\",\"name\": \"111\" }, {\"mid\": \"2\",\"name\": \"222\" }, {\"mid\": \"3\",\"name\": \"333\"},{\"mid\": \"4\",\"name\": \"444\" }, {\"mid\": \"5\", \"name\": \"555\" } ]}\r\n]";
            JArray jArray = JArray.Parse(str1);

            foreach (var jj in jArray)
            {
                // string job= jj.ToString();
                //JObject jObject=JObject.Parse(job);
                JObject job = (JObject)jj;

                if (jArray.Contains("Name"))
                {
                    JArray datArray = JArray.Parse(job["Name"].ToString());
                    foreach (var item in datArray)
                    {
                        JObject jdata = (JObject)item;

                        name = jdata["Name"].ToString();
                    }
                }

                if (file_objs.Contains("ProUrl"))
                {
                    JArray datArray = JArray.Parse(job["ProUrl"].ToString());
                    foreach (var item in datArray)
                    {
                        JObject jdata = (JObject)item;

                        name = jdata["name"].ToString();
                    }
                }
            }
            //if (json.Contains("name"))
            //{

            //};
            //if (json.IndexOf("\"Name\":") > -1)
            //{
            //    //存在name属性
            //    string jsonText1 = json[0].ToString();
            //    string jsonText2 = json[1].ToString();
            //    string jsonText3 = json[2].ToString();

            //    var mJObj = JObject.Parse(jsonText2);
            //}



            // mJObj.Add(); //新增,没试过
        }
Esempio n. 20
0
 public bool ContainsKey(string key)
 {
     return(columns.Contains(key));
 }
Esempio n. 21
0
            public override BWebServiceResponse OnRequest_Interruptable(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
            {
                if (_Context.Request.HttpMethod != "POST")
                {
                    _ErrorMessageAction?.Invoke("CheckModelsExist: POST method is accepted. But received request method:  " + _Context.Request.HttpMethod);
                    return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method: " + _Context.Request.HttpMethod));
                }

                string  RequestPayload = null;
                JObject ParsedBody;

                try
                {
                    using (var InputStream = _Context.Request.InputStream)
                    {
                        using var ResponseReader = new StreamReader(InputStream);

                        RequestPayload = ResponseReader.ReadToEnd();
                        ParsedBody     = JObject.Parse(RequestPayload);
                    }
                }
                catch (Exception e)
                {
                    _ErrorMessageAction?.Invoke("CheckModelsExist-> Malformed request body. Body content: " + RequestPayload + ", Exception: " + e.Message + ", Trace: " + e.StackTrace);
                    return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                }

                //get UserModels from parsed request body
                var UserModelIDs = new List <string>();

                if (ParsedBody["userModelIds"].Type != JTokenType.Array)
                {
                    return(BWebResponse.BadRequest("Request is invalid."));
                }
                var UserModelsJArray = (JArray)ParsedBody["userModelIds"];

                foreach (var CurrentUserModelID in UserModelsJArray)
                {
                    if (CurrentUserModelID.Type != JTokenType.String)
                    {
                        return(BWebResponse.BadRequest("Request is invalid."));
                    }

                    var UserModelID = (string)CurrentUserModelID;
                    if (!UserModelIDs.Contains(UserModelID))
                    {
                        UserModelIDs.Add(UserModelID);
                    }
                }

                //get UserSharedModels from parsed request body
                var UserSharedModelIDs = new List <string>();

                if (ParsedBody["userSharedModelIds"].Type != JTokenType.Array)
                {
                    return(BWebResponse.BadRequest("Request is invalid."));
                }
                var UserSharedModelsJArray = (JArray)ParsedBody["userSharedModelIds"];

                foreach (var CurrentUserSharedModelID in UserSharedModelsJArray)
                {
                    if (CurrentUserSharedModelID.Type != JTokenType.String)
                    {
                        return(BWebResponse.BadRequest("Request is invalid."));
                    }

                    var UserSharedModelID = (string)CurrentUserSharedModelID;
                    if (!UserSharedModelIDs.Contains(UserSharedModelID))
                    {
                        UserSharedModelIDs.Add(UserSharedModelID);
                    }
                }

                var CheckedUserModelIDs = new JArray();

                foreach (var ModelID in UserModelIDs)
                {
                    var ModelKey = new BPrimitiveType(ModelID);

                    if (!CommonMethods.TryGettingModelInfo(
                            DatabaseService,
                            ModelID,
                            out JObject _,
                            true, out ModelDBEntry ModelData,
                            out BWebServiceResponse _FailedResponse,
                            _ErrorMessageAction))
                    {
                        if (_FailedResponse.StatusCode >= 400 && _FailedResponse.StatusCode < 500)
                        {
                            continue;
                        }
                        else if (_FailedResponse.StatusCode >= 500)
                        {
                            return(BWebResponse.InternalError("Getting user model info operation has been failed."));
                        }
                    }

                    if (!CheckedUserModelIDs.Contains(ModelID))
                    {
                        CheckedUserModelIDs.Add(ModelID);
                    }
                }

                var CheckedUserSharedModelIDs = new JArray();

                foreach (var SharedModelID in UserSharedModelIDs)
                {
                    var ModelKey = new BPrimitiveType(SharedModelID);

                    if (!CommonMethods.TryGettingModelInfo(
                            DatabaseService,
                            SharedModelID,
                            out JObject _,
                            true, out ModelDBEntry ModelData,
                            out BWebServiceResponse _FailedResponse,
                            _ErrorMessageAction))
                    {
                        if (_FailedResponse.StatusCode >= 400 && _FailedResponse.StatusCode < 500)
                        {
                            continue;
                        }
                        else if (_FailedResponse.StatusCode >= 500)
                        {
                            return(BWebResponse.InternalError("Getting user shared model info operation has been failed."));
                        }
                    }

                    if (!CheckedUserSharedModelIDs.Contains(SharedModelID))
                    {
                        CheckedUserSharedModelIDs.Add(SharedModelID);
                    }
                }

                return(BWebResponse.StatusOK("Check models have successfully been completed.", new JObject()
                {
                    ["checkedUserModelIds"] = CheckedUserModelIDs,
                    ["checkedUserSharedModelIds"] = CheckedUserSharedModelIDs
                }));
            }
Esempio n. 22
0
        /// <summary>Update all info on the track
        /// <para><see cref="SpotifyLocalAPI.GetStatus()"/></para>
        /// </summary>
        public void UpdateTrack(bool canAdd)
        {
            if (bp != null)
            {
                bp.Dispose();
            }
            if (this.toast_isEnabled)
            {
                toast_timer.Start();
            }
            if (_spotify.GetStatus().Track != null && _spotify.GetStatus().Track.Length > 0 && _spotify.GetStatus().Running)
            {
                Size s = new Size(64, 64);
                bp = new Bitmap(_spotify.GetStatus().Track.GetAlbumArt(AlbumArtSize.Size160), s);
                pictureBox1.Image = bp;
                SetColors();
            }
            else
            {
                text_songName.Text   = (trackName = "No current song playing");
                trackNameLength      = 0;
                text_artistName.Text = "No artist";
                progressBar1.Maximum = 0;
                return;
            }
            text_songName.Text   = (trackName = _spotify.GetStatus().Track.TrackResource.Name + "              ");
            trackNameLength      = trackName.Length;
            text_artistName.Text = _spotify.GetStatus().Track.ArtistResource.Name;
            progressBar1.Maximum = _spotify.GetStatus().Track.Length;
            if (JsonOptions.GetOption("showAmountOfPlays").Equals("true") && canAdd)
            {
                int    plays    = 1;
                string songName = text_songName.Text.Trim();
                if (songName.Length > 10)
                {
                    songName = songName.Substring(0, 10);
                }
                string artistName = text_artistName.Text.Trim();
                if (artistName.Length > 7)
                {
                    artistName = artistName.Substring(0, 7);
                }

                for (int i = 0; i < songs.Count; i++)
                {
                    JObject _song = (JObject)songs[i];
                    if (((string)_song.GetValue("name")) == songName && ((string)_song.GetValue("artist")) == artistName)
                    {
                        string _p = (string)_song.GetValue("plays");
                        if (Int32.TryParse(_p, out plays))
                        {
                            plays += 1;
                        }
                        else
                        {
                            plays = 1;
                        }
                        songs.RemoveAt(i);
                        break;
                    }
                }
                JObject song = new JObject(
                    new JProperty("artist", artistName),
                    new JProperty("name", songName),
                    new JProperty("plays", plays)
                    );
                if (plays > 1)
                {
                    JObject oldSong = new JObject(
                        new JProperty("artist", artistName),
                        new JProperty("name", songName),
                        new JProperty("plays", plays - 1)
                        );
                    if (songs.Contains(oldSong))
                    {
                        songs.Remove(oldSong);
                    }
                }
                songs.Add(song);


                /*Song _Song = new Song();
                 * _Song.artist = text_artistName.Text;
                 * _Song.name = text_songName.Text.Trim();
                 * _Song.plays = plays;
                 * if(songHistory.Count >= 5) {
                 *  songHistory.RemoveAt(5);
                 * }
                 * songHistory.Add(_Song);*/

                string json = JsonConvert.SerializeObject(songs);
                File.WriteAllText("./songs.json", json);
                text_amountOfPlays.Text = plays.ToString();
            }
        }
Esempio n. 23
0
        private void btnConvert_Click(object sender, EventArgs e)
        {
            List <Transicion> trans_arr = new List <Transicion>();

            foreach (Transicion trans in this.automate_afn.Trans)
            {
                if (trans.Inicio.Equals(this.automate_afn.Estado_Inicial))
                {
                    trans_arr.Add(trans);
                }
            }


            for (int i = 0; i < trans_arr.Count; i++)
            {
                string[] next_states     = trans_arr[i].Siguiente;
                string   prev_state      = next_states.Equals(null) ? "" : string.Join(",", next_states.Distinct().ToList());
                bool     estado_agregado = false;
                foreach (Transicion trans_val in trans_arr)
                {
                    if (prev_state == trans_val.Inicio)
                    {
                        estado_agregado = true;
                        break;
                    }
                }

                if (estado_agregado == false)
                {
                    foreach (string letra in this.automate_afn.Alfabeto)
                    {
                        Transicion trans_add = new Transicion();
                        trans_add.Inicio = prev_state;
                        trans_add.Valor  = letra;
                        JArray next_st = new JArray();
                        foreach (string next_state in trans_arr[i].Siguiente)
                        {
                            foreach (Transicion state in this.automate_afn.Trans)
                            {
                                if (next_state.Equals(state.Inicio) && state.Valor.Equals(letra))
                                {
                                    string[] st        = next_st.ToObject <string[]>().Distinct().ToArray();
                                    string[] state_add = state.Siguiente.Distinct().ToArray();
                                    next_st = JArray.FromObject(st.Concat(state_add));
                                    break;
                                }
                            }
                        }
                        trans_add.Siguiente = next_st.ToObject <string[]>();
                        if (trans_add.Inicio != "" && trans_add.Siguiente != null)
                        {
                            trans_arr.Add(trans_add);
                        }
                    }
                }
            }

            //Console.WriteLine(JsonConvert.SerializeObject(trans_arr, Formatting.Indented));

            JArray acept_states   = new JArray();
            JArray new_states_arr = new JArray();
            Dictionary <string, string> new_states = new Dictionary <string, string>();

            foreach (Transicion state in trans_arr)
            {
                string estado_previo    = state.Inicio;
                string estado_siguiente = string.Join(",", state.Siguiente.Distinct().ToArray());
                //string estado_siguiente = string.Concat(",", state.Siguiente.Distinct<string>().ToArray());
                if (!new_states.ContainsKey(estado_previo))
                {
                    string new_state_prev = string.Concat("q", Convert.ToString(new_states.Count()));
                    new_states.Add(estado_previo, new_state_prev);
                    new_states_arr.Add(new_state_prev);
                    foreach (string estado_aceptacion in this.automate_afn.Estados_Aceptacion)
                    {
                        if (estado_previo.Contains(estado_aceptacion))
                        {
                            if (!acept_states.Contains(new_state_prev))
                            {
                                acept_states.Add(new_state_prev);
                            }
                        }
                    }
                }
                if (!new_states.ContainsKey(estado_siguiente))
                {
                    string new_state_next = string.Concat("q", Convert.ToString(new_states.Count()));
                    new_states.Add(estado_siguiente, new_state_next);
                    new_states_arr.Add(new_state_next);
                    foreach (string estado_aceptacion in this.automate_afn.Estados_Aceptacion)
                    {
                        if (estado_siguiente.Contains(estado_aceptacion))
                        {
                            if (!acept_states.Contains(new_state_next))
                            {
                                acept_states.Add(new_state_next);
                            }
                        }
                    }
                }
                state.Inicio    = new_states[estado_previo];
                state.Siguiente = new string[] { new_states[estado_siguiente] };
            }

            this.automata_afd                    = new Automata();
            this.automata_afd.Nombre             = this.automate_afn.Nombre;
            this.automata_afd.Estados            = new JArray(new_states.Values).ToObject <string[]>();
            this.automata_afd.Estado_Inicial     = this.automate_afn.Estado_Inicial;
            this.automata_afd.Estados_Aceptacion = acept_states.ToObject <string[]>();
            this.automata_afd.Alfabeto           = this.automate_afn.Alfabeto;
            this.automata_afd.Trans              = trans_arr.ToArray <Transicion>();

            txtTransiciones.ResetText();
            foreach (Transicion value in trans_arr)
            {
                string nextStates = string.Join(", ", value.Siguiente);
                string text       = string.Concat(value.Inicio, " --> ", value.Valor, " --> {", value.Siguiente[0], "}", Environment.NewLine);
                txtTransiciones.AppendText(text);
            }
        }
Esempio n. 24
0
    public void RemoveAt()
    {
      JValue v1 = new JValue(1);
      JValue v2 = new JValue(1);
      JValue v3 = new JValue(1);

      JArray j = new JArray();

      j.Add(v1);
      j.Add(v2);
      j.Add(v3);

      Assert.AreEqual(true, j.Contains(v1));
      j.RemoveAt(0);
      Assert.AreEqual(false, j.Contains(v1));

      Assert.AreEqual(true, j.Contains(v3));
      j.RemoveAt(1);
      Assert.AreEqual(false, j.Contains(v3));

      Assert.AreEqual(1, j.Count);
    }
Esempio n. 25
0
        public JObject Upgrade(JObject src)
        {
            JObject dst = (JObject)src.DeepClone();

            JsonUtil.SetIfAvailable(dst, "behaviour.groups.data.group-ff-1.ffgroup", 0);
            JsonUtil.SetIfAvailable(dst, "behaviour.groups.data.group-ff-2.ffgroup", 1);
            JsonUtil.SetIfAvailable(dst, "behaviour.groups.data.group-ff-3.ffgroup", 2);
            JsonUtil.SetIfAvailable(dst, "behaviour.groups.data.group-ff-4.ffgroup", 3);
            JsonUtil.SetIfAvailable(dst, "behaviour.groups.data.group-ff-5.ffgroup", 4);
            JsonUtil.SetIfAvailable(dst, "behaviour.groups.data.group-ff-6.ffgroup", 5);
            JsonUtil.SetIfAvailable(dst, "behaviour.groups.data.group-ff-7.ffgroup", 6);

            var enumTranslationDictionary = Enum.GetValues(typeof(FFXIVChatChannel)).Cast <FFXIVChatChannel>().ToDictionary(
                key => key.ToString().ToUpperInvariant(),
                value => GobchatChannelMapping.GetChannel(value).ChatChannel);

            JArray ReplaceContent(JArray array)
            {
                var result = new JArray();

                foreach (var element in array)
                {
                    var key = element.ToString().ToUpperInvariant();
                    if (enumTranslationDictionary.TryGetValue(key, out var replacement))
                    {
                        if (replacement == ChatChannel.None)
                        {
                            continue;
                        }
                        var value = replacement.ToString().ToUpperInvariant();
                        if (!result.Contains(value))
                        {
                            result.Add(value);
                        }
                    }
                }

                return(result);
            }

            JsonUtil.MoveIfAvailable(dst, "style.channel.animated-emote", dst, "style.channel.animatedemote");
            JsonUtil.MoveIfAvailable(dst, "style.channel.roll", dst, "style.channel.random");
            JsonUtil.MoveIfAvailable(dst, "style.channel.worldlinkshell-1", dst, "style.channel.crossworldlinkshell-1");
            JsonUtil.MoveIfAvailable(dst, "style.channel.worldlinkshell-2", dst, "style.channel.crossworldlinkshell-2");
            JsonUtil.MoveIfAvailable(dst, "style.channel.worldlinkshell-3", dst, "style.channel.crossworldlinkshell-3");
            JsonUtil.MoveIfAvailable(dst, "style.channel.worldlinkshell-4", dst, "style.channel.crossworldlinkshell-4");
            JsonUtil.MoveIfAvailable(dst, "style.channel.worldlinkshell-5", dst, "style.channel.crossworldlinkshell-5");
            JsonUtil.MoveIfAvailable(dst, "style.channel.worldlinkshell-6", dst, "style.channel.crossworldlinkshell-6");
            JsonUtil.MoveIfAvailable(dst, "style.channel.worldlinkshell-7", dst, "style.channel.crossworldlinkshell-7");
            JsonUtil.MoveIfAvailable(dst, "style.channel.worldlinkshell-8", dst, "style.channel.crossworldlinkshell-8");

            JsonUtil.ReplaceArrayIfAvailable(dst, "behaviour.channel.roleplay", ReplaceContent);
            JsonUtil.ReplaceArrayIfAvailable(dst, "behaviour.channel.mention", ReplaceContent);
            JsonUtil.ReplaceArrayIfAvailable(dst, "behaviour.channel.visible", ReplaceContent);
            JsonUtil.ReplaceArrayIfAvailable(dst, "behaviour.channel.rangefilter", ReplaceContent);

            JsonUtil.ReplaceArrayIfAvailable(dst, "behaviour.channel.visible", (array) =>
            {
                array.Add(ChatChannel.GobchatInfo.ToString().ToUpperInvariant());
                array.Add(ChatChannel.GobchatError.ToString().ToUpperInvariant());
                return(array);
            });

            return(dst);
        }
        public void IncludeInCopyToOutput(JArray itemsToInclude)
        {
            var buildOptions = JsonObject.GetOrAddProperty("buildOptions", null);
            //  var existingCopyToOutput = buildOptions[copyToOutputArray];
            var copyToOutput = buildOptions.Property("copyToOutput");

            if (copyToOutput != null)
            {
                if (copyToOutput.Value is JValue)
                {
                    // promote to include array.
                    var jvalue = (JValue)copyToOutput.Value;
                    //jvalue.Remove();

                    if (!itemsToInclude.Contains(jvalue.Value))
                    {
                        itemsToInclude.Add(jvalue.Value);
                    }

                    buildOptions["copyToOutput"]["include"] = itemsToInclude;
                }
                else if (copyToOutput.Value is JArray)
                {
                    // add to existing array.
                    var existingArray = (JArray)copyToOutput.Value;
                    IncludeInArray(existingArray, itemsToInclude);
                }
                else if (copyToOutput.Value is JObject)
                {
                    // check for an include property.

                    var copyToOutputObject = (JObject)copyToOutput.Value;
                    var includeProperty    = copyToOutputObject.Property("include");

                    if (includeProperty == null)
                    {
                        buildOptions["copyToOutput"]["include"] = itemsToInclude;
                    }
                    else if (includeProperty.Value is JValue)
                    {
                        // single value, promote to an array
                        var jvalue = (JValue)includeProperty.Value;
                        if (!itemsToInclude.Contains(jvalue.Value))
                        {
                            itemsToInclude.Add(jvalue.Value);
                        }
                        buildOptions["copyToOutput"]["include"] = itemsToInclude;
                    }
                    else if (includeProperty.Value is JArray)
                    {
                        // already array, merge
                        var propArray = (JArray)includeProperty.Value;
                        IncludeInArray(propArray, itemsToInclude);
                    }
                }
            }
            else
            {
                buildOptions["copyToOutput"]            = new JObject();
                buildOptions["copyToOutput"]["include"] = itemsToInclude;
            }
        }