public override void Init(object[] data) { base.Init(data); List<Buddy> buddyList = SmartfoxClient.Instance.GetBuddyList(); if (buddyList.Count > 0) { Utils.SetActive(noFriendLabel, false); EventDelegate.Set(btnSendInvite.onClick, EventSendInvite); JSONObject friend; friendList = new JSONArray(); for (int i = 0; i < buddyList.Count; i++) { friend = new JSONObject(); if (buddyList[i].IsOnline) { friend.Add("displayName", buddyList[i].GetVariable("displayName").GetStringValue()); friend.Add("cash", (long)buddyList[i].GetVariable("cash").GetDoubleValue()); friend.Add("username", buddyList[i].Name); friendList.Add(friend); } } InitScrollViewData(friendList); } else { // TO DO - dont have friend message Utils.SetActive(scrollview.gameObject, false); Utils.SetActive(btnSendInvite.gameObject, false); Utils.SetActive(noFriendLabel, true); Debug.Log("----------- DONE HAVE ANY FRIEND ----------------"); } }
public void LoadFriendRank(Action callback) { JSONArray friendList = new JSONArray (); foreach(JSONValue item in UserSingleton.Instance.FriendList){ JSONObject friend = item.Obj; friendList.Add (friend ["id"]); } JSONObject requestBody = new JSONObject (); requestBody.Add ("UserID", UserSingleton.Instance.UserID); requestBody.Add ("FriendList", friendList); HTTPClient.Instance.POST (Singleton.Instance.HOST + "/Rank/Friend", requestBody.ToString(), delegate(WWW www) { Debug.Log("LoadFriendRank" + www.text); string response = www.text; JSONObject obj = JSONObject.Parse(response); JSONArray arr = obj["Data"].Array; foreach(JSONValue item in arr){ int rank = (int)item.Obj["Rank"].Number; if(FriendRank.ContainsKey(rank)){ FriendRank.Remove(rank); } FriendRank.Add(rank,item.Obj); } callback(); }); }
private bool ShouldLoadData(Tab selectedTab) { JSONArray checkData = new JSONArray(); DateTime? checkTime = null; switch(selectedTab) { case Tab.TOP_RICHER: checkData = topRicherList; checkTime = topRicherLoadTime; break; case Tab.TOP_WINNER: checkData = topWinnerList; checkTime = topWinnerLoadTime; break; default: return false; } if (checkData == null || checkData.Length == 0) { return true; } else { if (checkTime.HasValue) { if (Utils.CurrentTime().Subtract((DateTime)checkTime).TotalSeconds >= RELOAD_DATA_SECONDS) { return true; } else { return false; } } else { return true; } } }
public override void Init(object[] data) { base.Init(data); EventDelegate.Set(tabInvite.onClick, EventTabInvite); EventDelegate.Set(tabFriends.onClick, EventTabFriends); // Get list friends from smartfox buddy list List<Buddy> buddyList = SmartfoxClient.Instance.GetBuddyList(); if (buddyList.Count > 0) { JSONObject friend; friendList = new JSONArray(); for (int i = 0; i < buddyList.Count; i++) { friend = new JSONObject(); if (buddyList[i].IsOnline) { friend.Add("displayName", buddyList[i].GetVariable("displayName").GetStringValue()); friend.Add("cash", (long)buddyList[i].GetVariable("cash").GetDoubleValue()); friend.Add("avatar", buddyList[i].GetVariable("avatar").GetStringValue()); friend.Add("facebookId", buddyList[i].GetVariable("facebookId").GetStringValue()); } else { friend.Add("displayName", buddyList[i].GetVariable("$displayName").GetStringValue()); friend.Add("cash", (long)buddyList[i].GetVariable("$cash").GetDoubleValue()); friend.Add("avatar", buddyList[i].ContainsVariable("$avatar") ? buddyList[i].GetVariable("$avatar").GetStringValue() : string.Empty); friend.Add("facebookId", buddyList[i].ContainsVariable("$facebookId") ? buddyList[i].GetVariable("$facebookId").GetStringValue() : string.Empty); } friend.Add("username", buddyList[i].Name); friendList.Add(friend); } InitScrollViewData(friendList); } else { Utils.SetActive(scrollview.gameObject, false); Debug.Log("----------- DONE HAVE ANY FRIEND ----------------"); } }
public JSONArray decodeArray(string str, ref int index) { if (str[index] != '[') return null; index++; JSONArray array = new JSONArray(); bool array_should_over = false; while (index < str.Length) { index = passWhiteSpace(str, index); if (str[index] == ']') { index++; return array; } else if (array_should_over) { throw new JSONError(str, index); } array.addJSONValue(decodeValue(str, ref index)); index = passWhiteSpace(str, index); if (str[index] != ',') { array_should_over = true; } else { index++; } } return null; }
public IEnumerator assess(string p_action, JSONNode p_values, Action<JSONNode> callback) { print("--- assess action (" + p_action + ") ---"); string putDataString = "{" + "\"action\": \"" + p_action + "\"" + ", \"values\": " + p_values.ToString() + "}"; string URL = baseURL + "/gameplay/" + idGameplay + "/assessAndScore"; WWW www = new WWW(URL, Encoding.UTF8.GetBytes(putDataString), headers); // wait for the requst to finish yield return www; JSONNode returnAssess = JSON.Parse(www.text); feedback = returnAssess["feedback"].AsArray; scores = returnAssess["scores"].AsArray; print("Action " + putDataString + " assessed! returned: " + returnAssess.ToString()); foreach (JSONNode f in feedback) { // log badge if (string.Equals(f["type"], "BADGE")) { badgesWon.Add(f); } } callback(returnAssess); }
//JSON Format: /* { "session": { "id": "session1234", "player": "user123", "game": "game1", "version": "version 1.0" }, "play_events" : [ { "time": "2015-02-17T22:43:45-5:00", "event": "PowerUp.FireBall", "value": "1.0", "level": "1-1"}, { "time": "2015-02-17T22:45:45-5:00", "event": "PowerUp.Mushroom", "value": "2.0", "level": "1-1"} ] } */ public static string ToJSON(Gloggr_Report r) { JSONNode n = new JSONClass(); n.Add ("session", Gloggr_SessionHeader.ToJSONObject(r.session) ); JSONArray a = new JSONArray(); foreach(Gloggr_PlayEvent e in r.play_events) { a.Add(Gloggr_PlayEvent.ToJSONObject(e)); } n.Add ("play_events", a); return n.ToString(); // string json = JsonConvert.SerializeObject(e, Formatting.Indented); // //from Gloggr_SessionHeader.ToJSON // //json = Gloggr_SessionHeader.FormatJSONKeys(json); // //from Gloggr_PlayEvent.ToJSON // //json = Gloggr_PlayEvent.FormatJSONKeys(json); // return json; }
public static string SerializeArray(JSONArray jsonArray) { StringBuilder builder = new StringBuilder(); builder.Append("["); for (int i = 0; i < jsonArray.Count; i++) { if (jsonArray[i] is JSONObject) { builder.Append(string.Format("{0},", SerializeObject((JSONObject) jsonArray[i]))); } else if (jsonArray[i] is JSONArray) { builder.Append(string.Format("{0},", SerializeArray((JSONArray) jsonArray[i]))); } else if (jsonArray[i] is string) { builder.Append(string.Format("{0},", jsonArray[i])); } else { builder.Append(string.Format("{0},", jsonArray[i])); } } if (builder.Length > 1) { builder.Remove(builder.Length - 1, 1); } builder.Append("]"); return builder.ToString(); }
public void SetResults(JSONObject jsonData) { spinDataResult = jsonData; resultsData = jsonData.GetArray("items"); winningGold = jsonData.GetArray("wGold"); // Calculate extra data (winning type, winning count from list result items) JSONObject extraData = SlotCombination.CalculateCombination(resultsData, GetNumLine()); winningCount = extraData.GetArray("wCount"); winningType = extraData.GetArray("wType"); // isJackpot = jsonData.GetBoolean("isJP"); freeSpinLeft = jsonData.GetInt("frLeft"); isBigWin = jsonData.GetBoolean("bWin"); gotFreeSpin = jsonData.GetInt("frCount") > 0; // bool[] winingItems = new bool[15]; // for (int i = 0; i < winningGold.Length; i++) { // if (winningGold[i].Number > 0) { // for (int j = 0; j < SlotCombination.NUM_REELS; j++) { // winingItems[SlotCombination.COMBINATION[i, j]] = true; // } // } // } for (int i = 0; i < slotReels.Length; i++) { slotReels[i].SetResults(new int[3] { (int)resultsData[i * 3].Number, (int)resultsData[i * 3 + 1].Number, (int)resultsData[i * 3 + 2].Number }); } }
// Use this for initialization void Start () { Messenger.AddListener<float>("Run Timer", UpdateEvents); PoIList = new Dictionary<int, PoIBase>(); HireableList = new Dictionary<int, PoIBase>(); //Read data from system file. string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "PoIData.txt"); string txt = System.IO.File.ReadAllText(filePath); JSONNode temp = JSONNode.Parse(txt); Hireables = temp["hireable"].AsArray; FillHireableRoster(); foreach(JSONNode node in temp["initial"].AsArray) { PoIBase newPOI = new PoIBase(); newPOI.InitializePoIBase(node); GlobalPlayerData.Staff.Add (idGen++, newPOI); } foreach(JSONNode node in temp["pois"].AsArray) { PoIBase newPOI = new PoIBase(); newPOI.InitializePoIBase(node); PoIList.Add (idGen++, newPOI); } }
/// <summary> /// Construct a copy of the JSONValue given as a parameter /// </summary> /// <param name="value"></param> public JSONValue(JSONValue value) { Type = value.Type; switch (Type) { case JSONValueType.String: Str = value.Str; break; case JSONValueType.Boolean: Boolean = value.Boolean; break; case JSONValueType.Number: Number = value.Number; break; case JSONValueType.Object: if (value.Obj != null) Obj = new JSONObject(value.Obj); break; case JSONValueType.Array: Array = new JSONArray(value.Array); break; } }
public override void Init(object[] data) { gameType = (BaseGameScreen.GameType)data[0]; EventDelegate.Set(btnBack.onClick, BackToSelectGame); EventDelegate.Set(btnCreateRoom.onClick, OpenPopupCreateRoom); // fake room list // roomList = new JSONArray(); roomList = ((JSONObject)data[1]).GetArray("rooms"); Debug.Log(roomList.ToString()); // fake room min bet // int[] roomBet = new int[] { 10000, 100000, 520000, 2000000}; // for (int i = 0; i < roomList.Length; i++) { // JSONObject room = roomList[i].Obj; // room.Add("id", i); // room.Add("name", "room " + i); // room.Add("minBet", roomBet[i % 4]); // // roomList.Add(room); // } InitScrollViewData(); // Set Bet Filter for (int i = 0; i < betFilterList.Length; i++) { betFilterPopupList.items.Add(betFilterList[i]); } EventDelegate.Set(betFilterPopupList.onChange, EventFilterBet); crtBetFilter = betFilterList[0]; }
// Use this for initialization void Start() { Debug.Log ("Loading credits file"); creditsAsset = Resources.Load ("Credits") as TextAsset; creditsJson = JSON.Parse (creditsAsset.text) as JSONArray; Invoke ("ShowCredits", 2f); }
public CustomGenerator() { numberOfObjects = 15; TextAsset json = (TextAsset) Resources.Load ("CustomGenerator"); Debug.Log(json.text); customObjects = (JSON.Parse (json.text)).AsArray; numberOfObjects = customObjects.Count; Debug.Log(numberOfObjects); }
public JSONValue ToJSON() { var result = new JSONArray(); foreach (var item in this.Items) { result.AddValue(item.ToObject()); } return result; }
public static JSONArray ExportData(this List<int> list) { var json_array = new JSONArray(); foreach (var num in list) json_array.Add(num); return json_array; }
public void setChatterArray(JSONArray records) { chatterArray = records; chatterFetched = true; if (records.Length > 0) { enableChatter(); } }
public static JSONValue ExportData(this AnimationCurve curve) { var key_frame_data = new JSONArray(); foreach (var key_frame in curve.keys) key_frame_data.Add(key_frame.ExportData()); return key_frame_data; }
public override void loadFileByPath(string filename) { string filecontent = System.IO.File.ReadAllText (outputDir + filename); JSONNode topography = JSON.Parse (filecontent) ["vadere"] ["topography"]; obstacles = topography["obstacles"].AsArray; sources = topography["sources"].AsArray; targets = topography["targets"].AsArray; IDmappings = getIDmappings (System.IO.File.ReadAllText (outputDir + "IDmappings.txt")); }
public static Property_TriggerItem create(JSONArray template) { switch (template.getString(0)) { case "SELF": return new Property_Self(); case "TARGET": return new Property_Target(); case "TRIGGERSOURCE": return new Property_TriggerSource(); case "TRIGGERTARGET": return new Property_TriggerTarget(); default: throw new ArgumentException("Invalid property " + template.getString(0)); } }
// Use this for initialization void Start() { string format = "yyyyMMdd-hhmm"; outputPath = "Assets/Resources/" + outputFileName + "-" + DateTime.Now.ToString (format); if (File.Exists (outputPath)) { Debug.Log ("ERROR: " + outputPath + " already exists"); return; } bookmarks = new JSONArray (); }
/// <summary> Synchronise les SwungMens acheté et achetable </summary> private static void ProcessSwungMens(JSONArray array) { Settings.Instance.ResetDefaultPlayer (); foreach (JSONValue value in array) { Player p = new Player (value.Obj); Settings.Instance.AddOrUpdate_Player (p); if (!Settings.Instance.Default_player.ContainsKey (p.UID)) Settings.Instance.Default_player.Add (p.UID, p); } }
public Friends(JSONArray array) { this.friends = new Dictionary<string, User>();//new User[friends.Length]; foreach (JSONValue friend in array) { User friend_user = new User(); friend_user.update(friend.Obj); friend_user.is_connected = false; this.friends.Add(friend_user.username, friend_user); } }
void Initialize(int id, string question, int correct, JSONArray answers) { this._id = id; this._question = question; this._correct = correct; this._answers = new List <Answer> (); foreach (JSONNode answer in answers) { this._answers.Add (new Answer(answer)); } }
public static Property_int create(JSONArray template) { switch (template.getString(0)) { case "mul": return new Property_Mul(template); case "add": return new Property_Add(template); case "count": return new Property_Count(template.getArray(1)); case "amountOf": return new Property_AmountOf(ResourceType.get(template.getString(1))); default: throw new ArgumentException("Invalid property " + template.getString(0)); } }
public static List<TriggeredAbility> createList(JSONArray listTemplate) { List<TriggeredAbility> result = new List<TriggeredAbility>(); if (listTemplate != null) { foreach (JSONArray template in listTemplate.asJSONArrays()) { result.Add(new TriggeredAbility(template)); } } return result; }
void EventSendInvite() { if (listInviteUsers.Count > 0) { JSONArray arr = new JSONArray(); for (int i = 0; i < listInviteUsers.Count; i++) { arr.Add(listInviteUsers[i]); } Debug.Log("EventSendInvite " + arr.ToString()); UserExtensionRequest.Instance.InviteToGame(arr, ScreenManager.Instance.CurrentSlotScreen.GetCrtGameType(), ScreenManager.Instance.CurrentSlotScreen.GetRoomId()); Close(); } }
public static void SetData(JSONArray users, Tab selectedTab) { switch(selectedTab) { case Tab.TOP_RICHER: topRicherList = users; topRicherLoadTime = Utils.CurrentTime(); break; case Tab.TOP_WINNER: topWinnerList = users; topWinnerLoadTime = Utils.CurrentTime(); break; } }
public void InitScrollViewData(JSONArray mFriendList) { friendList = mFriendList; friendListRows = new JSONArray(); JSONObject row = new JSONObject(); for (int i = 0; i < friendList.Length; i++) { if (Utils.IsOdd(i)) { row.Add("right", friendList[i].Obj); friendListRows.Add(row); } else { row = new JSONObject(); row.Add("left", friendList[i].Obj); if (i == friendList.Length - 1) { friendListRows.Add(row); } } } isLoading = false; wrapContent.ResetChildPositions(); scrollview.currentMomentum = Vector3.zero; scrollview.ResetPosition(); Transform tempGameObject; wrapContent.minIndex = -(friendListRows.Length - 1); wrapContent.onInitializeItem = UpdateRowDataOnScroll; bool canDrag = true; if (friendListRows.Length <= STOP_DRAG_NUMB_ROW) { canDrag = false; backgroundDragScrollView.enabled = false; } else { backgroundDragScrollView.enabled = true; } for (int i = 0; i < wrapContent.transform.childCount; i++) { tempGameObject = wrapContent.transform.GetChild(i); if (!tempGameObject.gameObject.activeSelf) { Utils.SetActive(tempGameObject.gameObject, true); } InviteRowScript tempRowScript = tempGameObject.GetComponent<InviteRowScript>(); tempRowScript.Init(scrollview); if (canDrag) { tempRowScript.dragScrollView.enabled = true; } else { tempRowScript.dragScrollView.enabled = false; } if (i < friendListRows.Length) { Utils.SetActive(tempGameObject.gameObject, true); tempRowScript.UpdateRowData(friendListRows[i].Obj); } else { Utils.SetActive(tempGameObject.gameObject, false); } } }
// ================================================================================ // loading and saving // -------------------------------------------------------------------------------- public JSONObject GetJSON() { JSONObject data = new JSONObject(); JSONArray wasUsedArray = new JSONArray(); foreach (var item in wasUsed) { wasUsedArray.Add(item); } data.Add("wasUsed", wasUsedArray); return data; }
public Pattern_Literal(JSONArray template, PatternScope scope) { literal = template.getString(1); }
public static void Handle(string InType, JSONNode InParam, JSONNode InThroughParam, string InExtra) { JSONNode backDataJson = null; switch (InType) { case "getRoomConfig": { var graphicOption = SceneManager.Instance.GetComponent <graphicOptionCTRL>(); int defaultPerformance = 2; if (null != graphicOption) { switch (graphicOption.graphicOption) { case graphicOptionCTRL.TierSetting.High: defaultPerformance = 2; break; case graphicOptionCTRL.TierSetting.Mid: defaultPerformance = 1; break; } } backDataJson = new JSONObject { ["result"] = "succeed", ["bgm"] = AudioManager.Instance.MusicVolume, ["effect"] = AudioManager.Instance.EffectVolume, ["performance"] = LocalDataController.GetLocalDataValue_Int(LocalDataController.GraphicOption, defaultPerformance) }; } break; case "setSoundBgm": AudioManager.Instance.MusicVolume = InParam["value"].AsInt; backDataJson = new JSONObject { ["result"] = "succeed" }; break; case "setSoundEffect": AudioManager.Instance.EffectVolume = InParam["value"].AsInt; backDataJson = new JSONObject { ["result"] = "succeed" }; break; case "setSoundBGMOn": AudioManager.Instance.MusicSwitch = true; backDataJson = new JSONObject { ["result"] = "succeed" }; break; case "setSoundBGMOff": AudioManager.Instance.MusicSwitch = false; backDataJson = new JSONObject { ["result"] = "succeed" }; break; case "setSoundEffectOn": AudioManager.Instance.EffectSwitch = true; backDataJson = new JSONObject { ["result"] = "succeed" }; break; case "setSoundEffectOff": AudioManager.Instance.EffectSwitch = false; backDataJson = new JSONObject { ["result"] = "succeed" }; break; case "setGoldValue": int gold = AccountManager.Instance.SetPropertyGold(InParam["value"].AsInt); AdaNetwork.GetProcess <MissionProcess>().missionManager.UpdateMission_GOLD(gold); backDataJson = new JSONObject { ["result"] = "succeed" }; break; case "setCashValue": int cash = AccountManager.Instance.SetPropertyCash(InParam["value"].AsInt); AdaNetwork.GetProcess <MissionProcess>().missionManager.UpdateMission_CASH(cash); backDataJson = new JSONObject { ["result"] = "succeed" }; break; case "setGraphicPerf": { int quality = InParam["value"].AsInt; var graphicOption = SceneManager.Instance.GetComponent <graphicOptionCTRL>(); if (graphicOption != null) { switch (quality) { case 1: graphicOption.SetGraphicTierMid(); LocalDataController.SetLocalDataValue_Int(LocalDataController.GraphicOption, quality); break; case 2: graphicOption.SetGraphicTierHigh(); LocalDataController.SetLocalDataValue_Int(LocalDataController.GraphicOption, quality); break; default: backDataJson = new JSONObject { ["result"] = "failed", ["value"] = 2, ["msg"] = "Out of range, Set graphic level = 2" }; graphicOption.SetGraphicTierHigh(); LocalDataController.SetLocalDataValue_Int(LocalDataController.GraphicOption, 2); break; } } else { backDataJson = new JSONObject { ["result"] = "failed", ["value"] = 2, ["msg"] = "Not found graphic setting." }; } if (null == backDataJson) { backDataJson = new JSONObject { ["result"] = "succeed" }; } } break; case "gotoUnityPage": ThirdPartyGotoUnity.GotoUnity(InParam); break; case "mission": if (InParam != null) { string playType = InParam["play_type"].Value; string categoryType = InParam["category_type"].Value; JSONArray missionTag = InParam["mission_tag"].AsArray; List <string> list = new List <string>(); for (int i = 0; i < missionTag.Count; i++) { list.Add(missionTag[i]); } MissionProcess.NativeSendMission(playType, categoryType, list.ToArray()); } break; case "missionCheck": var aCharacter = AdaAvatar.Instance.GetCurrCharacter(); var partsDatas = aCharacter.GetCurrEquipAllSlotID(); int stylebookId = InParam["stylebookId"].AsInt; bool customBg = InParam["customBg"].AsBool; JSONArray stampListArray = InParam["stampList"].AsArray; List <int> stampList = new List <int>(); for (int i = 0; i < stampListArray.Count; i++) { stampList.Add(stampListArray[i]); } AdaNetwork.GetProcess <MissionProcess>().StyleBookMissionCheck(stylebookId, partsDatas, stampList.ToArray(), customBg); break; case "attendMissionCheck": var data = DataTableManager.Instance.dailyAttendanceData.GetDailyData(); if (data != null) { AdaNetwork.GetProcess <MissionProcess>().missionManager.UpdateMission(MissionPlay_type.PARTICIPATE, MissionCategory_type.DAILYATTENDANCE, data.mission_tag); } break; case "playEffect": AudioManager.Instance.PlayEffect((AudioKey)InParam["index"].AsInt); break; case "playMusic": AudioManager.Instance.PlayMusic((AudioKey)InParam["index"].AsInt); break; case "mailReceive": { Log.Info("开始处理邮件", ColorName.Red); ResponseMailRecive value = JsonUtility.FromJson <ResponseMailRecive>(InParam.Value); MailH5MissionProcess.OnReceiveMailReceive(value); break; } case "mialReceiveAll": { Log.Info("开始处理全部邮件", ColorName.Red); ResponseMailReciveAll value = JsonUtility.FromJson <ResponseMailReciveAll>(InParam.Value); MailH5MissionProcess.OnReceiveMailReceiveAll(value); break; } case "ChallengeResult": { backDataJson = AdaNetwork.GetProcess <ChallengeProcess>().challengeResult; break; } default: Log.Error($"Not found third party H5 dispatch handle named {InType}."); backDataJson = new JSONObject() { ["result"] = "failed", ["msg"] = $"Not found third party H5 dispatch handle named {InType}." }; break; } Log.Info( $"[ThirdPartyH5Dispatch] -- Type = {InType}\nParam = {InParam}\nThroughParam = {InThroughParam}\nBackParam = {backDataJson}"); ThirdPartyBridge.ToNative(CommandType.H5AndUnity, MakeBackJsonNode(InType, backDataJson, InThroughParam)); ToNativeDone(InType); }
public Pattern_Identifier(JSONArray template, PatternScope scope) { }
public static List <JSONArray> ExampleRobotsJSON(int numberOfRobots) { List <JSONArray> sampleRobots = new List <JSONArray>(); for (int i = 0; i < numberOfRobots; i++) { var robotJSON = new JSONArray(); Debug.Log(i); if (i % 5 == 0) { robotJSON.Add(JSONRobotPart(1, 5, "block")); robotJSON.Add(JSONRobotPart(1, 4, "block")); robotJSON.Add(JSONRobotPart(1, 3, "block")); robotJSON.Add(JSONRobotPart(1, 2, "block")); robotJSON.Add(JSONRobotPart(1, 1, "center")); robotJSON.Add(JSONRobotPart(5, 5, "block")); robotJSON.Add(JSONRobotPart(5, 4, "block")); robotJSON.Add(JSONRobotPart(5, 3, "block")); robotJSON.Add(JSONRobotPart(5, 2, "block")); robotJSON.Add(JSONRobotPart(5, 1, "block")); robotJSON.Add(JSONRobotPart(4, 1, "block")); robotJSON.Add(JSONRobotPart(3, 1, "block")); robotJSON.Add(JSONRobotPart(2, 1, "block")); robotJSON.Add(JSONRobotPart(4, 5, "block")); robotJSON.Add(JSONRobotPart(3, 5, "block")); robotJSON.Add(JSONRobotPart(2, 5, "block")); } else if (i % 5 == 1) { robotJSON.Add(JSONRobotPart(1, 5, "center")); robotJSON.Add(JSONRobotPart(1, 4, "block")); robotJSON.Add(JSONRobotPart(1, 3, "block")); robotJSON.Add(JSONRobotPart(1, 2, "block")); robotJSON.Add(JSONRobotPart(1, 1, "block")); robotJSON.Add(JSONRobotPart(5, 5, "block")); robotJSON.Add(JSONRobotPart(5, 4, "block")); robotJSON.Add(JSONRobotPart(5, 3, "block")); robotJSON.Add(JSONRobotPart(5, 2, "block")); robotJSON.Add(JSONRobotPart(5, 1, "block")); robotJSON.Add(JSONRobotPart(4, 1, "block")); robotJSON.Add(JSONRobotPart(3, 1, "block")); robotJSON.Add(JSONRobotPart(2, 1, "block")); robotJSON.Add(JSONRobotPart(4, 5, "block")); robotJSON.Add(JSONRobotPart(3, 5, "block")); robotJSON.Add(JSONRobotPart(2, 5, "block")); } else if (i % 5 == 2) { robotJSON.Add(JSONRobotPart(1, 5, "block")); robotJSON.Add(JSONRobotPart(1, 4, "block")); robotJSON.Add(JSONRobotPart(1, 3, "block")); robotJSON.Add(JSONRobotPart(1, 2, "block")); robotJSON.Add(JSONRobotPart(1, 1, "block")); robotJSON.Add(JSONRobotPart(5, 5, "block")); robotJSON.Add(JSONRobotPart(5, 4, "block")); robotJSON.Add(JSONRobotPart(5, 3, "block")); robotJSON.Add(JSONRobotPart(5, 2, "block")); robotJSON.Add(JSONRobotPart(5, 1, "center")); robotJSON.Add(JSONRobotPart(4, 1, "block")); robotJSON.Add(JSONRobotPart(3, 1, "block")); robotJSON.Add(JSONRobotPart(2, 1, "block")); robotJSON.Add(JSONRobotPart(4, 5, "block")); robotJSON.Add(JSONRobotPart(3, 5, "block")); robotJSON.Add(JSONRobotPart(2, 5, "block")); } else if (i % 5 == 3) { robotJSON.Add(JSONRobotPart(1, 5, "block")); robotJSON.Add(JSONRobotPart(1, 4, "block")); robotJSON.Add(JSONRobotPart(1, 3, "block")); robotJSON.Add(JSONRobotPart(1, 2, "block")); robotJSON.Add(JSONRobotPart(1, 1, "block")); robotJSON.Add(JSONRobotPart(5, 5, "center")); robotJSON.Add(JSONRobotPart(5, 4, "block")); robotJSON.Add(JSONRobotPart(5, 3, "block")); robotJSON.Add(JSONRobotPart(5, 2, "block")); robotJSON.Add(JSONRobotPart(5, 1, "block")); robotJSON.Add(JSONRobotPart(4, 1, "block")); robotJSON.Add(JSONRobotPart(3, 1, "block")); robotJSON.Add(JSONRobotPart(2, 1, "block")); robotJSON.Add(JSONRobotPart(4, 5, "block")); robotJSON.Add(JSONRobotPart(3, 5, "block")); robotJSON.Add(JSONRobotPart(2, 5, "block")); } else if (i % 5 == 4) { robotJSON.Add(JSONRobotPart(3, 3, "center")); robotJSON.Add(JSONRobotPart(1, 1, "block")); robotJSON.Add(JSONRobotPart(1, 2, "block")); robotJSON.Add(JSONRobotPart(1, 3, "block")); robotJSON.Add(JSONRobotPart(1, 4, "block")); robotJSON.Add(JSONRobotPart(1, 5, "block")); robotJSON.Add(JSONRobotPart(2, 1, "block")); robotJSON.Add(JSONRobotPart(2, 2, "block")); robotJSON.Add(JSONRobotPart(2, 3, "block")); robotJSON.Add(JSONRobotPart(2, 4, "block")); robotJSON.Add(JSONRobotPart(2, 5, "block")); robotJSON.Add(JSONRobotPart(3, 1, "block")); robotJSON.Add(JSONRobotPart(3, 2, "block")); robotJSON.Add(JSONRobotPart(3, 4, "block")); robotJSON.Add(JSONRobotPart(3, 5, "block")); robotJSON.Add(JSONRobotPart(4, 1, "block")); robotJSON.Add(JSONRobotPart(4, 2, "block")); robotJSON.Add(JSONRobotPart(4, 3, "block")); robotJSON.Add(JSONRobotPart(4, 4, "block")); robotJSON.Add(JSONRobotPart(4, 5, "block")); robotJSON.Add(JSONRobotPart(5, 1, "block")); robotJSON.Add(JSONRobotPart(5, 2, "block")); robotJSON.Add(JSONRobotPart(5, 3, "block")); robotJSON.Add(JSONRobotPart(5, 4, "block")); robotJSON.Add(JSONRobotPart(5, 5, "block")); } sampleRobots.Add(robotJSON); } return(sampleRobots); }
/// <summary> /// Deserializes a Dialogue Designer dialogue from a JSON node. /// </summary> public void Deserialize(JSONNode node) { Characters = node.GetStringArrayChild("characters"); EditorVersion = node.GetStringChild("editor_version"); FileName = node.GetStringChild("file_name"); Languages = node.GetStringArrayChild("languages"); List <BaseNode> nodesList = new List <BaseNode>(); JSONArray nodesArrayNode = node.GetArrayChild("nodes"); foreach (JSONNode arrayElementNode in nodesArrayNode.Values) { BaseNode newNode = null; string nodeType = arrayElementNode.GetStringChild("node_type"); switch (nodeType) { case "show_message": if (arrayElementNode["choices"] != null) { newNode = CreateInstance <ShowMessageNodeChoice>(); } else { newNode = CreateInstance <ShowMessageNodeSimple>(); } break; case "start": newNode = CreateInstance <StartNode>(); break; case "condition_branch": newNode = CreateInstance <ConditionBranchNode>(); break; case "wait": newNode = CreateInstance <WaitNode>(); break; case "execute": newNode = CreateInstance <ExecuteNode>(); break; case "random_branch": newNode = CreateInstance <RandomBranchNode>(); break; case "chance_branch": newNode = CreateInstance <ChanceBranchNode>(); break; case "repeat": newNode = CreateInstance <RepeatNode>(); break; case "set_local_variable": if (arrayElementNode["toggle"]) { newNode = CreateInstance <SetLocalVariableBoolNode>(); } else if (arrayElementNode["operation_type"]) { newNode = CreateInstance <SetLocalVariableIntNode>(); } else { newNode = CreateInstance <SetLocalVariableStringNode>(); } break; case "comment": // skip break; default: Debug.LogErrorFormat("Dialogue deserialization: unknown node type '{0}'", nodeType); break; } if (newNode != null) { newNode.Deserialize(arrayElementNode); nodesList.Add(newNode); } } Nodes = nodesList.ToArray(); List <Variable> variablesBuffer = new List <Variable>(); JSONNode variablesNode = node["variables"]; if (variablesNode == null) { Debug.LogErrorFormat("JSON deserialization: expected 'variables' to be Object."); } else { foreach (string key in variablesNode.Keys) { Variable newVariable = variablesNode.GetObjectChild <Variable>(key); newVariable.SetName(key); variablesBuffer.Add(newVariable); } } Variables = variablesBuffer.ToArray(); name = FileName; OnAfterDeserialize(); }
private static void Traverse(JSONNode obj, TomlNode node) { if (obj is JSONArray jsonArr && node is TomlArray tomlArray) { foreach (var tomlArrayValue in tomlArray.Children) { var newNode = new JSONObject(); jsonArr.Add(newNode); Traverse(newNode, tomlArrayValue); } return; } if (node.HasValue) { switch (node) { case TomlString str: obj["type"] = "string"; obj["value"] = str.ToString(); break; case TomlInteger i: obj["type"] = "integer"; obj["value"] = i.Value.ToString(); break; case TomlFloat f: obj["type"] = "float"; obj["value"] = f.ToString(); break; case TomlDateTime dt: if (dt.OnlyDate) { obj["type"] = "date"; } else if (dt.OnlyTime) { obj["type"] = "time"; } else if (dt.Value.Kind == DateTimeKind.Local) { obj["type"] = "datetime-local"; } else { obj["type"] = "datetime"; } obj["value"] = dt.ToString(); break; case TomlBoolean b: obj["type"] = "bool"; obj["value"] = b.ToString(); break; case TomlArray arr: var jsonArray = new JSONArray(); obj["type"] = "array"; obj["value"] = jsonArray; foreach (var arrValue in arr.Children) { var o = new JSONObject(); jsonArray.Add(o); Traverse(o, arrValue); } break; } return; } foreach (var key in node.Keys) { var val = node[key]; JSONNode newNode; if (val is TomlArray arr && arr.ChildrenCount > 0 && arr[0] is TomlTable) { newNode = new JSONArray(); }
// Update is called once per frame void OnInspectorUpdate() { Repaint(); float currentTimeSecond = convertToSeconds(DateTime.Now); if (access_token.Length > 0 && currentTimeSecond - lastTokenTime > expiresIn) { access_token = ""; relog(); } if (publisher != null && publisher.www != null && publisher.www.isDone) { state = publisher.getState(); www = publisher.www; switch (state) { case ExporterState.CHECK_VERSION: JSONNode githubResponse = JSON.Parse(this.jsonify(www.text)); if (githubResponse != null && githubResponse[0]["tag_name"] != null) { latestVersion = githubResponse[0]["tag_name"]; if (exporterVersion != latestVersion) { bool update = EditorUtility.DisplayDialog("Exporter update", "A new version is available \n(you have version " + exporterVersion + ")\nIt's strongly rsecommended that you update now. The latest version may include important bug fixes and improvements", "Update", "Skip"); if (update) { Application.OpenURL(latestReleaseUrl); } } else { resizeWindow(fullSize); } } else { latestVersion = ""; resizeWindow(fullSize + new Vector2(0, 15)); } publisher.setIdle(); break; case ExporterState.REQUEST_CODE: JSONNode accessResponse = JSON.Parse(this.jsonify(www.text)); if (accessResponse["access_token"] != null) { access_token = accessResponse["access_token"]; expiresIn = accessResponse["expires_in"].AsFloat; lastTokenTime = convertToSeconds(DateTime.Now); publisher.getAccountType(access_token); if (exporterVersion != latestVersion) { resizeWindow(fullSize + new Vector2(0, 20)); } else { resizeWindow(fullSize); } } else { string errorDesc = accessResponse["error_description"]; EditorUtility.DisplayDialog("Authentication failed", "Failed to authenticate on Sketchfab.com.\nPlease check your credentials\n\nError: " + errorDesc, "Ok"); publisher.setIdle(); } break; case ExporterState.PUBLISH_MODEL: //foreach(string key in www.responseHeaders.Keys) //{ // Debug.Log("[" + key + "] = " + www.responseHeaders[key]); //} if (www.responseHeaders["STATUS"].Contains("201") == true) { string urlid = www.responseHeaders["LOCATION"].Split('/')[www.responseHeaders["LOCATION"].Split('/').Length - 1]; string url = skfbUrl + "models/" + urlid; Application.OpenURL(url); } else { EditorUtility.DisplayDialog("Upload failed", www.responseHeaders["STATUS"], "Ok"); } publisher.setIdle(); break; case ExporterState.GET_CATEGORIES: string jsonify = this.jsonify(www.text); if (!jsonify.Contains("results")) { Debug.Log(jsonify); Debug.Log("Failed to retrieve categories"); publisher.setIdle(); break; } JSONArray categoriesArray = JSON.Parse(jsonify)["results"].AsArray; foreach (JSONNode node in categoriesArray) { categories.Add(node["name"], node["slug"]); categoriesNames.Add(node["name"]); } publisher.setIdle(); break; case ExporterState.USER_ACCOUNT_TYPE: string accountRequest = this.jsonify(www.text); if (!accountRequest.Contains("account")) { Debug.Log(accountRequest); Debug.Log("Failed to retrieve user account type"); publisher.setIdle(); break; } var userSettings = JSON.Parse(accountRequest); isUserPro = userSettings["account"].ToString().Contains("free") == false; userDisplayName = userSettings["displayName"]; publisher.setIdle(); break; } } }
private void button1_Click(object sender, EventArgs e) { //string m="TaskNo171127000004"; //string s = string.Format("[{{\"taskNo\":\"{0}\"",m); if (string.IsNullOrEmpty(textBox1.Text)) { MessageBox.Show("请输入任务条数"); return; } string number = ""; string date = DateTime.Now.Year.ToString().PadLeft(4, '0') + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0'); string sql = string.Format(@"SELECT TOP 1 TaskNo FROM dbo.T_Task_Load WHERE TaskNo LIKE '%{0}%' ORDER BY TaskNo DESC", date); int[] weight = { 300, 500, 100 }; int[] height = { 1299, 1800, 1300 }; Random r = new Random(); string taskno = ""; if (comm.GetData(Properties.Settings.Default.sql, sql) != null) { taskno = comm.GetData(Properties.Settings.Default.sql, sql).ToString(); } for (int i = 0; i < int.Parse(textBox1.Text); i++) { if (!string.IsNullOrEmpty(taskno)) { number = date + (int.Parse(taskno.Substring(taskno.Length - 4, 4)) + i + 1).ToString().PadLeft(4, '0'); } else { number = date + ((i + 1).ToString().PadLeft(4, '0')); } int a = r.Next(0, weight.Length); int b = r.Next(0, height.Length); string TaskNo = "TaskNo" + number; string BoxOrPalletNo = "PX" + number; string BDNO = "BDNO" + number; string pn = "pn" + number; string str = string.Format(@"[{{""taskNo"":""{0}"", ""SN"":""{1}"", ""planningNo"":{2}, ""isHengwen"":{3}, ""isBLOCK"":1, ""taskType"":{4}, ""BDNO"":""{6}"", ""pn"":""{7}"", ""weight"":{8}, ""height"":{9}, ""SN_OLD"":"""", ""opTime"":""{5}""}}]", TaskNo, BoxOrPalletNo, "[\"\"]", 0, -1, DateTime.Now.ToString(), BDNO, pn, weight[a], height[b]); JSONArray jsarray = new JSONArray(str); string url = "http://127.0.0.1:8889/api/loadTasks"; HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; request.KeepAlive = true; request.AllowAutoRedirect = false; request.ContentType = "application/x-www-form-urlencoded"; byte[] postdatabtyes = Encoding.UTF8.GetBytes(jsarray.ToString()); request.ContentLength = postdatabtyes.Length; try { Stream requeststream = request.GetRequestStream(); requeststream.Write(postdatabtyes, 0, postdatabtyes.Length); requeststream.Close(); string resp; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); resp = sr.ReadToEnd(); } richTextBox1.Text += TaskNo + "==" + resp + "\n"; } catch (Exception ex) { throw new Exception(ex.Message.Replace(Environment.NewLine, "")); } } MessageBox.Show("下发" + textBox1.Text + "条上架任务成功"); textBox1.Text = ""; }
void sendVuforiaUpdate() { //var visibleObjectsString = "{\"amazonBox0zbc6yetuoyj\":[-0.9964230765028328,0.009800613580158324,-0.08393736781840644,0,0.022929297584320937,0.987345281122669,-0.15691860457929643,0,-0.08133670600902992,0.15828222984430484,0.9840378965122027,0,329.2388939106902,77.77425852082308,-1489.0291313193022,1],\"kepwareBox4Qimhnuea3n6\":[-0.9913746548884379,0.034050970326370084,-0.12655601222953172,0,0.051082427979348755,0.9896809533465255,-0.13387410555924745,0,-0.12069159903807483,0.1391844414830788,0.9828837698713899,0,212.63741144996703,206.15960431449824,-1826.5693898311488,1],\"_WORLD_OBJECT_local\":[-0.9742120258704184,-0.00437900631612313,-0.22559212287700664,0,-0.035464931453757634,-0.9844127588621392,0.17226278091636868,0,-0.22282991544549868,0.17582138398908906,0.9588711290537871,0,161.99950094104497,-166.5114134489016,-519.0149842693205,1],\"_WORLD_OBJECT_PF5x8fv3zcgm\":[-0.9742120258704184,-0.00437900631612313,-0.22559212287700664,0,-0.035464931453757634,-0.9844127588621392,0.17226278091636868,0,-0.22282991544549868,0.17582138398908906,0.9588711290537871,0,161.99950094104497,-166.5114134489016,-519.0149842693205,1]}"; //var visibleObjects = JSON.parse(visibleObjectsString); string visibleString = "\"{"; SimpleJSON.JSONObject ja = new SimpleJSON.JSONObject(); for (int i = 0; i < realityEditorObjectVisualizerList.Count; i++) { visibleString += "\\\"" + realityEditorObjectVisualizerList[i].name + "\\\":["; Matrix4x4 worldToOrigin = origin.transform.worldToLocalMatrix; Matrix4x4 worldToObject = realityEditorObjectVisualizerList[i].transform.worldToLocalMatrix; //M_world_object = M_origin_object * M_world_origin //M_origin_object = M_world_object * (M_world_origin)^-1 Matrix4x4 originToObject = worldToObject * worldToOrigin.inverse; Matrix4x4 objectToOrigin = originToObject.inverse; Matrix4x4 m = objectToOrigin; //Matrix4x4 m = originToObject; //Debug.Log("World to Origin: " + worldToOrigin); //Debug.Log("world to object: " + worldToObject); //Debug.Log("origin to object: " + originToObject); //Debug.Log("object to origin: " + objectToOrigin); /* * GameObject dummy = new GameObject(); * dummy.transform.position = realityEditorObjectVisualizerList[i].transform.position; * dummy.transform.rotation = realityEditorObjectVisualizerList[i].transform.rotation; * dummy.transform.parent = virtualCam.transform; * * Matrix4x4 m = Matrix4x4.TRS(dummy.transform.localPosition, dummy.transform.localRotation, dummy.transform.localScale); * m = m.inverse; * * * GameObject.Destroy(dummy); */ /* * //fix righthand? * m[0, 2] = -m[0, 2]; * m[1, 2] = -m[1, 2]; * m[2, 2] = -m[2, 2]; */ //fix righthand? //m[0, 0] = -m[0, 0]; //m[1, 0] = -m[1, 0]; //m[2, 0] = -m[2, 0]; /* * //fix rotation: * m[0, 0] = -m[0, 0]; * m[0, 1] = -m[0, 1]; * m[0, 2] = -m[0, 2]; */ //flip translation m[0, 3] = -m[0, 3]; m[1, 3] = -m[1, 3]; m[2, 3] = -m[2, 3]; //fix rotation: m[0, 2] = -m[0, 2]; m[1, 2] = -m[1, 2]; m[2, 2] = -m[2, 2]; /* * //flip all the x's * m[0, 0] = -m[0, 0]; * m[0, 1] = -m[0, 1]; * m[0, 2] = -m[0, 2]; * //m[0, 3] = -m[0, 3]; */ /* * for (int mm = 0; mm<3; mm++) * { * for(int nn = 0; nn<3; nn++) * { * m[mm, nn] = 0; * } * } * m[0, 0] = -1; * m[1, 1] = 1; * m[2, 2] = 1; */ //fix vuforia mm to m m[0, 3] = 1000.0f * m[0, 3]; m[1, 3] = 1000.0f * m[1, 3]; m[2, 3] = 1000.0f * m[2, 3]; //Debug.Log(realityEditorObjectVisualizerList[i].name); //Debug.Log("full matrix: " + m); JSONArray ma = new JSONArray(); for (int jj = 0; jj < 16; jj++) { //int sampleIdx = jj; //read through rows first int sampleIdx = (jj % 4) * 4 + (int)(jj / 4); int row = jj % 4; int col = (int)(jj / 4); //Debug.Log("idx: " + jj + " row: " + row + " col: " + col + " value: " + dummy.transform.localToWorldMatrix[row, col]); //visibleString += ((float)dummy.transform.localToWorldMatrix[sampleIdx]).ToString("0.00000000"); visibleString += (m[row, col]).ToString("0.00000000"); //this should be backwards, but works? if (jj < 15) { visibleString += ","; } ma.Add((float)m[sampleIdx]); } ja[realityEditorObjectVisualizerList[i].name] = ma; visibleString += "]"; if (i < realityEditorObjectVisualizerList.Count - 1) { visibleString += ","; } //dump matrix to array: //dummy.transform.localToWorldMatrix; } visibleString += "}\""; //Debug.Log("visible object string: " + visibleObjectsString); //Debug.Log("this object string: " + ja.ToString()); //Debug.Log("vis string: " + visibleString); GameObject.Find("pusher").GetComponent <Pusher>().Emit_VuforiaModuleUpdate_system_server(visibleString); }
public Pattern_Optional(JSONArray template, PatternScope scope) { body = scope.getPattern(template, 1); }
public Pattern_Multi(JSONArray template, PatternScope scope) { body = scope.getPattern(template, 1); }
public void init(JSONObject measure) { JSONArray beatsArr = measure["beats"] as JSONArray; int beatsCount = beatsArr.Count; Transform BeatTemp = transform.Find("_beat"); //init temp before copy BeatTemp.Find("_chord").GetComponent <Text>().text = ""; //init ends Transform[] beatsT = copyChild(BeatTemp, beatsCount); int beatOffset = BEAT0_OFFSET; for (int beatIdx = 0; beatIdx < beatsCount; ++beatIdx) { Transform beatT = beatsT[beatIdx]; beatT.localPosition = new Vector3(beatOffset, 0, 0); JSONObject beat = beatsArr[beatIdx] as JSONObject; JSONArray voicesArr = beat["voices"] as JSONArray; JSONObject voices_0 = voicesArr[0] as JSONObject; int duration = voices_0["duration"]; JSONArray notesArr = voices_0["notes"] as JSONArray; string beatLog = ""; JSONObject chord = beat["chord"] as JSONObject; if (chord != null) { currChordName = chord["name"]; beatT.Find("_chord").GetComponent <Text>().text = currChordName; markChord = true; } Transform[] notesT = copyChild(beatT.Find("0"), notesArr.Count); for (int noteIdx = 0; noteIdx < notesArr.Count; ++noteIdx) { JSONObject note = notesArr[noteIdx] as JSONObject; int gStr = note["string"]; int value = note["value"]; beatLog += string.Format("{0}:{1} ", gStr, value); Transform strT = notesT[noteIdx]; initEffect(strT.Find("_effects"), note["effect"] as JSONObject); int gStrIdx = gStr - 1; strT.localPosition = new Vector3(0, getStringPosY(gStrIdx), 0); Text strText = strT.Find("_value").GetComponent <Text>(); bool isTiledNote = note["tiedNote"] == true; //TODO bind to former note strText.text = isTiledNote? string.Format("({0})", value):value.ToString(); if (currChordName != null) { if (markChord) { if (_name2Chord[currChordName].isInChord(gStrIdx, value)) { //strText.color = Color.green; strText.text = "X"; } else { //strText.color = Color.red; markChord = false; } } } } beatOffset += BEAT_DEFAULT_WIDTH; beatLog += string.Format("duration:{0} ", duration); Logger.Log(tag, beatLog); } }
private BoardState CreateBoardStateFromJson(JSONNode json) { BoardState boardState = new BoardState(); boardState.wordBoardId = json["wordBoardId"].Value; boardState.wordBoardSize = json["wordBoardSize"].AsInt; boardState.nextHintIndex = json["nextHintIndex"].AsInt; // Parse the words JSONArray wordsJson = json["words"].AsArray; boardState.words = new string[wordsJson.Count]; for (int i = 0; i < wordsJson.Count; i++) { boardState.words[i] = wordsJson[i].Value; } // Parse the found words JSONArray foundWordsJson = json["foundWords"].AsArray; boardState.foundWords = new bool[foundWordsJson.Count]; for (int i = 0; i < foundWordsJson.Count; i++) { boardState.foundWords[i] = foundWordsJson[i].AsBool; } // Parse the tile states JSONArray tileStatesJson = json["tileStates"].AsArray; boardState.tileStates = new BoardState.TileState[tileStatesJson.Count]; for (int i = 0; i < tileStatesJson.Count; i++) { boardState.tileStates[i] = (BoardState.TileState)tileStatesJson[i].AsInt; } // Parse the tile lettes JSONArray tileLettersJson = json["tileLetters"].AsArray; boardState.tileLetters = new char[tileLettersJson.Count]; for (int i = 0; i < tileLettersJson.Count; i++) { boardState.tileLetters[i] = System.Convert.ToChar(tileLettersJson[i].Value); } // Parse the hint letters JSONArray hintLettersJson = json["hintLetters"].AsArray; boardState.hintLettersShown = new List <int[]>(hintLettersJson.Count); for (int i = 0; i < hintLettersJson.Count; i++) { string[] hintLetter = hintLettersJson[i].Value.Split(','); boardState.hintLettersShown.Add(new int[2] { System.Convert.ToInt32(hintLetter[0]), System.Convert.ToInt32(hintLetter[1]) }); } return(boardState); }
public static JObject ToJSON(this SmartCityProxy SmartCity, Boolean Embedded = false, Boolean ExpandChargingRoamingNetworkId = false, Boolean ExpandChargingPoolIds = false, Boolean ExpandChargingStationIds = false, Boolean ExpandEVSEIds = false) => SmartCity != null ? JSONObject.Create( new JProperty("id", SmartCity.Id.ToString()), Embedded ?null : ExpandChargingRoamingNetworkId ?new JProperty("roamingNetwork", SmartCity.RoamingNetwork.ToJSON()) : new JProperty("roamingNetworkId", SmartCity.RoamingNetwork.Id.ToString()), new JProperty("name", SmartCity.Name.ToJSON()), new JProperty("description", SmartCity.Description.ToJSON()), // Address // LogoURI // API - RobotKeys, Endpoints, DNS SRV // MainKeys SmartCity.Logo.IsNotNullOrEmpty() ?new JProperty("logos", JSONArray.Create( JSONObject.Create( new JProperty("uri", SmartCity.Logo), new JProperty("description", I18NString.Empty.ToJSON()) ) )) : null, SmartCity.Homepage.IsNotNullOrEmpty() ?new JProperty("homepage", SmartCity.Homepage) : null, SmartCity.HotlinePhoneNumber.IsNotNullOrEmpty() ?new JProperty("hotline", SmartCity.HotlinePhoneNumber) : null, SmartCity.DataLicenses.Any() ?new JProperty("dataLicenses", new JArray(SmartCity.DataLicenses.Select(license => license.ToJSON()))) : null //new JProperty("chargingPools", ExpandChargingPoolIds // ? new JArray(SmartCity.ChargingPools. ToJSON(Embedded: true)) // : new JArray(SmartCity.ChargingPoolIds. Select(id => id.ToString()))), //new JProperty("chargingStations", ExpandChargingStationIds // ? new JArray(SmartCity.ChargingStations. ToJSON(Embedded: true)) // : new JArray(SmartCity.ChargingStationIds.Select(id => id.ToString()))), //new JProperty("evses", ExpandEVSEIds // ? new JArray(SmartCity.EVSEs. ToJSON(Embedded: true)) // : new JArray(SmartCity.EVSEIds. Select(id => id.ToString()))) ) : null;
public Pattern_Sequence(JSONArray template, PatternScope scope) { this.template = template; this.scope = scope; }
public static void Notify(string errorClass, string errorMessage, string severity, string context, string stackTrace, string type, string severityReason) { if (apiKey_ == null || apiKey_ == "") { Debug.Log("BUGSNAG: ERROR: would not notify Bugsnag as no API key was set"); return; } if (notifyReleaseStages_ != null && !notifyReleaseStages_.Contains(releaseStage_)) { return; } var root = new JSONObject(); root["apiKey"] = apiKey_; var notifier = (root["notifier"] = new JSONObject()); notifier["name"] = "Bugsnag Unity Native"; notifier["version"] = "3.6.0-alpha"; notifier["url"] = "https://github.com/zorbathut/bugsnag-unity"; var eventRoot = (root["events"] = new JSONArray()); var events = new JSONObject(); eventRoot.Add(events); events["payloadVersion"] = "2"; var exceptions = (events["exceptions"] = new JSONArray()); var exception = (exceptions["0"] = new JSONObject()); exception["errorClass"] = errorClass; exception["message"] = errorMessage; var stacktrace = (exception["stacktrace"] = new JSONArray()); ParseStackTrace(stackTrace, stack => { var stackFrame = new JSONObject(); stackFrame["file"] = stack.file; stackFrame["lineNumber"] = stack.line; stackFrame["method"] = stack.method; stackFrame["inProject"] = true; // I mean, I guess? Hard to get a real answer for this. TODO some kind of callback to test the namespace? stacktrace.Add(stackFrame); }); var breadcrumbs = (events["breadcrumbs"] = new JSONArray()); for (int i = 0; i < breadcrumbs_.Count; ++i) { var breadcrumbData = breadcrumbs_[i]; var breadcrumb = new JSONObject(); breadcrumb["timestamp"] = breadcrumbData.timestamp.ToString("s", System.Globalization.CultureInfo.InvariantCulture); breadcrumb["name"] = breadcrumbData.name; breadcrumb["type"] = "manual"; breadcrumbs.Add(breadcrumb); } events["context"] = context; events["severity"] = severity; var user = (events["user"] = new JSONObject()); user["id"] = userId_; user["name"] = userName_; user["email"] = userEmail_; var app = (events["app"] = new JSONObject()); app["version"] = appVersion_; app["releaseStage"] = releaseStage_; app["type"] = "unity"; var device = (events["device"] = new JSONObject()); device["osVersion"] = SystemInfo.operatingSystem; var metaData = (events["metaData"] = new JSONObject()); foreach (var tabData in tabs_) { var tab = (metaData[tabData.Key] = new JSONObject()); foreach (var keyData in tabData.Value) { if (keyData.Value.Count == 1) { tab[keyData.Key] = keyData.Value[0]; continue; } var key = (tab[keyData.Key] = new JSONArray()); for (int i = 0; i < keyData.Value.Count; ++i) { key.Add(keyData.Value[i]); } } } GameObject.FindObjectOfType <Bugsnag>().StartCoroutine(WaitForResponse(root)); }
public static Array Wrap(JSONArray a) { return(new Array(a)); }
public Pattern_Operators(JSONArray template, PatternScope scope) { }
public void Save(bool auto = false) { PersistentUI.Instance.DisplayMessage($"{(auto ? "Auto " : "")}Saving...", PersistentUI.DisplayMessageType.BOTTOM); SelectionController.RefreshMap(); //Make sure our map is up to date. if (BeatSaberSongContainer.Instance.map._customEvents.Any()) { if (Settings.Instance.Saving_CustomEventsSchemaReminder) { //Example of advanced dialog box options. PersistentUI.Instance.ShowDialogBox("ChroMapper has detected you are using custom events in your map.\n\n" + "The current format for Custom Events goes against BeatSaver's enforced schema.\n" + "If you try to upload this map to BeatSaver, it will fail.", HandleCustomEventsDecision, "Ok", "Don't Remind Me"); } } new Thread(() => //I could very well move this to its own function but I need access to the "auto" variable. { Thread.CurrentThread.IsBackground = true; //Making sure this does not interfere with game thread //Saving Map Data string originalMap = BeatSaberSongContainer.Instance.map.directoryAndFile; string originalSong = BeatSaberSongContainer.Instance.song.directory; if (auto) { Queue <string> directory = new Queue <string>(originalSong.Split('/').ToList()); directory.Enqueue("autosaves"); directory.Enqueue($"{DateTime.Now.ToString("dd-MM-yyyy_HH-mm-ss")}"); //timestamp string autoSaveDir = string.Join("/", directory.ToArray()); Debug.Log($"Auto saved to: {autoSaveDir}"); //We need to create the autosave directory before we can save the .dat difficulty into it. System.IO.Directory.CreateDirectory(autoSaveDir); BeatSaberSongContainer.Instance.map.directoryAndFile = $"{autoSaveDir}/{BeatSaberSongContainer.Instance.difficultyData.beatmapFilename}"; BeatSaberSongContainer.Instance.song.directory = autoSaveDir; } BeatSaberSongContainer.Instance.map.Save(); BeatSaberSongContainer.Instance.map.directoryAndFile = originalMap; //Saving Map Requirement Info JSONArray requiredArray = new JSONArray(); //Generate suggestions and requirements array JSONArray suggestedArray = new JSONArray(); if (HasChromaEvents()) { suggestedArray.Add(new JSONString("Chroma Lighting Events")); } if (HasMappingExtensions()) { requiredArray.Add(new JSONString("Mapping Extensions")); } if (HasChromaToggle()) { requiredArray.Add(new JSONString("ChromaToggle")); } BeatSaberSong.DifficultyBeatmapSet set = BeatSaberSongContainer.Instance.song.difficultyBeatmapSets.Where(x => x == BeatSaberSongContainer.Instance.difficultyData.parentBeatmapSet).First(); //Grab our set BeatSaberSongContainer.Instance.song.difficultyBeatmapSets.Remove(set); //Yeet it out BeatSaberSong.DifficultyBeatmap data = set.difficultyBeatmaps.Where(x => x.beatmapFilename == BeatSaberSongContainer.Instance.difficultyData.beatmapFilename).First(); //Grab our diff data set.difficultyBeatmaps.Remove(data); //Yeet out our difficulty data if (BeatSaberSongContainer.Instance.difficultyData.customData == null) //if for some reason this be null, make new customdata { BeatSaberSongContainer.Instance.difficultyData.customData = new JSONObject(); } BeatSaberSongContainer.Instance.difficultyData.customData["_suggestions"] = suggestedArray; //Set suggestions BeatSaberSongContainer.Instance.difficultyData.customData["_requirements"] = requiredArray; //Set requirements set.difficultyBeatmaps.Add(BeatSaberSongContainer.Instance.difficultyData); //Add back our difficulty data BeatSaberSongContainer.Instance.song.difficultyBeatmapSets.Add(set); //Add back our difficulty set BeatSaberSongContainer.Instance.song.SaveSong(); //Save BeatSaberSongContainer.Instance.song.directory = originalSong; //Revert directory if it was changed by autosave }).Start(); }
IEnumerator CreateItemsRoutine(string jsonArrayString) { //Parsing JSON array string as an array JSONArray jsonArray = JSON.Parse(jsonArrayString) as JSONArray; for (int i = 0; i < jsonArray.Count; i++) { //Create local variables bool isDone = false; // are we done downloading string itemId = jsonArray[i].AsObject["itemID"]; string id = jsonArray[i].AsObject["ID"]; JSONObject itemInfoJson = new JSONObject(); // Create a callback to get the information from Web.cs Action <string> getItemInfoCallback = (itemInfo) => { isDone = true; JSONArray tempArray = JSON.Parse(itemInfo) as JSONArray; itemInfoJson = tempArray[0].AsObject; }; //Wait until Web.cs calls the callback we passed as parameter StartCoroutine(Main.Instance.Web.GetItem(itemId, getItemInfoCallback)); //Wait until callback is called from Web (info finished download) yield return(new WaitUntil(() => isDone == true)); //Instantiate GameObject (item prefab) GameObject itemGo = Instantiate(Resources.Load("Prefabs/Item") as GameObject); Item item = itemGo.AddComponent <Item>(); item.ID = id; item.itemID = itemId; itemGo.transform.SetParent(this.transform); itemGo.transform.localScale = Vector3.one; itemGo.transform.localPosition = Vector3.zero; //Fill infromation itemGo.transform.Find("Name").GetComponent <TMP_Text>().text = itemInfoJson["name"]; itemGo.transform.Find("Price").GetComponent <TMP_Text>().text = itemInfoJson["price"]; itemGo.transform.Find("Description").GetComponent <TMP_Text>().text = itemInfoJson["description"]; int imgVer = itemInfoJson["imgVer"].AsInt; byte[] bytes = ImageManager.Instance.LoadImage(itemId, imgVer); //Download the image if (bytes.Length == 0) { //Create a callback function to get the Sprite from Web.cs Action <byte[]> getItemIconCallback = (downloadedBytes) => { Sprite sprite = ImageManager.Instance.BytesToSprite(downloadedBytes); itemGo.transform.Find("Image").GetComponent <Image>().sprite = sprite; //Save the downloaded bytes as Image ImageManager.Instance.SaveImage(itemId, downloadedBytes, imgVer); ImageManager.Instance.SaveVersionJson(); }; StartCoroutine(Main.Instance.Web.GetItemIcon(itemId, getItemIconCallback)); } //Load from device else { Sprite sprite = ImageManager.Instance.BytesToSprite(bytes); itemGo.transform.Find("Image").GetComponent <Image>().sprite = sprite; } //Set the sell button itemGo.transform.Find("SellButton").GetComponent <Button>().onClick.AddListener(() => { string usersitemsID = id; string usersitemsItemID = itemId; string usersitemsUserId = Main.Instance.UserInfo.UserID; StartCoroutine(Main.Instance.Web.SellItem(usersitemsID, usersitemsItemID, usersitemsUserId)); itemGo.SetActive(false); }); } }
public void saveVuforiaObjectsToFile() { //update position of this object's struct in the dictionary: updateStructsBasedOnGameObjects(); JSONArray ja = new JSONArray(); foreach (KeyValuePair <string, realityEditorObjectStruct> pair in realityEditorObjectDict) { //Debug.Log("save operating on: " + pair.Key + " " + pair.Value.ip); //Debug.Log("content of struct"); Debug.Log(pair.Value.id + " " + pair.Value.ip + " " + pair.Value.temporaryChecksum + " " + pair.Value.versionNumber + " " + pair.Value.zone + " " + pair.Value.xmlAddress + " " + pair.Value.datAddress); //Debug.Log("temporary checksum value: " + pair.Value.temporaryChecksum + " nulloperator: " + (pair.Value.temporaryChecksum ?? "null") + " ==\"\"?" + (pair.Value.temporaryChecksum == "")); JSONNode jo = new SimpleJSON.JSONObject(); jo.Add("id", pair.Value.id ?? ""); jo.Add("ip", pair.Value.ip ?? ""); jo.Add("temporaryChecksum", pair.Value.temporaryChecksum ?? ""); jo.Add("versionNumber", pair.Value.versionNumber ?? ""); jo.Add("zone", pair.Value.zone ?? ""); jo.Add("xmlAddress", pair.Value.xmlAddress ?? ""); jo.Add("dataAddress", pair.Value.datAddress ?? ""); jo.Add("Tx", pair.Value.position.x); jo.Add("Ty", pair.Value.position.y); jo.Add("Tz", pair.Value.position.z); jo.Add("Qx", pair.Value.rotation.x); jo.Add("Qy", pair.Value.rotation.y); jo.Add("Qz", pair.Value.rotation.z); jo.Add("Qw", pair.Value.rotation.w); /* * jo.Add("id", pair.Value.id); * jo.Add("ip", pair.Value.ip); * jo.Add("temporaryChecksum", pair.Value.temporaryChecksum); * jo.Add("versionNumber", pair.Value.versionNumber); * jo.Add("zone", pair.Value.zone); * jo.Add("xmlAddress", pair.Value.xmlAddress); * jo.Add("dataAddress", pair.Value.datAddress); * jo.Add("Tx", pair.Value.position.x); * jo.Add("Ty", pair.Value.position.y); * jo.Add("Tz", pair.Value.position.z); * jo.Add("Qx", pair.Value.rotation.x); * jo.Add("Qy", pair.Value.rotation.y); * jo.Add("Qz", pair.Value.rotation.z); * jo.Add("Qw", pair.Value.rotation.w); */ //JSONNode cameraCalibrationResult = new JSONObject(); //cameraCalibrationResult.Add("camera_enumeration", 1); //cameraCalibrationResult.Add("serial_number", "cool"); //jo["id"] = pair.Value.id; /* * jo["ip"] = pair.Value.ip; * jo["temporaryChecksum"] = pair.Value.temporaryChecksum; * jo["versionNumber"] = pair.Value.versionNumber; * jo["zone"] = pair.Value.zone; * jo["xmlAddress"] = pair.Value.xmlAddress; * jo["datAddress"] = pair.Value.datAddress; * * * * * * * jo["Tx"] = pair.Value.position.x; * jo["Ty"] = pair.Value.position.y; * jo["Tz"] = pair.Value.position.z; * jo["Qx"] = pair.Value.rotation.x; * jo["Qy"] = pair.Value.rotation.y; * jo["Qz"] = pair.Value.rotation.z; * jo["QW"] = pair.Value.rotation.w; */ //Debug.Log("camera calibration result: " + cameraCalibrationResult.ToString()); //Debug.Log("adding jo: " + jo.ToString()); ja.Add(jo); } //Debug.Log("json array: " + ja.ToString()); System.IO.File.WriteAllText("vuforiaSaved.txt", ja.ToString()); }
public bool Save() { try { /* * LISTS */ //Just in case, I'm moving this up here System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; _events = _events.OrderBy(x => x._time).ToList(); _notes = _notes.OrderBy(x => x._time).ToList(); _obstacles = _obstacles.OrderBy(x => x._time).ToList(); _BPMChanges = _BPMChanges.OrderBy(x => x._time).ToList(); _bookmarks = _bookmarks.OrderBy(x => x._time).ToList(); _customEvents = _customEvents.OrderBy(x => x._time).ThenBy(x => x._type).ToList(); mainNode["_version"] = _version; JSONArray events = new JSONArray(); foreach (MapEvent e in _events) { events.Add(e.ConvertToJSON()); } JSONArray notes = new JSONArray(); foreach (BeatmapNote n in _notes) { notes.Add(n.ConvertToJSON()); } JSONArray obstacles = new JSONArray(); foreach (BeatmapObstacle o in _obstacles) { obstacles.Add(o.ConvertToJSON()); } JSONArray bpm = new JSONArray(); foreach (BeatmapBPMChange b in _BPMChanges) { bpm.Add(b.ConvertToJSON()); } JSONArray bookmarks = new JSONArray(); foreach (BeatmapBookmark b in _bookmarks) { bookmarks.Add(b.ConvertToJSON()); } JSONArray customEvents = new JSONArray(); foreach (BeatmapCustomEvent c in _customEvents) { customEvents.Add(c.ConvertToJSON()); } mainNode["_notes"] = notes; mainNode["_obstacles"] = obstacles; mainNode["_events"] = events; /* * According to new the new BeatSaver schema, which will be enforced sometime soon™, * Bookmarks, Custom Events, and BPM Changes are now pushed to _customData instead of being on top level. * * Private MM should already has this updated, however public MM will need a PR by someone, or maybe squeaksies if he * wants to go against his own words and go back to that. * * Since these are editor only things, it's fine if I implement them now. Besides, CM reads both versions anyways. */ if (_BPMChanges.Any()) { mainNode["_customData"]["_BPMChanges"] = bpm; } if (_bookmarks.Any()) { mainNode["_customData"]["_bookmarks"] = bookmarks; } if (_customEvents.Any()) { mainNode["_customEvents"] = customEvents; } if (_time > 0) { mainNode["_customData"]["_time"] = Math.Round(_time, 3); } using (StreamWriter writer = new StreamWriter(directoryAndFile, false)) { //Advanced users might want human readable JSON to perform easy modifications and reload them on the fly. //Thus, ChroMapper "beautifies" the JSON if you are in advanced mode. if (Settings.Instance.AdvancedShit) { writer.Write(mainNode.ToString(2)); } else { writer.Write(mainNode.ToString()); } } return(true); } catch (Exception e) { Debug.LogException(e); return(false); } }
public static JSONArray ExecuteQuerySync(string sql, Dictionary <string, object> parameters, bool useTransaction) { // Force transaction if it is an update, insert or delete. if (GAUtilities.StringMatch(sql.ToUpperInvariant(), "^(UPDATE|INSERT|DELETE)")) { useTransaction = true; } // Get database connection from singelton sharedInstance SqliteConnection sqlDatabasePtr = Instance.SqlDatabase; // Create mutable array for results JSONArray results = new JSONArray(); SqliteTransaction transaction = null; SqliteCommand command = null; try { if (useTransaction) { transaction = sqlDatabasePtr.BeginTransaction(); } command = sqlDatabasePtr.CreateCommand(); if (useTransaction) { command.Transaction = transaction; } command.CommandText = sql; command.Prepare(); // Bind parameters if (parameters.Count != 0) { foreach (KeyValuePair <string, object> pair in parameters) { command.Parameters.AddWithValue(pair.Key, pair.Value); } } using (SqliteDataReader reader = command.ExecuteReader()) { // Loop through results while (reader.Read()) { // get columns count int columnCount = reader.FieldCount; JSONObject row = new JSONObject(); for (int i = 0; i < columnCount; i++) { string column = reader.GetName(i); if (string.IsNullOrEmpty(column)) { continue; } row[column] = reader.GetValue(i).ToString(); } results.Add(row); } } if (useTransaction) { transaction.Commit(); } } catch (Exception e) { // TODO(nikolaj): Should we do a db validation to see if the db is corrupt here? GALogger.E("SQLITE3 ERROR: " + e); results = null; if (useTransaction) { if (transaction != null) { try { transaction.Rollback(); } catch (Exception ex) { GALogger.E("SQLITE3 ROLLBACK ERROR: " + ex); } finally { transaction.Dispose(); } } } } finally { if (command != null) { command.Dispose(); } if (transaction != null) { transaction.Dispose(); } } // Return results return(results); }
public static bool EnsureDatabase(bool dropDatabase, string key) { // lazy creation of db path if (string.IsNullOrEmpty(Instance.dbPath)) { // initialize db path #pragma warning disable 0429 #if WINDOWS_UWP || WINDOWS_WSA Instance.dbPath = InMemory ? ":memory:" : Path.Combine(GADevice.WritablePath, "ga.sqlite3"); #else Instance.dbPath = InMemory ? ":memory:" : Path.Combine(Path.Combine(GADevice.WritablePath, key), "ga.sqlite3"); if (!InMemory) { string d = Path.Combine(GADevice.WritablePath, key); if (!Directory.Exists(d)) { Directory.CreateDirectory(d); } } #endif #pragma warning restore 0429 GALogger.D("Database path set to: " + Instance.dbPath); } // Open database try { #if UNITY Instance.SqlDatabase = new SqliteConnection("URI=file:" + Instance.dbPath + ";Version=3"); #else Instance.SqlDatabase = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = Instance.dbPath }.ConnectionString); #endif Instance.SqlDatabase.Open(); Instance.DbReady = true; GALogger.I("Database opened: " + Instance.dbPath); } catch (Exception e) { Instance.DbReady = false; GALogger.W("Could not open database: " + Instance.dbPath + " " + e); return(false); } if (dropDatabase) { GALogger.D("Drop tables"); ExecuteQuerySync("DROP TABLE ga_events"); ExecuteQuerySync("DROP TABLE ga_state"); ExecuteQuerySync("DROP TABLE ga_session"); ExecuteQuerySync("DROP TABLE ga_progression"); ExecuteQuerySync("VACUUM"); } // Create statements string sql_ga_events = "CREATE TABLE IF NOT EXISTS ga_events(status CHAR(50) NOT NULL, category CHAR(50) NOT NULL, session_id CHAR(50) NOT NULL, client_ts CHAR(50) NOT NULL, event TEXT NOT NULL);"; string sql_ga_session = "CREATE TABLE IF NOT EXISTS ga_session(session_id CHAR(50) PRIMARY KEY NOT NULL, timestamp CHAR(50) NOT NULL, event TEXT NOT NULL);"; string sql_ga_state = "CREATE TABLE IF NOT EXISTS ga_state(key CHAR(255) PRIMARY KEY NOT NULL, value TEXT);"; string sql_ga_progression = "CREATE TABLE IF NOT EXISTS ga_progression(progression CHAR(255) PRIMARY KEY NOT NULL, tries CHAR(255));"; JSONArray results = ExecuteQuerySync(sql_ga_events); if (results == null) { return(false); } if (ExecuteQuerySync("SELECT status FROM ga_events LIMIT 0,1") == null) { GALogger.D("ga_events corrupt, recreating."); ExecuteQuerySync("DROP TABLE ga_events"); results = ExecuteQuerySync(sql_ga_events); if (results == null) { GALogger.W("ga_events corrupt, could not recreate it."); return(false); } } results = ExecuteQuerySync(sql_ga_session); if (results == null) { return(false); } if (ExecuteQuerySync("SELECT session_id FROM ga_session LIMIT 0,1") == null) { GALogger.D("ga_session corrupt, recreating."); ExecuteQuerySync("DROP TABLE ga_session"); results = ExecuteQuerySync(sql_ga_session); if (results == null) { GALogger.W("ga_session corrupt, could not recreate it."); return(false); } } results = ExecuteQuerySync(sql_ga_state); if (results == null) { return(false); } if (ExecuteQuerySync("SELECT key FROM ga_state LIMIT 0,1") == null) { GALogger.D("ga_state corrupt, recreating."); ExecuteQuerySync("DROP TABLE ga_state"); results = ExecuteQuerySync(sql_ga_state); if (results == null) { GALogger.W("ga_state corrupt, could not recreate it."); return(false); } } results = ExecuteQuerySync(sql_ga_progression); if (results == null) { return(false); } if (ExecuteQuerySync("SELECT progression FROM ga_progression LIMIT 0,1") == null) { GALogger.D("ga_progression corrupt, recreating."); ExecuteQuerySync("DROP TABLE ga_progression"); results = ExecuteQuerySync(sql_ga_progression); if (results == null) { GALogger.W("ga_progression corrupt, could not recreate it."); return(false); } } // All good TrimEventTable(); IsTableReady = true; GALogger.D("Database tables ensured present"); return(true); }
public ForgeClassObject(string location) { this.FileLocation = location; this.Filename = Path.GetFileName(FileLocation); this.ExactFilename = Path.GetFileNameWithoutExtension(FileLocation); if (ExactFilename == "NetworkManager") { return; } List <float> _interpolationValues = new List <float>(); JSONNode typeData = null; JSONNode typeHelperData = null; JSONNode interpolData = null; Type currentType = GetType("BeardedManStudios.Forge.Networking.Generated." + this.ExactFilename); GeneratedRPCAttribute aRPC = (GeneratedRPCAttribute)Attribute.GetCustomAttribute(currentType, typeof(GeneratedRPCAttribute)); GeneratedRPCVariableNamesAttribute aNames = (GeneratedRPCVariableNamesAttribute)Attribute.GetCustomAttribute(currentType, typeof(GeneratedRPCVariableNamesAttribute)); GeneratedInterpolAttribute aInterpol = (GeneratedInterpolAttribute)Attribute.GetCustomAttribute(currentType, typeof(GeneratedInterpolAttribute)); if (aRPC != null && !string.IsNullOrEmpty(aRPC.JsonData)) { typeData = JSON.Parse(aRPC.JsonData); } else { typeData = new JSONClass(); } if (aNames != null && !string.IsNullOrEmpty(aNames.JsonData)) { typeHelperData = JSON.Parse(aNames.JsonData); } else { typeHelperData = new JSONClass(); } if (aInterpol != null && !string.IsNullOrEmpty(aInterpol.JsonData)) { interpolData = JSON.Parse(aInterpol.JsonData); } else { interpolData = new JSONClass(); } #if FORGE_EDITOR_DEBUGGING string forgeClassDebug = "Loaded - " + this.ExactFilename + System.Environment.NewLine; #endif List <MethodInfo> uniqueMethods = new List <MethodInfo>(); List <PropertyInfo> uniqueProperties = new List <PropertyInfo>(); List <FieldInfo> uniqueFields = new List <FieldInfo>(); if (currentType == null) { throw new NullReferenceException("CANNOT PUT SOURCE CODE IN GENERATED FOLDER! PLEASE REMOVE NON GENERATED CODE!"); } MethodInfo[] methods = currentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy) .Where(m => m.GetParameters().Length == 1 && m.GetParameters()[0].ParameterType.FullName == "BeardedManStudios.Forge.Networking.RpcArgs").ToArray(); PropertyInfo[] properties = currentType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy); FieldInfo[] fields = currentType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy) .Where(attr => attr.IsDefined(typeof(ForgeGeneratedFieldAttribute), false)).ToArray(); uniqueMethods.AddRange(methods); uniqueProperties.AddRange(properties); uniqueFields.AddRange(fields); //If we don't find any fields containing the attribute, the class is either empty, or using the old format. Try parsing old format if (fields.Length == 0) { FieldInfo[] legacyFields = currentType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy); uniqueFields.AddRange(legacyFields); for (int i = 0; i < uniqueFields.Count; ++i) { switch (uniqueFields[i].Name) { case "IDENTITY": case "networkObject": case "fieldAltered": case "_dirtyFields": case "dirtyFields": uniqueFields.RemoveAt(i--); //TODO: Store the types for re-use continue; } if (uniqueFields[i].Name.EndsWith("Changed")) { uniqueFields.RemoveAt(i--); continue; } if (uniqueFields[i].Name.EndsWith("Interpolation")) { uniqueFields.RemoveAt(i--); //TODO: Store the types for re-use continue; } } } if (currentType.BaseType != null) { Type baseType = currentType.BaseType; Type networkBehavior = currentType.GetInterface("INetworkBehavior"); Type factoryInterface = currentType.GetInterface("INetworkObjectFactory"); bool isMonobehavior = currentType.IsSubclassOf(typeof(MonoBehaviour)); if (baseType.FullName == "BeardedManStudios.Forge.Networking.NetworkObject") { ObjectClassType = ForgeBaseClassType.NetworkObject; IdentityValue = ++IDENTITIES; } else if (networkBehavior != null && !isMonobehavior) { ObjectClassType = ForgeBaseClassType.NetworkBehavior; } else if (baseType == typeof(MonoBehaviour) || isMonobehavior) { ObjectClassType = ForgeBaseClassType.MonoBehavior; } else if (factoryInterface != null) { ObjectClassType = ForgeBaseClassType.ObjectFactory; } else if (baseType == typeof(Enum)) { ObjectClassType = ForgeBaseClassType.Enums; } else { ObjectClassType = ForgeBaseClassType.Custom; } MethodInfo[] baseMethods = baseType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy); PropertyInfo[] baseProperties = baseType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy); FieldInfo[] baseFields = baseType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy); for (int i = 0; i < baseMethods.Length; ++i) { for (int x = 0; x < uniqueMethods.Count; ++x) { if (uniqueMethods[x].Name == baseMethods[i].Name && uniqueMethods[x].GetParameters().Length == baseMethods[i].GetParameters().Length) { var argsA = uniqueMethods[x].GetParameters(); var argsB = baseMethods[i].GetParameters(); bool same = true; for (int j = 0; j < argsA.Length; j++) { if (!argsA[j].Equals(argsB[j])) { same = false; break; } } if (same) { uniqueMethods.RemoveAt(x); } break; } } } for (int i = 0; i < baseProperties.Length; ++i) { for (int x = 0; x < uniqueProperties.Count; ++x) { if (uniqueProperties[x].Name == baseProperties[i].Name) { uniqueProperties.RemoveAt(x); break; } } } for (int i = 0; i < baseFields.Length; ++i) { for (int x = 0; x < uniqueFields.Count; ++x) { if (uniqueFields[x].Name == baseFields[i].Name) { uniqueFields.RemoveAt(x); break; } } } } #if FORGE_EDITOR_DEBUGGING forgeClassDebug += "Properties:\n"; foreach (PropertyInfo a in uniqueProperties) { forgeClassDebug += a.Name + " (" + a.PropertyType + ")" + System.Environment.NewLine; } forgeClassDebug += System.Environment.NewLine; forgeClassDebug += "Fields:\n"; #endif if (ObjectClassType != ForgeBaseClassType.Enums) { if (interpolData != null) { JSONArray currentInterpolationVariables = interpolData["inter"].AsArray; if (currentInterpolationVariables != null) { for (int i = 0; i < currentInterpolationVariables.Count; ++i) { float interPolVal = currentInterpolationVariables[i].AsFloat; _interpolationValues.Add(interPolVal); } } } else { for (int i = 0; i < uniqueFields.Count; ++i) { _interpolationValues.Add(ForgeNetworkingEditor.DEFAULT_INTERPOLATE_TIME); } } for (int i = 0; i < uniqueFields.Count; ++i) { if (_interpolationValues.Count == 0) { break; } ForgeClassFieldValue val = ForgeClassFieldValue.GetClassField(uniqueFields[i], currentType, _interpolationValues[i] > 0, _interpolationValues[i]); Fields.Add(val); #if FORGE_EDITOR_DEBUGGING Debug.Log(val); forgeClassDebug += uniqueFields[i].Name + " (" + uniqueFields[i].FieldType + ")" + System.Environment.NewLine; #endif } } #if FORGE_EDITOR_DEBUGGING forgeClassDebug += System.Environment.NewLine; forgeClassDebug += "Methods:\n"; #endif List <List <ForgeAcceptableRPCTypes> > rpcSupportedTypes = new List <List <ForgeAcceptableRPCTypes> >(); if (typeData != null) { JSONArray currentRPCVariables = typeData["types"].AsArray; if (currentRPCVariables != null) { for (int i = 0; i < currentRPCVariables.Count; ++i) { JSONArray singularArray = currentRPCVariables[i].AsArray; if (singularArray != null) { List <ForgeAcceptableRPCTypes> singularSupportedTypes = new List <ForgeAcceptableRPCTypes>(); for (int x = 0; x < singularArray.Count; ++x) { ForgeAcceptableRPCTypes singularType = ForgeClassFieldRPCValue.GetTypeFromAcceptable(singularArray[x].Value); singularSupportedTypes.Add(singularType); } rpcSupportedTypes.Add(singularSupportedTypes); } } } } else { for (int i = 0; i < uniqueMethods.Count; ++i) { rpcSupportedTypes.Add(new List <ForgeAcceptableRPCTypes>()); } } List <List <string> > typeHelpers = new List <List <string> >(); if (typeHelperData != null) { JSONArray currentHelperRPCTypes = typeHelperData["types"].AsArray; if (currentHelperRPCTypes != null) { for (int i = 0; i < currentHelperRPCTypes.Count; ++i) { JSONArray singularHelperArray = currentHelperRPCTypes[i].AsArray; if (singularHelperArray != null) { List <string> singularSupportedTypes = new List <string>(new string[Mathf.Max(singularHelperArray.Count, rpcSupportedTypes.Count)]); for (int x = 0; x < singularHelperArray.Count; ++x) { string singularHelperType = singularHelperArray[x].Value.Replace(" ", string.Empty); singularSupportedTypes[x] = singularHelperType; } typeHelpers.Add(singularSupportedTypes); } } } } else { //This is missing the type helper data for (int i = 0; i < rpcSupportedTypes.Count; ++i) { typeHelpers.Add(new List <string>(new string[rpcSupportedTypes[i].Count])); } } for (int i = 0; i < uniqueMethods.Count; ++i) { RPCS.Add(new ForgeClassRPCValue(uniqueMethods[i], rpcSupportedTypes[i], typeHelpers[i])); #if FORGE_EDITOR_DEBUGGING ParameterInfo[] paramsInfo = a.GetParameters(); string parameters = ""; foreach (ParameterInfo info in paramsInfo) { parameters += info.ParameterType + ", "; } forgeClassDebug += a.Name + " (" + parameters + ")" + System.Environment.NewLine; #endif } #if FORGE_EDITOR_DEBUGGING forgeClassDebug += "Class Type: " + ObjectClassType; forgeClassDebug += "\nSearchName: " + StrippedSearchName; forgeClassDebug += "\nIsNetworkedObject: " + IsNetworkObject; forgeClassDebug += "\nIsNetworkBehavior: " + IsNetworkBehavior; forgeClassDebug += System.Environment.NewLine; Debug.Log(forgeClassDebug); #endif }
public Pattern_Bind(JSONArray template, PatternScope scope) { bindName = template.getString(1); body = scope.getPattern(template, 2); }
private void CreateSocket(string name, string password) { _socket = new SocketIOClient.Client("http://" + _baseAddress + "/ "); _socket.On("connect", (fn) => { Debug.Log("connect - socket"); Dictionary <string, string> args = new Dictionary <string, string>(); args.Add("pseudo", name); args.Add("password", password); _socket.Emit("authentication", args); _socket.On("unauthorized", (data) => { Debug.Log("unauthorized"); if (Unauthorized != null) { Unauthorized(JSON.Parse(data.Encoded)); } _socket.Close(); }); _socket.On("authenticated", (data) => { Debug.Log("authenticated"); if (Authenticated != null) { Authenticated(JSONNode.Parse(data.Encoded)); } _socket.On("lobbylist", (result) => { if (LobbyList != null) { JSONNode resultjson = JSONNode.Parse(result.Encoded); JSONArray arguments = resultjson["args"].AsArray; JSONArray actualresult = arguments[0].AsArray; LobbyList(actualresult); } }); _socket.On("lobbycreated", (result) => { if (LobbyCreated != null) { LobbyCreated(JSONNode.Parse(result.Encoded)); } }); _socket.On("lobbyfull", (result) => { if (LobbyFull != null) { LobbyFull(JSONNode.Parse(result.Encoded)); } }); _socket.On("lobbyjoined", (result) => { if (LobbyJoined != null) { JSONNode resultjson = JSONNode.Parse(result.Encoded)["args"][0]; LobbyJoined(resultjson); } }); _socket.On("lobbyleft", (result) => { if (LobbyLeft != null) { LobbyLeft(JSONNode.Parse(result.Encoded)); } }); _socket.On("readyset", (result) => { if (ReadySet != null) { JSONNode resultjson = JSONNode.Parse(result.Encoded)["args"][0]; ReadySet(resultjson); } }); _socket.On("goingame", (result) => { if (GoInGame != null) { GoInGame(JSONNode.Parse(result.Encoded)["args"][0]); } }); _socket.On("unreadyset", (result) => { if (UnReadySet != null) { UnReadySet(JSONNode.Parse(result.Encoded)["args"][0]); } }); _socket.On("cantunready", (result) => { if (CantUnready != null) { CantUnready(JSONNode.Parse(result.Encoded)["args"][0]); } }); _socket.On("countdown", (result) => { if (Countdown != null) { Countdown(JSONNode.Parse(result.Encoded)["args"][0]); } }); _socket.On("playerjoined", (result) => { if (PlayerJoined != null) { PlayerJoined(JSONNode.Parse(result.Encoded)["args"][0]); } }); _socket.On("playerleft", (result) => { if (PlayerLeft != null) { PlayerLeft(JSONNode.Parse(result.Encoded)["args"][0]); } }); _socket.On("opponentreadyup", (result) => { if (OpponentReadyUp != null) { OpponentReadyUp(JSONNode.Parse(result.Encoded)["args"][0]); } }); _socket.On("opponentunready", (result) => { if (OpponentUnready != null) { OpponentUnready(JSONNode.Parse(result.Encoded)["args"][0]); } }); _socket.On("update", (result) => { if (Update != null) { Update(JSONNode.Parse(result.Encoded)["args"][0]); } }); _socket.On("gameover", (result) => { if (Gameover != null) { Gameover(JSONNode.Parse(result.Encoded)["args"][0]); } }); _socket.On("result", (result) => { if (Result != null) { Result(JSONNode.Parse(result.Encoded)["args"][0]); } }); }); }); _socket.Error += (sender, e) => { Debug.Log("socket Error: " + e.Message.ToString()); if (Error != null) { Error(e.Message.ToString()); } }; }
// CleverTap API usage examples // Just for illustration here in Start /* -------------------------------------------------------------------------------- * CLEVERTAP API USAGE * -------------------------------------------------------------------------------- */ //Add common feature codes here void OnStartCommon() { // record special Charged event Dictionary <string, object> chargeDetails = new Dictionary <string, object>(); chargeDetails.Add("Amount", 500); chargeDetails.Add("Currency", "USD"); chargeDetails.Add("Payment Mode", "Credit card"); Dictionary <string, object> item = new Dictionary <string, object>(); item.Add("price", 50); item.Add("Product category", "books"); item.Add("Quantity", 1); Dictionary <string, object> item2 = new Dictionary <string, object>(); item2.Add("price", 100); item2.Add("Product category", "plants"); item2.Add("Quantity", 10); List <Dictionary <string, object> > items = new List <Dictionary <string, object> >(); items.Add(item); items.Add(item2); CleverTapBinding.RecordChargedEventWithDetailsAndItems(chargeDetails, items); // record basic event with no properties CleverTapBinding.RecordEvent("testEvent"); // record event with properties Dictionary <string, object> Props = new Dictionary <string, object>(); Props.Add("testKey", "testValue"); CleverTapBinding.RecordEvent("testEventWithProps", Props); // set user location CleverTapBinding.SetLocation(34.147785, -118.144516); // reset the user profile after a login with a new Identity Dictionary <string, string> newProps = new Dictionary <string, string>(); newProps.Add("email", "*****@*****.**"); newProps.Add("Identity", "123456"); CleverTapBinding.OnUserLogin(newProps); // get the CleverTap unique install attributionidentifier string CleverTapAttributionIdentifier = CleverTapBinding.ProfileGetCleverTapAttributionIdentifier(); Debug.Log("CleverTapAttributionIdentifier is: " + (!String.IsNullOrEmpty(CleverTapAttributionIdentifier) ? CleverTapAttributionIdentifier : "NULL")); // get the CleverTap unique profile identifier string CleverTapID = CleverTapBinding.ProfileGetCleverTapID(); Debug.Log("CleverTapID is: " + (!String.IsNullOrEmpty(CleverTapID) ? CleverTapID : "NULL")); // get event and session data int firstTime = CleverTapBinding.EventGetFirstTime("App Launched"); int lastTime = CleverTapBinding.EventGetLastTime("App Launched"); int occurrences = CleverTapBinding.EventGetOccurrences("App Launched"); Debug.Log(String.Format("App Launched first time is {0} last time is {1} occurrences is {2}", firstTime, lastTime, occurrences)); JSONClass history = CleverTapBinding.UserGetEventHistory(); Debug.Log(String.Format("User event history is {0}", history)); int elapsedTime = CleverTapBinding.SessionGetTimeElapsed(); int totalVisits = CleverTapBinding.UserGetTotalVisits(); int screenCount = CleverTapBinding.UserGetScreenCount(); int previousVisitTime = CleverTapBinding.UserGetPreviousVisitTime(); Debug.Log(String.Format("session stats: elapsed time: {0}, total visits: {1}, screen count: {2}, previous visit time: {3}", elapsedTime, totalVisits, screenCount, previousVisitTime)); // get session referrer utm values JSONClass utmDetail = CleverTapBinding.SessionGetUTMDetails(); Debug.Log(String.Format("session utm details is {0}", utmDetail)); // get event data for a specific event JSONClass eventDetail = CleverTapBinding.EventGetDetail("App Launchedd"); Debug.Log(String.Format("event detail is {0}", eventDetail)); // get user profile attributes // scalar value string profileName = CleverTapBinding.ProfileGet("Name"); Debug.Log("profileName is: " + (!String.IsNullOrEmpty(profileName) ? profileName : "NULL")); // multi-value (array) string multiValueProperty = CleverTapBinding.ProfileGet("multiAndroid"); Debug.Log("multiValueProperty is: " + (!String.IsNullOrEmpty(multiValueProperty) ? multiValueProperty : "NULL")); if (!String.IsNullOrEmpty(multiValueProperty)) { try { JSONArray values = (JSONArray)JSON.Parse(multiValueProperty); } catch { Debug.Log("unable to parse json"); } } }
public static void SetQuestionWasAnswered(string shieldNum, string key) { string values = PlayerPrefs.GetString("opened_questions"); if (values != null && values.Length > 0) { var jsonStr = JSON.Parse(values); var listNode = jsonStr [key].AsArray; if (listNode != null) { foreach (JSONData i in listNode) { if (i.Value == shieldNum) { return; } } JSONNode jnod = new JSONNode(); jnod.Add(shieldNum); listNode.Add(shieldNum); jsonStr [key] = listNode; } else { JSONArray listNode1 = new JSONArray(); JSONNode jnod1 = new JSONNode(); jnod1.Add(shieldNum); listNode1.Add(shieldNum); jsonStr.Add(key, listNode1); } //UserController.currentUser.Motto = jsonStr.ToString(); //profile.SaveUser (); PlayerPrefs.SetString("opened_questions", jsonStr.ToString()); return; } else { JSONArray listNode = new JSONArray(); JSONNode jnod = new JSONNode(); jnod.Add(shieldNum); listNode.Add(shieldNum); JSONClass rootNode = new JSONClass(); rootNode.Add(key, listNode); //UserController.currentUser.Motto = rootNode.ToString(); //profile.SaveUser (); PlayerPrefs.SetString("opened_questions", rootNode.ToString()); return; } }
private Array(JSONArray a) : base(a) { a_ = a; }