public PRIZECommandHandler(TCPWrapper MyTCPWrapper, BasicCommunication.MessageParser MyMessageParser,HelpCommandHandler MyHelpCommandHandler, MySqlManager MyMySqlManager, Inventory MyInventory, TradeHandler MyTradeHandler, Stats MyStats, Logger MyLogger, ActorHandler MyActorHandler)
        {
            this.TheTCPWrapper = MyTCPWrapper;
            this.TheMessageParser = MyMessageParser;
            this.TheHelpCommandHandler = MyHelpCommandHandler;
            this.TheMySqlManager = MyMySqlManager;
            this.TheInventory = MyInventory;
            this.TheTradeHandler = MyTradeHandler;
            this.TheStats = MyStats;
            this.TheActorHandler = MyActorHandler;
            this.TheLogger = MyLogger;
            this.TheTCPWrapper.GotCommand += new TCPWrapper.GotCommandEventHandler(OnGotCommand);

            //this.CommandIsDisabled = MyMySqlManager.CheckIfCommandIsDisabled("#inv",Settings.botid);

            //if (CommandIsDisabled == false)
            {
                if (Settings.IsTradeBot == true && TheMySqlManager.IGamble())
                {
                    TheHelpCommandHandler.AddCommand("#prize - show my prize list");
                    TheHelpCommandHandler.AddCommand("#prizes - null");
                }
                TheMessageParser.Got_PM += new BasicCommunication.MessageParser.Got_PM_EventHandler(OnGotPM);
                this.TheInventory.GotNewInventoryList += new Inventory.GotNewInventoryListEventHandler(OnGotNewInventoryList);
                this.TheMessageParser.Got_AbortTrade += new BasicCommunication.MessageParser.Got_AbortTrade_EventHandler(OnGotAbortTrade);
            }
        }
Exemple #2
0
 public static Logger GetInstance()
 {
     if(instance == null) {
         instance = new Logger("wintumbra.log");
     }
     return instance;
 }
Exemple #3
0
 public LoggerEventArgs(Logger logger, Logger.LogLevel logLevel, string Message, Exception exception = null)
 {
     Logger = logger;
     LogLevel = logLevel;
     LogMessage = Message;
     if (exception != null) Exception = exception;
 }
        public static void run(String[] args)
        {
            Point a = new Point(49, 49);
            Point b = new Point(0, 0);

            Logger log = new Logger();
            Stopwatch s = new Stopwatch();

            log.addToLog("Initializing "+mapWidth+"x"+mapHeight+" map...");
            initMap();
            AStarMap map = new AStarMap(mapWidth, mapHeight, obstacleMap);

            log.addToLog("Generating Bresenham's Line from "+a.x+","+a.y+" to "+b.x+","+b.y+"...");
            s.Start();
            List<Point> line = Bresenham.getCellsOnLine(a, b);
            s.Stop();
            log.addToLog("Generation took " + s.ElapsedMilliseconds + " ms");

            String str = "";
            foreach(Point point in line)
            {
                str = str+"("+point.x+","+point.y+") ";
            }
            log.addToLog("Line is:" + str);

            log.addToLog("Writing line to map...");
            log.addToLog("Printing map...");
            new PrintMap(map, line);
        }
        public static void run(String[] args)
        {
            Logger log = new Logger();
            Stopwatch s = new Stopwatch();

            log.addToLog("Map initializing...");
            AStarMap map = new AStarMap(mapData.getMapWidth(), mapData.getMapHeight(), mapData.getObstacleMap());

            log.addToLog("Heuristic initializing...");
            //AStarHeuristic heuristic = new ClosestHeuristic();
            AStarHeuristic heuristic = new DiagonalHeuristic();

            log.addToLog("AStar initializing...");
            AStar aStar = new AStar(map, heuristic);

            log.addToLog("Calculating shortest path...");
            s.Start();
            List<Point> shortestPath = aStar.calcShortestPath(startX, startY, goalX, goalY);
            s.Stop();

            log.addToLog("Time to calculate path in milliseconds: " + s.ElapsedMilliseconds);

            log.addToLog("Printing map of shortest path...");
            new PrintMap(map, shortestPath);
        }
        public void ShouldFailOnMissingAuthAttribute()
        {
            var logger = new Logger();
            var builder = new AppBuilderFactory().Create();
            builder.SetLoggerFactory(new LoggerFactory(logger));
            var context = new OwinContext();
            var request = (OwinRequest)context.Request;
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
            request.SetHeader("Authorization", new string[] { "Hawk " + 
                "ts = \"1353788437\", mac = \"/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=\", ext = \"hello\""});

            var response = (OwinResponse)context.Response;
            response.StatusCode = 401;

            var middleware = new HawkAuthenticationMiddleware(
                new AppFuncTransition((env) => 
                    {
                        response.StatusCode = 401;
                        return Task.FromResult<object>(null);
                    }),
                builder,
                new HawkAuthenticationOptions
                {
                    Credentials = GetCredential
                }
            );

            middleware.Invoke(context);

            Assert.AreEqual(401, response.StatusCode);
            Assert.AreEqual("Missing attributes", logger.Messages[0]);
        }
        public TextCommandsHandler(TCPWrapper MyTCPWrapper, BasicCommunication.MessageParser MyMessageParser, HelpCommandHandler MyHelpCommandHandler, MySqlManager MyMySqlManager, Logger MyLogger)
        {
            this.TheTCPWrapper = MyTCPWrapper;
            this.TheMessageParser = MyMessageParser;
            this.TheHelpCommandHandler = MyHelpCommandHandler;
            this.TheMySqlManager = MyMySqlManager;
            this.TheLogger = MyLogger;
            //this.CommandIsDisabled = MyMySqlManager.CheckIfCommandIsDisabled("#donate",Settings.botid);
            string commands = TheMySqlManager.TextCommandlist(Settings.botid);
            if (commands.Length == 0)
            {
                return;
            }
            string[] commandsarray = commands.Split(' ');
            foreach (string command in commandsarray)
            {
                string paddedcommand = "";
                if (command[0] != '#')
                    paddedcommand = "#";
                paddedcommand = paddedcommand + command;
                if (TheMySqlManager.CheckIfTextCommandIsDisabled(paddedcommand, Settings.botid) == false)
                {
                    string text = TheMySqlManager.TextCommandHelpText(paddedcommand, Settings.botid);
                    TheHelpCommandHandler.AddCommand(paddedcommand + text);
                }

            }
            TheMessageParser.Got_PM += new BasicCommunication.MessageParser.Got_PM_EventHandler(OnGotPM);
        }
        public PostCheckBack(string postLogPath, TimeSpan checkRate)
        {
            logger = new Logger<Post>(postLogPath);
            chkRate = checkRate;

            Task.Run(() => CheckPosts());
        }
Exemple #9
0
        /// <summary>
        /// Creates a missile with homing and target finding capabilities.
        /// </summary>
        public GuidedMissile(IMyEntity missile, IMyCubeBlock firedBy, TargetingOptions opt, Ammo ammo, LastSeen initialTarget = null, bool isSlave = false)
            : base(missile, firedBy)
        {
            myLogger = new Logger("GuidedMissile", () => missile.getBestName(), () => m_stage.ToString());
            myAmmo = ammo;
            myDescr = ammo.Description;
            if (ammo.Description.HasAntenna)
                myAntenna = new MissileAntenna(missile);
            TryHard = true;

            AllGuidedMissiles.Add(this);
            missile.OnClose += missile_OnClose;

            if (myAmmo.IsCluster && !isSlave)
                myCluster = new Cluster(myAmmo.MagazineDefinition.Capacity - 1);
            accelerationPerUpdate = (myDescr.Acceleration + myAmmo.MissileDefinition.MissileAcceleration) / 60f;
            addSpeedPerUpdate = myDescr.Acceleration / 60f;

            Options = opt;
            Options.TargetingRange = ammo.Description.TargetRange;
            myTargetSeen = initialTarget;

            myLogger.debugLog("Options: " + Options, "GuidedMissile()");
            //myLogger.debugLog("AmmoDescription: \n" + MyAPIGateway.Utilities.SerializeToXML<Ammo.AmmoDescription>(myDescr), "GuidedMissile()");
        }
Exemple #10
0
        public Download(Uri uri, string key, CookieContainer cc, JObject song)
        {
            m_uri = uri;
            m_key = key;
            m_cc = cc;
            m_song = song;

            song["Status"] = "Opening file";
            string filename = (string)song["ArtistName"] + " - " + (string)song["Name"] + ".mp3";
            m_logger = new Logger(this.GetType().ToString() + " " + filename);
            string dst = "";
            string path = "";
            if (Main.PATH.Length != 0)
                path = Main.PATH + Path.DirectorySeparatorChar;
            dst = path + filename;
            try
            {
                m_path = dst;
                m_fs = new FileStream(dst, FileMode.Create);
            }
            catch (Exception ex)
            {
                char[] invalf = Path.GetInvalidFileNameChars();
                foreach (char c in invalf)
                    filename = filename.Replace(c, '_');
                dst = path + filename;
                try
                {
                    m_path = dst;
                    m_fs = new FileStream(dst, FileMode.Create);
                }
                catch (Exception exc)
                {
                    for (int i = 0; i < dst.Length; i++)
                    {
                        if (!Char.IsLetterOrDigit(dst[i]))
                            filename = filename.Replace(dst[i], '_');
                        dst = path + filename;
                    }
                    try
                    {
                        m_path = dst;
                        m_fs = new FileStream(dst, FileMode.Create);
                    }
                    catch (Exception exc2)
                    {
                        throw new Exception("Could not save the file buddy. (" + exc2.Message + ")");
                    }
                }
            }

            m_logger.Info("Starting download");
            song["Status"] = "Starting download";
            Segment s = new Segment(uri, cc, key, 0, SEGMENT_SIZE-1, m_path);
            m_segments.Add(s);
            s.Progress += new EventHandler(s_Progress);
            s.HeadersReceived += new Segment.HeadersReceivedHandler(s_HeadersReceived);
            s.Start();
            m_start = DateTime.Now;
        }
Exemple #11
0
        public ManualMessage(IMyCubeBlock block)
        {
            m_logger = new Logger(GetType().Name, block);
            m_block = block;

            Registrar.Add(block, this);
        }
Exemple #12
0
 public Sensor(string Name, bool Simulation, Logger Logger)
 {
     this.Name = Name;
     this.Simulation = Simulation;
     this.logger = Logger;
     LastMeasurements = new List<Measurement>();
 }
Exemple #13
0
 public State(string projectToken, string target, Logger logger, string workingDirectory)
 {
     this.projectToken = projectToken;
     this.target = (target != null) ? target : Constants.DEFAULT_TARGET;
     this.logger = (logger != null) ? logger : new NullLogger();
     db = new Db(this.logger, workingDirectory);
 }
Exemple #14
0
        public Grinder(Mover mover, AllNavigationSettings navSet, float maxRange)
            : base(mover, navSet)
        {
            this.m_logger = new Logger(GetType().Name, () => m_controlBlock.CubeGrid.DisplayName, () => m_stage.ToString());
            this.m_startPostion = m_controlBlock.CubeBlock.GetPosition();
            this.m_longestDimension = m_controlBlock.CubeGrid.GetLongestDim();

            PseudoBlock navBlock = m_navSet.Settings_Current.NavigationBlock;
            m_navGrind = navBlock.Block is Ingame.IMyShipGrinder
                ? new MultiBlock<MyObjectBuilder_ShipGrinder>(navBlock.Block)
                : new MultiBlock<MyObjectBuilder_ShipGrinder>(() => m_mover.Block.CubeGrid);

            if (m_navGrind.FunctionalBlocks == 0)
            {
                m_logger.debugLog("no working grinders", Logger.severity.INFO);
                return;
            }

            m_grinderOffset = m_navGrind.Block.GetLengthInDirection(m_navGrind.Block.GetFaceDirection()[0]) * 0.5f + 2.5f;
            if (m_navSet.Settings_Current.DestinationRadius > m_longestDimension)
            {
                m_logger.debugLog("Reducing DestinationRadius from " + m_navSet.Settings_Current.DestinationRadius + " to " + m_longestDimension, Logger.severity.DEBUG);
                m_navSet.Settings_Task_NavRot.DestinationRadius = m_longestDimension;
            }

            this.m_finder = new GridFinder(m_navSet, mover.Block, maxRange);
            this.m_finder.GridCondition = GridCondition;

            m_navSet.Settings_Task_NavRot.NavigatorMover = this;
            m_navSet.Settings_Task_NavRot.NavigatorRotator = this;
        }
        /// <summary>
        /// Load this configuratin from xml element.
        /// </summary>
        /// <param name="xmlElement"></param>
        /// <param name="logger"></param>
        public void Load(XmlElement xmlElement, Logger logger)
        {
            bool found = false;
            foreach (XmlNode node in xmlElement.ChildNodes)
            {
                found = true;
                var config = GrainTypeConfiguration.Load((XmlElement)node, logger);
                if (null == config) continue;

                if (config.AreDefaults)
                {
                    defaults = config;
                }
                else
                {
                    if (classSpecific.ContainsKey(config.FullTypeName))
                    {
                        throw new InvalidOperationException(string.Format("duplicate type {0} in configuration", config.FullTypeName));
                    }
                    classSpecific.Add(config.FullTypeName, config);
                }
            }

            if (!found)
            {
                throw new InvalidOperationException("empty GrainTypeConfiguration element");
            }
        }
        public void ProcessPage(Uri outputFolder, Func<Uri, bool> isLocalUrl, Dictionary<Uri, string> pages, Dictionary<Uri, string> resources, Uri pageUrl, HtmlDocument pageDocument, Logger logger)
        {
            pageDocument.OptionOutputOptimizeAttributeValues = true;
            foreach (var textNode in (from node in pageDocument.DocumentNode.Descendants()
                                      where node.NodeType == HtmlNodeType.Text
                                      select node).ToArray())
            {
                if (string.IsNullOrWhiteSpace(textNode.InnerText))
                {
                    textNode.Remove();
                }

                textNode.InnerHtml = textNode.InnerHtml.Trim();
            }

            foreach (var commentNode in (from node in pageDocument.DocumentNode.Descendants()
                                         where node.NodeType == HtmlNodeType.Comment
                                         select node).ToArray())
            {
                if (!DoctypeRegex.IsMatch(commentNode.InnerHtml) &&
                    !StartsWithIEConditionalCommentRegex.IsMatch(commentNode.InnerHtml) &&
                    !EndsWithIEConditionalCommentRegex.IsMatch(commentNode.InnerHtml))
                {
                    commentNode.Remove();
                }
            }
        }
    internal TcpListenerWebSocketContext (
      TcpClient tcpClient,
      string protocol,
      bool secure,
      ServerSslConfiguration sslConfig,
      Logger logger)
    {
      _tcpClient = tcpClient;
      _secure = secure;
      _logger = logger;

      var netStream = tcpClient.GetStream ();
      if (secure) {
        var sslStream = new SslStream (
          netStream, false, sslConfig.ClientCertificateValidationCallback);

        sslStream.AuthenticateAsServer (
          sslConfig.ServerCertificate,
          sslConfig.ClientCertificateRequired,
          sslConfig.EnabledSslProtocols,
          sslConfig.CheckCertificateRevocation);

        _stream = sslStream;
      }
      else {
        _stream = netStream;
      }

      _request = HttpRequest.Read (_stream, 90000);
      _uri = HttpUtility.CreateRequestUrl (
        _request.RequestUri, _request.Headers["Host"], _request.IsWebSocketRequest, secure);

      _websocket = new WebSocket (this, protocol);
    }
 public void LogMessageTest()
 {
     Scrabble.Logger tempLog = new Logger();
     tempLog.LogMessage("Testing...");
     string inFile = System.IO.File.ReadAllText(System.IO.Directory.GetCurrentDirectory() + "\\Logs\\" + tempLog.now + "_VERBOSE_LOG.txt");
     Assert.IsFalse(inFile.Equals("Testing..."));
 }
 public Humidity_Air_HIH4000(string Name, bool Simulation, Adc_MCP3208 Adc, int Channel, string CalibrationFile, Logger Logger)
     : this(Name, Simulation, Adc, Channel, Logger)
 {
     //Load the calibration file
     calibration = Calibration_2Points.Load(CalibrationFile);
     Initialization();
 }
        public override bool Valid(Logger logger)
        {
            this.logger = logger;

            base.faceNumberChecker(this.Token, 5, new int[] { 5, 6 });

            this.checkPoints();

            Bulges = base.pointsChecker(this.Par2);

            //对Bulges不足的情况,用0补上
            if (Bulges.Count < Points.Count)
            {
                for (int i = 0; i < Points.Count - Bulges.Count; i++)
                {
                    Bulges.Add(0);
                }
            }

            this.ToolName = base.notEmptyStringChecker(this.Par7, "PLINE/刀具名称");

            ToolComp = base.toolCompChecker(this.Par8, "PLINE/刀具补偿");

            if (this.FaceNumber == 5)
            {
                OnFace5 = true;
            }
            else if (this.FaceNumber == 6)
            {
                OnFace5 = false;
            }

            return this.IsValid;
        }
 public void AddToGameStateTest()
 {
     Scrabble.Logger tempLog = new Logger();
     tempLog.AddToGameState("Testing...");
     string inFile = System.IO.File.ReadAllText(System.IO.Directory.GetCurrentDirectory() + "\\Logs\\" + tempLog.now + "_GAMESTATE_LOG.txt");
     Assert.IsFalse(inFile.Equals("Testing..."));
 }
Exemple #22
0
 public PlanetChecker(IMyCubeGrid grid)
 {
     this.m_logger = new Logger(GetType().Name, grid.getBestName, ClosestPlanet.getBestName, CurrentState.ToString);
     this.m_grid = grid;
     this.m_cells = new MyQueue<Vector3I>(8);
     this.m_cellsUnique = new HashSet<Vector3I>();
 }
Exemple #23
0
		    public ParseColors(Environments env, Logger log) {
                this.env = env;
			    if (!File.Exists(env.ROOT + "lib" + env.DELIM + "colors.csv")) {
				    log.Report(2, "ParseColors", "File colors.csv does not exist");
				    return;
			    }
		    }
Exemple #24
0
 public AppVeyor(Logger logger, IEnvironment environment, IHttpClientFactory httpClientFactory)
 {
     _logger = logger;
     _environment = environment;
     _httpClientFactory = httpClientFactory;
     _appVeyorApiUrl = _environment.GetEnvironmentVariable("APPVEYOR_API_URL");
 }
Exemple #25
0
        public void Test_New()
        {
            var log = new Logger ();

            Assert.AreEqual (0, log.LogCount);
            Assert.AreEqual (0, log.Logs.Count ());
        }
        public void ShouldFailOnInvalidAuthFormat()
        {
            var logger = new Logger();
            var builder = new AppBuilderFactory().Create();
            builder.SetLoggerFactory(new LoggerFactory(logger));

            var request = OwinRequest.Create();
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
            request.SetHeader("Authorization", new string[] { "Hawk " +
                ""});

            var response = new OwinResponse(request);

            var middleware = new HawkAuthenticationMiddleware(
                new AppFuncTransition((env) =>
                {
                    response.StatusCode = 401;
                    return Task.FromResult<object>(null);
                }),
               builder,
               new HawkAuthenticationOptions
               {
                   Credentials = GetCredential
               }
            );

            middleware.Invoke(request, response);

            Assert.AreEqual(401, response.StatusCode);
            Assert.AreEqual("Invalid header format", logger.Messages[0]);
        }
Exemple #27
0
		private static void Entities_OnCloseAll()
		{
			MyAPIGateway.Entities.OnCloseAll -= Entities_OnCloseAll;
			MyAPIGateway.Multiplayer.UnregisterMessageHandler(ModID, ReceiveMessageUserSetting);
			User = null;
			staticLogger = null;
		}
Exemple #28
0
 public ImageProcessor(StateColor setState, ShowState showState, TaskScheduler guiContext, Logger log)
 {
     _setState = setState;
     _showState = showState;
     GuiContext = guiContext;
     _logger = log;
 }
        public CommandReturnCodes RunCommands(TextReader input, TextWriter output, Logger logger, IEnumerable<ResponseLine> responseLines) {
            var agent = CreateAgent();

            CommandReturnCodes result = StartHost(agent, input, output);
            if (result != CommandReturnCodes.Ok)
                return result;

            foreach (var line in responseLines) {
                logger.LogInfo("{0} ({1}): Running command: {2}", line.Filename, line.LineNumber, line.LineText);

                var args = new OrchardParametersParser().Parse(new CommandParametersParser().Parse(line.Args));

                result = (CommandReturnCodes)agent.GetType().GetMethod("RunCommand").Invoke(agent, new object[] { 
                    input,
                    output,
                    args.Tenant,
                    args.Arguments.ToArray(),
                    args.Switches});

                if (result != CommandReturnCodes.Ok) {
                    output.WriteLine("{0} ({1}): Command returned error ({2})", line.Filename, line.LineNumber, result);
                    return result;
                }
            }

            result = StopHost(agent, input, output);
            return result;
        }
Exemple #30
-1
		public RadioAntenna(IMyCubeBlock block)
			: base(block)
		{
			myLogger = new Logger("RadioAntenna", () => CubeBlock.CubeGrid.DisplayName);
			myRadioAntenna = CubeBlock as Ingame.IMyRadioAntenna;
			Registrar.Add(myRadioAntenna, this);
		}