Пример #1
0
		public FWCMixForm(Console c)
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
			console = c;

			if(FWCEEPROM.Model == 0)
			{
				lblIntSpkr.Enabled = false;
				tbIntSpkr.Enabled = false;
				chkIntSpkrSel.Enabled = false;
			}

			Common.RestoreForm(this, "FWCMixer", false);

			chkMicSel_CheckedChanged(this, EventArgs.Empty);
			chkLineInRCASel_CheckedChanged(this, EventArgs.Empty);
			chkLineInPhonoSel_CheckedChanged(this, EventArgs.Empty);
			chkLineInDB9Sel_CheckedChanged(this, EventArgs.Empty);
			chkIntSpkrSel_CheckedChanged(this, EventArgs.Empty);
			chkExtSpkrSel_CheckedChanged(this, EventArgs.Empty);
			chkHeadphoneSel_CheckedChanged(this, EventArgs.Empty);
			chkLineOutRCASel_CheckedChanged(this, EventArgs.Empty);
			tbMic_Scroll(this, EventArgs.Empty);
			tbLineInRCA_Scroll(this, EventArgs.Empty);
			tbLineInPhono_Scroll(this, EventArgs.Empty);
			tbLineInDB9_Scroll(this, EventArgs.Empty);
			tbIntSpkr_Scroll(this, EventArgs.Empty);
			tbExtSpkr_Scroll(this, EventArgs.Empty);
			tbHeadphone_Scroll(this, EventArgs.Empty);
			tbLineOutRCA_Scroll(this, EventArgs.Empty);
		}
Пример #2
0
        public FlexControlBasicForm(Console c)
        {
            InitializeComponent();
            console = c;

            // setup the actual FlexControl Interface
            fc_interface = new FlexControlInterface2(c);

            // populate knob combobox controls
            foreach (FlexControlKnobFunction function in Enum.GetValues(typeof(FlexControlKnobFunction)))
            {
                string s = KnobFunction2String(function);
                comboButtonLeft.Items.Add(s);
                comboButtonMid.Items.Add(s);
                comboButtonRight.Items.Add(s);
                comboButtonKnob.Items.Add(s);
            }

            // setup defaults
            comboButtonLeft.Text = "Tune RIT";
            comboButtonMid.Text = "Audio Gain";
            comboButtonRight.Text = "Tune VFO B";
            comboButtonKnob.Text = "Tune VFO A";            

            // restore any saved configuration
            Common.RestoreForm(this, "FlexControlBasicForm", false);            
        }
Пример #3
0
 protected ConsoleCommand(Console console, string name, string info = "")
 {
     Console = console;
     Name = name;
     Args = "no arguments";
     Info = info;
 }
Пример #4
0
		public SIOListenerII(Console c)
		{
			console = c;
			console.Activated += new EventHandler(console_Activated);
			console.Closing += new System.ComponentModel.CancelEventHandler(console_Closing);
			parser = new CATParser(console);

			//event handler for Serial RX Events
			SDRSerialPort.serial_rx_event += new SerialRXEventHandler(SerialRXEventHandler);
		
			if ( console.CATEnabled )  // if CAT is on, fire it up 
			{ 
				try 
				{ 
					enableCAT();  
				}
				catch ( Exception ex ) 
				{					
					// fixme??? how cool is to to pop a msg box from an exception handler in a constructor ?? 
					//  seems ugly to me (wjt) 
					console.CATEnabled = false; 
					if ( console.setupForm != null ) 
					{ 
						console.setupForm.copyCATPropsToDialogVars(); // need to make sure the props on the setup page get reset 
					}
					MessageBox.Show("Could not initialize CAT control.  Exception was:\n\n " + ex.Message + 
						"\n\nCAT control has been disabled.", "Error Initializing CAT control", 
						MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
		}
Пример #5
0
        static void Main(string[] args)
        {
            try {
                var help = new Help(System.Console.Out);

                if (help.AreHelpArguments(args)) {
                    help.PrintHelp();
                } else {
                    var masterFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*" + Console.MasterConfigExtension);

                    Console console = new Console();

                    if (masterFiles.Length > 0) {
                        foreach (string masterConfigFileName in masterFiles) {
                            console.BuildConfigFilesFromMaster(masterConfigFileName);
                        }
                    } else {
                        System.Console.WriteLine(String.Format("could not find any files with extension `{0}'", Console.MasterConfigExtension));
                    }
                }
            }
            catch (ConfgenException e)
            {
                System.Console.WriteLine(e.Message);
                Environment.Exit(1);
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e);
                Environment.Exit(1);
            }
        }
Пример #6
0
 public FRdialog(Info info, Console c, mainWindow m)
 {
     this.info = info;
     InitializeComponent();
     console = c;
     mainWindow = m;
 }
        public static int Main(string[] args)
        {
            try
            {
                var arguments = Args.InvokeAction<Arguments>(args).Args;
                IPackageSourceFileFactory packageSourceFileFactory = new PackageSourceFileFactory();
                var packageSourceFile = packageSourceFileFactory.CreatePackageSourceFile();
                var packageManager = new PackageManagerModule(packageSourceFile);
                var packageSource = string.IsNullOrWhiteSpace(arguments.Source)
                                            ? packageManager.ActiveSource
                                            : packageManager.GetSource(arguments.Source);
                var sourceFactory = new SourcePackageRepositoryFactory(packageSource);
                IPackageInstallerFactory factory = new PackageInstallerFactory(
                    sourceFactory, new SystemConfigurationManager(), new PhysicalDirectorySystem());
                var installer = factory.CreatePackageInstaller(arguments.Destination, arguments.Configuration);
                var program = new Console(arguments, installer);

                return program.Start();
            }
            catch (Exception)
            {
                System.Console.WriteLine(ArgUsage.GetUsage<Arguments>());
                return 1;
            }
        }
 public PreSelForm(Console c)
 {
     InitializeComponent();
     console = c;
     mox = c.MOX;
     UpdatePreSel();
 }
Пример #9
0
        public ConsoleInput(Console.IViewer viewer)
        {
            _Viewer = viewer;
            _Doskey = new Doskey(10);

            _Prompt = ">>";
        }
Пример #10
0
		public FWCAntForm(Console c)
		{
			InitializeComponent();
			console = c;
			FWC.GetRX2OK(out rx2_ok);
			RX2OK = rx2_ok;
			if(RX2OK)
			{
				uint temp;
				FWC.GetRFIORev(out temp);
				if((temp&0xFF) < 34)
					comboRX2Ant.Items.Remove("ANT 1");
			}

			// Set mode first
			ArrayList a = DB.GetVars("FWCAnt");
			a.Sort();

			foreach(string s in a)
			{
				if(s.StartsWith("radModeExpert") && s.IndexOf("True") >= 0)
				{
					radModeExpert.Checked = true;
					break;
				}
			}

			Common.RestoreForm(this, "FWCAnt", false);

			if(radModeSimple.Checked)
				radModeSimple_CheckedChanged(this, EventArgs.Empty);
		}
Пример #11
0
        public DebugForm(Console c, bool enable_debug)
        {
            try
            {
                this.AutoScaleMode = AutoScaleMode.Inherit;
                InitializeComponent();
                float dpi = this.CreateGraphics().DpiX;
                float ratio = dpi / 96.0f;
                string font_name = this.Font.Name;
                float size = (float)(8.25 / ratio);
                System.Drawing.Font new_font = new System.Drawing.Font(font_name, size);
                this.Font = new_font;
                this.PerformAutoScale();
                this.PerformLayout();
                console = c;

                if (enable_debug)
                {
                    chkAudio.Checked = true;
                    chkCAT.Checked = true;
                    chkConsole.Checked = true;
                    chkDirectX.Checked = true;
                    chkEthernet.Checked = true;
                    chkIRRemote.Checked = true;
                    chkUSB.Checked = true;
                }
            }
            catch (Exception ex)
            {
                Debug.Write(ex.ToString());
            }
        }
Пример #12
0
    private void Awake()
    {
        Inst = this;

        ListCommand = new List<DescriptionConsoleMethod>();

        foreach (var item in typeof(Console).GetMethods())
        {
            if (Attribute.IsDefined(item, typeof(ConsoleMethodAttribute)))
            {
                var attr = Attribute.GetCustomAttribute(item, typeof(ConsoleMethodAttribute)) as ConsoleMethodAttribute;

                var paramList = new List<Tuple<string, string>>();

                if (!string.IsNullOrEmpty(attr.Params))
                {
                    paramList.AddRange(attr.Params.Split(';').Select(param => param.Split(',')).Select(mas => new Tuple<string, string>(mas[0], mas[1])));
                }

                ListCommand.Add(new DescriptionConsoleMethod
                {
                    Name = item.Name,
                    Description = attr.Name,
                    Params = paramList
                });
            }
        }
    }
Пример #13
0
        public void ShouldCreateConfigFileForNamedEnv()
        {
            var masterConfig = new XElement("stuff",
                                            new XAttribute(Console.BuildConfigForAttribute, "dev, systest, uat"),
                                            new XElement("dome", new XAttribute("name", "7")),
                                            new XElement("hill", new XElement("speed", new XAttribute(ConfigurationGenerator.ForEnvironmentsAttribute, "systest"), "some text")),
                                            new XElement("development", new XAttribute(ConfigurationGenerator.ForEnvironmentsAttribute, Console.DefaultEnvironment), 4));

            var config = new XElement("stuff",
                                      new XElement("dome", new XAttribute("name", "7")),
                                      new XElement("hill", new XElement("speed", "some text")));

            var diskAccessMock = new Mock<IXmlLoaderSaver>();
            const string masterFileName = "app.master.config";
            diskAccessMock.Setup(ls => ls.Load(masterFileName)).Returns(new XDocument(masterConfig));

            XDocument exportedConfig = null;

            diskAccessMock.Setup(ls => ls.Save(It.IsAny<XDocument>(), "the.config")).Callback<XDocument, string>((doc, fn) => exportedConfig = doc);

            var console = new Console();
            console.BuildConfigFilesFromMaster(masterFileName, "the.config", "systest", diskAccessMock.Object);

            Assert.That(exportedConfig, Is.Not.Null);
            Assert.AreEqual(config.ToString(), exportedConfig.ToString());
        }
Пример #14
0
        public static Response Pack(NuGetPackRequest request)
        {
            var console = new Console();
            PackageBuilder builder = new PackageBuilder();
            var command = new PackCommand
            {
                BasePath = PathTools.OptimizePath(request.BaseDirectory),
                OutputDirectory = PathTools.OptimizePath(request.OutputDirectory),
                Version = request.Version,
                Console = console,
                Verbosity = Verbosity.Detailed,
                Rules = new IPackageRule[0],
            };
            command.Arguments.Add(request.SpecPath);

            try
            {
                command.Execute();
            }
            catch (Exception e)
            {
                console.WriteError(e);
            }

            return new Response(console.Messages);
        }
Пример #15
0
		public FWCCalForm(Console c)
		{
			InitializeComponent();
			console = c;
            switch (console.CurrentModel)
            {
                case Model.FLEX5000:
                    if (!FWCEEPROM.RX2OK)
                    {
                        grpRX2.Visible = false;
                        this.Height -= grpRX2.Height;
                    }
                    break; // do nothing
                case Model.FLEX3000:
                    this.Text = this.Text.Replace("FLEX-5000", "FLEX-3000");
                    grpRX2.Visible = false;
                    this.Height -= grpRX2.Height;
                    break;
                case Model.FLEX1500:
                    this.Text = this.Text.Replace("FLEX-5000", "FLEX-1500");
                    grpRX2.Visible = false;
                    btnResetTRXChecksums.Visible = false;
                    grpTRX.Height -= btnResetTRXChecksums.Height;
                    this.Height -= (grpRX2.Height + btnResetTRXChecksums.Height);
                    break;
            }
		}
Пример #16
0
        public SaveMem(Console c)
        {
            InitializeComponent();
            console = c;

            InitAGCModes();
            InitDSPModes();

            comboGroup.DataSource = DB.dsMemory.Tables["GroupList"];
            comboGroup.ValueMember = "GroupID";
            comboGroup.DisplayMember = "GroupName";
            comboMode.SelectedIndex = (int)console.RX1DSPMode;
            if(console.RX1DSPMode != DSPMode.DRM &&
                console.RX1DSPMode != DSPMode.SPEC)
                comboFilter.SelectedIndex = (int)console.RX1Filter;
            comboStepSize.SelectedIndex = console.StepSize;
            comboAGC.SelectedIndex = (int)console.RX1AGCMode;
            udSquelch.Value = console.Squelch;

            txtFreq.Text = console.VFOAFreq.ToString("f6");
            chkScan.Checked = true;
            comboGroup.SelectedIndex = 0;

            this.ActiveControl = btnOK;		// OK has focus initially
        }
Пример #17
0
        public CWKeyer2(Console c)
        {
            console = c;
            hw = console.Hdw;
            siolisten = console.Siolisten;
            Thread.Sleep(50);
            DttSP.NewKeyer(600.0f, true, 0.0f, 3.0f, 25.0f, (float)Audio.SampleRate1);
            RadioDSP.KeyerIambicMode = 0;
            Thread.Sleep(50);

            CWTone = new Thread(new ThreadStart(DttSP.KeyerSoundThread));
            CWTone.Name = "CW Sound Thread";
            CWTone.Priority = ThreadPriority.Highest;
            CWTone.IsBackground = true;

            CWTone.Start();

            Keyer  = new Thread(new ThreadStart(KeyThread));
            Keyer.Name = "CW KeyThread";
            Keyer.Priority = ThreadPriority.Highest;
            Keyer.IsBackground = true;
            Keyer.Start();

            timer = new HiPerfTimer();
        }
Пример #18
0
 public MultiPSKEthernetServer(Console c)
 {
     console = c;
     receive_buffer = new byte[65535];
     send_buffer = new byte[65535];
     send_event = new AutoResetEvent(false);
     server_event = new AutoResetEvent(false);
 }
Пример #19
0
    public void SetupConsole()
    {
        if (Console.instance != null)
            return;

        Console.instance = this;
        this.Text = "";
    }
Пример #20
0
        private void btnTest_Click(object sender, EventArgs e)
        {
            FillServer();
            Console con = new Console(m_server);
            con.ShowDialog(this);

            m_invalid = !con.Passed;
        }
 public BenchmarkThread(Console console, BenchmarkArguments args, BenchmarkShared shared, Example example)
 {
     this.console = console;
     this.args = args;
     this.shared = shared;
     this.example = example;
     random = new RandomShift();
 }
Пример #22
0
 protected WindowConsole()
 {
     _AutoPowerRegulator = new AutoPowerRegulator(new PowerRegulator());
     Viewer = new ConsoleViewer();
     _Input = new ConsoleInput(Viewer);
     _Console = new Console(_Input, Viewer);
     _Updater = new Updater();
 }
Пример #23
0
 void Start()
 {
     console = Camera.main.GetComponent<Console> ();
     player = this.gameObject;
     rigidbody = player.GetComponent<Rigidbody2D> ();
     soundCollider = player.GetComponent<CircleCollider2D>();
     currentJumpForce = minJumpForce;
     dir = Instantiate (arrow, player.transform.position, Quaternion.identity) as GameObject;
 }
Пример #24
0
        public static void Destroy()
        {
            if (Instance == null)
                return;

            waitEvent.Set();
            Instance.BeginInvoke((Action)Instance.Close);
            Instance = null;
        }
Пример #25
0
        public ProductionDebug(Console c)
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            console = c;
        }
    public static Console GetConsole()
    {
        // Lazy Initialization
        if (singleton == null)
        {
            singleton = new Console();
        }

        return singleton;
    }
Пример #27
0
 public OVPN(Console parent)
 {
     InitializeComponent();
     console = parent;
     vpnConsole = this.richTextBox1;
     this.KeyPreview = true;
     this.KeyDown += new KeyEventHandler(OVPN_KeyDown);
     this.richTextBox1.TextChanged += new EventHandler(richTextBox1_TextChanged);
     this.ActiveControl = textBox1;
 }
Пример #28
0
        public Main()
        {
            InitializeComponent();
            this.Location = new Point(Screen.AllScreens[0].Bounds.Width / 2 - this.Size.Width / 2, 0);
            console = new Console(this);
            console.Show();

            graphics = new GraphicsCore(this);
            game = new Game();
        }
		public DiversityForm(Console c)
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
			console = c;

			Common.RestoreForm(this, "DiversityForm", false);
		}
Пример #30
0
 public void OnDestroy()
 {
     if (isInit)
     {
         applicationIsQuitting = true;
         _lock = null;
         _instance = null;
     }
     StopAsyncWriteLog();
 }
Пример #31
0
        static void Main()
        {
            string idVillain = Console.ReadLine();

            using var connection = new SqlConnection(@"Server=.\SQLEXPRESS;
                                                       Database=MinionsDB;
                                                       Integrated Security=true;");
            connection.Open();

            var transaction = connection.BeginTransaction();

            var command = new SqlCommand("SELECT Name " +
                                         "  FROM Villains " +
                                         " WHERE Id = @villainId", connection);

            command.Parameters.AddWithValue("@villainId", idVillain);

            command.Transaction = transaction;

            string nameVillain = command.ExecuteScalar()?.ToString();

            string result = string.Empty;

            if (nameVillain == null)
            {
                result = "No such villain was found.";
            }
            else
            {
                try
                {
                    command = new SqlCommand("DELETE FROM MinionsVillains " +
                                             "WHERE VillainId = @villainId", connection);
                    command.Parameters.AddWithValue("@villainId", idVillain);

                    command.Transaction = transaction;

                    int num = command.ExecuteNonQuery();

                    command = new SqlCommand("DELETE FROM Villains " +
                                             " WHERE Id = @villainId", connection);
                    command.Parameters.AddWithValue("@villainId", idVillain);

                    command.Transaction = transaction;

                    command.ExecuteNonQuery();

                    transaction.Commit();

                    result = $"{nameVillain} was deleted." + Environment.NewLine +
                             $"{num} minions were released.";
                }
                catch (Exception ex)
                {
                    try
                    {
                        result = ex.Message;

                        transaction.Rollback();
                    }
                    catch (Exception e)
                    {
                        result = e.Message;
                    }
                }
            }

            Console.WriteLine(result);
        }
Пример #32
0
 public void Drive()
 {
     Console.WriteLine($"The {Name} zips through the waves with the greatest of ease, and can get up to {MaxWaterSpeed} mph.");
 }
        public virtual void CalculateStatistics()
        {
            var allStudentsPoints = 0d;
            var campusPoints = 0d;
            var statePoints = 0d;
            var nationalPoints = 0d;
            var internationalPoints = 0d;
            var standardPoints = 0d;
            var honorPoints = 0d;
            var dualEnrolledPoints = 0d;

            foreach (var student in Students)
            {
                student.LetterGrade = GetLetterGrade(student.AverageGrade);
                student.GPA = GetGPA(student.LetterGrade, student.Type);

                Console.WriteLine("{0} ({1}:{2}) GPA: {3}.", student.Name, student.LetterGrade, student.AverageGrade, student.GPA);
                allStudentsPoints += student.AverageGrade;

                switch (student.Enrollment)
                {
                    case EnrollmentType.Campus:
                        campusPoints += student.AverageGrade;
                        break;
                    case EnrollmentType.State:
                        statePoints += student.AverageGrade;
                        break;
                    case EnrollmentType.National:
                        nationalPoints += student.AverageGrade;
                        break;
                    case EnrollmentType.International:
                        internationalPoints += student.AverageGrade;
                        break;
                }

                switch (student.Type)
                {
                    case StudentType.Standard:
                        standardPoints += student.AverageGrade;
                        break;
                    case StudentType.Honors:
                        honorPoints += student.AverageGrade;
                        break;
                    case StudentType.DualEnrolled:
                        dualEnrolledPoints += student.AverageGrade;
                        break;
                }
            }

            // #todo refactor into it's own method with calculations performed here
            Console.WriteLine("Average Grade of all students is " + (allStudentsPoints / Students.Count));
            if (campusPoints != 0)
                Console.WriteLine("Average for only local students is " + (campusPoints / Students.Where(e => e.Enrollment == EnrollmentType.Campus).Count()));
            if (statePoints != 0)
                Console.WriteLine("Average for only state students (excluding local) is " + (statePoints / Students.Where(e => e.Enrollment == EnrollmentType.State).Count()));
            if (nationalPoints != 0)
                Console.WriteLine("Average for only national students (excluding state and local) is " + (nationalPoints / Students.Where(e => e.Enrollment == EnrollmentType.National).Count()));
            if (internationalPoints != 0)
                Console.WriteLine("Average for only international students is " + (internationalPoints / Students.Where(e => e.Enrollment == EnrollmentType.International).Count()));
            if (standardPoints != 0)
                Console.WriteLine("Average for students excluding honors and dual enrollment is " + (standardPoints / Students.Where(e => e.Type == StudentType.Standard).Count()));
            if (honorPoints != 0)
                Console.WriteLine("Average for only honors students is " + (honorPoints / Students.Where(e => e.Type == StudentType.Honors).Count()));
            if (dualEnrolledPoints != 0)
                Console.WriteLine("Average for only dual enrolled students is " + (dualEnrolledPoints / Students.Where(e => e.Type == StudentType.DualEnrolled).Count()));
        }
Пример #34
0
 private static void OpenPresents()
 {
     Console.WriteLine("Opening Presents");
     Thread.Sleep(TimeSpan.FromSeconds(1));
     Console.WriteLine("Finished Opening Presents");
 }
Пример #35
0
	static int[] Read() => Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
Пример #36
0
 public void Fly()
 {
     Console.WriteLine("fly with wings");
 }
Пример #37
0
        public static double descuento(double valor)
        {
            Console.WriteLine(valor);
            return valor*.9;

        }
Пример #38
0
        /// <summary>
        /// Reading from the console or other resource.
        /// </summary>
        /// <returns></returns>
        public string ReadLine()
        {
            var input = Console.ReadLine();

            return(input);
        }
Пример #39
0
 public void Play()
 {
     Console.WriteLine("Icricketplayer");
 }
Пример #40
0
		static void Main(string[] args)
		{
			string input = Console.ReadLine();

			Dictionary<string, Trainer> trainers = new Dictionary<string, Trainer>();

			while (input != "Tournament")
			{
				string[] inputParts = input.Split(' ', StringSplitOptions.RemoveEmptyEntries).ToArray();

				string trainerName = inputParts[0];
				string pokemonName = inputParts[1];
				string pokemonElement = inputParts[2];
				int pokemonHealth = int.Parse(inputParts[3]);

				Pokemon pokemon = new Pokemon();
				pokemon.Name = pokemonName;
				pokemon.Element = pokemonElement;
				pokemon.Health = pokemonHealth;

				if(!trainers.ContainsKey(trainerName))
				{
					trainers[trainerName] = new Trainer(trainerName);

					trainers[trainerName].Pokemons = new List<Pokemon>();
				}
				trainers[trainerName].Pokemons.Add(pokemon);
				trainers[trainerName].Badges = 0;

				input = Console.ReadLine();
			}
			
			input = Console.ReadLine();

			while (input != "End")
			{
				string currentElement = input;

				foreach (var trainer in trainers.Values)
				{
					if(trainer.Pokemons.Any(e => e.Element == currentElement))
					{
						trainer.Badges++;
					}
					else
					{
						foreach (var pokemon in trainer.Pokemons)
						{
							pokemon.Health -= 10;
						}
					}
					HealthChek(trainer);
				}

				input = Console.ReadLine();
			}

			foreach (var trainer in trainers.Values.OrderByDescending(x => x.Badges))
			{
				Console.WriteLine($"{trainer.Name} {trainer.Badges} {trainer.Pokemons.Count}");
			}
		}
Пример #41
0
 public override Cascade.DishSoap WhatIAm()
 {
     Console.WriteLine("I'm a default dish soap");
     return this;
 }
Пример #42
0
        static void Main()
        {
            int[,] board = new int[16, 16];

            for (int i = 0; i < 16; i++)
            {
                string currentLine = Console.ReadLine();
                for (int j = 0; j < 16; j++)
                {
                    char currentSymbol = currentLine[j];
                    board[i, j] = currentSymbol - '0';
                }
            }

            while (true)
            {
                string currentOperation = Console.ReadLine();

                if (currentOperation == "cut")
                {
                    string wire = Console.ReadLine();
                    if (wire == "blue")
                    {
                        int countBlue = 0;
                        int countRed  = 0;


                        for (int row = 1; row < 15; row++)
                        {
                            for (int col = 1; col < 8; col++)
                            {
                                int currentRow = row;
                                int currentCol = col;


                                int aboveRow = row - 1;
                                int belowRow = row + 1;

                                int beforeCol = col - 1;
                                int afterCol  = col + 1;

                                bool topLeft      = false;
                                bool topMiddle    = false;
                                bool topRight     = false;
                                bool currentRight = false;
                                bool currentLeft  = false;
                                bool bottomLeft   = false;
                                bool bottomMiddle = false;
                                bool bottomRight  = false;

                                //check if all are 1
                                if (aboveRow >= 0 && beforeCol >= 0 && board[aboveRow, beforeCol] == 1)
                                {
                                    topLeft = true;
                                }

                                if (aboveRow >= 0 && board[aboveRow, currentCol] == 1)
                                {
                                    topMiddle = true;
                                }

                                if (aboveRow >= 0 && afterCol < 16 && board[aboveRow, afterCol] == 1)
                                {
                                    topRight = true;
                                }

                                if (beforeCol >= 0 && board[currentRow, beforeCol] == 1)
                                {
                                    currentLeft = true;
                                }

                                if (afterCol < 16 && board[currentRow, afterCol] == 1)
                                {
                                    currentRight = true;
                                }

                                if (belowRow < 16 && beforeCol >= 0 && board[belowRow, beforeCol] == 1)
                                {
                                    bottomLeft = true;
                                }

                                if (belowRow < 16 && board[belowRow, currentCol] == 1)
                                {
                                    bottomMiddle = true;
                                }

                                if (belowRow < 16 && afterCol < 16 && board[belowRow, afterCol] == 1)
                                {
                                    bottomRight = true;
                                }


                                // if  all are 1 turn them into 0
                                if (topLeft && topMiddle && topRight && currentLeft && currentRight && bottomLeft && bottomMiddle && bottomRight)
                                {
                                    countRed++;
                                }
                            }
                        }
                        Console.WriteLine(countRed);
                        Console.WriteLine("desarmed");
                    }
                    else
                    {
                        int countRed = 0;


                        for (int row = 1; row < 15; row++)
                        {
                            for (int col = 8; col < 15; col++)
                            {
                                int currentRow = row;
                                int currentCol = col;


                                int aboveRow = row - 1;
                                int belowRow = row + 1;

                                int beforeCol = col - 1;
                                int afterCol  = col + 1;

                                bool topLeft      = false;
                                bool topMiddle    = false;
                                bool topRight     = false;
                                bool currentRight = false;
                                bool currentLeft  = false;
                                bool bottomLeft   = false;
                                bool bottomMiddle = false;
                                bool bottomRight  = false;

                                //check if all are 1
                                if (aboveRow >= 0 && beforeCol >= 0 && board[aboveRow, beforeCol] == 1)
                                {
                                    topLeft = true;
                                }

                                if (aboveRow >= 0 && board[aboveRow, currentCol] == 1)
                                {
                                    topMiddle = true;
                                }

                                if (aboveRow >= 0 && afterCol < 16 && board[aboveRow, afterCol] == 1)
                                {
                                    topRight = true;
                                }

                                if (beforeCol >= 0 && board[currentRow, beforeCol] == 1)
                                {
                                    currentLeft = true;
                                }

                                if (afterCol < 16 && board[currentRow, afterCol] == 1)
                                {
                                    currentRight = true;
                                }

                                if (belowRow < 16 && beforeCol >= 0 && board[belowRow, beforeCol] == 1)
                                {
                                    bottomLeft = true;
                                }

                                if (belowRow < 16 && board[belowRow, currentCol] == 1)
                                {
                                    bottomMiddle = true;
                                }

                                if (belowRow < 16 && afterCol < 16 && board[belowRow, afterCol] == 1)
                                {
                                    bottomRight = true;
                                }


                                // if  all are 1 turn them into 0
                                if (topLeft && topMiddle && topRight && currentLeft && currentRight && bottomLeft && bottomMiddle && bottomRight)
                                {
                                    countRed++;
                                }
                            }
                        }

                        if (countRed == 0)
                        {
                            Console.WriteLine(countRed);
                            Console.WriteLine("desarmed");
                        }
                        else
                        {
                        }
                    }

                    break;
                }

                if (currentOperation == "hover" || currentOperation == "operate")
                {
                    int currentRow = int.Parse(Console.ReadLine());
                    int currentCol = int.Parse(Console.ReadLine());

                    if (currentOperation == "hover")
                    {
                        int currentNumber = board[currentRow, currentCol];
                        if (currentNumber == 1)
                        {
                            Console.WriteLine('*');
                        }
                        else
                        {
                            Console.WriteLine('-');
                        }
                    }

                    if (currentOperation == "operate")
                    {
                        int currentNumber = board[currentRow, currentCol];

                        if (currentNumber == 1)
                        {
                            Console.WriteLine("missed");

                            int count = 0;


                            for (int row = 1; row < 15; row++)
                            {
                                for (int col = 1; col < 15; col++)
                                {
                                    int aboveRow = row - 1;
                                    int belowRow = row + 1;

                                    int beforeCol = col - 1;
                                    int afterCol  = col + 1;

                                    bool topLeft      = false;
                                    bool topMiddle    = false;
                                    bool topRight     = false;
                                    bool currentRight = false;
                                    bool currentLeft  = false;
                                    bool bottomLeft   = false;
                                    bool bottomMiddle = false;
                                    bool bottomRight  = false;

                                    //check if all are 1
                                    if (aboveRow >= 0 && beforeCol >= 0 && board[aboveRow, beforeCol] == 1)
                                    {
                                        topLeft = true;
                                    }

                                    if (aboveRow >= 0 && board[aboveRow, currentCol] == 1)
                                    {
                                        topMiddle = true;
                                    }

                                    if (aboveRow >= 0 && afterCol < 16 && board[aboveRow, afterCol] == 1)
                                    {
                                        topRight = true;
                                    }

                                    if (beforeCol >= 0 && board[currentRow, beforeCol] == 1)
                                    {
                                        currentLeft = true;
                                    }

                                    if (afterCol < 16 && board[currentRow, afterCol] == 1)
                                    {
                                        currentRight = true;
                                    }

                                    if (belowRow < 16 && beforeCol >= 0 && board[belowRow, beforeCol] == 1)
                                    {
                                        bottomLeft = true;
                                    }

                                    if (belowRow < 16 && board[belowRow, currentCol] == 1)
                                    {
                                        bottomMiddle = true;
                                    }

                                    if (belowRow < 16 && afterCol < 16 && board[belowRow, afterCol] == 1)
                                    {
                                        bottomRight = true;
                                    }


                                    // if  all are 1 turn them into 0
                                    if (topLeft && topMiddle && topRight && currentLeft && currentRight && bottomLeft && bottomMiddle && bottomRight)
                                    {
                                        count++;
                                    }
                                }
                            }

                            if (count == 0)
                            {
                                Console.WriteLine(count);
                                Console.WriteLine("desarmed");
                            }
                            else
                            {
                            }


                            Console.WriteLine(count);
                            Console.WriteLine("BOOM");
                            break;
                        }
                        else
                        {
                            int aboveRow = currentRow - 1;
                            int belowRow = currentRow + 1;

                            int beforeCol = currentCol - 1;
                            int afterCol  = currentCol + 1;

                            bool topLeft      = false;
                            bool topMiddle    = false;
                            bool topRight     = false;
                            bool currentRight = false;
                            bool currentLeft  = false;
                            bool bottomLeft   = false;
                            bool bottomMiddle = false;
                            bool bottomRight  = false;

                            //check if all are 1
                            if (aboveRow >= 0 && beforeCol >= 0 && board[aboveRow, beforeCol] == 1)
                            {
                                topLeft = true;
                            }

                            if (aboveRow >= 0 && board[aboveRow, currentCol] == 1)
                            {
                                topMiddle = true;
                            }

                            if (aboveRow >= 0 && afterCol < 16 && board[aboveRow, afterCol] == 1)
                            {
                                topRight = true;
                            }

                            if (beforeCol >= 0 && board[currentRow, beforeCol] == 1)
                            {
                                currentLeft = true;
                            }

                            if (afterCol < 16 && board[currentRow, afterCol] == 1)
                            {
                                currentRight = true;
                            }

                            if (belowRow < 16 && beforeCol >= 0 && board[belowRow, beforeCol] == 1)
                            {
                                bottomLeft = true;
                            }

                            if (belowRow < 16 && board[belowRow, currentCol] == 1)
                            {
                                bottomMiddle = true;
                            }

                            if (belowRow < 16 && afterCol < 16 && board[belowRow, afterCol] == 1)
                            {
                                bottomRight = true;
                            }


                            // if  all are 1 turn them into 0
                            if (topLeft && topMiddle && topRight && currentLeft && currentRight && bottomLeft && bottomMiddle && bottomRight)
                            {
                                for (int row = aboveRow; row <= belowRow; row++)
                                {
                                    for (int col = beforeCol; col <= afterCol; col++)
                                    {
                                        board[row, col] = 0;
                                    }
                                }
                            }
                        }
                    }
                }
            }



            //Console.WriteLine();

            //for (int i = 0; i < 16; i++)
            //{
            //   for (int j = 0; j < 16; j++)
            //   {
            //      Console.Write(board[i, j]);
            //   }
            //   Console.WriteLine();

            //}
        }
Пример #43
0
    public Carla(ReadOnlyTargetRules Target) : base(Target)
    {
        PrivatePCHHeaderFile = "Carla.h";

        if (IsWindows(Target))
        {
            bEnableExceptions = true;
        }

        // Read config about carsim
        string CarlaPluginPath     = Path.GetFullPath(ModuleDirectory);
        string ConfigDir           = Path.GetFullPath(Path.Combine(CarlaPluginPath, "../../../../Config/"));
        string OptionalModulesFile = Path.Combine(ConfigDir, "OptionalModules.ini");

        string[] text = System.IO.File.ReadAllLines(OptionalModulesFile);
        foreach (string line in text)
        {
            if (line.Contains("CarSim ON"))
            {
                Console.WriteLine("Enabling carsim");
                UsingCarSim = true;
                PublicDefinitions.Add("WITH_CARSIM");
                PrivateDefinitions.Add("WITH_CARSIM");
            }
            if (line.Contains("Chrono ON"))
            {
                Console.WriteLine("Enabling chrono");
                UsingChrono = true;
                PublicDefinitions.Add("WITH_CHRONO");
                PrivateDefinitions.Add("WITH_CHRONO");
            }
        }

        PublicIncludePaths.AddRange(
            new string[] {
            // ... add public include paths required here ...
        }
            );

        PrivateIncludePaths.AddRange(
            new string[] {
            // ... add other private include paths required here ...
        }
            );

        PublicDependencyModuleNames.AddRange(
            new string[]
        {
            "Core",
            "RenderCore",
            "RHI",
            "ProceduralMeshComponent"
            // ... add other public dependencies that you statically link with here ...
        }
            );
        if (UsingCarSim)
        {
            PublicDependencyModuleNames.AddRange(new string[] { "CarSim" });
        }

        if (Target.Type == TargetType.Editor)
        {
            PublicDependencyModuleNames.AddRange(new string[] { "UnrealEd" });
        }

        PrivateDependencyModuleNames.AddRange(
            new string[]
        {
            "AIModule",
            "AssetRegistry",
            "CoreUObject",
            "Engine",
            "Foliage",
            "ImageWriteQueue",
            "Json",
            "JsonUtilities",
            "Landscape",
            "PhysX",
            "PhysXVehicles",
            "PhysXVehicleLib",
            "Slate",
            "SlateCore"
            // ... add private dependencies that you statically link with here ...
        }
            );
        if (UsingCarSim)
        {
            PrivateDependencyModuleNames.AddRange(new string[] { "CarSim" });
            PrivateIncludePathModuleNames.AddRange(new string[] { "CarSim" });
        }


        DynamicallyLoadedModuleNames.AddRange(
            new string[]
        {
            // ... add any modules that your module loads dynamically here ...
        }
            );

        AddCarlaServerDependency(Target);
    }
Пример #44
0
 public static void Main(string[] args)
 {
     int[] myArray = { 1, 2, 3, 4, 5 };
     Console.WriteLine(Somme(myArray));
     Console.WriteLine(ArrayAverage(myArray));
 }
Пример #45
0
 static void Main(string[] args)
 {
     Player player = new Player();
     ((ICricket)player).Play();
     Console.ReadKey();
Пример #46
0
 public static double aumento(double valor)
 {
     Console.WriteLine(valor);
     return valor*1.05;
 }
Пример #47
0
        public static void Main()
        {
            //Тест 1: при выборе правила вводим 0
            try
            {
                Inicial test1 = new Inicial();
                int tu1 = test1.SetVar("0");
            }
            catch
            {
                Console.WriteLine("Тест 1 - Ошибка обработки!");
            }
            finally
            {
                Console.WriteLine("Тест 1 пройден");
            }

            //Тест 2: при выборе правила вводим 7
            try
            {
                Inicial test2 = new Inicial();
                int tu2 = test2.SetVar("7");
            }
            catch
            {
                Console.WriteLine("Тест 2 - Ошибка обработки!");
            }
            finally
            {
                Console.WriteLine("Тест 2 пройден");
            }

            //Тест 3: при выборе правила вводим "test"
            try
            {
                Inicial test3 = new Inicial();
                int tu3 = test3.SetVar("test");
            }
            catch
            {
                Console.WriteLine("Тест 3 - Ошибка обработки!");
            }
            finally
            {
                Console.WriteLine("Тест 3 пройден");
            }

            //Тест 4: при выборе правила вводим "'@#$%#!@#"
            try
            {
                Inicial test4 = new Inicial();
                int tu4 = test4.SetVar("'@#$%#!@#");
            }
            catch
            {
                Console.WriteLine("Тест 4 - Ошибка обработки!");
            }
            finally
            {
                Console.WriteLine("Тест 4 пройден");
            }
           
            
            Console.WriteLine("");

            // ручная проверка: 

            Inicial init1 = new Inicial(); 
            init1.Mess();
            ConsoleReader CReaderCol = new ConsoleReader();
            int uu = 0;

            while (uu == 0)
            {
                string u = CReaderCol.GetNextStr1(); // пользователь вводит данные
                uu = init1.SetVar(u);

            }
            (string oc1, string oc2, string oc3) = init1.SortIni(uu); // выводим последовательность цветов, в зависимости от выбранного правила

            Console.WriteLine(oc1);
            Console.WriteLine(oc2);
            Console.WriteLine(oc3);

        GenObj gen1 = new GenObj(); // создаем массив несоритрованных объектов
        List<Obj> oL1 = gen1.genobj(oc1, oc2, oc3).Item2; 

        SorterMain sort1 = new SorterMain();     // сортируем массив объеков
            sort1.InList(oL1);            
        }
Пример #48
0
		static void Main(string[] args)
		{
			List<User> allUsers = new List<User>();
			while (true)
			{
				string input = Console.ReadLine();
				if (input == "end of dates")
				{
					break;
				}
				string[] nameDates = input.Split(' ', ',');
				string name = nameDates[0];
				var textDates = nameDates.Skip(1).ToList();
				List<DateTime> dates = textDates
					.Select(d => DateTime
					.ParseExact(d, "dd/MM/yyyy", CultureInfo.InvariantCulture))
					.ToList();
				if (allUsers.Select(u => u.Name).Contains(name))
				{
					for (int i = 0; i < allUsers.Count; i++)
					{
						if (allUsers[i].Name == name)
						{
							allUsers[i].Dates.AddRange(dates);
						}
					}
					
				}
				else
				{
					User user = new User
					{
						Name = name,
						Dates = dates,
						Comments = new List<string>()
					};
					allUsers.Add(user);
				}
				
			}

			while (true)
			{
				var input = Console.ReadLine();
				if (input == "end of comments")
				{
					break;
				}
				var nameComment = input.Split('-');
				var name = nameComment[0];
				var comment = nameComment[1];
				foreach (var user in allUsers)
				{
					if (user.Name == name)
					{
						user.Comments.Add(comment);
					}
				}
			}

			allUsers = allUsers.OrderBy(u => u.Name).ToList();
			foreach (var user in allUsers)
			{
				Console.WriteLine(user.Name);
				Console.WriteLine("Comments:");
				foreach (var comment in user.Comments)
				{
					Console.WriteLine($"- {comment}");
				}
				Console.WriteLine("Dates attended:");
				user.Dates = user.Dates.OrderBy(x => x).ToList();
				foreach (var date in user.Dates)
				{
					Console.WriteLine($"-- {date:dd/MM/yyyy}");
				}
			}
		}
Пример #49
0
 public static double rebaja(double valor)
 {
     Console.WriteLine(valor);
     return valor/2;
 }
Пример #50
0
 public virtual string GetNextStr2()
 {
     return Console.ReadLine();
 }
Пример #51
0
        public void Run(bool skipConnVerification)
        {
            var hostConnStr = _connectionStringResolver.GetNameOrConnectionString(new ConnectionStringResolveArgs(MultiTenancySides.Host));
            if (hostConnStr.IsNullOrWhiteSpace())
            {
                Log.Write("Configuration file should contain a connection string named 'Default'");
                return;
            }

            Log.Write("Host database: " + hostConnStr);
            if (!skipConnVerification)
            {
                Log.Write("Continue to migration for this host database and all tenants..? (Y/N): ");
                var command = Console.ReadLine();
                if (!command.IsIn("Y", "y"))
                {
                    Log.Write("Migration canceled.");
                    return;
                }
            }

            Log.Write("HOST database migration started...");

            try
            {
                _migrator.CreateOrMigrateForHost();
            }
            catch (Exception ex)
            {
                Log.Write("An error occured during migration of host database:");
                Log.Write(ex.ToString());
                Log.Write("Canceled migrations.");
                return;
            }

            Log.Write("HOST database migration completed.");
            Log.Write("--------------------------------------------------------");

            var migratedDatabases = new HashSet<string>();
            var tenants = _tenantRepository.GetAllList(t => t.ConnectionString != null && t.ConnectionString != "");
            for (int i = 0; i < tenants.Count; i++)
            {
                var tenant = tenants[i];
                Log.Write(string.Format("Tenant database migration started... ({0} / {1})", (i + 1), tenants.Count));
                Log.Write("Name              : " + tenant.Name);
                Log.Write("TenancyName       : " + tenant.TenancyName);
                Log.Write("Tenant Id         : " + tenant.Id);
                Log.Write("Connection string : " + SimpleStringCipher.Instance.Decrypt(tenant.ConnectionString));

                if (!migratedDatabases.Contains(tenant.ConnectionString))
                {
                    try
                    {
                        _migrator.CreateOrMigrateForTenant(tenant);
                    }
                    catch (Exception ex)
                    {
                        Log.Write("An error occured during migration of tenant database:");
                        Log.Write(ex.ToString());
                        Log.Write("Skipped this tenant and will continue for others...");
                    }

                    migratedDatabases.Add(tenant.ConnectionString);
                }
                else
                {
                    Log.Write("This database has already migrated before (you have more than one tenant in same database). Skipping it....");
                }

                Log.Write(string.Format("Tenant database migration completed. ({0} / {1})", (i + 1), tenants.Count));
                Log.Write("--------------------------------------------------------");
            }

            Log.Write("All databases have been migrated.");
        }
        static void ExecuteExampleCodeFromBook()
        {
            string plainText = "This is my super super secret data";

            // byte array to hold the encrypted message
            byte[] encryptedText;

            // byte arrays to hold the key that was used for encryption
            byte[] key1;
            byte[] key2;

            // byte array to hold the initialization vector that was used for encryption
            byte[] initializationVector1;
            byte[] initializationVector2;

            using (Aes aes1 = Aes.Create())
            {
                // copy the key and the initialization vector
                key1 = aes1.Key;
                initializationVector1 = aes1.IV;

                // create an encryptor to encrypt some data
                ICryptoTransform encryptor1 = aes1.CreateEncryptor();

                // Create a new memory stream to receive the 
                // encrypted data. 

                using (MemoryStream encryptMemoryStream = new MemoryStream())
                {
                    // create a CryptoStream, tell it the stream to write to
                    // and the encryptor to use. Also set the mode
                    using (CryptoStream cryptoStream1 = new CryptoStream(encryptMemoryStream,
                        encryptor1, CryptoStreamMode.Write))
                    {
                        // Add another layer of encryption
                        using (Aes aes2 = Aes.Create())
                        {
                            // copy the key and the initialization vector
                            key2 = aes2.Key;
                            initializationVector2 = aes2.IV;

                            ICryptoTransform encryptor2 = aes2.CreateEncryptor();

                            using (CryptoStream cryptoStream2 = new CryptoStream(cryptoStream1, encryptor2, CryptoStreamMode.Write))
                            {
                                using (StreamWriter swEncrypt = new StreamWriter(cryptoStream2))
                                {
                                    //Write the secret message to the stream.
                                    swEncrypt.Write(plainText);
                                }
                                // get the encrypted message from the stream
                                encryptedText = encryptMemoryStream.ToArray();
                            }
                        }
                    }
                }
            }

            // Dump out our data
            Console.WriteLine("String to encrypt: {0}", plainText);
            dumpBytes("Key1: ", key1);
            dumpBytes("Initialization Vector1: ", initializationVector1);
            dumpBytes("Key2: ", key2);
            dumpBytes("Initialization Vector2: ", initializationVector2);
            dumpBytes("Encrypted: ", encryptedText);

            // Now do the decryption
            string decryptedText;

            using (Aes aesd1 = Aes.Create())
            {
                // Configure the aes instances with the key and 
                // initialization vector to use for the decryption
                aesd1.Key = key1;
                aesd1.IV = initializationVector1;

                // Create a decryptor from aes1
                ICryptoTransform decryptor1 = aesd1.CreateDecryptor();

                using (MemoryStream decryptStream = new MemoryStream(encryptedText))
                {
                    using (CryptoStream decryptCryptoStream1 =
                        new CryptoStream(decryptStream, decryptor1, CryptoStreamMode.Read))
                    {
                        using (Aes aesd2 = Aes.Create())
                        {
                            // Configure the aes instances with the key and 
                            // initialization vector to use for the decryption
                            aesd2.Key = key2;
                            aesd2.IV = initializationVector2;

                            // Create a decryptor from aes2
                            ICryptoTransform decryptor2 = aesd2.CreateDecryptor();

                            using (CryptoStream decryptCryptoStream2 =
                                new CryptoStream(decryptCryptoStream1, decryptor2, CryptoStreamMode.Read))
                            {
                                using (StreamReader srDecrypt = new StreamReader(decryptCryptoStream2))
                                {
                                    decryptedText = srDecrypt.ReadToEnd();
                                }
                            }
                        }
                    }
                }

                Console.WriteLine("Decrypted string: {0}", decryptedText);

                Console.ReadKey();
            }
        }
Пример #53
0
    private static int run(Ice.Communicator communicator)
    {
        HelloPrx hello = null;

        try
        {
            hello = HelloPrxHelper.checkedCast(communicator.stringToProxy("hello"));
        }
        catch (Ice.NotRegisteredException)
        {
            var query =
                IceGrid.QueryPrxHelper.checkedCast(communicator.stringToProxy("DemoIceGrid/Query"));
            hello = HelloPrxHelper.checkedCast(query.findObjectByType("::Demo::Hello"));
        }
        if (hello == null)
        {
            Console.WriteLine("couldn't find a `::Demo::Hello' object");
            return(1);
        }

        menu();

        string line = null;

        do
        {
            try
            {
                Console.Write("==> ");
                Console.Out.Flush();
                line = Console.In.ReadLine();
                if (line == null)
                {
                    break;
                }
                if (line.Equals("t"))
                {
                    hello.sayHello();
                }
                else if (line.Equals("s"))
                {
                    hello.shutdown();
                }
                else if (line.Equals("x"))
                {
                    // Nothing to do
                }
                else if (line.Equals("?"))
                {
                    menu();
                }
                else
                {
                    Console.WriteLine("unknown command `" + line + "'");
                    menu();
                }
            }
            catch (Ice.LocalException ex)
            {
                Console.WriteLine(ex);
            }
        }while(!line.Equals("x"));

        return(0);
    }
Пример #54
0
 static void Main()
 {
     int[] a = { 1, 5, 9, 7, 9 };
     int[] b = { 8, 7, 4, 6 };
     Console.WriteLine(Add(a, b));
 }
Пример #55
0
 private static void PlayPartyGames()
 {
     Console.WriteLine("Starting games");
     Thread.Sleep(TimeSpan.FromSeconds(2));
     Console.WriteLine("Finishing Games");
 }
Пример #56
0
        static async Task Main(string[] args)
        {
            var headerPath  = args[0];
            var libraryPath = args[1];
            var gitHubToken = args[2];
            var repoPath    = args[3];

            var repoSlug   = Environment.GetEnvironmentVariable("GITHUB_REPOSITORY");
            var repoSplits = repoSlug.Split('/');
            var repoOwner  = repoSplits[0];
            var repoName   = repoSplits[1];

            var gitHubClient = new GitHubClient(new ProductHeaderValue("Tgstation.Server.DMApiUpdater", "1.0.0"))
            {
                Credentials = new Octokit.Credentials(gitHubToken)
            };

            var releaseTask = GetLatestDMApiBytes(gitHubClient, repoOwner, repoName);

            Console.WriteLine("Deleting old DMAPI...");

            var targetHeaderPath = Path.Combine(repoPath, headerPath);

            if (File.Exists(targetHeaderPath))
            {
                File.Delete(targetHeaderPath);
            }

            var targetLibraryPath = Path.Combine(repoPath, libraryPath);

            if (Directory.Exists(targetLibraryPath))
            {
                RecursiveDelete(targetLibraryPath);
            }

            var releaseTuple = await releaseTask;
            var zipBytes     = releaseTuple.Item1;

            Console.WriteLine("Unzipping replacement DMAPI...");
            using var zipStream = new MemoryStream(zipBytes);
            using var archive   = new ZipArchive(zipStream, ZipArchiveMode.Read);
            foreach (var entry in archive.Entries)
            {
                if (entry.FullName.EndsWith('/'))
                {
                    continue;
                }

                string targetPath;
                if (entry.Name.Equals("tgs.dm", StringComparison.Ordinal))
                {
                    targetPath = targetHeaderPath;
                }
                else
                {
                    targetPath = Path.Combine(targetLibraryPath, "..", entry.FullName);
                }

                var dir = Path.GetDirectoryName(targetPath);
                Directory.CreateDirectory(dir);
                entry.ExtractToFile(targetPath);
            }
        }
        /*  [DataMember(Name = "id")]
         * public long Id { get; set; }*/


        public Notification Process(BusinessDbContext context, string adminId, ValidationSender sender, string connectionString, Notification notification)
        {
            var queryString = $@"
              SELECT DISTINCT ON(users.""Id"") users.""Id"", users.""ValidatedEmail"", users.""ValidatedSms"",  users.""Enabled"", users.""Email"", users.""PhoneNumber"",  users.""EnabledEmail"", users.""EnabledSms"",
                addr.""GeoLocation"", addr.""UserId"",
                noti.""AffectedArea"" FROM public.""Address""  addr, public.""AllUsers"" users, public.""Notifications"" noti
                where ST_Intersects(ST_SetSRID(noti.""AffectedArea"",4326),addr.""GeoLocation"") and users.""Id"" = addr.""UserId"" and  noti.""Id"" = {notification.Id}
                ";

            var foundUsers = new List <Rows>();

            try
            {
                using (var connection = context.Database.GetDbConnection())
                {
                    connection.Open();

                    using (var command = connection.CreateCommand())
                    {
                        command.CommandText = queryString;
                        using (var reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                foundUsers.Add(new Rows()
                                {
                                    Id             = (Guid)reader[0],
                                    ValidatedEmail = (bool)reader[1],
                                    ValidatedSms   = (bool)reader[2],
                                    Enabled        = (bool)reader[3],
                                    Email          = (reader[4] ?? "").ToString(),
                                    PhoneNumber    = (reader[5] ?? "").ToString(),
                                    EnabledEmail   = (bool)reader[6],
                                    EnabledSms     = (bool)reader[7]
                                });
                            }
                        }
                    }


                    context.Notifications.Update(notification);
                    notification.Status        = NotiStatus.Published;
                    notification.Published     = DateTime.Now;
                    notification.PublishedById = new Guid(adminId);
                    context.SaveChanges();

                    Log.Information("Sending out notification to {count} users", foundUsers.Count);

                    // Use the notification bounds and find the users which fall into those bounds
#pragma warning disable 4014
                    Broadcast(connectionString, sender, foundUsers, notification);
#pragma warning restore 4014

                    // Use their communication information which has been validated to fire off the messages

                    // Collect stats with the broadcasting

                    return(notification);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Пример #58
0
        /// <summary>
        /// Handles receiving bytes of data over the WebSocket.
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="data"></param>
        private void OnMessage(IWebSocketConnection socket, string message)
        {
            Console.WriteLine($"Socket {socket.ConnectionInfo} received {message}.");
            var packet   = JToken.Parse(message);
            var packetId = packet.Value <int>("PacketId");
            var uid      = packet.Value <int>("UserId");

            // Compare packet IDs to the client packets
            switch (packetId)
            {
            // Login request from client
            case 0:
                if (_table.GameInProgress)
                {
                    return;
                }

                if (uid == -1)
                {
                    Console.WriteLine("Creating new user.");
                    // unknown user
                    uid = Guid.NewGuid().GetHashCode();
                    Console.WriteLine($"User was created with UID {uid}.");
                }

                lock (_userIdMapLock)
                {
                    UserIdToSockets[uid] = socket;
                }

                var loginStatus = default(byte);

                if (_table.Players.Count >= _maxPlayers)
                {
                    loginStatus = 1;
                }
                else
                {
                    // Player is able to be seated at the table.
                    loginStatus = 0;
                    _table.AddPlayer(new Model.Player(uid));
                }

                var responsePacket = new LoginResponse
                {
                    PacketId    = 0,
                    LoginStatus = loginStatus,
                    UserId      = uid
                };

                socket.Send(JsonConvert.SerializeObject(responsePacket));

                if (_table.Players.Count == _maxPlayers)
                {
                    _table.StartGame();
                }
                break;

            // Bet/call request
            case 1:
                if (uid != _table.ActivePlayer.Id || !_table.GameInProgress)
                {
                    return;
                }

                Console.WriteLine($"Player {uid} submitted bid for {packet.Value<int>("BetAmount")}");
                if (_table.PlaceBet(uid, packet.Value <int>("BetAmount")))
                {
                    var updateChipPacket = new UpdatePlayerChipCount
                    {
                        PacketId     = 5,
                        UserId       = uid,
                        NewChipCount = _table.ActivePlayer.Chips,
                        NewPotCount  = _table.Pot
                    };

                    BroadcastMessage(JsonConvert.SerializeObject(updateChipPacket));
                    _table.CycleActivePlayer();
                }
                break;

            // General action request
            case 2:
                if (uid != _table.ActivePlayer.Id || !_table.GameInProgress)
                {
                    return;
                }

                var action  = packet.Value <GeneralAction>("Action");
                var handled = false;
                if (action == GeneralAction.Check)
                {
                    handled = _table.HandleCheck(uid);
                }
                else
                {
                    handled = _table.MarkPlayerFolded(uid);
                }

                if (handled)
                {
                    _table.CycleActivePlayer();
                }
                break;
            }
        }
Пример #59
0
 static void Main(string[] args)
 {
     Console.WriteLine("Hello World! modified");
 }
Пример #60
0
 static void doWork()
 {
     Console.WriteLine(Util.Sum(2, 4, 6, 8));	
 }