public BuildShelterActivity(Person actor, NeedEntry needEntry, EngineSettings settings, ConsoleHelper console)
     : base(actor, needEntry, settings, console)
 {
     // TODO
     //WoodFelling = new FellWoodActivity ();
     //TimberMilling = new MillTimberActivity ();
 }
        public BaseActivity(Person actor, NeedEntry needEntry, EngineSettings settings, ConsoleHelper console)
        {
            Actor = actor;
            NeedEntry = needEntry;
            Settings = settings;
            Console = console;

            InitializeItemsProduced ();
            InitializeItemsConsumed ();
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            //STEP 1: Download dataset
            DownloadDataset(originalDataDirectoryPath);

            //Step 2: Prepare data by adding second column with value total number of features.
            PrepareDataset(originalDataPath, preparedDataPath);

            MLContext mlContext = new MLContext();

            //STEP 3: Common data loading configuration
            var fullDataView = mlContext.Data.LoadFromTextFile <UrlData>(path: Path.Combine(preparedDataPath, "*"),
                                                                         hasHeader: false,
                                                                         allowSparse: true);

            //Step 4: Divide the whole dataset into 80% training and 20% testing data.
            TrainTestData trainTestData = mlContext.Data.TrainTestSplit(fullDataView, testFraction: 0.2, seed: 1);
            IDataView     trainDataView = trainTestData.TrainSet;
            IDataView     testDataView  = trainTestData.TestSet;

            //Step 5: Map label value from string to bool
            var UrlLabelMap = new Dictionary <string, bool>();

            UrlLabelMap["+1"] = true;  //Malicious url
            UrlLabelMap["-1"] = false; //Benign
            var dataProcessingPipeLine = mlContext.Transforms.Conversion.MapValue("LabelKey", UrlLabelMap, "LabelColumn");

            ConsoleHelper.PeekDataViewInConsole(mlContext, trainDataView, dataProcessingPipeLine, 2);

            //Step 6: Append trainer to pipeline
            var trainingPipeLine = dataProcessingPipeLine.Append(
                mlContext.BinaryClassification.Trainers.FieldAwareFactorizationMachine(labelColumnName: "LabelKey", featureColumnName: "FeatureVector"));

            //Step 7: Train the model
            Console.WriteLine("====Training the model=====");
            var mlModel = trainingPipeLine.Fit(trainDataView);

            Console.WriteLine("====Completed Training the model=====");
            Console.WriteLine("");

            //Step 8: Evaluate the model
            Console.WriteLine("====Evaluating the model=====");
            var predictions = mlModel.Transform(testDataView);
            var metrics     = mlContext.BinaryClassification.Evaluate(data: predictions, labelColumnName: "LabelKey", scoreColumnName: "Score");

            ConsoleHelper.PrintBinaryClassificationMetrics(mlModel.ToString(), metrics);

            // Try a single prediction
            Console.WriteLine("====Predicting sample data=====");
            var predEngine = mlContext.Model.CreatePredictionEngine <UrlData, UrlPrediction>(mlModel);
            // Create sample data to do a single prediction with it
            var sampleDatas = CreateSingleDataSample(mlContext, trainDataView);

            foreach (var sampleData in sampleDatas)
            {
                UrlPrediction predictionResult = predEngine.Predict(sampleData);
                Console.WriteLine($"Single Prediction --> Actual value: {sampleData.LabelColumn} | Predicted value: {predictionResult.Prediction}");
            }
            Console.WriteLine("====End of Process..Press any key to exit====");
            Console.ReadLine();
        }
Beispiel #4
0
    static async Task Main()
    {
        Console.Title = "Samples.ServiceControl.RabbitMQAdapter.Shipping";

        #region ShippingConfiguration

        var endpointConfiguration = new EndpointConfiguration("Samples.ServiceControl.RabbitMQAdapter.Shipping");

        var transport = endpointConfiguration.UseTransport <RabbitMQTransport>();
        transport.ConnectionString("host=localhost");
        transport.DelayedDelivery().DisableTimeoutManager();

        transport.UseDirectRoutingTopology();

        endpointConfiguration.SendFailedMessagesTo("adapter_error");
        endpointConfiguration.AuditProcessedMessagesTo("adapter_audit");
        endpointConfiguration.SendHeartbeatTo("adapter_Particular.ServiceControl");

        #endregion

        endpointConfiguration.UsePersistence <InMemoryPersistence>();

        var chaos = new ChaosGenerator();
        endpointConfiguration.RegisterComponents(
            registration: components =>
        {
            components.ConfigureComponent(() => chaos, DependencyLifecycle.SingleInstance);
        });

        var recoverability = endpointConfiguration.Recoverability();
        recoverability.Immediate(
            customizations: immediate =>
        {
            immediate.NumberOfRetries(0);
        });
        recoverability.Delayed(
            customizations: delayed =>
        {
            delayed.NumberOfRetries(0);
        });
        recoverability.DisableLegacyRetriesSatellite();
        endpointConfiguration.EnableInstallers();

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        Console.WriteLine("Press enter to exit");
        Console.WriteLine("Press 'f' to toggle simulating of message processing failure");
        while (true)
        {
            var key = Console.ReadKey();
            Console.WriteLine();
            if (key.Key == ConsoleKey.Enter)
            {
                break;
            }
            var lowerInvariant = char.ToLowerInvariant(key.KeyChar);
            if (lowerInvariant == 'f')
            {
                chaos.IsFailing = !chaos.IsFailing;
                Console.WriteLine($"Failure simulation is now turned {(chaos.IsFailing ? "on" : "off")}");
                ConsoleHelper.ToggleTitle();
            }
        }
        await endpointInstance.Stop()
        .ConfigureAwait(false);
    }
 private void Afficher()
 {
     ConsoleHelper.AfficherEntete("Afficher les Participants");
     this.liste = MethodesParticipant.GetParticipants();
     ConsoleHelper.AfficherListe(this.liste, strategieAffichageParticipants);
 }
Beispiel #6
0
 private static void Client_OnPrivateMessage(PrivateMessage msg)
 {
     ConsoleHelper.WriteLine("收到私信:{0}", msg.Content);
 }
 public DrinkWaterNeedIdentifier(EngineSettings settings, ConsoleHelper console)
     : base(ActivityVerb.Drink, ItemType.Water, PersonVitalType.Thirst, settings, console)
 {
 }
 public PersonEnergyEffect(EngineSettings settings, ConsoleHelper console)
     : base(settings, console)
 {
 }
Beispiel #9
0
        public override int Execute(string[] args)
        {
            // sanity check
            if (args.Length != 2)
            {
                throw new ArgumentException("incorrect number of arguments");
            }

            Progress.Message = "Searching";
            string filePattern = args[1];
            string root        = Directory.GetCurrentDirectory();

            IO.CheckRootAndPattern(ref root, ref filePattern);
            List <string> files = IO.GetAllFiles(root, filePattern);

            ConsoleHelper.DebugWriteLine("pattern: " + filePattern);
            ConsoleHelper.DebugWriteLine("root: " + root);
            if (files.Count == 0)
            {
                throw new FileNotFoundException("unable to find any files that match pattern: \"" + filePattern + "\" in root: \"" + root + "\"");
            }

            int counter = 0;

            foreach (string file in files)
            {
                try
                {
                    Progress.Message = "ReIndenting " + IO.GetFilename(file);

                    switch (IO.GetFileExtension(file).ToLower())
                    {
                    case "vb":
                        counter++;

                        var lines    = IO.ReadFileLines(file);
                        var newlines = new List <string>();

                        int  level        = 0;
                        bool linecontinue = false;
                        //bool levelup = false;
                        bool meta            = false;
                        bool metaContinue    = false;
                        int  linenumber      = 0;
                        int  lastIndentLevel = 0;

                        foreach (string line in lines)
                        {
                            linenumber++;
                            string newline = line.TrimWhiteSpace();

                            // clean string
                            string temp = StringHelper.Remove(line, new List <string> {
                                "Private", "Protected", "Public", "Shared", "Overridable", "Overrides", "Overloads", "Friend", "ReadOnly", "WriteOnly", "Partial", "Shadows", "Default", "NotInheritable"
                            });
                            temp = temp.TrimWhiteSpace();

                            // trim meta tags
                            meta = false;
                            if (temp.StartsWith("<"))
                            {
                                if (temp.Contains(">"))
                                {
                                    meta = true;
                                    temp = temp.Substring(temp.IndexOf('>') + 1);
                                }
                                else if (temp.EndsWith("_"))
                                {
                                    temp         = temp.Substring(temp.IndexOf('_'));
                                    metaContinue = false;
                                }
                                else
                                {
                                    ConsoleHelper.DebugWriteLine("invalid meta tag in code : " + file);
                                }
                            }
                            else if (metaContinue)
                            {
                                if (temp.Contains(">"))
                                {
                                    meta         = true;
                                    metaContinue = false;
                                    temp         = temp.Substring(temp.IndexOf('>') + 1);
                                }
                                else
                                {
                                    temp = "";
                                }
                            }

                            // trim comments
                            if (temp.Contains("'"))
                            {
                                temp = temp.Substring(0, temp.IndexOf('\''));
                            }

                            temp = temp.TrimWhiteSpace();

                            string firstword = StringHelper.FirstWord(temp);
                            string lastword  = StringHelper.LastWord(temp);

                            if (!string.IsNullOrEmpty(firstword) && firstword[0] != '\'')
                            {
                                // ******************** Level Down Before Print *************************** //
                                // single level
                                if (StringHelper.StartsWith(temp, new List <string>()
                                {
                                    "Loop", "Next", "End", "End If", "ElseIf", "#End If", "#ElseIf", "#Else", "Catch", "Finally", "End Try", "End Select", "End Sub", "End Function", "End Enum", "Case"
                                }) ||
                                    (firstword == "Else" && !temp.StartsWith("Else :")))
                                {
                                    level--;
                                }

                                // double level
                                if (StringHelper.StartsWith(temp, new List <string>()
                                {
                                    "End Select"
                                }))
                                {
                                    level--;
                                }

                                // ******************** correction for line continuation *************************** //
                                int correction = level;
                                //correction -= ((linecontinue) ? 1 : 0);
                                //correction -= ((linecontinue & !levelup) ? 1 : 0);
                                if (level + correction < 0)
                                {
                                    if (temp != "#End Region")
                                    {
                                        ConsoleHelper.DebugWriteLine("invalid vb code : " + IO.GetFilename(file));
                                        //ConsoleHelper.DebugWriteLine("file: " + file);
                                        ConsoleHelper.DebugWriteLine("temp: " + temp);
                                        ConsoleHelper.DebugWriteLine("line: " + linenumber.ToString());
                                    }
                                }

                                // ******************** Print Line *************************** //
                                lastIndentLevel = correction;
                                if (correction < 0)
                                {
                                    correction = 0;
                                }
                                newlines.Add(new String('\t', correction) + (linecontinue ? new String(' ', 2) : "") + newline);

                                linecontinue = StringHelper.EndsWith(temp, new List <string>()
                                {
                                    "_"
                                }) & !meta;

                                // ******************** Level Up after line *************************** //
                                if (StringHelper.EndsWith(temp, new List <string>()
                                {
                                    "Then", "Else", "#ElseIf", "#Else"
                                }) ||
                                    StringHelper.StartsWith(temp, new List <string>()
                                {
                                    "Namespace", "Class", "Structure", "Function", "Property", "Operator", "Enum", "Sub", "Module", "SyncLock", "Select Case", "Case", "For", "For Each", "Do", "Do While", "While", "Try", "Catch", "Finally", "With", "Custom Event"
                                }) ||
                                    temp.StartsWith("AddHandler(") || temp.StartsWith("RemoveHandler(") || temp.StartsWith("RaiseEvent(") ||
                                    (firstword == "Get") || (firstword == "Set"))
                                {
                                    level++;
                                    //levelup = true;
                                }
                                else
                                {
                                    //if (!linecontinue) levelup = false;
                                }

                                // double level
                                if (StringHelper.StartsWith(temp, new List <string>()
                                {
                                    "Select Case"
                                }))
                                {
                                    level++;
                                }
                            }
                            else
                            {
                                if (newline.StartsWith("'"))
                                {
                                    if (level < 0)
                                    {
                                        level = 0;
                                    }
                                    newlines.Add(new String('\t', level) + newline);
                                }
                                else
                                {
                                    newlines.Add(newline);
                                }
                            }
                        }

                        if (lastIndentLevel != 0)
                        {
                            IO.WriteFileLines(file + ".error", newlines);
                            throw new Exception("failed to indent " + IO.GetFilename(file));
                        }

                        IO.WriteFileLines(file, newlines);

                        break;

                    default:
                        break;
                    }
                }
                catch (Exception ex)
                {
                    ConsoleHelper.WriteException(ex);
                }
            }

            ConsoleHelper.WriteLine(counter.ToString() + " File" + ((counter != 1) ? "s" : "") + " Checked", ConsoleColor.DarkYellow);
            return(ConsoleHelper.EXIT_OK);
        }
 public override void Execute(List <string> _params, CommandSenderInfo _senderInfo)
 {
     try
     {
         if (_params.Count < 1 && _params.Count > 3)
         {
             SdtdConsole.Instance.Output(string.Format("Wrong number of arguments, expected 1 to 3, found {0}", _params.Count));
             return;
         }
         if (_params[0].ToLower().Equals("off"))
         {
             if (Bounties.IsEnabled)
             {
                 Bounties.IsEnabled = false;
                 LoadConfig.WriteXml();
                 SdtdConsole.Instance.Output(string.Format("Bounties has been set to off"));
                 return;
             }
             else
             {
                 SdtdConsole.Instance.Output(string.Format("Bounties is already off"));
                 return;
             }
         }
         else if (_params[0].ToLower().Equals("on"))
         {
             if (!Bounties.IsEnabled)
             {
                 Bounties.IsEnabled = true;
                 LoadConfig.WriteXml();
                 SdtdConsole.Instance.Output(string.Format("Bounties has been set to on"));
                 return;
             }
             else
             {
                 SdtdConsole.Instance.Output(string.Format("Bounties is already on"));
                 return;
             }
         }
         else if (_params[0].ToLower().Equals("edit"))
         {
             if (_params.Count != 3)
             {
                 SdtdConsole.Instance.Output(string.Format("Wrong number of arguments, expected 3, found {0}", _params.Count));
                 return;
             }
             int _value;
             if (!int.TryParse(_params[2], out _value))
             {
                 SdtdConsole.Instance.Output(string.Format("Must input a valid interger: {0}", _params[2]));
                 return;
             }
             ClientInfo _cInfo = ConsoleHelper.ParseParamIdOrName(_params[1]);
             if (_cInfo != null)
             {
                 Bounties.ConsoleEdit(_cInfo.playerId, _value);
             }
             else
             {
                 SdtdConsole.Instance.Output(string.Format("No player found online with id or name: {0}. Checking steam id", _params[1]));
                 if (_params[1].Length != 17)
                 {
                     SdtdConsole.Instance.Output(string.Format("Can not edit: Invalid steam id {0}", _params[1]));
                     return;
                 }
                 Bounties.ConsoleEdit(_params[1], _value);
             }
         }
         else if (_params[0].ToLower().Equals("remove"))
         {
             if (_params.Count != 2)
             {
                 SdtdConsole.Instance.Output(string.Format("Wrong number of arguments, expected 2, found {0}", _params.Count));
                 return;
             }
             ClientInfo _cInfo = ConsoleHelper.ParseParamIdOrName(_params[1]);
             if (_cInfo != null)
             {
                 Bounties.ConsoleRemoveBounty(_cInfo.playerId);
             }
             else
             {
                 SdtdConsole.Instance.Output(string.Format("No player found online with id or name: {0}. Checking steam id", _params[1]));
                 if (_params[1].Length != 17)
                 {
                     SdtdConsole.Instance.Output(string.Format("Can not remove: Invalid steam id {0}", _params[1]));
                     return;
                 }
                 Bounties.ConsoleRemoveBounty(_params[1]);
             }
         }
         else if (_params[0].ToLower().Equals("list"))
         {
             if (_params.Count != 1)
             {
                 SdtdConsole.Instance.Output(string.Format("Wrong number of arguments, expected 1, found {0}", _params.Count));
                 return;
             }
             Bounties.ConsoleBountyList();
         }
         else
         {
             SdtdConsole.Instance.Output(string.Format("Invalid argument {0}", _params[0]));
         }
     }
     catch (Exception e)
     {
         Log.Out(string.Format("[SERVERTOOLS] Error in BountiesConsole.Execute: {0}", e.Message));
     }
 }
Beispiel #11
0
 public ThirstEffect(EngineSettings settings, ConsoleHelper console)
     : base(settings, console)
 {
 }
 public CollectWaterActivity(Person actor, NeedEntry needEntry, EngineSettings settings, ConsoleHelper console)
     : base(actor, needEntry, settings, console)
 {
 }
 public ActivityCreator(EngineSettings settings, ConsoleHelper console)
 {
     Settings = settings;
     Console = console;
 }
Beispiel #14
0
        /// <summary>
        /// Displays a menu of options after each post
        /// until the user exits the loop.
        /// </summary>
        public void LoopDisplay()
        {
            if (Posts.Count == 0)
            {
                VisiblePostIndex = 0;
            }

            else
            {
                for (VisiblePostIndex = 0; VisiblePostIndex <= Posts.Count; VisiblePostIndex++)
                {
                    ExitLoop = false;

                    //Console.Clear();

                    RepeatFinalPost();

                    if (VisiblePost < Posts.Count - 1)
                    {
                        ShowPost();
                    }

                    ShowRedAlert();

                    ShowBlueAlert();

                    ResetAlertValues();

                    Console.WriteLine();

                    string[] choices = new string[]
                    {
                        " [1] Like ", "  [3] Remove this post", "  [5] Comment \n",
                        " [2] Unlike ", "[4] Remove all posts ", " [6] Next post ",
                        "[7] Main Menu"
                    };

                    int choice = ConsoleHelper.SelectChoice2(choices);

                    switch (choice)
                    {
                    case 1:
                        LikePost(Posts[VisiblePostIndex]);

                        VisiblePostIndex--;

                        break;

                    case 2:
                        UnlikePost(Posts[VisiblePostIndex]);

                        VisiblePostIndex--;

                        break;

                    case 3:
                        RemovePost();

                        VisiblePostIndex--;

                        break;

                    case 4:
                        RemoveAllPosts();

                        break;

                    case 5:
                        AddComment(Posts[VisiblePostIndex]);

                        VisiblePostIndex--;

                        break;

                    case 6:
                        ShowNextPost();

                        break;

                    case 7:
                        Console.Clear();

                        ExitLoop = true;

                        break;

                    default:
                        break;
                    }

                    if (ExitLoop && NoPosts)
                    {
                        VisiblePost = 0;

                        BlueAlert = "\n    -- All posts removed --\n";

                        Console.WriteLine();

                        break;
                    }

                    else

                    {
                        if (ExitLoop)
                        {
                            VisiblePost = 0;

                            Console.WriteLine();

                            break;
                        }
                    }
                }
            }
        }
Beispiel #15
0
 public static void Main(String[] args)
 {
     ConsoleHelper.SetConsoleFont(5);
     Calculating();
 }
 public StarvationEffect(EngineSettings settings, ConsoleHelper console)
     : base(settings, console)
 {
 }
Beispiel #17
0
        public BaseActivity(Person actor, NeedEntry needEntry, EngineSettings settings, ConsoleHelper console)
        {
            Actor     = actor;
            NeedEntry = needEntry;
            Settings  = settings;
            Console   = console;

            InitializeItemsProduced();
            InitializeItemsConsumed();
        }
 public override void Execute(List <string> _params, CommandSenderInfo _senderInfo)
 {
     try
     {
         if (_params[0].ToLower().Equals("add"))
         {
             if (_params.Count != 2)
             {
                 SdtdConsole.Instance.Output(string.Format("Wrong number of arguments, expected 2, found {0}.", _params.Count));
                 return;
             }
             ClientInfo _cInfo = ConsoleHelper.ParseParamIdOrName(_params[1]);
             if (_cInfo != null)
             {
                 bool _highPingImmune = PersistentContainer.Instance.Players[_cInfo.playerId].HighPingImmune;
                 if (_highPingImmune)
                 {
                     SdtdConsole.Instance.Output(string.Format("Can not add Id. {0} is already in the Ping Immunity list.", _params[1]));
                 }
                 else
                 {
                     PersistentContainer.Instance.Players[_cInfo.playerId].HighPingImmune = true;
                     PersistentContainer.Instance.Save();
                     SdtdConsole.Instance.Output(string.Format("Added Id {0} to the Ping Immunity list.", _params[1]));
                 }
             }
             else
             {
                 if (_params[1].Length != 17)
                 {
                     SdtdConsole.Instance.Output(string.Format("Player must be online or when offline use their steam Id which must be 17 numbers in length. Can not add Id: {0}", _params[1]));
                     return;
                 }
                 else
                 {
                     PersistentPlayer p = PersistentContainer.Instance.Players[_params[1]];
                     {
                         if (p != null)
                         {
                             bool _highPingImmune = PersistentContainer.Instance.Players[_params[1]].HighPingImmune;
                             if (_highPingImmune)
                             {
                                 SdtdConsole.Instance.Output(string.Format("Can not add Id. {0} is already in the Ping Immunity list.", _params[1]));
                             }
                             else
                             {
                                 PersistentContainer.Instance.Players[_params[1]].HighPingImmune = true;
                                 PersistentContainer.Instance.Save();
                                 SdtdConsole.Instance.Output(string.Format("Added Id {0} to the Ping Immunity list.", _params[1]));
                             }
                         }
                     }
                 }
             }
         }
         else if (_params[0].ToLower().Equals("remove"))
         {
             if (_params.Count != 2)
             {
                 SdtdConsole.Instance.Output(string.Format("Wrong number of arguments, expected 2, found {0}", _params.Count));
                 return;
             }
             if (_params[1].Length != 17)
             {
                 SdtdConsole.Instance.Output(string.Format("Player must be online or when offline use their steam Id which must be 17 numbers in length. Can not add Id: {0}", _params[1]));
                 return;
             }
             else
             {
                 PersistentPlayer p = PersistentContainer.Instance.Players[_params[1]];
                 {
                     if (p != null)
                     {
                         bool _highPingImmune = PersistentContainer.Instance.Players[_params[1]].HighPingImmune;
                         if (_highPingImmune)
                         {
                             SdtdConsole.Instance.Output(string.Format("Can not remove Id. {0} is not in the Ping Immunity list.", _params[1]));
                         }
                         else
                         {
                             PersistentContainer.Instance.Players[_params[1]].HighPingImmune = true;
                             PersistentContainer.Instance.Save();
                             SdtdConsole.Instance.Output(string.Format("Removed Id {0} from the Ping Immunity list.", _params[1]));
                         }
                     }
                 }
             }
         }
         else if (_params[0].ToLower().Equals("list"))
         {
             if (_params.Count != 1)
             {
                 SdtdConsole.Instance.Output(string.Format("Wrong number of arguments, expected 1, found {0}.", _params.Count));
                 return;
             }
             else
             {
                 if (HighPingKicker.Dict.Count == 0)
                 {
                     SdtdConsole.Instance.Output("There are no players on the Ping Immunity list.");
                     return;
                 }
                 else
                 {
                     SdtdConsole.Instance.Output("High Ping Immunity List");
                     foreach (KeyValuePair <string, string> _c in HighPingKicker.Dict)
                     {
                         SdtdConsole.Instance.Output(string.Format("Player Id: {0} with name {1}", _c.Key, _c.Value));
                     }
                 }
             }
         }
         else
         {
             SdtdConsole.Instance.Output(string.Format("Invalid argument {0}.", _params[0]));
         }
     }
     catch (Exception e)
     {
         Log.Out(string.Format("[SERVERTOOLS] Error in PingImmunityCommandConsole.Run: {0}.", e));
     }
 }
 public void Execute(CommandContext context)
 {
     File.Delete(context.AppConfigFilePath);
     ConsoleHelper.PrintMsg("配置重置成功!");
 }
Beispiel #20
0
 public HungerEffect(EngineSettings settings, ConsoleHelper console)
     : base(settings, console)
 {
 }
Beispiel #21
0
        /// <summary>
        /// Run example
        /// </summary>
        /// <a href="http://en.wikipedia.org/wiki/Geometric_distribution">Geometric distribution</a>
        public void Run()
        {
            // 1. Initialize the new instance of the Geometric distribution class with parameter P = 0.2
            var geometric = new Geometric(0.2);

            Console.WriteLine(@"1. Initialize the new instance of the Geometric distribution class with parameter P = {0}", geometric.P);
            Console.WriteLine();

            // 2. Distributuion properties:
            Console.WriteLine(@"2. {0} distributuion properties:", geometric);

            // Cumulative distribution function
            Console.WriteLine(@"{0} - Сumulative distribution at location '3'", geometric.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000"));

            // Probability density
            Console.WriteLine(@"{0} - Probability mass at location '3'", geometric.Probability(3).ToString(" #0.00000;-#0.00000"));

            // Log probability density
            Console.WriteLine(@"{0} - Log probability mass at location '3'", geometric.ProbabilityLn(3).ToString(" #0.00000;-#0.00000"));

            // Entropy
            Console.WriteLine(@"{0} - Entropy", geometric.Entropy.ToString(" #0.00000;-#0.00000"));

            // Largest element in the domain
            Console.WriteLine(@"{0} - Largest element in the domain", geometric.Maximum.ToString(" #0.00000;-#0.00000"));

            // Smallest element in the domain
            Console.WriteLine(@"{0} - Smallest element in the domain", geometric.Minimum.ToString(" #0.00000;-#0.00000"));

            // Mean
            Console.WriteLine(@"{0} - Mean", geometric.Mean.ToString(" #0.00000;-#0.00000"));

            // Median
            Console.WriteLine(@"{0} - Median", geometric.Median.ToString(" #0.00000;-#0.00000"));

            // Mode
            Console.WriteLine(@"{0} - Mode", geometric.Mode.ToString(" #0.00000;-#0.00000"));

            // Variance
            Console.WriteLine(@"{0} - Variance", geometric.Variance.ToString(" #0.00000;-#0.00000"));

            // Standard deviation
            Console.WriteLine(@"{0} - Standard deviation", geometric.StdDev.ToString(" #0.00000;-#0.00000"));

            // Skewness
            Console.WriteLine(@"{0} - Skewness", geometric.Skewness.ToString(" #0.00000;-#0.00000"));
            Console.WriteLine();

            // 3. Generate 10 samples of the Geometric distribution
            Console.WriteLine(@"3. Generate 10 samples of the Geometric distribution");
            for (var i = 0; i < 10; i++)
            {
                Console.Write(geometric.Sample().ToString("N05") + @" ");
            }

            Console.WriteLine();
            Console.WriteLine();

            // 4. Generate 100000 samples of the Geometric(0.2, 20) distribution and display histogram
            Console.WriteLine(@"4. Generate 100000 samples of the Geometric(0.2, 20) distribution and display histogram");
            var data = new double[100000];

            for (var i = 0; i < data.Length; i++)
            {
                data[i] = geometric.Sample();
            }

            ConsoleHelper.DisplayHistogram(data);
            Console.WriteLine();

            // 5. Generate 100000 samples of the Geometric(0.5) distribution and display histogram
            Console.WriteLine(@"5. Generate 100000 samples of the Geometric(0.5) distribution and display histogram");
            geometric.P = 0.5;
            for (var i = 0; i < data.Length; i++)
            {
                data[i] = geometric.Sample();
            }

            ConsoleHelper.DisplayHistogram(data);
            Console.WriteLine();

            // 6. Generate 100000 samples of the Geometric(0.8) distribution and display histogram
            Console.WriteLine(@"6. Generate 100000 samples of the Geometric(0.8) distribution and display histogram");
            geometric.P = 0.8;
            for (var i = 0; i < data.Length; i++)
            {
                data[i] = geometric.Sample();
            }

            ConsoleHelper.DisplayHistogram(data);
        }
Beispiel #22
0
 private static void Client_OnGroupMessage(GroupMessage msg)
 {
     ConsoleHelper.WriteLine("收到群组信息:{0}", msg.Content);
 }
Beispiel #23
0
        /// <summary>
        /// socket 传输字节解码
        /// 格式为:1+4+8+4+x+4+x+x
        /// </summary>
        /// <param name="data"></param>
        /// <param name="onDecode"></param>
        bool Decode(byte[] data, Action <RSocketMsg[], uint> onDecode)
        {
            uint offset = 0;

            try
            {
                if (data != null && data.Length >= offset + MIN)
                {
                    var list = new List <RSocketMsg>();

                    while (data.Length >= offset + MIN)
                    {
                        var total = BitConverter.ToUInt32(data, (int)offset + 1);

                        if (data.Length >= offset + total + 1)
                        {
                            var qm = new RSocketMsg((RSocketMsgType)data[offset]);
                            offset           += 5;
                            qm.Total          = total;
                            qm.SequenceNumber = BitConverter.ToInt64(data, (int)offset);

                            offset += 8;

                            qm.SLen = BitConverter.ToUInt32(data, (int)offset);
                            offset += 4;


                            if (qm.SLen > 0)
                            {
                                var narr = new byte[qm.SLen];
                                Buffer.BlockCopy(data, (int)offset, narr, 0, narr.Length);
                                qm.ServiceName = Encoding.UTF8.GetString(narr);
                            }
                            offset += qm.SLen;

                            qm.MLen = BitConverter.ToUInt32(data, (int)offset);

                            offset += 4;

                            if (qm.MLen > 0)
                            {
                                var tarr = new byte[qm.MLen];
                                Buffer.BlockCopy(data, (int)offset, tarr, 0, tarr.Length);
                                qm.MethodName = Encoding.UTF8.GetString(tarr);
                            }
                            offset += qm.MLen;

                            var dlen = qm.Total - 8 - 4 - 4 - qm.SLen - 4 - qm.MLen;

                            if (dlen > 0)
                            {
                                var darr = new byte[dlen];
                                Buffer.BlockCopy(data, (int)offset, darr, 0, (int)dlen);
                                qm.Data = darr;
                                offset += dlen;
                            }
                            list.Add(qm);
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (list.Count > 0)
                    {
                        onDecode?.Invoke(list.ToArray(), offset);
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                ConsoleHelper.WriteLine($"RCoder.Decode error:{ex.Message} stack:{ex.StackTrace} data:{data.Length} offset:{offset}");
            }
            onDecode?.Invoke(null, 0);
            return(false);
        }
Beispiel #24
0
 private static void Client_OnChannelMessage(ChannelMessage msg)
 {
     ConsoleHelper.WriteLine("收到频道消息:{0}", msg.Content);
 }
        public void BuildAndTrain(IEnumerable <ImageData> imageSet)
        {
            ConsoleWriteHeader("Read model");
            Console.WriteLine($"Model location: {inputTensorFlowModelFilePath}");
            Console.WriteLine($"Training file: {dataLocation}");

            // 1. Load images information (filenames and labels) in IDataView

            //Load the initial single full Image-Set
            //
            IDataView fullImagesDataset         = mlContext.Data.LoadFromEnumerable(imageSet);
            IDataView shuffledFullImagesDataset = mlContext.Data.ShuffleRows(fullImagesDataset);

            // Split the data 90:10 into train and test sets, train and evaluate.
            TrainTestData trainTestData = mlContext.Data.TrainTestSplit(shuffledFullImagesDataset, testFraction: 0.10);
            IDataView     trainDataView = trainTestData.TrainSet;
            IDataView     testDataView  = trainTestData.TestSet;

            // 2. Load images in-memory while applying image transformations
            // Input and output column names have to coincide with the input and output tensor names of the TensorFlow model
            // You can check out those tensor names by opening the Tensorflow .pb model with a visual tool like Netron: https://github.com/lutzroeder/netron
            // TF .pb model --> input node --> INPUTS --> input --> id: "input"
            // TF .pb model --> Softmax node --> INPUTS --> logits --> id: "softmax2_pre_activation" (Inceptionv1) or "InceptionV3/Predictions/Reshape" (Inception v3)

            var dataProcessPipeline = mlContext.Transforms.Conversion.MapValueToKey(outputColumnName: LabelAsKey, inputColumnName: "Label")
                                      .Append(mlContext.Transforms.LoadImages(outputColumnName: "image_object", imageFolder: imagesFolder, inputColumnName: nameof(DataModels.ImageData.ImagePath)))
                                      .Append(mlContext.Transforms.ResizeImages(outputColumnName: "image_object_resized",
                                                                                imageWidth: ImageSettingsForTFModel.imageWidth, imageHeight: ImageSettingsForTFModel.imageHeight,
                                                                                inputColumnName: "image_object"))
                                      .Append(mlContext.Transforms.ExtractPixels(outputColumnName: "input", inputColumnName: "image_object_resized",
                                                                                 interleavePixelColors: ImageSettingsForTFModel.channelsLast,
                                                                                 offsetImage: ImageSettingsForTFModel.mean,
                                                                                 scaleImage: ImageSettingsForTFModel.scale)) //for Inception v3 needs scaleImage: set to 1/255f. Not needed for InceptionV1.
                                      .Append(mlContext.Model.LoadTensorFlowModel(inputTensorFlowModelFilePath).
                                              ScoreTensorFlowModel(outputColumnNames: new[] { "InceptionV3/Predictions/Reshape" },
                                                                   inputColumnNames: new[] { "input" },
                                                                   addBatchDimensionInput: false)); // (For Inception v1 --> addBatchDimensionInput: true)  (For Inception v3 --> addBatchDimensionInput: false)

            // 3. Set the training algorithm and convert back the key to the categorical values
            var trainer          = mlContext.MulticlassClassification.Trainers.LbfgsMaximumEntropy(labelColumnName: LabelAsKey, featureColumnName: "InceptionV3/Predictions/Reshape"); //"softmax2_pre_activation" for Inception v1
            var trainingPipeline = dataProcessPipeline.Append(trainer)
                                   .Append(mlContext.Transforms.Conversion.MapKeyToValue(PredictedLabelValue, "PredictedLabel"));

            // 4. Train the model
            // Measuring training time
            var watch = System.Diagnostics.Stopwatch.StartNew();

            ConsoleWriteHeader("Training the ML.NET classification model");
            ITransformer model = trainingPipeline.Fit(trainDataView);

            watch.Stop();
            long elapsedMs = watch.ElapsedMilliseconds;

            Console.WriteLine("Training with transfer learning took: " + (elapsedMs / 1000).ToString() + " seconds");

            // 5. Make bulk predictions and calculate quality metrics
            ConsoleWriteHeader("Create Predictions and Evaluate the model quality");
            IDataView predictionsDataView = model.Transform(testDataView);

            // This is an optional step, but it's useful for debugging issues
            var loadedModelOutputColumnNames = predictionsDataView.Schema
                                               .Where(col => !col.IsHidden).Select(col => col.Name);

            // 5.1 Show the predictions
            ConsoleWriteHeader("*** Showing all the predictions ***");
            List <ImagePredictionEx> predictions = mlContext.Data.CreateEnumerable <ImagePredictionEx>(predictionsDataView, false, true).ToList();

            predictions.ForEach(pred => ConsoleWriteImagePrediction(pred.ImagePath, pred.Label, pred.PredictedLabelValue, pred.Score.Max()));

            // 5.2 Show the performance metrics for the multi-class classification
            var classificationContext = mlContext.MulticlassClassification;

            ConsoleWriteHeader("Classification metrics");
            var metrics = classificationContext.Evaluate(predictionsDataView, labelColumnName: LabelAsKey, predictedLabelColumnName: "PredictedLabel");

            ConsoleHelper.PrintMultiClassClassificationMetrics(trainer.ToString(), metrics);

            // 6. Save the model to assets/outputs
            ConsoleWriteHeader("Save model to local file");
            ModelHelpers.DeleteAssets(outputMlNetModelFilePath);

            mlContext.Model.Save(model, predictionsDataView.Schema, outputMlNetModelFilePath);
            Console.WriteLine($"Model saved: {outputMlNetModelFilePath}");
        }
Beispiel #26
0
 private void _receiver_OnError(string ID, Exception ex)
 {
     ConsoleHelper.WriteLine("接收文件过程发生异常,ID:{0} err:{1}", ID, ex.Message);
 }
Beispiel #27
0
        private static void Server_OnMessage(string id, WSProtocal data)
        {
            ConsoleHelper.WriteLine("WSServer 收到{0}的消息:{1}", ConsoleColor.Green, id, Encoding.UTF8.GetString(data.Content));

            _server.Reply(id, data);
        }
Beispiel #28
0
        /// <summary>
        /// Run example
        /// </summary>
        /// <a href="http://en.wikipedia.org/wiki/Pareto_distribution">Pareto distribution</a>
        public void Run()
        {
            // 1. Initialize the new instance of the Pareto distribution class with parameters Shape = 3, Scale = 1
            var pareto = new Pareto(1, 3);

            Console.WriteLine(@"1. Initialize the new instance of the Pareto distribution class with parameters Shape = {0}, Scale = {1}", pareto.Shape, pareto.Scale);
            Console.WriteLine();

            // 2. Distributuion properties:
            Console.WriteLine(@"2. {0} distributuion properties:", pareto);

            // Cumulative distribution function
            Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", pareto.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));

            // Probability density
            Console.WriteLine(@"{0} - Probability density at location '0.3'", pareto.Density(0.3).ToString(" #0.00000;-#0.00000"));

            // Log probability density
            Console.WriteLine(@"{0} - Log probability density at location '0.3'", pareto.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));

            // Entropy
            Console.WriteLine(@"{0} - Entropy", pareto.Entropy.ToString(" #0.00000;-#0.00000"));

            // Largest element in the domain
            Console.WriteLine(@"{0} - Largest element in the domain", pareto.Maximum.ToString(" #0.00000;-#0.00000"));

            // Smallest element in the domain
            Console.WriteLine(@"{0} - Smallest element in the domain", pareto.Minimum.ToString(" #0.00000;-#0.00000"));

            // Mean
            Console.WriteLine(@"{0} - Mean", pareto.Mean.ToString(" #0.00000;-#0.00000"));

            // Median
            Console.WriteLine(@"{0} - Median", pareto.Median.ToString(" #0.00000;-#0.00000"));

            // Mode
            Console.WriteLine(@"{0} - Mode", pareto.Mode.ToString(" #0.00000;-#0.00000"));

            // Variance
            Console.WriteLine(@"{0} - Variance", pareto.Variance.ToString(" #0.00000;-#0.00000"));

            // Standard deviation
            Console.WriteLine(@"{0} - Standard deviation", pareto.StdDev.ToString(" #0.00000;-#0.00000"));

            // Skewness
            Console.WriteLine(@"{0} - Skewness", pareto.Skewness.ToString(" #0.00000;-#0.00000"));
            Console.WriteLine();

            // 3. Generate 10 samples of the Pareto distribution
            Console.WriteLine(@"3. Generate 10 samples of the Pareto distribution");
            for (var i = 0; i < 10; i++)
            {
                Console.Write(pareto.Sample().ToString("N05") + @" ");
            }

            Console.WriteLine();
            Console.WriteLine();

            // 4. Generate 100000 samples of the Pareto(1, 3) distribution and display histogram
            Console.WriteLine(@"4. Generate 100000 samples of the Pareto(1, 3) distribution and display histogram");
            var data = new double[100000];

            for (var i = 0; i < data.Length; i++)
            {
                data[i] = pareto.Sample();
            }

            ConsoleHelper.DisplayHistogram(data);
            Console.WriteLine();

            // 5. Generate 100000 samples of the Pareto(1, 1) distribution and display histogram
            Console.WriteLine(@"5. Generate 100000 samples of the Pareto(1, 1) distribution and display histogram");
            pareto.Shape = 1;
            for (var i = 0; i < data.Length; i++)
            {
                data[i] = pareto.Sample();
            }

            ConsoleHelper.DisplayHistogram(data);
            Console.WriteLine();

            // 6. Generate 100000 samples of the Pareto(10, 5) distribution and display histogram
            Console.WriteLine(@"6. Generate 100000 samples of the Pareto(10, 50) distribution and display histogram");
            pareto.Shape = 50;
            pareto.Scale = 10;
            for (var i = 0; i < data.Length; i++)
            {
                data[i] = pareto.Sample();
            }

            ConsoleHelper.DisplayHistogram(data);
        }
Beispiel #29
0
 private static void Client_OnError(string ID, Exception ex)
 {
     ConsoleHelper.WriteLine("WSClient 出现异常:{0}", ConsoleColor.DarkGray, ex.Message);
 }
        public static void BuildAndTrainModel(string DataSetLocation, string ModelPath, MyTrainerStrategy selectedStrategy)
        {
            // Create MLContext to be shared across the model creation workflow objects 
            // Set a random seed for repeatable/deterministic results across multiple trainings.
            var mlContext = new MLContext(seed: 1);

            // STEP 1: Common data loading configuration
            var trainingDataView = mlContext.Data.LoadFromTextFile<GitHubIssue>(DataSetLocation, hasHeader: true, separatorChar:'\t', allowSparse: false);
             
            // STEP 2: Common data process configuration with pipeline data transformations
            var dataProcessPipeline = mlContext.Transforms.Conversion.MapValueToKey(outputColumnName: "Label",inputColumnName:nameof(GitHubIssue.Area))
                            .Append(mlContext.Transforms.Text.FeaturizeText(outputColumnName: "TitleFeaturized",inputColumnName:nameof(GitHubIssue.Title)))
                            .Append(mlContext.Transforms.Text.FeaturizeText(outputColumnName: "DescriptionFeaturized", inputColumnName: nameof(GitHubIssue.Description)))
                            .Append(mlContext.Transforms.Concatenate(outputColumnName:"Features", "TitleFeaturized", "DescriptionFeaturized"))
                            .AppendCacheCheckpoint(mlContext);  
                            // Use in-memory cache for small/medium datasets to lower training time. 
                            // Do NOT use it (remove .AppendCacheCheckpoint()) when handling very large datasets.

            // (OPTIONAL) Peek data (such as 2 records) in training DataView after applying the ProcessPipeline's transformations into "Features" 
            Common.ConsoleHelper.PeekDataViewInConsole(mlContext, trainingDataView, dataProcessPipeline, 2);

            // STEP 3: Create the selected training algorithm/trainer
            IEstimator<ITransformer> trainer = null; 
            switch(selectedStrategy)
            {
                case MyTrainerStrategy.SdcaMultiClassTrainer:                 
                     trainer = mlContext.MulticlassClassification.Trainers.SdcaMaximumEntropy("Label", "Features");
                     break;
                case MyTrainerStrategy.OVAAveragedPerceptronTrainer:
                {
                    // Create a binary classification trainer.
                    var averagedPerceptronBinaryTrainer = mlContext.BinaryClassification.Trainers.AveragedPerceptron("Label", "Features",numberOfIterations: 10);
                    // Compose an OVA (One-Versus-All) trainer with the BinaryTrainer.
                    // In this strategy, a binary classification algorithm is used to train one classifier for each class, "
                    // which distinguishes that class from all other classes. Prediction is then performed by running these binary classifiers, "
                    // and choosing the prediction with the highest confidence score.
                    trainer = mlContext.MulticlassClassification.Trainers.OneVersusAll(averagedPerceptronBinaryTrainer);
                        
                    break;
                }
                default:
                    break;
            }

            //Set the trainer/algorithm and map label to value (original readable state)
            var trainingPipeline = dataProcessPipeline.Append(trainer)
                    .Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel"));

            // STEP 4: Cross-Validate with single dataset (since we don't have two datasets, one for training and for evaluate)
            // in order to evaluate and get the model's accuracy metrics

            Console.WriteLine("=============== Cross-validating to get model's accuracy metrics ===============");
            var crossValidationResults= mlContext.MulticlassClassification.CrossValidate(data:trainingDataView, estimator:trainingPipeline, numberOfFolds: 6, labelColumnName:"Label");
                    
            ConsoleHelper.PrintMulticlassClassificationFoldsAverageMetrics(trainer.ToString(), crossValidationResults);

            // STEP 5: Train the model fitting to the DataSet
            Console.WriteLine("=============== Training the model ===============");
            var trainedModel = trainingPipeline.Fit(trainingDataView);

            // (OPTIONAL) Try/test a single prediction with the "just-trained model" (Before saving the model)
            GitHubIssue issue = new GitHubIssue() { ID = "Any-ID", Title = "WebSockets communication is slow in my machine", Description = "The WebSockets communication used under the covers by SignalR looks like is going slow in my development machine.." };
            // Create prediction engine related to the loaded trained model
            var predEngine = mlContext.Model.CreatePredictionEngine<GitHubIssue, GitHubIssuePrediction>(trainedModel);
            //Score
            var prediction = predEngine.Predict(issue);
            Console.WriteLine($"=============== Single Prediction just-trained-model - Result: {prediction.Area} ===============");
            //

            // STEP 6: Save/persist the trained model to a .ZIP file
            Console.WriteLine("=============== Saving the model to a file ===============");
            mlContext.Model.Save(trainedModel, trainingDataView.Schema, ModelPath);

            Common.ConsoleHelper.ConsoleWriteHeader("Training process finalized");
        }
Beispiel #31
0
 private static void Client_OnMessage(WSProtocal data)
 {
     ConsoleHelper.WriteLine("WSClient 收到的消息:{0}", ConsoleColor.DarkGray, Encoding.UTF8.GetString(data.Content));
 }
Beispiel #32
0
        private static void Main(string[] args)
        {
            //Create the MLContext to share across components for deterministic results
            MLContext mlContext = new MLContext(seed: 1);  //Seed set to any number so you have a deterministic environment

            // STEP 1: Common data loading configuration
            IDataView fullData = mlContext.Data.ReadFromTextFile(path: DataPath,
                                                                 columns: new[]
            {
                new TextLoader.Column(DefaultColumnNames.Label, DataKind.R4, 0),
                new TextLoader.Column(nameof(IrisData.SepalLength), DataKind.R4, 1),
                new TextLoader.Column(nameof(IrisData.SepalWidth), DataKind.R4, 2),
                new TextLoader.Column(nameof(IrisData.PetalLength), DataKind.R4, 3),
                new TextLoader.Column(nameof(IrisData.PetalWidth), DataKind.R4, 4),
            },
                                                                 hasHeader: true,
                                                                 separatorChar: '\t');

            //Split dataset in two parts: TrainingDataset (80%) and TestDataset (20%)
            (IDataView trainingDataView, IDataView testingDataView) = mlContext.Clustering.TrainTestSplit(fullData, testFraction: 0.2);

            //STEP 2: Process data transformations in pipeline
            var dataProcessPipeline = mlContext.Transforms.Concatenate(DefaultColumnNames.Features, nameof(IrisData.SepalLength), nameof(IrisData.SepalWidth), nameof(IrisData.PetalLength), nameof(IrisData.PetalWidth));

            // (Optional) Peek data in training DataView after applying the ProcessPipeline's transformations
            Common.ConsoleHelper.PeekDataViewInConsole(mlContext, trainingDataView, dataProcessPipeline, 10);
            Common.ConsoleHelper.PeekVectorColumnDataInConsole(mlContext, DefaultColumnNames.Features, trainingDataView, dataProcessPipeline, 10);

            // STEP 3: Create and train the model
            var trainer          = mlContext.Clustering.Trainers.KMeans(featureColumn: DefaultColumnNames.Features, clustersCount: 3);
            var trainingPipeline = dataProcessPipeline.Append(trainer);
            var trainedModel     = trainingPipeline.Fit(trainingDataView);

            // STEP4: Evaluate accuracy of the model
            IDataView predictions = trainedModel.Transform(testingDataView);
            var       metrics     = mlContext.Clustering.Evaluate(predictions, score: DefaultColumnNames.Score, features: DefaultColumnNames.Features);

            ConsoleHelper.PrintClusteringMetrics(trainer.ToString(), metrics);

            // STEP5: Save/persist the model as a .ZIP file
            using (var fs = new FileStream(ModelPath, FileMode.Create, FileAccess.Write, FileShare.Write))
                mlContext.Model.Save(trainedModel, fs);

            Console.WriteLine("=============== End of training process ===============");

            Console.WriteLine("=============== Predict a cluster for a single case (Single Iris data sample) ===============");

            // Test with one sample text
            var sampleIrisData = new IrisData()
            {
                SepalLength = 3.3f,
                SepalWidth  = 1.6f,
                PetalLength = 0.2f,
                PetalWidth  = 5.1f,
            };

            using (var stream = new FileStream(ModelPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                ITransformer model = mlContext.Model.Load(stream);
                // Create prediction engine related to the loaded trained model
                var predEngine = model.CreatePredictionEngine <IrisData, IrisPrediction>(mlContext);

                //Score
                var resultprediction = predEngine.Predict(sampleIrisData);

                Console.WriteLine($"Cluster assigned for setosa flowers:" + resultprediction.SelectedClusterId);
            }

            Console.WriteLine("=============== End of process, hit any key to finish ===============");
            Console.ReadKey();
        }
Beispiel #33
0
 private static void Client_OnPong(DateTime date)
 {
     ConsoleHelper.WriteLine("WSClient 收到pong:{0}", ConsoleColor.DarkGray, date);
 }
Beispiel #34
0
 public void SendEmail(String pMessage, String pAddress)
 {
     SystemWideLogging.LogServiceClient.LogEvent("EmailService :: EmailService.Services\\EmailService.Services\\EmailService.cs   :: public void SendEmail(String pMessage, String pAddress)", "Received an MSMQ Request and Sending Email ( pMessage=" + pMessage + " , pAddress " + pAddress + " )");
     ConsoleHelper.WriteLine(ConsoleColor.Green, "Send to: " + pAddress);
     Console.WriteLine(pMessage);
 }
Beispiel #35
0
 private static void Client_OnDisconnected(string ID, Exception ex)
 {
     ConsoleHelper.WriteLine("WSClient 连接已断开:" + ex.Message, ConsoleColor.DarkGray);
 }
        async static Task Main(string[] args)
        {
            try
            {
                ConsoleHelper.Initialize();

                // Print identity.
                Console.WriteLine("Tugas Kelompok Teknik Visualisasi Grafis - Transformasi 3D");
                Console.WriteLine("Identitas Anggota Kelompok :");
                Console.WriteLine("Daffa Bil Nadzary                19/439811/TK/48541");
                Console.WriteLine("Firdaus Bisma Suryakusuma        19/444051/TK/49247");
                Console.WriteLine("Hafizh Aradhana Harimurti        19/444053/TK/49249");
                Console.WriteLine("Please wait a while.");
                Console.WriteLine();
                await Task.Delay(3000);

                // Start up renderer
                _renderer = new RendererServer();

                Console.WriteLine();

                // Load default model
                Console.WriteLine("Loading default model(cube)...");
                var modelFileContent = File.ReadAllText($"./Models/default-cube.txt");
                _model         = ModelData.Deserialize(modelFileContent);
                _originalModel = _model.Clone();
                await _renderer.RenderAwaitableAsync(_originalModel);

                // Load default scene
                Console.WriteLine("Loading default scene...");
                var sceneFileContent = File.ReadAllText($"./Scenes/default-scene.txt");
                _scene = SceneData.Deserialize(sceneFileContent);
                await _renderer.SetSceneAwaitableAsync(_scene);

                Console.WriteLine();

                // Prompt action
                while (true)
                {
                    Console.WriteLine("Select an action :");
                    Console.WriteLine("[0] Load model");
                    Console.WriteLine("[1] Load scene");
                    Console.WriteLine("[2] Save model");
                    Console.WriteLine("[3] Save scene");
                    Console.WriteLine("[4] Perform a single transformation");
                    Console.WriteLine("[5] Chain multiple transformations");
                    Console.WriteLine("[6] Inspect model");
                    Console.WriteLine("[7] Stop inspecting model");
                    Console.WriteLine("[8] Reset model");
                    Console.WriteLine("[9] Exit");
                    Console.Write("Select : ");
                    var ans = Console.ReadLine();
                    Console.WriteLine();

                    if (ans == "9")
                    {
                        break;
                    }

                    switch (ans)
                    {
                    case "0":
                        if (_inspectionCancellation != null)
                        {
                            _inspectionCancellation.Cancel();
                        }
                        await LoadModel();

                        break;

                    case "1":
                        if (_inspectionCancellation != null)
                        {
                            _inspectionCancellation.Cancel();
                        }
                        await LoadScene();

                        break;

                    case "2":
                        if (_inspectionCancellation != null)
                        {
                            _inspectionCancellation.Cancel();
                        }
                        _model.Serialize();
                        Console.Write("Input desired model name without .txt extension : ");
                        var _modelName = Console.ReadLine();
                        SaveModel($"./Models/{_modelName}.txt", _model);
                        break;

                    case "3":
                        if (_inspectionCancellation != null)
                        {
                            _inspectionCancellation.Cancel();
                        }
                        _scene.Serialize();
                        Console.WriteLine("Input desired scene name without .txt extension : ");
                        var _sceneName = Console.ReadLine();
                        SaveScene($"./Models/{_sceneName}.txt", _scene);
                        break;

                    case "4":
                        if (_inspectionCancellation != null)
                        {
                            _inspectionCancellation.Cancel();
                        }
                        _preTransformedModel = _model.Clone();
                        BeginTransformation(false);
                        await _renderer.RenderAwaitableAsync(_model);

                        break;

                    case "5":
                        if (_inspectionCancellation != null)
                        {
                            _inspectionCancellation.Cancel();
                        }
                        _preTransformedModel = _model.Clone();
                        BeginTransformation(true);
                        await _renderer.RenderAwaitableAsync(_model);

                        break;

                    case "6":
                        if (_inspectionCancellation != null)
                        {
                            _inspectionCancellation.Cancel();
                        }
                        _inspectionCancellation = new CancellationTokenSource();
                        InspectModel(_inspectionCancellation.Token);
                        break;

                    case "7":
                        _inspectionCancellation.Cancel();
                        _inspectionCancellation = null;
                        break;

                    case "8":
                        _model = _originalModel.Clone();
                        await _renderer.RenderAwaitableAsync(_model);

                        if (_inspectionCancellation != null)
                        {
                            _inspectionCancellation.Cancel();
                        }
                        break;

                    default:
                        if (_inspectionCancellation != null)
                        {
                            _inspectionCancellation.Cancel();
                        }
                        WriteError("Action not recognized.");
                        break;
                    }

                    Console.WriteLine();
                }

                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();

                _renderer.Close();
            }
            catch (Exception e)
            {
                WriteError(e.Message);
            }
        }
Beispiel #37
0
        static void Main(string[] args)
        {
            ConsoleHelper.WriteLine("WSServer 正在初始化....", ConsoleColor.Green);
            _server.OnMessage += Server_OnMessage;
            _server.Start();
            ConsoleHelper.WriteLine("WSServer 就绪,回车启动客户端", ConsoleColor.Green);

            ConsoleHelper.ReadLine();

            WSClient client = new WSClient();

            client.OnPong         += Client_OnPong;
            client.OnMessage      += Client_OnMessage;
            client.OnError        += Client_OnError;
            client.OnDisconnected += Client_OnDisconnected;

            ConsoleHelper.WriteLine("WSClient 正在连接到服务器...", ConsoleColor.DarkGray);

            var connected = client.Connect();

            if (connected)
            {
                ConsoleHelper.WriteLine("WSClient 连接成功,回车测试消息", ConsoleColor.DarkGray);
                ConsoleHelper.ReadLine();
                //client.Close();
                //ConsoleHelper.ReadLine();


                var loop = true;

                Task.Run(() =>
                {
                    while (loop)
                    {
                        ConsoleHelper.WriteLine("WSClient 正在发送消息...", ConsoleColor.DarkGray);

                        client.Send("hello world!");

                        Thread.Sleep(1000);
                    }
                });

                ConsoleHelper.ReadLine();
                loop = false;
                ConsoleHelper.WriteLine("WSClient 正在ping服务器...", ConsoleColor.DarkGray);
                Thread.Sleep(2000);
                client.Ping();


                ConsoleHelper.ReadLine();
                ConsoleHelper.WriteLine("WSClient 正在断开连接...");
                Thread.Sleep(1000);
                client.Close();
            }
            else
            {
                ConsoleHelper.WriteLine("WSClient 连接失败", ConsoleColor.DarkGray);
            }


            ConsoleHelper.ReadLine();
        }
 public GatherFoodActivity(Person actor, NeedEntry needEntry, EngineSettings settings, ConsoleHelper console)
     : base(actor, needEntry, settings, console)
 {
 }
Beispiel #39
0
 private static void Server_OnDisconnected(string ID, Exception ex)
 {
     ConsoleHelper.WriteLine($"{ID}已断开连接,ex:{ex.Message}", ConsoleColor.Red);
 }
 public FightActivity(Person person, NeedEntry needEntry, EngineSettings settings, ConsoleHelper console)
     : base(person, needEntry, settings, console)
 {
 }
Beispiel #41
0
        private static void FunTest()
        {
            //===============================================================
            ConsoleHelper.WriteLine("回车开始私信测试开始...");
            ConsoleHelper.ReadLine();
            var cc1 = new MessageClient();

            cc1.OnPrivateMessage += Client_OnPrivateMessage;

            var cc2 = new MessageClient();

            cc2.OnPrivateMessage += Client_OnPrivateMessage;

            cc1.Connect();
            cc2.Connect();

            cc1.Login();
            cc2.Login();

            Task.Run(() =>
            {
                while (true)
                {
                    cc1.SendPrivateMsg(cc2.ID, "你好呀,cc2!");
                    cc2.SendPrivateMsg(cc1.ID, "你好呀,cc1!");
                    Thread.Sleep(500);
                }
            });

            Parallel.For(0, 1000, (i) =>
            {
                cc1.SendPrivateMsg(cc2.ID, "你好呀,cc2!");
            });

            //===============================================================
            ConsoleHelper.WriteLine("回车开始频道测试开始...");
            ConsoleHelper.ReadLine();

            MessageClient client = new MessageClient();

            client.OnChannelMessage += Client_OnChannelMessage;

            ConsoleHelper.WriteLine("客户正在连接...");

            string channelName = "频道测试一";

            client.Connect();

            ConsoleHelper.WriteLine("客户端就绪");

            client.Login();
            ConsoleHelper.WriteLine("客户端登录成功");

            client.Subscribe(channelName);
            ConsoleHelper.WriteLine("客户端订阅成功");

            Task.Run(() =>
            {
                while (true)
                {
                    client.SendChannelMsg(channelName, "hello!");

                    Thread.Sleep(500);
                }
            });

            //===============================================================
            ConsoleHelper.WriteLine("回车开始订阅频道消息...");
            ConsoleHelper.ReadLine();

            List <MessageClient> list = new List <MessageClient>();

            Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 100; i++)
                {
                    var c = new MessageClient();
                    if (i < 10)
                    {
                        c.OnChannelMessage += Client_OnChannelMessage2;
                    }
                    list.Add(c);
                    c.Connect();
                    c.Login();
                    c.Subscribe(channelName);
                }
            });
            //===============================================================

            ConsoleHelper.WriteLine("回车开始群组测试");
            ConsoleHelper.ReadLine();

            cc1.OnGroupMessage += Client_OnGroupMessage;
            cc2.OnGroupMessage += Client_OnGroupMessage;

            var groupName = "萌一号蠢";

            cc1.SendCreateGroup(groupName);
            cc2.SendAddMember(groupName);


            Task.Run(() =>
            {
                while (true)
                {
                    cc1.SendGroupMessage(groupName, "群主广播了!");
                    cc2.SendGroupMessage(groupName, "群主万岁!");
                    Thread.Sleep(100);
                }
            });



            ConsoleHelper.ReadLine();
            ConsoleHelper.WriteLine("The function test has been completed.");
            //===============================================================

            cc2.SendRemoveMember(groupName);
            cc1.SendRemoveGroup(groupName);
            client.Unsubscribe(channelName);
        }
 public BuildShelterNeedIdentifier(EngineSettings settings, ConsoleHelper console)
     : base(ActivityVerb.Build, ItemType.Shelter, PersonVitalType.NotSet, settings, console)
 {
 }
 public EatFoodNeedIdentifier(EngineSettings settings, ConsoleHelper console)
     : base(ActivityVerb.Eat, ItemType.Food, PersonVitalType.Hunger, settings, console)
 {
 }