/// <summary>
 /// de activates the pause that stops the world from turning and sets the round start time to now
 /// </summary>
 public void deActivatePose()
 {
     poseActive = false;
     GameObject.Find("InitHolder").GetComponent<InitScript>().playerStats.setNewBeginTime();
     log = GameObject.Find("LogSys(Clone)").GetComponent<LogSystem>();
     log.pushEvent("STARTROUND");
 }
Beispiel #2
0
        public static void Write(LogLevel level, LogSystem system, String message)
        {
            if (message == null) return;

            s_stringbuilder.Length = 0;
            s_stringbuilder.AppendFormat("{0, -25:u}{1, -10}{2, -23}{3}", DateTime.Now, level, system, message);

            String line = s_stringbuilder.ToString();
            WriteLine(line);
        }
	/// <summary>
	/// dumps the log messages this logger is holding into a new logger
	/// </summary>
	public virtual void DumpLogMessages(LogSystem newLogger) {
	    lock(this) {
		if (!(pendingMessages.Count == 0)) {
		    // iterate and log each individual message...
		    foreach(Object[] data in pendingMessages) {
			newLogger.LogVelocityMessage(((Int32)data[0]), (String)data[1]);
		    }
		}
	    }
	}
Beispiel #4
0
        public static void Write(LogLevel level, LogSystem system, String format, params Object[] args)
        {
            if (format == null || args == null) return;

            s_stringbuilder.Length = 0;
            s_stringbuilder.AppendFormat("{0, -25:u}{1, -10}{2, -23}", DateTime.Now, level, system);
            s_stringbuilder.AppendFormat(format, args);

            String line = s_stringbuilder.ToString();
            WriteLine(line);
        }
 static LoggingManager()
 {
     s_logSystem = new LogSystem();
     s_logSystem.OnLog += OnLogMessage;
 }
        public override IEnumerator RunTest()
        {
            LogSystem.InstallDefaultReactors();

            //  Test Assistant using loaded credentials
            Assistant autoAssisant = new Assistant();

            while (!autoAssisant.Credentials.HasIamTokenData())
            {
                yield return(null);
            }
            autoAssisant.VersionDate = _assistantVersionDate;
            autoAssisant.ListWorkspaces(OnAutoListWorkspaces, OnFail);
            while (!_autoListWorkspacesTested)
            {
                yield return(null);
            }

            VcapCredentials vcapCredentials = new VcapCredentials();
            fsData          data            = null;

            string result = null;
            string credentialsFilepath = "../sdk-credentials/credentials.json";

            //  Load credentials file if it exists. If it doesn't exist, don't run the tests.
            if (File.Exists(credentialsFilepath))
            {
                result = File.ReadAllText(credentialsFilepath);
            }
            else
            {
                yield break;
            }

            //  Add in a parent object because Unity does not like to deserialize root level collection types.
            result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES");

            //  Convert json to fsResult
            fsResult r = fsJsonParser.Parse(result, out data);

            if (!r.Succeeded)
            {
                throw new WatsonException(r.FormattedMessages);
            }

            //  Convert fsResult to VcapCredentials
            object obj = vcapCredentials;

            r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
            if (!r.Succeeded)
            {
                throw new WatsonException(r.FormattedMessages);
            }

            //  Set credentials from imported credntials
            Credential credential = vcapCredentials.GetCredentialByname("assistant-sdk")[0].Credentials;
            //  Create credential and instantiate service
            TokenOptions tokenOptions = new TokenOptions()
            {
                IamApiKey = credential.IamApikey,
            };

            Credentials credentials = new Credentials(tokenOptions, credential.Url);

            _workspaceId = credential.WorkspaceId.ToString();

            //  Wait for tokendata
            while (!credentials.HasIamTokenData())
            {
                yield return(null);
            }

            _service             = new Assistant(credentials);
            _service.VersionDate = _assistantVersionDate;

            //  List Workspaces
            _service.ListWorkspaces(OnListWorkspaces, OnFail);
            while (!_listWorkspacesTested)
            {
                yield return(null);
            }
            //  Create Workspace
            CreateWorkspace workspace = new CreateWorkspace()
            {
                Name           = _createdWorkspaceName,
                Description    = _createdWorkspaceDescription,
                Language       = _createdWorkspaceLanguage,
                LearningOptOut = true
            };

            _service.CreateWorkspace(OnCreateWorkspace, OnFail, workspace);
            while (!_createWorkspaceTested)
            {
                yield return(null);
            }
            //  Get Workspace
            _service.GetWorkspace(OnGetWorkspace, OnFail, _createdWorkspaceId);
            while (!_getWorkspaceTested)
            {
                yield return(null);
            }
            //  Update Workspace
            UpdateWorkspace updateWorkspace = new UpdateWorkspace()
            {
                Name        = _createdWorkspaceName + "-updated",
                Description = _createdWorkspaceDescription + "-updated",
                Language    = _createdWorkspaceLanguage
            };

            _service.UpdateWorkspace(OnUpdateWorkspace, OnFail, _createdWorkspaceId, updateWorkspace);
            while (!_updateWorkspaceTested)
            {
                yield return(null);
            }

            //  Message with customerID
            //  Create customData object
            Dictionary <string, object> customData = new Dictionary <string, object>();
            //  Create a dictionary of custom headers
            Dictionary <string, string> customHeaders = new Dictionary <string, string>();

            //  Add to the header dictionary
            customHeaders.Add("X-Watson-Metadata", "customer_id=" + _unitySdkTestCustomerID);
            //  Add the header dictionary to the custom data object
            customData.Add(Constants.String.CUSTOM_REQUEST_HEADERS, customHeaders);
            Dictionary <string, object> input = new Dictionary <string, object>();

            input.Add("text", _inputString);
            MessageRequest messageRequest = new MessageRequest()
            {
                Input = input
            };

            _service.Message(OnMessage, OnFail, _workspaceId, messageRequest, null, customData);
            while (!_messageTested)
            {
                yield return(null);
            }
            _messageTested = false;

            input["text"] = _conversationString0;
            MessageRequest messageRequest0 = new MessageRequest()
            {
                Input   = input,
                Context = _context
            };

            _service.Message(OnMessage, OnFail, _workspaceId, messageRequest0);
            while (!_messageTested)
            {
                yield return(null);
            }
            _messageTested = false;

            input["text"] = _conversationString1;
            MessageRequest messageRequest1 = new MessageRequest()
            {
                Input   = input,
                Context = _context
            };

            _service.Message(OnMessage, OnFail, _workspaceId, messageRequest1);
            while (!_messageTested)
            {
                yield return(null);
            }
            _messageTested = false;

            input["text"] = _conversationString2;
            MessageRequest messageRequest2 = new MessageRequest()
            {
                Input   = input,
                Context = _context
            };

            _service.Message(OnMessage, OnFail, _workspaceId, messageRequest2);
            while (!_messageTested)
            {
                yield return(null);
            }

            //  List Intents
            _service.ListIntents(OnListIntents, OnFail, _createdWorkspaceId);
            while (!_listIntentsTested)
            {
                yield return(null);
            }
            //  Create Intent
            CreateIntent createIntent = new CreateIntent()
            {
                Intent      = _createdIntent,
                Description = _createdIntentDescription
            };

            _service.CreateIntent(OnCreateIntent, OnFail, _createdWorkspaceId, createIntent);
            while (!_createIntentTested)
            {
                yield return(null);
            }
            //  Get Intent
            _service.GetIntent(OnGetIntent, OnFail, _createdWorkspaceId, _createdIntent);
            while (!_getIntentTested)
            {
                yield return(null);
            }
            //  Update Intents
            string       updatedIntent            = _createdIntent + "-updated";
            string       updatedIntentDescription = _createdIntentDescription + "-updated";
            UpdateIntent updateIntent             = new UpdateIntent()
            {
                Intent      = updatedIntent,
                Description = updatedIntentDescription
            };

            _service.UpdateIntent(OnUpdateIntent, OnFail, _createdWorkspaceId, _createdIntent, updateIntent);
            while (!_updateIntentTested)
            {
                yield return(null);
            }

            //  List Examples
            _service.ListExamples(OnListExamples, OnFail, _createdWorkspaceId, updatedIntent);
            while (!_listExamplesTested)
            {
                yield return(null);
            }
            //  Create Examples
            CreateExample createExample = new CreateExample()
            {
                Text = _createdExample
            };

            _service.CreateExample(OnCreateExample, OnFail, _createdWorkspaceId, updatedIntent, createExample);
            while (!_createExampleTested)
            {
                yield return(null);
            }
            //  Get Example
            _service.GetExample(OnGetExample, OnFail, _createdWorkspaceId, updatedIntent, _createdExample);
            while (!_getExampleTested)
            {
                yield return(null);
            }
            //  Update Examples
            string        updatedExample = _createdExample + "-updated";
            UpdateExample updateExample  = new UpdateExample()
            {
                Text = updatedExample
            };

            _service.UpdateExample(OnUpdateExample, OnFail, _createdWorkspaceId, updatedIntent, _createdExample, updateExample);
            while (!_updateExampleTested)
            {
                yield return(null);
            }

            //  List Entities
            _service.ListEntities(OnListEntities, OnFail, _createdWorkspaceId);
            while (!_listEntitiesTested)
            {
                yield return(null);
            }
            //  Create Entities
            CreateEntity entity = new CreateEntity()
            {
                Entity      = _createdEntity,
                Description = _createdEntityDescription
            };

            _service.CreateEntity(OnCreateEntity, OnFail, _createdWorkspaceId, entity);
            while (!_createEntityTested)
            {
                yield return(null);
            }
            //  Get Entity
            _service.GetEntity(OnGetEntity, OnFail, _createdWorkspaceId, _createdEntity);
            while (!_getEntityTested)
            {
                yield return(null);
            }
            //  Update Entities
            string       updatedEntity            = _createdEntity + "-updated";
            string       updatedEntityDescription = _createdEntityDescription + "-updated";
            UpdateEntity updateEntity             = new UpdateEntity()
            {
                Entity      = updatedEntity,
                Description = updatedEntityDescription
            };

            _service.UpdateEntity(OnUpdateEntity, OnFail, _createdWorkspaceId, _createdEntity, updateEntity);
            while (!_updateEntityTested)
            {
                yield return(null);
            }

            //  List Values
            _service.ListValues(OnListValues, OnFail, _createdWorkspaceId, updatedEntity);
            while (!_listValuesTested)
            {
                yield return(null);
            }
            //  Create Values
            CreateValue value = new CreateValue()
            {
                Value = _createdValue
            };

            _service.CreateValue(OnCreateValue, OnFail, _createdWorkspaceId, updatedEntity, value);
            while (!_createValueTested)
            {
                yield return(null);
            }
            //  Get Value
            _service.GetValue(OnGetValue, OnFail, _createdWorkspaceId, updatedEntity, _createdValue);
            while (!_getValueTested)
            {
                yield return(null);
            }
            //  Update Values
            string      updatedValue = _createdValue + "-updated";
            UpdateValue updateValue  = new UpdateValue()
            {
                Value = updatedValue
            };

            _service.UpdateValue(OnUpdateValue, OnFail, _createdWorkspaceId, updatedEntity, _createdValue, updateValue);
            while (!_updateValueTested)
            {
                yield return(null);
            }

            //  List Synonyms
            _service.ListSynonyms(OnListSynonyms, OnFail, _createdWorkspaceId, updatedEntity, updatedValue);
            while (!_listSynonymsTested)
            {
                yield return(null);
            }
            //  Create Synonyms
            CreateSynonym synonym = new CreateSynonym()
            {
                Synonym = _createdSynonym
            };

            _service.CreateSynonym(OnCreateSynonym, OnFail, _createdWorkspaceId, updatedEntity, updatedValue, synonym);
            while (!_createSynonymTested)
            {
                yield return(null);
            }
            //  Get Synonym
            _service.GetSynonym(OnGetSynonym, OnFail, _createdWorkspaceId, updatedEntity, updatedValue, _createdSynonym);
            while (!_getSynonymTested)
            {
                yield return(null);
            }
            //  Update Synonyms
            string        updatedSynonym = _createdSynonym + "-updated";
            UpdateSynonym updateSynonym  = new UpdateSynonym()
            {
                Synonym = updatedSynonym
            };

            _service.UpdateSynonym(OnUpdateSynonym, OnFail, _createdWorkspaceId, updatedEntity, updatedValue, _createdSynonym, updateSynonym);
            while (!_updateSynonymTested)
            {
                yield return(null);
            }

            //  List Dialog Nodes
            _service.ListDialogNodes(OnListDialogNodes, OnFail, _createdWorkspaceId);
            while (!_listDialogNodesTested)
            {
                yield return(null);
            }
            //  Create Dialog Nodes
            CreateDialogNode createDialogNode = new CreateDialogNode()
            {
                DialogNode  = _dialogNodeName,
                Description = _dialogNodeDesc
            };

            _service.CreateDialogNode(OnCreateDialogNode, OnFail, _createdWorkspaceId, createDialogNode);
            while (!_createDialogNodeTested)
            {
                yield return(null);
            }
            //  Get Dialog Node
            _service.GetDialogNode(OnGetDialogNode, OnFail, _createdWorkspaceId, _dialogNodeName);
            while (!_getDialogNodeTested)
            {
                yield return(null);
            }
            //  Update Dialog Nodes
            string           updatedDialogNodeName        = _dialogNodeName + "_updated";
            string           updatedDialogNodeDescription = _dialogNodeDesc + "_updated";
            UpdateDialogNode updateDialogNode             = new UpdateDialogNode()
            {
                DialogNode  = updatedDialogNodeName,
                Description = updatedDialogNodeDescription
            };

            _service.UpdateDialogNode(OnUpdateDialogNode, OnFail, _createdWorkspaceId, _dialogNodeName, updateDialogNode);
            while (!_updateDialogNodeTested)
            {
                yield return(null);
            }

            //  List Logs In Workspace
            _service.ListLogs(OnListLogs, OnFail, _createdWorkspaceId);
            while (!_listLogsInWorkspaceTested)
            {
                yield return(null);
            }
            //  List All Logs
            var filter = "(language::en,request.context.metadata.deployment::deployment_1)";

            _service.ListAllLogs(OnListAllLogs, OnFail, filter);
            while (!_listAllLogsTested)
            {
                yield return(null);
            }

            //  List Counterexamples
            _service.ListCounterexamples(OnListCounterexamples, OnFail, _createdWorkspaceId);
            while (!_listCounterexamplesTested)
            {
                yield return(null);
            }
            //  Create Counterexamples
            CreateCounterexample example = new CreateCounterexample()
            {
                Text = _createdCounterExampleText
            };

            _service.CreateCounterexample(OnCreateCounterexample, OnFail, _createdWorkspaceId, example);
            while (!_createCounterexampleTested)
            {
                yield return(null);
            }
            //  Get Counterexample
            _service.GetCounterexample(OnGetCounterexample, OnFail, _createdWorkspaceId, _createdCounterExampleText);
            while (!_getCounterexampleTested)
            {
                yield return(null);
            }
            //  Update Counterexamples
            string updatedCounterExampleText          = _createdCounterExampleText + "-updated";
            UpdateCounterexample updateCounterExample = new UpdateCounterexample()
            {
                Text = updatedCounterExampleText
            };

            _service.UpdateCounterexample(OnUpdateCounterexample, OnFail, _createdWorkspaceId, _createdCounterExampleText, updateCounterExample);
            while (!_updateCounterexampleTested)
            {
                yield return(null);
            }

            //  Delete Counterexample
            _service.DeleteCounterexample(OnDeleteCounterexample, OnFail, _createdWorkspaceId, updatedCounterExampleText);
            while (!_deleteCounterexampleTested)
            {
                yield return(null);
            }
            //  Delete Dialog Node
            _service.DeleteDialogNode(OnDeleteDialogNode, OnFail, _createdWorkspaceId, updatedDialogNodeName);
            while (!_deleteDialogNodeTested)
            {
                yield return(null);
            }
            //  Delete Synonym
            _service.DeleteSynonym(OnDeleteSynonym, OnFail, _createdWorkspaceId, updatedEntity, updatedValue, updatedSynonym);
            while (!_deleteSynonymTested)
            {
                yield return(null);
            }
            //  Delete Value
            _service.DeleteValue(OnDeleteValue, OnFail, _createdWorkspaceId, updatedEntity, updatedValue);
            while (!_deleteValueTested)
            {
                yield return(null);
            }
            //  Delete Entity
            _service.DeleteEntity(OnDeleteEntity, OnFail, _createdWorkspaceId, updatedEntity);
            while (!_deleteEntityTested)
            {
                yield return(null);
            }
            //  Delete Example
            _service.DeleteExample(OnDeleteExample, OnFail, _createdWorkspaceId, updatedIntent, updatedExample);
            while (!_deleteExampleTested)
            {
                yield return(null);
            }
            //  Delete Intent
            _service.DeleteIntent(OnDeleteIntent, OnFail, _createdWorkspaceId, updatedIntent);
            while (!_deleteIntentTested)
            {
                yield return(null);
            }
            //  Delete Workspace
            _service.DeleteWorkspace(OnDeleteWorkspace, OnFail, _createdWorkspaceId);
            while (!_deleteWorkspaceTested)
            {
                yield return(null);
            }
            //  Delete User Data
            _service.DeleteUserData(OnDeleteUserData, OnFail, _unitySdkTestCustomerID);
            while (!_deleteUserDataTested)
            {
                yield return(null);
            }

            Log.Debug("TestAssistant.RunTest()", "Assistant examples complete.");

            yield break;
        }
        public override IEnumerator RunTest()
        {
            LogSystem.InstallDefaultReactors();

            contractAFilepath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/compare-comply/contract_A.pdf";
            contractBFilepath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/compare-comply/contract_B.pdf";
            tableFilepath     = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/compare-comply/TestTable.pdf";

            string objectStorageCredentialsInputFilepath  = "../sdk-credentials/cloud-object-storage-credentials-input.json";
            string objectStorageCredentialsOutputFilepath = "../sdk-credentials/cloud-object-storage-credentials-output.json";

            #region Get Credentials
            VcapCredentials vcapCredentials = new VcapCredentials();
            fsData          data            = null;

            string result = null;
            string credentialsFilepath = "../sdk-credentials/credentials.json";

            //  Load credentials file if it exists. If it doesn't exist, don't run the tests.
            if (File.Exists(credentialsFilepath))
            {
                result = File.ReadAllText(credentialsFilepath);
            }
            else
            {
                yield break;
            }

            //  Add in a parent object because Unity does not like to deserialize root level collection types.
            result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES");

            //  Convert json to fsResult
            fsResult r = fsJsonParser.Parse(result, out data);
            if (!r.Succeeded)
            {
                throw new WatsonException(r.FormattedMessages);
            }

            //  Convert fsResult to VcapCredentials
            object obj = vcapCredentials;
            r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
            if (!r.Succeeded)
            {
                throw new WatsonException(r.FormattedMessages);
            }

            //  Set credentials from imported credntials
            Credential credential = vcapCredentials.GetCredentialByname("compare-comply-sdk")[0].Credentials;
            _url = credential.Url.ToString();

            //  Create credential and instantiate service
            TokenOptions tokenOptions = new TokenOptions()
            {
                IamApiKey = credential.IamApikey
            };
            #endregion

            Credentials credentials = new Credentials(tokenOptions, credential.Url);

            //  Wait for tokendata
            while (!credentials.HasIamTokenData())
            {
                yield return(null);
            }

            compareComply             = new CompareComply(credentials);
            compareComply.VersionDate = versionDate;

            byte[] contractA = File.ReadAllBytes(contractAFilepath);
            byte[] contractB = File.ReadAllBytes(contractBFilepath);
            byte[] table     = File.ReadAllBytes(tableFilepath);

            byte[] objectStorageCredentialsInputData  = File.ReadAllBytes(objectStorageCredentialsInputFilepath);
            byte[] objectStorageCredentialsOutputData = File.ReadAllBytes(objectStorageCredentialsOutputFilepath);

            compareComply.ConvertToHtml(OnConvertToHtml, OnFail, contractA, fileContentType: "application/pdf");
            while (!convertToHtmlTested)
            {
                yield return(null);
            }

            compareComply.ClassifyElements(OnClassifyElements, OnFail, contractA);
            while (!classifyElementsTested)
            {
                yield return(null);
            }

            compareComply.ExtractTables(OnExtractTables, OnFail, table);
            while (!extractTablesTested)
            {
                yield return(null);
            }

            compareComply.CompareDocuments(OnCompareDocuments, OnFail, contractA, contractB, file1ContentType: "application/pdf", file2ContentType: "application/pdf");
            while (!compareDocumentsTested)
            {
                yield return(null);
            }

            DateTime before = new DateTime(2018, 11, 15);
            DateTime after  = new DateTime(2018, 11, 14);
            compareComply.ListFeedback(
                successCallback: OnListFeedback,
                failCallback: OnFail,
                feedbackType: "element_classification",
                before: before,
                after: after,
                documentTitle: "unity-test-feedback-doc",
                modelId: "contracts",
                modelVersion: "2.0.0",
                categoryRemoved: "Responsibilities",
                categoryAdded: "Amendments",
                categoryNotChanged: "Audits",
                typeRemoved: "End User:Exclusion",
                typeAdded: "Disclaimer:Buyer",
                typeNotChanged: "Obligation:IBM",
                pageLimit: 1
                );
            while (!listFeedbackTested)
            {
                yield return(null);
            }


            #region Feedback Data
            FeedbackInput feedbackData = new FeedbackInput()
            {
                UserId       = "user_id_123x",
                Comment      = "Test feedback comment",
                FeedbackData = new FeedbackDataInput()
                {
                    FeedbackType = "element_classification",
                    Document     = new ShortDoc()
                    {
                        Hash  = "",
                        Title = "doc title"
                    },
                    ModelId      = "contracts",
                    ModelVersion = "11.00",
                    Location     = new Location()
                    {
                        Begin = 241,
                        End   = 237
                    },
                    Text           = "1. IBM will provide a Senior Managing Consultant / expert resource, for up to 80 hours, to assist Florida Power & Light (FPL) with the creation of an IT infrastructure unit cost model for existing infrastructure.",
                    OriginalLabels = new OriginalLabelsIn()
                    {
                        Types = new List <TypeLabel>()
                        {
                            new TypeLabel()
                            {
                                Label = new Label()
                                {
                                    Nature = "Obligation",
                                    Party  = "IBM"
                                },
                                ProvenanceIds = new List <string>()
                                {
                                    "85f5981a-ba91-44f5-9efa-0bd22e64b7bc",
                                    "ce0480a1-5ef1-4c3e-9861-3743b5610795"
                                }
                            },
                            new TypeLabel()
                            {
                                Label = new Label()
                                {
                                    Nature = "End User",
                                    Party  = "Exclusion"
                                },
                                ProvenanceIds = new List <string>()
                                {
                                    "85f5981a-ba91-44f5-9efa-0bd22e64b7bc",
                                    "ce0480a1-5ef1-4c3e-9861-3743b5610795"
                                }
                            }
                        },
                        Categories = new List <Category>()
                        {
                            new Category()
                            {
                                Label         = "Responsibilities",
                                ProvenanceIds = new List <string>()
                                {
                                }
                            },
                            new Category()
                            {
                                Label         = "Amendments",
                                ProvenanceIds = new List <string>()
                                {
                                }
                            }
                        }
                    },
                    UpdatedLabels = new UpdatedLabelsIn()
                    {
                        Types = new List <TypeLabel>()
                        {
                            new TypeLabel()
                            {
                                Label = new Label()
                                {
                                    Nature = "Obligation",
                                    Party  = "IBM"
                                }
                            },
                            new TypeLabel()
                            {
                                Label = new Label()
                                {
                                    Nature = "Disclaimer",
                                    Party  = "buyer"
                                }
                            }
                        },
                        Categories = new List <Category>()
                        {
                            new Category()
                            {
                                Label = "Responsibilities",
                            },
                            new Category()
                            {
                                Label = "Audits"
                            }
                        }
                    }
                }
            };
            #endregion

            compareComply.AddFeedback(
                successCallback: OnAddFeedback,
                failCallback: OnFail,
                feedbackData: feedbackData
                );
            while (!addFeedbackTested)
            {
                yield return(null);
            }

            //  temporary fix for a bug requiring `x-watson-metadata` header
            Dictionary <string, object> customData    = new Dictionary <string, object>();
            Dictionary <string, string> customHeaders = new Dictionary <string, string>();
            customHeaders.Add("x-watson-metadata", "customer_id=sdk-test-customer-id");
            customData.Add(Constants.String.CUSTOM_REQUEST_HEADERS, customHeaders);

            compareComply.GetFeedback(
                successCallback: OnGetFeedback,
                failCallback: OnFail,
                feedbackId: feedbackId,
                modelId: "contracts",
                customData: customData
                );
            while (!getFeedbackTested)
            {
                yield return(null);
            }

            compareComply.DeleteFeedback(
                successCallback: OnDeleteFeedback,
                failCallback: OnFail,
                feedbackId: feedbackId,
                modelId: "contracts"
                );
            while (!deleteFeedbackTested)
            {
                yield return(null);
            }

            compareComply.ListBatches(
                successCallback: OnListBatches,
                failCallback: OnFail
                );
            while (!listBatchesTested)
            {
                yield return(null);
            }

            compareComply.CreateBatch(
                successCallback: OnCreateBatch,
                failCallback: OnFail,
                function: "html_conversion",
                inputCredentialsFile: objectStorageCredentialsInputData,
                inputBucketLocation: "us-south",
                inputBucketName: "compare-comply-integration-test-bucket-input",
                outputCredentialsFile: objectStorageCredentialsOutputData,
                outputBucketLocation: "us-south",
                outputBucketName: "compare-comply-integration-test-bucket-output"
                );
            while (!createBatchTested)
            {
                yield return(null);
            }

            compareComply.GetBatch(
                successCallback: OnGetBatch,
                failCallback: OnFail,
                batchId: batchId
                );
            while (!getBatchTestsed)
            {
                yield return(null);
            }

            compareComply.UpdateBatch(
                successCallback: OnUpdateBatch,
                failCallback: OnFail,
                batchId: batchId,
                action: "rescan",
                modelId: "contracts"
                );
            while (!updateBatchTested)
            {
                yield return(null);
            }

            Log.Debug("TestCompareComplyV1.RunTests()", "Compare and Comply integration tests complete!");
        }
Beispiel #8
0
        private static void run_creature_stats()
        {
            // Run stats
            List <Creature> creatures = Session.Creatures;

            bool[] is_minion_options = { false, true };
            bool[] is_leader_options = { false, true };

            string       datafile = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Creatures.csv";
            StreamWriter sw       = new StreamWriter(datafile);

            try
            {
                sw.Write("Level,Flag,Role,Minion,Leader,Tier,TierX,Creatures,Powers");
                // Conditions
                foreach (string condition in Conditions.GetConditions())
                {
                    sw.Write("," + condition);
                }
                // Damage types
                foreach (DamageType damage in Enum.GetValues(typeof(DamageType)))
                {
                    sw.Write("," + damage);
                }
                sw.WriteLine();

                for (int level = 1; level <= 40; ++level)
                {
                    foreach (bool is_minion in is_minion_options)
                    {
                        foreach (bool is_leader in is_leader_options)
                        {
                            foreach (RoleType role in Enum.GetValues(typeof(RoleType)))
                            {
                                foreach (RoleFlag flag in Enum.GetValues(typeof(RoleFlag)))
                                {
                                    List <Creature> list = get_creatures(creatures, level, is_minion, is_leader, role, flag);

                                    List <CreaturePower> powers = new List <CreaturePower>();
                                    foreach (Creature c in list)
                                    {
                                        powers.AddRange(c.CreaturePowers);
                                    }
                                    if (powers.Count == 0)
                                    {
                                        continue;
                                    }

                                    string tier = "";
                                    if (level < 11)
                                    {
                                        tier = "heroic";
                                    }
                                    else if (level < 21)
                                    {
                                        tier = "paragon";
                                    }
                                    else
                                    {
                                        tier = "epic";
                                    }

                                    string tierx = "";
                                    if (level < 4)
                                    {
                                        tierx = "early heroic";
                                    }
                                    else if (level < 8)
                                    {
                                        tierx = "mid heroic";
                                    }
                                    else if (level < 11)
                                    {
                                        tierx = "late heroic";
                                    }
                                    else if (level < 14)
                                    {
                                        tierx = "early paragon";
                                    }
                                    else if (level < 18)
                                    {
                                        tierx = "mid paragon";
                                    }
                                    else if (level < 21)
                                    {
                                        tierx = "late paragon";
                                    }
                                    else if (level < 24)
                                    {
                                        tierx = "early epic";
                                    }
                                    else if (level < 28)
                                    {
                                        tierx = "mid epic";
                                    }
                                    else if (level < 31)
                                    {
                                        tierx = "late epic";
                                    }
                                    else
                                    {
                                        tierx = "epic plus";
                                    }

                                    sw.Write(level + "," + flag + "," + role + "," + is_minion + "," + is_leader + "," + tier + "," + tierx + "," + list.Count + "," + powers.Count);

                                    foreach (string condition in Conditions.GetConditions())
                                    {
                                        int count = 0;

                                        string str = condition.ToLower();
                                        foreach (CreaturePower power in powers)
                                        {
                                            if (power.Details.ToLower().Contains(str))
                                            {
                                                count += 1;
                                            }
                                        }

                                        double pc = 0;
                                        if (powers.Count != 0)
                                        {
                                            pc = (double)count / powers.Count;
                                        }

                                        sw.Write("," + pc);
                                    }

                                    foreach (DamageType damage in Enum.GetValues(typeof(DamageType)))
                                    {
                                        int count = 0;

                                        string str = damage.ToString().ToLower();
                                        foreach (CreaturePower power in powers)
                                        {
                                            if (power.Details.ToLower().Contains(str))
                                            {
                                                count += 1;
                                            }
                                        }

                                        double pc = 0;
                                        if (powers.Count != 0)
                                        {
                                            pc = (double)count / powers.Count;
                                        }

                                        sw.Write("," + pc);
                                    }

                                    sw.WriteLine();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogSystem.Trace(ex);
            }
            finally
            {
                sw.Close();
            }
        }
 protected override bool ExecCommand(StoryInstance instance, long delta)
 {
     GfxStorySystem.Instance.SendMessage("show_dlg", m_StoryDlgId.Value);
     LogSystem.Info("showdlg {0}", m_StoryDlgId.Value);
     return(false);
 }
 public void OneTimeSetup()
 {
     LogSystem.InstallDefaultReactors();
 }
Beispiel #11
0
 internal void LogError(LogSystem logSystem, Exception e)
 {
 }
 private void OnClosed()
 {
     LogSystem.Error("LobbyNetworkSystem.OnClosed");
 }
Beispiel #13
0
    public bool Execute(object sender, SkillInstance instance, long delta, long curSectionTime)
    {
        GfxSkillSenderInfo senderObj = sender as GfxSkillSenderInfo;

        if (null == senderObj)
        {
            return(false);
        }
        if (senderObj.ConfigData.type == (int)SkillOrImpactType.Skill)
        {
            return(false);//track只能在impact或buff里使用
        }
        GameObject obj = senderObj.GfxObj;

        if (null != obj)
        {
            if (curSectionTime >= m_TriggerProxy.StartTime)
            {
                if (!m_IsStarted)
                {
                    m_IsStarted = true;

                    Vector3 dest;
                    string  trackBone = m_TrackBone.Get(instance);
                    m_BoneTransform = Utility.FindChildRecursive(obj.transform, trackBone);
                    if (null != m_BoneTransform)
                    {
                        dest = m_BoneTransform.position;
                    }
                    else
                    {
                        dest    = obj.transform.position;
                        dest.y += 1.5f;
                        LogSystem.Warn("[skill:{0} dsl skill id:{1}] trackbullet bone {2} can't find.", senderObj.SkillId, instance.DslSkillId, trackBone);
                    }
                    m_StartPos = EntityController.Instance.GetImpactSenderPosition(senderObj.ObjId, senderObj.SkillId, senderObj.Seq);
                    object speedObj;
                    if (instance.Variables.TryGetValue("emitSpeed", out speedObj))
                    {
                        m_Speed = (float)speedObj;
                    }
                    else
                    {
                        return(false);
                    }
                    long duration = m_Duration.Get(instance);
                    m_Lifetime = duration / 1000.0f;
                    if (Geometry.DistanceSquare(m_StartPos.x, m_StartPos.z, dest.x, dest.z) > 0.01f)
                    {
                        m_TargetPos = Utility.FrontOfTarget(dest, m_StartPos, m_Speed * m_Lifetime);
                    }
                    else
                    {
                        m_TargetPos = obj.transform.TransformPoint(0, 0, m_Speed * m_Lifetime);
                    }

                    long newSectionDuration = m_TriggerProxy.StartTime + (long)(m_Lifetime * 1000);
                    if (instance.CurSectionDuration < newSectionDuration)
                    {
                        instance.SetCurSectionDuration(newSectionDuration);
                    }
                    Quaternion dir;
                    object     dirObj;
                    if (instance.Variables.TryGetValue("emitDir", out dirObj))
                    {
                        dir = (Quaternion)dirObj;
                    }
                    else
                    {
                        dir = Quaternion.identity;
                    }
                    Vector3 scale;
                    object  scaleObj;
                    if (instance.Variables.TryGetValue("emitScale", out scaleObj))
                    {
                        scale = (Vector3)scaleObj;
                    }
                    else
                    {
                        scale = Vector3.one;
                    }
                    Vector3    lookDir = dest - m_StartPos;
                    Quaternion q       = Quaternion.LookRotation(lookDir);
                    m_ControlPos = m_StartPos + Vector3.Scale(q * dir * Vector3.forward, scale * lookDir.magnitude * 0.5f);
                    string effectPath = SkillParamUtility.RefixResourceVariable("emitEffect", instance, senderObj.ConfigData.resources);
                    m_Effect = ResourceSystem.Instance.NewObject(effectPath, m_Lifetime) as GameObject;
                    if (null != m_Effect)
                    {
                        senderObj.TrackEffectObj = m_Effect;
                        TriggerUtil.SetObjVisible(m_Effect, true);
                        m_Effect.SetActive(false);
                        m_Effect.transform.position      = m_StartPos;
                        m_Effect.transform.localRotation = q;
                        m_Effect.SetActive(true);

                        EffectManager em = instance.CustomDatas.GetData <EffectManager>();
                        if (em == null)
                        {
                            em = new EffectManager();
                            instance.CustomDatas.AddData <EffectManager>(em);
                        }
                        em.AddEffect(m_Effect);
                        em.SetParticleSpeed(instance.EffectScale);
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(effectPath))
                        {
                            LogSystem.Warn("[skill:{0} dsl skill id:{1}] trackbullet effect is empty.", senderObj.SkillId, instance.DslSkillId);
                        }
                        else
                        {
                            LogSystem.Warn("[skill:{0} dsl skill id:{1}] trackbullet effect {2} can't find.", senderObj.SkillId, instance.DslSkillId, effectPath);
                        }
                    }
                }
                else if (null != m_Effect)
                {
                    Vector3 dest;
                    if (null != m_BoneTransform)
                    {
                        dest = m_BoneTransform.position;
                    }
                    else
                    {
                        dest    = obj.transform.position;
                        dest.y += 1.5f;
                    }
                    dest = Utility.FrontOfTarget(m_StartPos, dest, 0.1f);
                    //m_Effect.transform.position = Vector3.MoveTowards(m_Effect.transform.position, m_TargetPos, m_RealSpeed * Time.deltaTime);
                    m_Effect.transform.position = Utility.GetBezierPoint(m_StartPos, m_ControlPos, m_TargetPos, (curSectionTime - m_TriggerProxy.StartTime) / 1000.0f / m_Lifetime);
                    var pos = m_Effect.transform.position;
                    if (!m_IsHit)
                    {
                        float distSqr = float.MaxValue;
                        if (m_LastPos.sqrMagnitude > Geometry.c_FloatPrecision)
                        {
                            ScriptRuntime.Vector2 np;
                            ScriptRuntime.Vector2 targetPos = new ScriptRuntime.Vector2(dest.x, dest.z);
                            ScriptRuntime.Vector2 lastPos   = new ScriptRuntime.Vector2(m_LastPos.x, m_LastPos.z);
                            distSqr = Geometry.PointToLineSegmentDistanceSquare(targetPos, lastPos, new ScriptRuntime.Vector2(pos.x, pos.z), out np);
                        }
                        else
                        {
                            distSqr = (dest - pos).sqrMagnitude;
                        }
                        m_LastPos = pos;
                        if (distSqr <= m_BulletRadiusSquare)
                        {
                            float curTime  = Time.time;
                            float interval = m_DamageInterval.Get(instance) / 1000.0f;
                            if (m_LastTime + interval <= curTime)
                            {
                                m_LastTime = curTime;

                                m_HitEffectRotation = Quaternion.LookRotation(m_StartPos - dest);
                                int impactId = TriggerUtil.GetSkillImpactId(instance.Variables, senderObj.ConfigData);
                                Dictionary <string, object> args;
                                TriggerUtil.CalcImpactConfig(0, impactId, instance, senderObj.ConfigData, out args);
                                if (args.ContainsKey("hitEffectRotation"))
                                {
                                    args["hitEffectRotation"] = m_HitEffectRotation;
                                }
                                else
                                {
                                    args.Add("hitEffectRotation", m_HitEffectRotation);
                                }
                                EntityController.Instance.TrackSendImpact(senderObj.ObjId, senderObj.SkillId, senderObj.Seq, impactId, args);
                                //m_IsHit = true;
                            }
                        }
                    }
                    if (curSectionTime > m_TriggerProxy.StartTime + m_Lifetime * 1000)
                    {
                        m_Effect.SetActive(false);
                        ResourceSystem.Instance.RecycleObject(m_Effect);
                        m_Effect = null;
                        instance.StopCurSection();
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
                return(true);
            }
            else
            {
                return(true);
            }
        }
        else
        {
            instance.StopCurSection();
            return(false);
        }
    }
Beispiel #14
0
 void Start()
 {
     LogSystem.InstallDefaultReactors();
     Runnable.Run(CreateService());
     Debug.Log("Inicializando");
 }
Beispiel #15
0
        internal static TokenData GetAuthenticated(string tokenCode, string address, CommonParam param)
        {
            TokenData result = null;

            try
            {
                if (String.IsNullOrWhiteSpace(tokenCode) || String.IsNullOrWhiteSpace(address))
                {
                    return(null);
                }

                if (String.IsNullOrWhiteSpace(Config.BASE_URI))
                {
                    LogSystem.Warn("Khong co cau hinh dia chi AAS");
                    return(null);
                }

                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(Config.BASE_URI);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.Timeout = new TimeSpan(0, 0, Config.TIME_OUT);
                    client.DefaultRequestHeaders.Add(HttpHeaderConstant.TOKEN_PARAM, tokenCode);
                    client.DefaultRequestHeaders.Add(HttpHeaderConstant.ADDRESS_PARAM, address);

                    HttpResponseMessage respenseMessage = client.GetAsync(AAS.URI.AasToken.GET_AUTHENTICATED).Result;
                    LogSystem.Debug(string.Format("Request URI: {0}{1}", Config.BASE_URI, AAS.URI.AasToken.GET_AUTHENTICATED));
                    if (respenseMessage.IsSuccessStatusCode)
                    {
                        string responseData = respenseMessage.Content.ReadAsStringAsync().Result;
                        LogSystem.Debug(string.Format("Response data: {0}", responseData));
                        ApiResultObject <TokenData> data = JsonConvert.DeserializeObject <ApiResultObject <TokenData> >(responseData);
                        if (data != null && data.Data != null && data.Success)
                        {
                            result = data.Data;
                        }
                        else
                        {
                            LogSystem.Info(String.Format("Khong lay duoc TokenData. TokeCode = {0}, Address = {1}", tokenCode, address));
                            if (data.Param != null && data.Param.Messages != null && data.Param.Messages.Count > 0)
                            {
                                param.Messages.AddRange(data.Param.Messages);
                            }
                            if (data.Param != null && data.Param.BugCodes != null && data.Param.BugCodes.Count > 0)
                            {
                                param.BugCodes.AddRange(data.Param.BugCodes);
                            }
                        }
                    }
                    else
                    {
                        throw new Exception(string.Format("Loi khi goi API: {0}{1}. StatusCode: {2}", Config.BASE_URI, AAS.URI.AasToken.GET_AUTHENTICATED, respenseMessage.StatusCode.GetHashCode()));
                    }
                }
            }
            catch (Exception ex)
            {
                LogSystem.Error(ex);
                result = null;
            }
            return(result);
        }
Beispiel #16
0
    public void Recenter()
    {
        if (this.mScrollView == null)
        {
            this.mScrollView = NGUITools.FindInParents <UIScrollView>(base.gameObject);
            if (this.mScrollView == null)
            {
                LogSystem.LogWarning(new object[]
                {
                    base.GetType(),
                    " requires ",
                    typeof(UIScrollView),
                    " on a parent object in order to work",
                    this
                });
                base.enabled = false;
                return;
            }
            this.mScrollView.onDragFinished = new UIScrollView.OnDragFinished(this.OnDragFinished);
            if (this.mScrollView.horizontalScrollBar != null)
            {
                this.mScrollView.horizontalScrollBar.onDragFinished = new UIProgressBar.OnDragFinished(this.OnDragFinished);
            }
            if (this.mScrollView.verticalScrollBar != null)
            {
                this.mScrollView.verticalScrollBar.onDragFinished = new UIProgressBar.OnDragFinished(this.OnDragFinished);
            }
        }
        if (this.mScrollView.panel == null)
        {
            return;
        }
        Vector3[] worldCorners = this.mScrollView.panel.worldCorners;
        Vector3   vector       = (worldCorners[2] + worldCorners[0]) * 0.5f;
        Vector3   b            = vector - this.mScrollView.currentMomentum * (this.mScrollView.momentumAmount * 0.1f);

        this.mScrollView.currentMomentum = Vector3.zero;
        float     num        = 3.40282347E+38f;
        Transform target     = null;
        Transform transform  = base.transform;
        int       num2       = 0;
        int       i          = 0;
        int       childCount = transform.childCount;

        while (i < childCount)
        {
            Transform child = transform.GetChild(i);
            float     num3  = Vector3.SqrMagnitude(child.position - b);
            if (num3 < num)
            {
                num    = num3;
                target = child;
                num2   = i;
            }
            i++;
        }
        if (this.nextPageThreshold > 0f && UICamera.currentTouch != null && this.mCenteredObject != null && this.mCenteredObject.transform == transform.GetChild(num2))
        {
            Vector2 totalDelta             = UICamera.currentTouch.totalDelta;
            UIScrollView.Movement movement = this.mScrollView.movement;
            float num4;
            if (movement != UIScrollView.Movement.Horizontal)
            {
                if (movement != UIScrollView.Movement.Vertical)
                {
                    num4 = totalDelta.magnitude;
                }
                else
                {
                    num4 = totalDelta.y;
                }
            }
            else
            {
                num4 = totalDelta.x;
            }
            if (num4 > this.nextPageThreshold)
            {
                if (num2 > 0)
                {
                    target = transform.GetChild(num2 - 1);
                }
            }
            else if (num4 < -this.nextPageThreshold && num2 < transform.childCount - 1)
            {
                target = transform.GetChild(num2 + 1);
            }
        }
        this.CenterOn(target, vector);
    }
Beispiel #17
0
        public override IEnumerator RunTest()
        {
            LogSystem.InstallDefaultReactors();

            VcapCredentials vcapCredentials = new VcapCredentials();
            fsData          data            = null;

            string result = null;
            string credentialsFilepath = "../sdk-credentials/credentials.json";

            //  Load credentials file if it exists. If it doesn't exist, don't run the tests.
            if (File.Exists(credentialsFilepath))
            {
                result = File.ReadAllText(credentialsFilepath);
            }
            else
            {
                yield break;
            }

            //  Add in a parent object because Unity does not like to deserialize root level collection types.
            result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES");

            //  Convert json to fsResult
            fsResult r = fsJsonParser.Parse(result, out data);

            if (!r.Succeeded)
            {
                throw new WatsonException(r.FormattedMessages);
            }

            //  Convert fsResult to VcapCredentials
            object obj = vcapCredentials;

            r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
            if (!r.Succeeded)
            {
                throw new WatsonException(r.FormattedMessages);
            }

            //  Set credentials from imported credntials
            Credential credential = vcapCredentials.GetCredentialByname("visual-recognition-sdk")[0].Credentials;

            _apikey = credential.ApiKey.ToString();
            _url    = credential.Url.ToString();

            //  Create credential and instantiate service
            Credentials credentials = new Credentials(_apikey, _url);

            _visualRecognition             = new VisualRecognition(credentials);
            _visualRecognition.VersionDate = _visualRecognitionVersionDate;

            //          Get all classifiers
            Log.Debug("TestVisualRecognition.RunTest()", "Attempting to get all classifiers");
            if (!_visualRecognition.GetClassifiersBrief(OnGetClassifiers, OnFail))
            {
                Log.Debug("TestVisualRecognition.GetClassifiers()", "Failed to get all classifiers!");
            }

            while (!_getClassifiersTested)
            {
                yield return(null);
            }

#if TRAIN_CLASSIFIER
            _isClassifierReady = false;
            //          Train classifier
            Log.Debug("TestVisualRecognition.RunTest()", "Attempting to train classifier");
            string positiveExamplesPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/giraffe_positive_examples.zip";
            string negativeExamplesPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/negative_examples.zip";
            Dictionary <string, string> positiveExamples = new Dictionary <string, string>();
            positiveExamples.Add("giraffe", positiveExamplesPath);
            if (!_visualRecognition.TrainClassifier(OnTrainClassifier, OnFail, "unity-test-classifier-ok-to-delete", positiveExamples, negativeExamplesPath))
            {
                Log.Debug("TestVisualRecognition.TrainClassifier()", "Failed to train classifier!");
            }

            while (!_trainClassifierTested)
            {
                yield return(null);
            }

            //          Find classifier by ID
            Log.Debug("TestVisualRecognition.RunTest()", "Attempting to find classifier by ID");
            if (!_visualRecognition.GetClassifier(OnGetClassifier, OnFail, _classifierID))
            {
                Log.Debug("TestVisualRecognition.GetClassifier()", "Failed to get classifier!");
            }

            while (!_getClassifierTested)
            {
                yield return(null);
            }
#endif

            //  Classify get
            Log.Debug("TestVisualRecognition.RunTest()", "Attempting to get classify via URL");
            if (!_visualRecognition.Classify(_imageURL, OnClassifyGet, OnFail))
            {
                Log.Debug("TestVisualRecognition.Classify()", "Classify image failed!");
            }

            while (!_classifyGetTested)
            {
                yield return(null);
            }

            //  Classify post image
            Log.Debug("TestVisualRecognition.RunTest()", "Attempting to classify via image on file system");
            string   imagesPath    = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/giraffe_to_classify.jpg";
            string[] owners        = { "IBM", "me" };
            string[] classifierIDs = { "default", _classifierID };
            if (!_visualRecognition.Classify(OnClassifyPost, OnFail, imagesPath, owners, classifierIDs, 0.5f))
            {
                Log.Debug("TestVisualRecognition.Classify()", "Classify image failed!");
            }

            while (!_classifyPostTested)
            {
                yield return(null);
            }

            //  Detect faces get
            Log.Debug("TestVisualRecognition.RunTest()", "Attempting to detect faces via URL");
            if (!_visualRecognition.DetectFaces(_imageURL, OnDetectFacesGet, OnFail))
            {
                Log.Debug("TestVisualRecognition.DetectFaces()", "Detect faces failed!");
            }

            while (!_detectFacesGetTested)
            {
                yield return(null);
            }

            //  Detect faces post image
            Log.Debug("TestVisualRecognition.RunTest()", "Attempting to detect faces via image");
            string faceExamplePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/obama.jpg";
            if (!_visualRecognition.DetectFaces(OnDetectFacesPost, OnFail, faceExamplePath))
            {
                Log.Debug("TestVisualRecognition.DetectFaces()", "Detect faces failed!");
            }

            while (!_detectFacesPostTested)
            {
                yield return(null);
            }

#if DELETE_TRAINED_CLASSIFIER
            Runnable.Run(IsClassifierReady(_classifierToDelete));
            while (!_isClassifierReady)
            {
                yield return(null);
            }

            //  Download Core ML Model
            Log.Debug("TestVisualRecognition.RunTest()", "Attempting to get Core ML Model");
            if (!_visualRecognition.GetCoreMLModel(OnGetCoreMLModel, OnFail, _classifierID))
            {
                Log.Debug("TestVisualRecognition.GetCoreMLModel()", "Failed to get core ml model!");
            }
            while (!_getCoreMLModelTested)
            {
                yield return(null);
            }

            //  Delete classifier by ID
            Log.Debug("TestVisualRecognition.RunTest()", "Attempting to delete classifier");
            if (!_visualRecognition.DeleteClassifier(OnDeleteClassifier, OnFail, _classifierToDelete))
            {
                Log.Debug("TestVisualRecognition.DeleteClassifier()", "Failed to delete classifier!");
            }

            while (!_deleteClassifierTested)
            {
                yield return(null);
            }
#endif

            Log.Debug("TestVisualRecognition.RunTest()", "Visual Recogition tests complete");
            yield break;
        }
Beispiel #18
0
    void Start()
    {
        LogSystem.InstallDefaultReactors();

        ////	Get Voices
        //Log.Debug("ExampleTextToSpeech", "Attempting to get voices.");
        //m_TextToSpeech.GetVoices(OnGetVoices);

        ////	Get Voice
        ////string selectedVoice = "en-US_AllisonVoice";
        //Log.Debug("ExampleTextToSpeech", "Attempting to get voice {0}.", VoiceType.en_US_Allison);
        //m_TextToSpeech.GetVoice(OnGetVoice, VoiceType.en_US_Allison);

        ////	Get Pronunciation
        //string testWord = "Watson";
        //Log.Debug("ExampleTextToSpeech", "Attempting to get pronunciation of {0}", testWord);
        //m_TextToSpeech.GetPronunciation(OnGetPronunciation, testWord, VoiceType.en_US_Allison);

        // Get Customizations
        //Log.Debug("ExampleTextToSpeech", "Attempting to get a list of customizations");
        //m_TextToSpeech.GetCustomizations(OnGetCustomizations);

        //	Create Customization
        //Log.Debug("ExampleTextToSpeech", "Attempting to create a customization");
        //string customizationName = "unity-example-customization";
        //string customizationLanguage = "en-US";
        //string customizationDescription = "A text to speech voice customization created within Unity.";
        //m_TextToSpeech.CreateCustomization(OnCreateCustomization, customizationName, customizationLanguage, customizationDescription);

        //	Delete Customization
        //Log.Debug("ExampleTextToSpeech", "Attempting to delete a customization");
        //string customizationIdentifierToDelete = "1476ea80-5355-4911-ac99-ba39162a2d34";
        //if (!m_TextToSpeech.DeleteCustomization(OnDeleteCustomization, customizationIdentifierToDelete))
        //	Log.Debug("ExampleTextToSpeech", "Failed to delete custom voice model!");

        //	Get Customization
        //Log.Debug("ExampleTextToSpeech", "Attempting to get a customization");
        //string customizationIdentifierToGet = "1476ea80-5355-4911-ac99-ba39162a2d34";
        //if (!m_TextToSpeech.GetCustomization(OnGetCustomization, customizationIdentifierToGet))
        //	Log.Debug("ExampleTextToSpeech", "Failed to get custom voice model!");

        //	Update Customization
        Log.Debug("ExampleTextToSpeech", "Attempting to update a customization");
        Word word0 = new Word();

        word0.word        = "hello";
        word0.translation = "hullo";
        Word word1 = new Word();

        word1.word        = "goodbye";
        word1.translation = "gbye";
        Word word2 = new Word();

        word2.word        = "hi";
        word2.translation = "ohiooo";
        Word[]            words             = { word0, word1, word2 };
        CustomVoiceUpdate customVoiceUpdate = new CustomVoiceUpdate();

        customVoiceUpdate.words       = words;
        customVoiceUpdate.description = "My updated description";
        customVoiceUpdate.name        = "My updated name";
        string customizationIdToUpdate = "1476ea80-5355-4911-ac99-ba39162a2d34";

        if (!m_TextToSpeech.UpdateCustomization(OnUpdateCustomization, customizationIdToUpdate, customVoiceUpdate))
        {
            Log.Debug("ExampleTextToSpeech", "Failed to update customization!");
        }

        //	Get Customization Words
        //Log.Debug("ExampleTextToSpeech", "Attempting to get a customization's words");
        //string customIdentifierToGetWords = "1476ea80-5355-4911-ac99-ba39162a2d34";
        //if (!m_TextToSpeech.GetCustomizationWords(OnGetCustomizationWords, customIdentifierToGetWords))
        //	Log.Debug("ExampleTextToSpeech", "Failed to get {0} words!", customIdentifierToGetWords);

        //	Add Customization Words
        //Log.Debug("ExampleTextToSpeech", "Attempting to add words to a customization");
        //string customIdentifierToAddWords = "1476ea80-5355-4911-ac99-ba39162a2d34";
        //Words words = new Words();
        //Word word0 = new Word();
        //word0.word = "bananna";
        //word0.translation = "bunanna";
        //Word word1 = new Word();
        //word1.word = "orange";
        //word1.translation = "arange";
        //Word word2 = new Word();
        //word2.word = "tomato";
        //word2.translation = "tomahto";
        //Word[] wordArray = { word0, word1, word2 };
        //words.words = wordArray;
        //if (!m_TextToSpeech.AddCustomizationWords(OnAddCustomizationWords, customIdentifierToAddWords, words))
        //	Log.Debug("ExampleTextToSpeech", "Failed to add words to {0}!", customIdentifierToAddWords);

        //	Delete Customization Word
        //Log.Debug("ExampleTextToSpeech", "Attempting to delete customization word from custom voice model.");
        //string customIdentifierToDeleteWord = "1476ea80-5355-4911-ac99-ba39162a2d34";
        //string wordToDelete = "goodbye";
        //if (!m_TextToSpeech.DeleteCustomizationWord(OnDeleteCustomizationWord, customIdentifierToDeleteWord, wordToDelete))
        //	Log.Debug("ExampleTextToSpeech", "Failed to delete {0} from {1}!", wordToDelete, customIdentifierToDeleteWord);

        //	Get Customization Word
        //Log.Debug("ExampleTextToSpeech", "Attempting to get the translation of a custom voice model's word.");
        //string customIdentifierToGetWord = "1476ea80-5355-4911-ac99-ba39162a2d34";
        //string customIdentifierWord = "hello";
        //if (!m_TextToSpeech.GetCustomizationWord(OnGetCustomizationWord, customIdentifierToGetWord, customIdentifierWord))
        //	Log.Debug("ExampleTextToSpeech", "Failed to get the translation of {0} from {1}!", customIdentifierWord, customIdentifierToGetWord);

        //	Add Customization Word - This is not working. The PUT method is not supported by Unity.
        //Log.Debug("ExampleTextToSpeech", "Attempting to add a single word and translation to a custom voice model.");
        //string customIdentifierToAddWordAndTranslation = "1476ea80-5355-4911-ac99-ba39162a2d34";
        //string word = "grasshopper";
        //string translation = "guhrasshoppe";
        //if (!m_TextToSpeech.AddCustomizationWord(OnAddCustomizationWord, customIdentifierToAddWordAndTranslation, word, translation))
        //	Log.Debug("ExampleTextToSpeech", "Failed to add {0}/{1} to {2}!", word, translation, customIdentifierToAddWordAndTranslation);


        //m_TextToSpeech.Voice = VoiceType.en_US_Allison;
        //m_TextToSpeech.ToSpeech(m_TestString, HandleToSpeechCallback, true);
    }
	/// <summary> Initialize the Velocity logging system.
	/// *
	/// @throws Exception
	/// </summary>
	private void  initializeLogger() {
	    /*
	    * Initialize the logger. We will eventually move all
	    * logging into the logging manager.
	    */

	    if (logSystem is PrimordialLogSystem) {
		PrimordialLogSystem pls = (PrimordialLogSystem)logSystem;
		logSystem = LogManager.createLogSystem(this);

		/*
		* in the event of failure, lets do something to let it 
		* limp along.
		*/
		if (logSystem == null) {
		    logSystem = new NullLogSystem();
		} else {
		    pls.DumpLogMessages(logSystem);
		}
	    }
	}
Beispiel #20
0
 void Start()
 {
     LogSystem.InstallDefaultReactors();
     Runnable.Run(Example());
 }
        internal void Tick()
        {
            try {
                if (!m_IsWaitStart)
                {
                    long curTime = TimeUtility.GetLocalMilliseconds();

                    if (!IsConnected)
                    {
                        if (m_LastConnectTime + c_ConnectionTimeout < curTime)
                        {
                            LogSystem.Info("IsConnected == false. CurTime {0} LastConnectTime {1}", curTime, m_LastConnectTime);
                            Disconnect(true);//防止连接在稍后建立导致状态失效
                            ConnectIfNotOpen();
                        }
                    }
                    else
                    {
                        if (m_IsQueueing)  //排队过程
                        {
                            if (m_LastQueueingTime + c_GetQueueingCountInterval < curTime)
                            {
                                m_LastQueueingTime = curTime;

                                SendGetQueueingCount();
                            }
                            if (m_LastShowQueueingTime + c_ShowQueueingCountInterval < curTime && m_QueueingNum > 0)
                            {
                                m_LastShowQueueingTime = curTime;

                                ClientModule.Instance.HighlightPrompt("Tip_QueueingCount", m_QueueingNum);
                            }
                        }
                        else if (m_HasLoggedOn) //断线重连过程与正常游戏情形
                        {
                            if (m_IsLogining)   //登录中
                            {
                                if (m_LastConnectTime + c_LoginTimeout < curTime)
                                {
                                    LogSystem.Info("Login time out, disconnect and connect again. CurTime {0} LastConnectTime {1}", curTime, m_LastConnectTime);
                                    //断开连接
                                    if (IsConnected)
                                    {
                                        Disconnect();
                                    }
                                }
                            }
                            else
                            {
                                if (m_LastHeartbeatTime + c_PingInterval < curTime)
                                {
                                    m_LastHeartbeatTime = curTime;
                                    if (m_LastReceiveHeartbeatTime == 0)
                                    {
                                        m_LastReceiveHeartbeatTime = curTime;
                                    }
                                    SendHeartbeat();
                                }
                                if (m_LastReceiveHeartbeatTime > 0 && m_LastReceiveHeartbeatTime + c_PingTimeout < curTime)
                                {
                                    LogSystem.Info("Heartbeat time out, disconnect and connect again. CurTime {0} LastReceiveHeartbeatTime {1} LastHeartbeatTime {2} LastConnectTime {3}", curTime, m_LastReceiveHeartbeatTime, m_LastHeartbeatTime, m_LastConnectTime);
                                    //断开连接
                                    if (IsConnected)
                                    {
                                        Disconnect();
                                        m_LastReceiveHeartbeatTime        = 0;
                                        TimeUtility.LobbyLastResponseTime = 0;
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                LogSystem.Error("Exception:{0}\n{1}", e.Message, e.StackTrace);
            }
        }
 private void OnLog(string msg)
 {
     LogSystem.Info("LobbyNetworkSystem.OnLog:{0}", msg);
 }
 public void OneTimeSetup()
 {
     service = new LanguageTranslatorService("versionDate", authenticator);
     LogSystem.InstallDefaultReactors();
 }
 private void OnDataReceived(byte[] data)
 {
     LogSystem.Info("Receive Data Message:\n{0}", Helper.BinToHex(data));
 }
Beispiel #25
0
    /// <summary>
    /// 请求服务器
    /// </summary>
    /// <param name="www"></param>
    /// <returns></returns>
    private IEnumerator Request(WWW www, HttpSendPackage package)
    {
        LogSystem.Log(www.url);
        CallBackArgs args     = new CallBackArgs();
        float        timeOut  = Time.time;
        float        progress = www.progress;

        while (www != null && !www.isDone)
        {
            if (progress < www.progress)
            {
                timeOut  = Time.time;
                progress = www.progress;
            }

            if (Time.time - timeOut > TIME_OUT)
            {
                www.Dispose();
                AppDebug.LogWarning("HTTP超时");
                ++package.timeOutCount;
                if (package.timeOutCount >= MAX_TIME_OUT_COUNT)
                {
                    if (package.callBack != null)
                    {
                        args.HasError = true;
                        args.ErrorMsg = "请求超时";
                        package.callBack(args);
                    }
                }
                else
                {
                    if (package.isPost)
                    {
                        PostUrl(package);
                    }
                    else
                    {
                        GetUrl(package);
                    }
                }

                yield break;
            }
            yield return(null);
        }

        yield return(www);

        if (www.error == null)
        {
            AppDebug.Log(www.text);
            if (www.text.Equals("null", StringComparison.OrdinalIgnoreCase))
            {
                if (package.callBack != null)
                {
                    args.HasError = true;
                    args.ErrorMsg = "未请求到数据";
                    package.callBack(args);
                }
            }
            else
            {
                if (package.callBack != null)
                {
                    try
                    {
                        args.HasError = false;
                        LitJson.JsonData jsonData = LitJson.JsonMapper.ToObject(www.text);
                        args.Value = new Ret()
                        {
                            code = jsonData["code"].ToString().ToInt(),
                            data = jsonData["data"],
                            msg  = jsonData["msg"].ToString()
                        };
                    }
                    catch
                    {
                        AppDebug.Log(www.text);
                        args.HasError = true;
                        args.ErrorMsg = "数据异常";
                    }
                    finally
                    {
                        package.callBack(args);
                        if (args.Value != null && (args.Value.code == -91017 || args.Value.code == -91018))
                        {
                            if (OnTokenError != null)
                            {
                                OnTokenError(args);
                            }
                        }
                    }
                }
            }
        }
        else
        {
            if (package.callBack != null)
            {
                args.HasError = true;
                args.ErrorMsg = "网络异常";
                package.callBack(args);
            }
            AppDebug.Log("连接失败" + www.error);
        }
        www.Dispose();
    }
        public override IEnumerator RunTest()
        {
            LogSystem.InstallDefaultReactors();

            VcapCredentials vcapCredentials = new VcapCredentials();
            fsData          data            = null;

            string result = null;

            var vcapUrl      = Environment.GetEnvironmentVariable("VCAP_URL");
            var vcapUsername = Environment.GetEnvironmentVariable("VCAP_USERNAME");
            var vcapPassword = Environment.GetEnvironmentVariable("VCAP_PASSWORD");

            using (SimpleGet simpleGet = new SimpleGet(vcapUrl, vcapUsername, vcapPassword))
            {
                while (!simpleGet.IsComplete)
                {
                    yield return(null);
                }

                result = simpleGet.Result;
            }

            //  Add in a parent object because Unity does not like to deserialize root level collection types.
            result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES");

            //  Convert json to fsResult
            fsResult r = fsJsonParser.Parse(result, out data);

            if (!r.Succeeded)
            {
                throw new WatsonException(r.FormattedMessages);
            }

            //  Convert fsResult to VcapCredentials
            object obj = vcapCredentials;

            r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
            if (!r.Succeeded)
            {
                throw new WatsonException(r.FormattedMessages);
            }

            //  Set credentials from imported credntials
            Credential credential = vcapCredentials.VCAP_SERVICES["personality_insights"];

            _username = credential.Username.ToString();
            _password = credential.Password.ToString();
            _url      = credential.Url.ToString();

            //  Create credential and instantiate service
            Credentials credentials = new Credentials(_username, _password, _url);

            //  Or authenticate using token
            //Credentials credentials = new Credentials(_url)
            //{
            //    AuthenticationToken = _token
            //};

            _personalityInsights             = new PersonalityInsights(credentials);
            _personalityInsights.VersionDate = _personalityInsightsVersionDate;

            _dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json";

            if (!_personalityInsights.GetProfile(OnGetProfileJson, OnFail, _dataPath, ContentType.TextHtml, ContentLanguage.English, ContentType.ApplicationJson, AcceptLanguage.English, true, true, true))
            {
                Log.Debug("ExamplePersonalityInsights.GetProfile()", "Failed to get profile!");
            }
            while (!_getProfileJsonTested)
            {
                yield return(null);
            }

            if (!_personalityInsights.GetProfile(OnGetProfileText, OnFail, _testString, ContentType.TextHtml, ContentLanguage.English, ContentType.ApplicationJson, AcceptLanguage.English, true, true, true))
            {
                Log.Debug("ExamplePersonalityInsights.GetProfile()", "Failed to get profile!");
            }
            while (!_getProfileTextTested)
            {
                yield return(null);
            }

            Log.Debug("ExamplePersonalityInsights.RunTest()", "Personality insights examples complete.");

            yield break;
        }
Beispiel #27
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// 运行事件
        /// </summary>
        /// <param name=string.Empty></param>
        /// <returns></returns>
        /// -----------------------------------------------------------------------------
        public void Run()
        {
            if (m_Mode == TIMER_MODE.DELAYTIME)
            {
                if (Time.realtimeSinceStartup - m_StartTime > m_duration)
                {
                    if (this.m_TimerEvent != null && AsyncTrigger.IsTargetValid(this.m_TimerEvent.Target))
                    {
                        try
                        {
                            this.m_TimerEvent();
                        }
                        catch (System.Exception ex)
                        {
                            TimerManager.Destroy(this.m_Name);
                            LogSystem.LogError("Time event catch 1", ex.ToString());
                        }
                    }
                    else if (this.m_TimerArgsEvent != null && AsyncTrigger.IsTargetValid(this.m_TimerArgsEvent.Target))
                    {
                        try
                        {
                            this.m_TimerArgsEvent(m_Args);
                        }
                        catch (System.Exception ex)
                        {
                            TimerManager.Destroy(this.m_Name);
                            LogSystem.LogError("Time event catch 1", ex.ToString());
                        }
                    }
                    TimerManager.Destroy(this.m_Name);
                }
                return;
            }
            else if (m_Mode == TIMER_MODE.COUNTTIME)
            {
                float lastTime = Time.realtimeSinceStartup - m_time;
                if (lastTime > 1.0f)
                {
                    m_time = Time.realtimeSinceStartup;
                    try
                    {
                        if (this.m_TimerCountArgsEvent != null && AsyncTrigger.IsTargetValid(this.m_TimerCountArgsEvent.Target))
                        {
                            this.m_TimerCountArgsEvent(Mathf.CeilToInt(this.TimeLeft), m_Args);
                        }
                    }
                    catch (System.Exception ex)
                    {
                        TimerManager.Destroy(this.m_Name);
                        LogSystem.LogError("Time event catch2 ", ex.ToString());
                    }

                    if (this.TimeLeft <= 0f)
                    {
                        TimerManager.Destroy(this.m_Name);
                    }
                }
                return;
            }

            if (this.TimeLeft > 0.0f)
            {
                return;
            }

            try
            {
                if (this.m_TimerEvent != null && AsyncTrigger.IsTargetValid(this.m_TimerEvent.Target))
                {
                    this.m_TimerEvent();
                }

                if (this.m_TimerArgsEvent != null && AsyncTrigger.IsTargetValid(this.m_TimerArgsEvent.Target))
                {
                    this.m_TimerArgsEvent(m_Args);
                }
            }
            catch (System.Exception ex)
            {
                TimerManager.Destroy(this.m_Name);
                LogSystem.LogError("Time event catch3", ex.ToString());
            }

            if (m_Mode == TIMER_MODE.NORMAL)
            {
                Destroy(this.m_Name);
            }
            else
            {
                m_StartTime = Time.realtimeSinceStartup + this.TimeLeft;
            }
        }
        public override IEnumerator RunTest()
        {
            LogSystem.InstallDefaultReactors();

            try
            {
                VcapCredentials vcapCredentials = new VcapCredentials();
                fsData          data            = null;

                //  Get credentials from a credential file defined in environmental variables in the VCAP_SERVICES format.
                //  See https://www.ibm.com/watson/developercloud/doc/common/getting-started-variables.html.
                var environmentalVariable = Environment.GetEnvironmentVariable("VCAP_SERVICES");
                var fileContent           = File.ReadAllText(environmentalVariable);

                //  Add in a parent object because Unity does not like to deserialize root level collection types.
                fileContent = Utility.AddTopLevelObjectToJson(fileContent, "VCAP_SERVICES");

                //  Convert json to fsResult
                fsResult r = fsJsonParser.Parse(fileContent, out data);
                if (!r.Succeeded)
                {
                    throw new WatsonException(r.FormattedMessages);
                }

                //  Convert fsResult to VcapCredentials
                object obj = vcapCredentials;
                r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
                if (!r.Succeeded)
                {
                    throw new WatsonException(r.FormattedMessages);
                }

                //  Set credentials from imported credntials
                Credential credential = vcapCredentials.VCAP_SERVICES["tradeoff_analytics"][TestCredentialIndex].Credentials;
                _username = credential.Username.ToString();
                _password = credential.Password.ToString();
                _url      = credential.Url.ToString();
            }
            catch
            {
                Log.Debug("TestTradeoffAnalytics.RunTest()", "Failed to get credentials from VCAP_SERVICES file. Please configure credentials to run this test. For more information, see: https://github.com/watson-developer-cloud/unity-sdk/#authentication");
            }

            //  Create credential and instantiate service
            Credentials credentials = new Credentials(_username, _password, _url);

            //  Or authenticate using token
            //Credentials credentials = new Credentials(_url)
            //{
            //    AuthenticationToken = _token
            //};

            _tradeoffAnalytics = new TradeoffAnalytics(credentials);

            Problem problemToSolve = new Problem();

            problemToSolve.subject = "Test Subject";

            List <Column> listColumn  = new List <Column>();
            Column        columnPrice = new Column();

            columnPrice.description = "Price Column to minimize";
            columnPrice.range       = new ValueRange();
            ((ValueRange)columnPrice.range).high = 600;
            ((ValueRange)columnPrice.range).low  = 0;
            columnPrice.type         = "numeric";
            columnPrice.key          = "price";
            columnPrice.full_name    = "Price";
            columnPrice.goal         = "min";
            columnPrice.is_objective = true;
            columnPrice.format       = "$####0.00";

            Column columnWeight = new Column();

            columnWeight.description  = "Weight Column to minimize";
            columnWeight.type         = "numeric";
            columnWeight.key          = "weight";
            columnWeight.full_name    = "Weight";
            columnWeight.goal         = "min";
            columnWeight.is_objective = true;
            columnWeight.format       = "####0 g";

            Column columnBrandName = new Column();

            columnBrandName.description  = "All Brand Names";
            columnBrandName.type         = "categorical";
            columnBrandName.key          = "brand";
            columnBrandName.full_name    = "Brand";
            columnBrandName.goal         = "max";
            columnBrandName.is_objective = true;
            columnBrandName.preference   = new string[] { "Samsung", "Apple", "HTC" };
            columnBrandName.range        = new CategoricalRange();
            ((CategoricalRange)columnBrandName.range).keys = new string[] { "Samsung", "Apple", "HTC" };

            listColumn.Add(columnPrice);
            listColumn.Add(columnWeight);
            //            listColumn.Add(columnBrandName);

            problemToSolve.columns = listColumn.ToArray();


            List <Option> listOption = new List <Option>();

            Option option1 = new Option();

            option1.key    = "1";
            option1.name   = "Samsung Galaxy S4";
            option1.values = new TestDataValue();
            (option1.values as TestDataValue).weight = 130;
            (option1.values as TestDataValue).brand  = "Samsung";
            (option1.values as TestDataValue).price  = 249;
            listOption.Add(option1);

            Option option2 = new Option();

            option2.key    = "2";
            option2.name   = "Apple iPhone 5";
            option2.values = new TestDataValue();
            (option2.values as TestDataValue).weight = 112;
            (option2.values as TestDataValue).brand  = "Apple";
            (option2.values as TestDataValue).price  = 599;
            listOption.Add(option2);

            Option option3 = new Option();

            option3.key    = "3";
            option3.name   = "HTC One";
            option3.values = new TestDataValue();
            (option3.values as TestDataValue).weight = 143;
            (option3.values as TestDataValue).brand  = "HTC";
            (option3.values as TestDataValue).price  = 299;
            listOption.Add(option3);

            problemToSolve.options = listOption.ToArray();

            _tradeoffAnalytics.GetDilemma(OnGetDilemma, OnFail, problemToSolve, false);
            while (!_GetDillemaTested)
            {
                yield return(null);
            }

            Log.Debug("ExampleTradeoffAnalyitics.RunTest()", "Tradeoff analytics examples complete.");

            yield break;
        }
        private void OnRecvMessage()
        {
            try {
                m_NetClient.MessageReceivedEvent.WaitOne(1000);
                NetIncomingMessage im;
                while ((im = m_NetClient.ReadMessage()) != null)
                {
                    switch (im.MessageType)
                    {
                    case NetIncomingMessageType.DebugMessage:
                    case NetIncomingMessageType.VerboseDebugMessage:
                        LogSystem.Info("Debug Message: {0}", im.ReadString());
                        break;

                    case NetIncomingMessageType.ErrorMessage:
                        LogSystem.Info("Error Message: {0}", im.ReadString());
                        break;

                    case NetIncomingMessageType.WarningMessage:
                        LogSystem.Info("Warning Message: {0}", im.ReadString());
                        break;

                    case NetIncomingMessageType.StatusChanged:
                        NetConnectionStatus status = (NetConnectionStatus)im.ReadByte();
                        string reason = im.ReadString();
                        if (null != im.SenderConnection)
                        {
                            LogSystem.Info("Network Status Changed:{0} Reason:{1}\nStatistic:{2}", status, reason, im.SenderConnection.Statistics.ToString());
                            LogMessageCount();
                            if (NetConnectionStatus.Disconnected == status)
                            {
                                m_IsConnected    = false;
                                m_CanSendMessage = false;
                                if (reason.CompareTo("disconnect") == 0)
                                {
                                    if (!m_IsWaitStart)
                                    {
                                        m_IsWaitStart = true;
                                        m_NetClient.Disconnect("bye for disconnect");
                                        PluginFramework.Instance.QueueAction(this.OnRoomServerWaitStart);
                                    }
                                }
                            }
                            else if (NetConnectionStatus.Connected == status)
                            {
                                OnConnected(im.SenderConnection);
                            }
                        }
                        else
                        {
                            LogSystem.Info("Network Status Changed:{0} reason:{1}", status, reason);
                        }
                        break;

                    case NetIncomingMessageType.Data:
                    case NetIncomingMessageType.UnconnectedData:
                        if (!m_IsConnected && NetIncomingMessageType.Data == im.MessageType)
                        {
                            break;
                        }
                        try {
                            byte[] data = im.ReadBytes(im.LengthBytes);
                            int    id;
                            object msg = Serialize.Decode(data, out id);
                            if (msg != null)
                            {
                                PushMsg(id, msg, data.Length, im.SenderConnection);
                            }
                        } catch (Exception ex) {
                            LogSystem.Error("Decode Message exception:{0}\n{1}", ex.Message, ex.StackTrace);
                        }
                        break;

                    default:
                        break;
                    }
                    m_NetClient.Recycle(im);
                }
            } catch (Exception e) {
                LogSystem.Error("Exception:{0}\n{1}", e.Message, e.StackTrace);
            }
        }
        public override bool Execute(object sender, SkillInstance instance, long delta, long curSectionTime)
        {
            GfxSkillSenderInfo senderObj = sender as GfxSkillSenderInfo;

            if (null == senderObj)
            {
                return(false);
            }
            if (senderObj.ConfigData.type == (int)SkillOrImpactType.Skill)
            {
                return(false);//track只能在impact或buff里使用
            }
            GameObject obj = senderObj.GfxObj;

            if (null != obj)
            {
                if (curSectionTime >= StartTime)
                {
                    if (!m_IsStarted)
                    {
                        m_IsStarted = true;
                        Vector3 dest;
                        string  trackBone = m_TrackBone.Get(instance);
                        m_BoneTransform = Utility.FindChildRecursive(obj.transform, trackBone);
                        if (null != m_BoneTransform)
                        {
                            dest = m_BoneTransform.position;
                        }
                        else
                        {
                            dest    = obj.transform.position;
                            dest.y += 1.5f;
                            LogSystem.Warn("[skill:{0} dsl skill id:{1}] track bone {2} can't find.", senderObj.SkillId, instance.DslSkillId, trackBone);
                        }
                        m_StartPos = EntityController.Instance.GetImpactSenderPosition(senderObj.ActorId, senderObj.SkillId, senderObj.Seq);
                        dest       = Utility.FrontOfTarget(m_StartPos, dest, 0.1f);
                        object speedObj;
                        if (instance.Variables.TryGetValue("emitSpeed", out speedObj))
                        {
                            m_Speed = (float)speedObj;
                        }
                        else
                        {
                            return(false);
                        }
                        float duration = m_Duration.Get(instance);
                        if (duration > Geometry.c_FloatPrecision)
                        {
                            float d = duration / 1000.0f;
                            m_Lifetime = d;
                            m_Speed    = (dest - m_StartPos).magnitude / m_Lifetime;
                        }
                        else
                        {
                            m_Lifetime = 1.0f;
                            if (m_Speed > Geometry.c_FloatPrecision)
                            {
                                m_Lifetime = (dest - m_StartPos).magnitude / m_Speed;
                            }
                        }
                        long newSectionDuration = StartTime + (long)(m_Lifetime * 1000);
                        if (instance.CurSectionDuration < newSectionDuration)
                        {
                            instance.SetCurSectionDuration(newSectionDuration);
                        }
                        Quaternion dir;
                        object     dirObj;
                        if (instance.Variables.TryGetValue("emitDir", out dirObj))
                        {
                            dir = (Quaternion)dirObj;
                        }
                        else
                        {
                            dir = Quaternion.identity;
                        }
                        Vector3 scale;
                        object  scaleObj;
                        if (instance.Variables.TryGetValue("emitScale", out scaleObj))
                        {
                            scale = (Vector3)scaleObj;
                        }
                        else
                        {
                            scale = Vector3.one;
                        }
                        Vector3    lookDir = dest - m_StartPos;
                        Quaternion q       = Quaternion.LookRotation(lookDir);
                        m_ControlPos = m_StartPos + Vector3.Scale(q * dir * Vector3.forward, scale * lookDir.magnitude * 0.5f);
                        string effectPath = SkillParamUtility.RefixResourceVariable("emitEffect", instance, senderObj.ConfigData.resources);
                        m_Effect = ResourceSystem.Instance.NewObject(effectPath, m_Lifetime) as GameObject;
                        if (null != m_Effect)
                        {
                            senderObj.TrackEffectObj = m_Effect;
                            TriggerUtil.SetObjVisible(m_Effect, true);
                            m_Effect.SetActive(false);
                            m_Effect.transform.position      = m_StartPos;
                            m_Effect.transform.localRotation = q;
                            m_Effect.SetActive(true);
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(effectPath))
                            {
                                LogSystem.Warn("[skill:{0} dsl skill id:{1}] track effect is empty.", senderObj.SkillId, instance.DslSkillId);
                            }
                            else
                            {
                                LogSystem.Warn("[skill:{0} dsl skill id:{1}] track effect {2} can't find.", senderObj.SkillId, instance.DslSkillId, effectPath);
                            }
                        }
                    }
                    else if (null != m_Effect)
                    {
                        if (!m_NotMove && !m_IsHit)
                        {
                            Vector3 dest;
                            if (null != m_BoneTransform)
                            {
                                dest = m_BoneTransform.position;
                            }
                            else
                            {
                                dest    = obj.transform.position;
                                dest.y += 1.5f;
                            }
                            dest = Utility.FrontOfTarget(m_StartPos, dest, 0.1f);
                            //m_Effect.transform.position = Vector3.MoveTowards(m_Effect.transform.position, dest, m_RealSpeed * Time.deltaTime);
                            m_Effect.transform.position = Utility.GetBezierPoint(m_StartPos, m_ControlPos, dest, (curSectionTime - StartTime) / 1000.0f / m_Lifetime);
                            if ((dest - m_Effect.transform.position).sqrMagnitude <= 0.01f)
                            {
                                m_HitEffectRotation = Quaternion.LookRotation(m_StartPos - dest);
                                if (m_NoImpact)
                                {
                                    instance.SetVariable("hitEffectRotation", m_HitEffectRotation);
                                }
                                else
                                {
                                    int impactId = EntityController.Instance.GetTrackSendImpact(senderObj.ActorId, senderObj.Seq, instance.Variables);
                                    Dictionary <string, object> args;
                                    TriggerUtil.CalcImpactConfig(0, impactId, instance, senderObj.ConfigData, out args);
                                    if (args.ContainsKey("hitEffectRotation"))
                                    {
                                        args["hitEffectRotation"] = m_HitEffectRotation;
                                    }
                                    else
                                    {
                                        args.Add("hitEffectRotation", m_HitEffectRotation);
                                    }
                                    EntityController.Instance.TrackSendImpact(senderObj.ActorId, senderObj.SkillId, senderObj.Seq, impactId, args);
                                    int senderId, targetId;
                                    EntityController.Instance.CalcSenderAndTarget(senderObj, out senderId, out targetId);
                                }
                                m_IsHit = true;
                            }
                        }
                        if (curSectionTime > StartTime + m_Lifetime * 1000)
                        {
                            m_Effect.SetActive(false);
                            ResourceSystem.Instance.RecycleObject(m_Effect);
                            m_Effect = null;
                            instance.StopCurSection();
                            return(false);
                        }
                    }
                    else
                    {
                        return(false);
                    }

                    //GameFramework.LogSystem.Debug("EmitEffectTriger:{0}", m_EffectPath);
                    return(true);
                }
                else
                {
                    return(true);
                }
            }
            else
            {
                instance.StopCurSection();
                return(false);
            }
        }
Beispiel #31
0
 public Result(LogSystem LogOfGame)
 {
     data = LogOfGame.getLogList();
     calculateRoundScores();
 }
Beispiel #32
0
 void Start()
 {
     LogSystem.InstallDefaultReactors();
     Runnable.Run(CreateService());
 }
Beispiel #33
0
 void Start()
 {
     _as = GetComponent <AudioSource>();
     LogSystem.InstallDefaultReactors();
     Runnable.Run(ServiceCreator());
 }
Beispiel #34
0
        public override IEnumerator RunTest()
        {
            LogSystem.InstallDefaultReactors();

            m_ConfigurationJsonPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/Discovery/exampleConfigurationData.json";
            m_FilePathToIngest      = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/watson_beats_jeopardy.html";
            m_DocumentFilePath      = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/watson_beats_jeopardy.html";

            #region Get Environments and Add Environment
            //  Get Environments
            Log.Debug("ExampleDiscoveryV1", "Attempting to get environments");
            if (!m_Discovery.GetEnvironments((GetEnvironmentsResponse resp, string data) =>
            {
                if (resp != null)
                {
                    foreach (Environment environment in resp.environments)
                    {
                        Log.Debug("ExampleDiscoveryV1", "environment_id: {0}", environment.environment_id);
                    }
                }
                else
                {
                    Log.Debug("ExampleDiscoveryV1", "Discovery.GetEnvironments(); resp is null");
                }

                Test(resp.environments != null);
                m_GetEnvironmentsTested = true;
            }))
            {
                Log.Debug("ExampleDiscoveryV1", "Failed to get environments");
            }

            while (!m_GetEnvironmentsTested)
            {
                yield return(null);
            }

            //  Add Environment
            Log.Debug("ExampleDiscoveryV1", "Attempting to add environment");
            if (!m_Discovery.AddEnvironment((Environment resp, string data) =>
            {
                if (resp != null)
                {
                    Log.Debug("ExampleDiscoveryV1", "Added {0}", resp.environment_id);
                    m_CreatedEnvironmentID = resp.environment_id;
                }
                else
                {
                    Log.Debug("ExampleDiscoveryV1", "Discovery.AddEnvironment(); resp is null, {0}", data);
                }

                Test(!string.IsNullOrEmpty(resp.environment_id));
                m_AddEnvironmentsTested = true;
            }, m_CreatedEnvironmentName, m_CreatedEnvironmentDescription, 1))
            {
                Log.Debug("ExampleDiscoveryV1", "Failed to add environment");
            }

            while (!m_AddEnvironmentsTested)
            {
                yield return(null);
            }

            //  Check for active environment
            Runnable.Run(CheckEnvironmentStatus());
            while (!m_IsEnvironmentActive)
            {
                yield return(null);
            }
            #endregion

            #region Get Configurations and add Configuration
            //  Get Configurations
            Log.Debug("ExampleDiscoveryV1", "Attempting to get configurations");
            if (!m_Discovery.GetConfigurations((GetConfigurationsResponse resp, string data) =>
            {
                if (resp != null)
                {
                    if (resp.configurations != null && resp.configurations.Length > 0)
                    {
                        foreach (ConfigurationRef configuration in resp.configurations)
                        {
                            Log.Debug("ExampleDiscoveryV1", "Configuration: {0}, {1}", configuration.configuration_id, configuration.name);
                        }
                    }
                    else
                    {
                        Log.Debug("ExampleDiscoveryV1", "There are no configurations for this environment.");
                    }
                }
                else
                {
                    Log.Debug("ExampleDiscoveryV1", "Discovery.GetConfigurations(); resp is null, {0}", data);
                }

                Test(resp.configurations != null);
                m_GetConfigurationsTested = true;
            }, m_CreatedEnvironmentID))
            {
                Log.Debug("ExampleDiscoveryV1", "Failed to get configurations");
            }

            while (!m_GetConfigurationsTested)
            {
                yield return(null);
            }

            //  Add Configuration
            Log.Debug("ExampleDiscoveryV1", "Attempting to add configuration");
            if (!m_Discovery.AddConfiguration((Configuration resp, string data) =>
            {
                if (resp != null)
                {
                    Log.Debug("ExampleDiscoveryV1", "Configuration: {0}, {1}", resp.configuration_id, resp.name);
                    m_CreatedConfigurationID = resp.configuration_id;
                }
                else
                {
                    Log.Debug("ExampleDiscoveryV1", "Discovery.AddConfiguration(); resp is null, {0}", data);
                }

                Test(!string.IsNullOrEmpty(resp.configuration_id));
                m_AddConfigurationTested = true;
            }, m_CreatedEnvironmentID, m_ConfigurationJsonPath))
            {
                Log.Debug("ExampleDiscoveryV1", "Failed to add configuration");
            }

            while (!m_AddConfigurationTested)
            {
                yield return(null);
            }
            #endregion

            #region GetCollections and Add Collection
            //  Get Collections
            Log.Debug("ExampleDiscoveryV1", "Attempting to get collections");
            if (!m_Discovery.GetCollections((GetCollectionsResponse resp, string customData) =>
            {
                if (resp != null)
                {
                    if (resp.collections != null && resp.collections.Length > 0)
                    {
                        foreach (CollectionRef collection in resp.collections)
                        {
                            Log.Debug("ExampleDiscoveryV1", "Collection: {0}, {1}", collection.collection_id, collection.name);
                        }
                    }
                    else
                    {
                        Log.Debug("ExampleDiscoveryV1", "There are no collections");
                    }
                }
                else
                {
                    Log.Debug("ExampleDiscoveryV1", "Discovery.GetCollections(); resp is null");
                }

                Test(resp != null);
                m_GetCollectionsTested = true;
            }, m_CreatedEnvironmentID))
            {
                Log.Debug("ExampleDiscovery", "Failed to get collections");
            }

            while (!m_GetCollectionsTested)
            {
                yield return(null);
            }

            //  Add Collection
            Log.Debug("ExampleDiscoveryV1", "Attempting to add collection");
            if (!m_Discovery.AddCollection((CollectionRef resp, string data) =>
            {
                if (resp != null)
                {
                    Log.Debug("ExampleDiscoveryV1", "Collection: {0}, {1}", resp.collection_id, resp.name);
                    m_CreatedCollectionID = resp.collection_id;
                }
                else
                {
                    Log.Debug("ExampleDiscoveryV1", "Discovery.AddCollection(); resp is null, {0}", data);
                }

                Test(!string.IsNullOrEmpty(resp.collection_id));
                m_AddCollectionTested = true;
            }, m_CreatedEnvironmentID, m_CreatedCollectionName, m_CreatedCollectionDescription, m_CreatedConfigurationID))
            {
                Log.Debug("ExampleDiscovery", "Failed to add collection");
            }

            while (!m_AddCollectionTested)
            {
                yield return(null);
            }
            #endregion

            #region Get Fields
            Log.Debug("ExampleDiscoveryV1", "Attempting to get fields");
            if (!m_Discovery.GetFields((GetFieldsResponse resp, string customData) =>
            {
                if (resp != null)
                {
                    foreach (Field field in resp.fields)
                    {
                        Log.Debug("ExampleDiscoveryV1", "Field: {0}, type: {1}", field.field, field.type);
                    }
                }
                else
                {
                    Log.Debug("ExampleDiscoveryV1", "Discovery.GetFields(); resp is null");
                }

                Test(resp != null);
                m_GetFieldsTested = true;
            }, m_CreatedEnvironmentID, m_CreatedCollectionID))
            {
                Log.Debug("ExampleDiscoveryV1", "Failed to get fields");
            }

            while (!m_GetFieldsTested)
            {
                yield return(null);
            }
            #endregion

            #region Add Document
            //  Add Document
            Log.Debug("ExampleDiscoveryV1", "Attempting to add document");
            if (!m_Discovery.AddDocument((DocumentAccepted resp, string data) =>
            {
                if (resp != null)
                {
                    Log.Debug("ExampleDiscoveryV1", "Added Document {0} {1}", resp.document_id, resp.status);
                    m_CreatedDocumentID = resp.document_id;
                }
                else
                {
                    Log.Debug("ExampleDiscoveryV1", "Discovery.AddDocument(); resp is null, {0}", data);
                }

                Test(!string.IsNullOrEmpty(resp.document_id));
                m_AddDocumentTested = true;
            }, m_CreatedEnvironmentID, m_CreatedCollectionID, m_DocumentFilePath, m_CreatedConfigurationID, null))
            {
                Log.Debug("ExampleDiscovery", "Failed to add document");
            }

            while (!m_AddDocumentTested)
            {
                yield return(null);
            }
            #endregion

            #region Query
            //  Query
            Log.Debug("ExampleDiscoveryV1", "Attempting to query");
            if (!m_Discovery.Query((QueryResponse resp, string data) =>
            {
                if (resp != null)
                {
                    Log.Debug("ExampleDiscoveryV1", resp.ToString());
                }
                else
                {
                    Log.Debug("ExampleDiscoveryV1", "resp is null, {0}", data);
                }

                Test(resp != null);
                m_QueryTested = true;
            }, m_CreatedEnvironmentID, m_CreatedCollectionID, null, m_Query, null, 10, null, 0))
            {
                Log.Debug("ExampleDiscovery", "Failed to query");
            }

            while (!m_QueryTested)
            {
                yield return(null);
            }
            #endregion

            #region Document
            //  Get Document
            Log.Debug("ExampleDiscoveryV1", "Attempting to get document");
            if (!m_Discovery.GetDocument((DocumentStatus resp, string data) =>
            {
                if (resp != null)
                {
                    Log.Debug("ExampleDiscoveryV1", "Got Document {0} {1}", resp.document_id, resp.status);
                }
                else
                {
                    Log.Debug("ExampleDiscoveryV1", "Discovery.GetDocument(); resp is null, {0}", data);
                }

                Test(!string.IsNullOrEmpty(resp.status));
                m_GetDocumentTested = true;
            }, m_CreatedEnvironmentID, m_CreatedCollectionID, m_CreatedDocumentID))
            {
                Log.Debug("ExampleDiscovery", "Failed to get document");
            }

            while (!m_GetDocumentTested)
            {
                yield return(null);
            }

            //  Update Document
            Log.Debug("ExampleDiscoveryV1", "Attempting to update document");
            if (!m_Discovery.UpdateDocument((DocumentAccepted resp, string data) =>
            {
                if (resp != null)
                {
                    Log.Debug("ExampleDiscoveryV1", "Updated Document {0} {1}", resp.document_id, resp.status);
                }
                else
                {
                    Log.Debug("ExampleDiscoveryV1", "Discovery.UpdateDocument(); resp is null, {0}", data);
                }

                Test(!string.IsNullOrEmpty(resp.status));
                m_UpdateDocumentTested = true;
            }, m_CreatedEnvironmentID, m_CreatedCollectionID, m_CreatedDocumentID, m_DocumentFilePath, m_CreatedConfigurationID, null))
            {
                Log.Debug("ExampleDiscovery", "Failed to update document");
            }

            while (!m_UpdateDocumentTested)
            {
                yield return(null);
            }

            //  Delete Document
            Runnable.Run(DeleteDocument());

            while (!m_DeleteDocumentTested)
            {
                yield return(null);
            }
            #endregion

            #region Collection
            //  Get Collection
            Log.Debug("ExampleDiscoveryV1", "Attempting to get collection");
            if (!m_Discovery.GetCollection((Collection resp, string data) =>
            {
                if (resp != null)
                {
                    Log.Debug("ExampleDiscoveryV1", "Collection: {0}, {1}", resp.collection_id, resp.name);
                }
                else
                {
                    Log.Debug("ExampleDiscoveryV1", "Failed to get collections");
                }

                Test(!string.IsNullOrEmpty(resp.name));
                m_GetCollectionTested = true;
            }, m_CreatedEnvironmentID, m_CreatedCollectionID))
            {
                Log.Debug("ExampleDiscovery", "Failed to get collection");
            }

            while (!m_GetCollectionTested)
            {
                yield return(null);
            }

            //  Delete Collection
            Runnable.Run(DeleteCollection());
            while (!m_DeleteCollectionTested)
            {
                yield return(null);
            }
            #endregion

            #region Configuration
            //  Get Configuration
            Log.Debug("ExampleDiscoveryV1", "Attempting to get configuration");
            if (!m_Discovery.GetConfiguration((Configuration resp, string data) =>
            {
                if (resp != null)
                {
                    Log.Debug("ExampleDiscoveryV1", "Configuration: {0}, {1}", resp.configuration_id, resp.name);
                }
                else
                {
                    Log.Debug("ExampleDiscoveryV1", "Discovery.GetConfiguration(); resp is null, {0}", data);
                }

                Test(!string.IsNullOrEmpty(resp.name));
                m_GetConfigurationTested = true;
            }, m_CreatedEnvironmentID, m_CreatedConfigurationID))
            {
                Log.Debug("ExampleDiscoveryV1", "Failed to get configuration");
            }

            while (!m_GetConfigurationTested)
            {
                yield return(null);
            }

            //  Preview Configuration
            Log.Debug("ExampleDiscoveryV1", "Attempting to preview configuration");
            if (!m_Discovery.PreviewConfiguration((TestDocument resp, string data) =>
            {
                if (resp != null)
                {
                    Log.Debug("ExampleDiscoveryV1", "Preview succeeded: {0}", resp.status);
                }
                else
                {
                    Log.Debug("ExampleDiscoveryV1", "Discovery.PreviewConfiguration(); resp is null {0}", data);
                }

                Test(resp != null);
                m_PreviewConfigurationTested = true;
            }, m_CreatedEnvironmentID, m_CreatedConfigurationID, null, m_FilePathToIngest, m_Metadata))
            {
                Log.Debug("ExampleDiscoveryV1", "Failed to preview configuration");
            }

            while (!m_PreviewConfigurationTested)
            {
                yield return(null);
            }

            //  Delete Configuration
            Runnable.Run(DeleteConfiguration());
            while (!m_DeleteConfigurationTested)
            {
                yield return(null);
            }
            #endregion

            #region Environment
            //  Get Environment
            Log.Debug("ExampleDiscoveryV1", "Attempting to get environment");
            if (!m_Discovery.GetEnvironment((Environment resp, string data) =>
            {
                if (resp != null)
                {
                    Log.Debug("ExampleDiscoveryV1", "environment_name: {0}", resp.name);
                }
                else
                {
                    Log.Debug("ExampleDiscoveryV1", "Discovery.GetEnvironment(); resp is null");
                }

                Test(!string.IsNullOrEmpty(resp.name));
                m_GetEnvironmentTested = true;
            }, m_CreatedEnvironmentID))
            {
                Log.Debug("ExampleDiscoveryV1", "Failed to get environment");
            }

            while (!m_GetEnvironmentTested)
            {
                yield return(null);
            }

            //  Delete Environment
            Runnable.Run(DeleteEnvironment());

            while (!m_DeleteEnvironmentTested)
            {
                yield return(null);
            }
            #endregion

            yield break;
        }
Beispiel #35
0
    void Start()
    {
        LogSystem.InstallDefaultReactors();

        ////          Get all classifiers
        //Log.Debug("ExampleVisualRecognition", "Attempting to get all classifiers");
        //if (!m_VisualRecognition.GetClassifiers(OnGetClassifiers))
        //    Log.Debug("ExampleVisualRecognition", "Getting classifiers failed!");

        ////          Find classifier by name
        //Log.Debug("ExampleVisualRecognition", "Attempting to find classifier by name");
        //m_VisualRecognition.FindClassifier(OnFindClassifier, m_classifierName);

        ////          Find classifier by ID
        //Log.Debug("ExampleVisualRecognition", "Attempting to find classifier by ID");
        //if (!m_VisualRecognition.GetClassifier(OnGetClassifier, m_classifierID))
        //    Log.Debug("ExampleVisualRecognition", "Getting classifier failed!");

        ////          Delete classifier by ID
        //Log.Debug("ExampleVisualRecognition", "Attempting to delete classifier");
        //if (!m_VisualRecognition.DeleteClassifier(OnDeleteClassifier, m_classifierToDelete))
        //    Log.Debug("ExampleVisualRecognition", "Deleting classifier failed!");

        ////          Train classifier
        //Log.Debug("ExampleVisualRecognition", "Attempting to train classifier");
        //string positiveExamplesPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/giraffe_positive_examples.zip";
        //string negativeExamplesPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/negative_examples.zip";
        //Dictionary<string, string> positiveExamples = new Dictionary<string, string>();
        //positiveExamples.Add("giraffe", positiveExamplesPath);
        //if (!m_VisualRecognition.TrainClassifier(OnTrainClassifier, "unity-test-classifier-example", positiveExamples, negativeExamplesPath))
        //    Log.Debug("ExampleVisualRecognition", "Train classifier failed!");

        ////          Classify get
        //Log.Debug("ExampleVisualRecognition", "Attempting to get classify via URL");
        //if (!m_VisualRecognition.Classify(OnClassify, m_imageURL))
        //    Log.Debug("ExampleVisualRecognition", "Classify image failed!");

        ////          Classify post image
        Log.Debug("ExampleVisualRecognition", "Attempting to classify via image on file system");
        string imagesPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/giraffe_to_classify.jpg";

        string[] owners        = { "IBM", "me" };
        string[] classifierIDs = { "default", m_classifierID };
        if (!m_VisualRecognition.Classify(imagesPath, OnClassify, owners, classifierIDs, 0.5f))
        {
            Log.Debug("ExampleVisualRecognition", "Classify image failed!");
        }

        ////          Detect faces get
        //Log.Debug("ExampleVisualRecognition", "Attempting to detect faces via URL");
        //if (!m_VisualRecognition.DetectFaces(OnDetectFaces, m_imageURL))
        //    Log.Debug("ExampleVisualRecogntiion", "Detect faces failed!");

        ////          Detect faces post image
        //Log.Debug("ExampleVisualRecognition", "Attempting to detect faces via image");
        //string faceExamplePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/obama.jpg";
        //if (!m_VisualRecognition.DetectFaces(faceExamplePath, OnDetectFaces))
        //    Log.Debug("ExampleVisualRecognition", "Detect faces failed!");

        ////          Recognize text get
        //Log.Debug("ExampleVisualRecognition", "Attempting to recognizeText via URL");
        //if (!m_VisualRecognition.RecognizeText(OnRecognizeText, m_imageTextURL))
        //    Log.Debug("ExampleVisualRecognition", "Recognize text failed!");

        ////          Recognize text post image
        //Log.Debug("ExampleVisualRecognition", "Attempting to recognizeText via image");
        //string textExamplePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/from_platos_apology.png";
        //if (!m_VisualRecognition.RecognizeText(textExamplePath, OnRecognizeText))
        //    Log.Debug("ExampleVisualRecognition", "Recognize text failed!");
    }
    // Update is called once per frame
    void Update()
    {
        NormalGoal.getPercentageReachedBananas(playerStats);
        if (!worldSpawner.goalReached)worldSpawner.setGoalReached(NormalGoal.isGoalReached(playerStats));
        if (worldSpawner.endTileReached)
        {
            if (NormalGoal.nextLevel())
            {
                if (wait15Sec())
                {
                    Application.LoadLevel(1);

                }
                else
                {
                    if (playerStats.roundBananaRatio() >= 0) displayNumber = 0;
                    if (playerStats.roundBananaRatio() > 10) displayNumber = 1;
                    if (playerStats.roundBananaRatio() > 20) displayNumber = 2;
                    if (playerStats.roundBananaRatio() > 30) displayNumber = 3;
                    if (playerStats.roundBananaRatio() > 40) displayNumber = 4;
                    Destroy(GameObject.Find("HUD"));
                    NormalGoal.rounds++;
                    fullScreen.guiTexture.texture = BetweenScreens[displayNumber];
                    // display wait round screen
                }

            }
            else
            {
                if (wait15Sec())
                {

                    Destroy(GameObject.Find("KinectPointMan"));
                    Destroy(GameObject.Find("KinectPrefab"));
                    Destroy(GameObject.Find("GameSettings"));
                    Application.LoadLevel(0);
                }
                else
                {
                    NormalGoal.rounds++;
                    if (!madeResults)
                    {
                        fullScreen.guiTexture.texture = goodScreen;
                        log = worldSpawner.log;
                        Result results = new Result(log);
                        int c = 0;
                        int[] ratios = new int[results.amountOfRounds*2];
                        foreach (RoundScore r in results.rounds)
                        {
                            ratios[(c * 2)] = r.getPickupRatio();
                            ratios[(c * 2) + 1] = r.getObstacleAvoidedRatio();
                            c++;
                        }
                        madeResults = true;
                        this.gameObject.GetComponent<mono_gmail>().mailStart(ratios,results.rounds[0].getStartTime(),results.totalAmountOfBananas(),results.totalAmountOfFeathers(),results.GetMostHitObstacle());

                    }
                    else
                    {
                        if (playerStats.roundBananaRatio() >= 0) displayNumber = 0;
                        if (playerStats.roundBananaRatio() > 10) displayNumber = 1;
                        if (playerStats.roundBananaRatio() > 20) displayNumber = 2;
                        if (playerStats.roundBananaRatio() > 30) displayNumber = 3;
                        if (playerStats.roundBananaRatio() > 40) displayNumber = 4;
                        Destroy(GameObject.Find("HUD"));
                        fullScreen.guiTexture.texture = EndScreens[displayNumber];
                        // goed gedaan screen
                    }
                }
            }

        }
    }
 void Start()
 {
     LogSystem.InstallDefaultReactors();
     Runnable.Run(CreateAuthenticateServices());
     _assistantStatus = EProcessingStatus.Idle;
 }
 void Start()
 {
     log = GameObject.Find("LogSys(Clone)").GetComponent<LogSystem>();
 }
Beispiel #39
0
 private void Start()
 {
     LogSystem.InstallDefaultReactors();
 }
Beispiel #40
0
    public static void Log(object message)
    {
#if DEBUG_LOG
        LogSystem.Log(message.ToString());
#endif
    }
 void Start()
 {
     log = GameObject.Find("LogSys(Clone)").GetComponent<LogSystem>();
     funnie = GameObject.Find ("ParrotContainer").GetComponent<FunnieMovementScript>();
 }