Exemplo n.º 1
0
        public void ReturnColumnCollectionTest()
        {
            var dataMethods      = DataMethods.GetInstance();
            var returnADataTable = new ReturnADataTable_ForTesting();

            var testDataTable = returnADataTable.TestDataTable();

            Console.WriteLine("DataTable Row Count " + testDataTable.Rows.Count);

            //var testCollection = dataMethods.ReturnColumnCollection<string>(testDataTable, _csvHeader[0]);
            //var testCollection = dataMethods.ReturnColumnCollection<string>(testDataTable, _csvHeader[1]);
            //var testCollection = dataMethods.ReturnColumnCollection<int>(testDataTable, _csvHeader[2]);
            var testCollection = dataMethods.ReturnColumnCollection <string>(testDataTable, _csvHeader[3]);

            Console.WriteLine("Column from dataTable");
            foreach (var cell in testCollection.ToArray())
            {
                Console.WriteLine(cell);
            }

            Console.WriteLine("TestArray");
            foreach (var cell in _colArray4)
            {
                Console.WriteLine(cell);
            }


            //CollectionAssert.AreEqual(testCollection.ToArray(), colArray1);
            //CollectionAssert.AreEqual(testCollection.ToArray(), colArray2);
            //CollectionAssert.AreEqual(testCollection.ToArray(), colArray3);
            CollectionAssert.AreEqual(testCollection.ToArray(), _colArray4);

            //Assert.AreEqual(4, testCollection.Count);
        }
Exemplo n.º 2
0
        private void SaveNote(int rowIndex)
        {
            object note = NotesGrid.Rows[rowIndex].Cells["NoteColumn"].Value;

            if (note == null || note.ToString().Trim() == string.Empty)
            {
                return;
            }

            DateTime noteDate = InsertDateOnNote(rowIndex);

            int noteId;

            if (NotesGrid.Rows[rowIndex].Cells["IDColumn"].Value == null)
            {
                noteId = 0;
            }
            else
            {
                bool isInt = int.TryParse(NotesGrid.Rows[rowIndex].Cells["IDColumn"].Value.ToString(), out noteId);
                if (!isInt)
                {
                    noteId = 0;
                }
            }

            DataMethods tmp       = new DataMethods();
            Note        savedNote = tmp.AddNote(noteId, ConversationID, noteDate, note.ToString());

            DisplayNoteInGrid(rowIndex, savedNote);
        }
Exemplo n.º 3
0
        private async Task Client_JoinedGuild(SocketGuild arg)
        {
            var botGuilds = Client.Guilds.ToList();

            foreach (SocketGuild botGuild in botGuilds)
            {
                var serverRecord = DataMethods.GetServer(botGuild.Id);

                if (serverRecord == null)
                {
                    await DataMethods.AddServer(botGuild.Id, botGuild.Name);

                    Console.WriteLine("server added - " + botGuild.Name);

                    var introChannels = botGuild.TextChannels.Where(x => x.Name.Contains("intros")).ToList();

                    Console.WriteLine("wrote list of channels");

                    foreach (SocketTextChannel introChannel in introChannels)
                    {
                        await DataMethods.AddIntroChannel(botGuild.Id, introChannel.Id);
                    }

                    Console.WriteLine("added channels to database");
                }
            }
        }
Exemplo n.º 4
0
        private async Task Client_Ready()
        {
            await Client.SetGameAsync("!!help for commands", "http://www.google.com", ActivityType.Watching);

            DataMethods.ReloadMenus();

            var botGuilds = Client.Guilds.ToList();

            foreach (SocketGuild botGuild in botGuilds)
            {
                var serverRecord = DataMethods.GetServer(botGuild.Id);

                if (serverRecord == null)
                {
                    await DataMethods.AddServer(botGuild.Id, botGuild.Name);

                    Console.WriteLine("server added - " + botGuild.Name);

                    var introChannels = botGuild.TextChannels.Where(x => x.Name.Contains("intros")).ToList();

                    Console.WriteLine("wrote list of channels");

                    foreach (SocketTextChannel introChannel in introChannels)
                    {
                        await DataMethods.AddIntroChannel(botGuild.Id, introChannel.Id);
                    }
                }
            }
        }
Exemplo n.º 5
0
        public async Task ListKinks()
        {
            var kinksAndLimits = DataMethods.GetUserKinksAndLimits();

            if (kinksAndLimits == null)
            {
                await CommandStatus("There appear to be no kinks or limits", "listkinks");

                return;
            }

            string dmString = "​\n" + "**" + "All Kinks:" + "\n━━━━━━━" + "**" + "\n\n​";

            foreach (var gk in kinksAndLimits)
            {
                dmString += gk.Group.KinkGroupName + "\n━━━━━━━" + "\n\n​";

                foreach (var k in gk.KinksForGroup)
                {
                    dmString += k.KinkName + " - " + k.KinkDesc + "\n";
                }

                dmString += "\n​";
            }



            await DmSplit(dmString);
            await CommandStatus("DM Sent", "listkinks");
        }
Exemplo n.º 6
0
            public async Task Give(IUser User = null, int Amount = 0)
            {
                //stones give @fifthfiend 1000
                //group  cmd  user        amount

                //checks
                //does user have permissions?
                //does user have enough stones?
                if (User == null)
                {
                    //The executer has not mentioned a user
                    await Context.Channel.SendMessageAsync(":x: You didn't mention a user to give the stones to! Please use this syntax: !!stones give **<@user> <amount>");

                    return;
                }

                //Make sure a user has been pinged
                if (User.IsBot)
                {
                    await Context.Channel.SendMessageAsync(":x: Bots can't use this bot, so you can't give stones to a bot!");

                    return;
                }

                //At this point we know a user is pinged and is not a bot
                if (Amount < 1)
                {
                    await Context.Channel.SendMessageAsync($":x: You need to specify a valid amount of stones that I need to give to {User.Username}!");

                    return;
                }

                //user is pinged, not a bot, gave a valid coin number

                SocketGuildUser User1 = Context.User as SocketGuildUser;

                if (!User1.GuildPermissions.Administrator)
                {
                    await Context.Channel.SendMessageAsync($":x: You don't have administrator permissions in this discord server! Ask an administrator or the owner to execute this command!");

                    return;
                }


                //execution
                //calculations (games)
                // telling the user what he's gotten

                await Context.Channel.SendMessageAsync($":tada: {User.Mention} you have received **{Amount}** stones from {Context.User.Username}");

                //saving the data
                //save the data to the database
                //save a file

                await DataMethods.SaveStones(User.Id, Amount);

                return;
            }
Exemplo n.º 7
0
        public async Task EditGroupMenu(ulong postID, params string[] parameters)
        {
            //var postToEdit = await Context.Channel.GetMessageAsync(postID) as SocketMessage;

            (KinkGroupMenu menuRecord, string groupName) = DataMethods.getMenuRecord(postID, Context.Guild.Id);

            if (menuRecord == null)
            {
                await Context.Channel.SendMessageAsync("Invalid post");

                return;
            }
            bool isLimit = false;

            if (menuRecord.LimitMsgID == postID)
            {
                isLimit = true;
            }

            if (
                (isLimit && menuRecord.LimitChannelID != Context.Channel.Id) ||
                (!isLimit && menuRecord.KinkChannelID != Context.Channel.Id)
                )
            {
                await Context.Channel.SendMessageAsync("Wrong channel");

                return;
            }

            string limitOrKink = isLimit ? "Limit" : "Kink";
            string editMenuMsg = "Editing the " + limitOrKink + " menu for Kink Group - " + groupName + "\n\n​";

            editMenuMsg += "Do you want to reuse existing data or start from scratch? Reuse, Scratch, or anything else to quit." + "\n\n​";

            var menuEditMessage = await Context.Channel.SendMessageAsync(editMenuMsg);

            /*
             * if (!Vars.menuBuilder.IsActive)
             * {
             *  await Context.Channel.SendMessageAsync("Fartz (variable is false)");
             *
             * }
             */

            Vars.menuBuilder.EmojiMenuID   = isLimit ? menuRecord.LimitMsgID : menuRecord.KinkMsgID;
            Vars.menuBuilder.EditMenuID    = menuEditMessage.Id;
            Vars.menuBuilder.ChannelID     = Context.Channel.Id;
            Vars.menuBuilder.UserID        = Context.User.Id;
            Vars.menuBuilder.ServerID      = Context.Guild.Id;
            Vars.menuBuilder.CommandStep   = 2;
            Vars.menuBuilder.IsActive      = true;
            Vars.menuBuilder.IsLimitMenu   = isLimit;
            Vars.menuBuilder.KinkGroupName = groupName;
            Vars.menuBuilder.KinkGroupID   = menuRecord.KinkGroupID;
            Vars.menuBuilder.KinksToUpdate = DataMethods.GetKinksInGroupWithEmojis(menuRecord.KinkGroupID, Context.Guild.Id);
        }
Exemplo n.º 8
0
        public async Task Dodge()
        {
            await DataMethods.RemoveOldAttacks();

            (ulong AttackerId, string Name) = DataMethods.getAttacker(Context.User.Id);

            if (AttackerId == 0)
            {
                await Context.Channel.SendMessageAsync("what are you dodging?");

                return;
            }
            else
            {
                Random rng          = new Random();
                int    DodgeAttempt = rng.Next(1, 100);

                IUser Attacker = Context.Guild.GetUser(AttackerId);
                if (Name.Equals("shoot"))
                {
                    if (DodgeAttempt > 50)
                    {
                        await Context.Channel.SendMessageAsync($"*{Context.User.Mention} dodges a bullet from {Attacker.Mention}! Wow, that was quick!*");
                    }
                    else
                    {
                        await Context.Channel.SendMessageAsync($"*{Context.User.Mention} fails to dodge, and takes a bullet right in the face from {Attacker.Mention}!*  :boom:");
                    }
                }
                else if (Name.Equals("spank"))
                {
                    if (DodgeAttempt > 70)
                    {
                        await Context.Channel.SendMessageAsync($"*{Context.User.Mention} gets their butt out of the way! Better luck next time {Attacker.Mention}!*");
                    }
                    else
                    {
                        await Context.Channel.SendMessageAsync($"*{Context.User.Mention} fails to dodge, and takes a spank right on the butt from {Attacker.Mention}!*  :boom:");
                    }
                }
                else if (Name.Equals("whip"))
                {
                    if (DodgeAttempt > 60)
                    {
                        await Context.Channel.SendMessageAsync($"*{Attacker.Mention} cracks their whip at thin air as {Context.User.Mention} evades!*");
                    }
                    else
                    {
                        await Context.Channel.SendMessageAsync($"*{Context.User.Mention} fails to dodge, and takes a vicious lashing from {Attacker.Mention}!*  :boom:");
                    }
                }

                await DataMethods.RemoveAttack(Context.User.Id);
            }
        }
Exemplo n.º 9
0
        private void LoadNotes(string conversationId)
        {
            NotesGrid.Rows.Clear();
            DataMethods tmp   = new DataMethods();
            List <Note> notes = tmp.GetNotes(conversationId);

            foreach (Note note in notes)
            {
                int newRowIndex = NotesGrid.Rows.Add();
                DisplayNoteInGrid(newRowIndex, note);
            }
        }
Exemplo n.º 10
0
        private void UserDeletingRow(object sender, System.Windows.Forms.DataGridViewRowCancelEventArgs e)
        {
            int noteId = GetNoteIdFromGrid(e.Row.Index);

            if (noteId <= 0)
            {
                // Note not in DB nothing to do.
                return;
            }

            var tmp = new DataMethods();

            tmp.DeleteNote(noteId);
        }
Exemplo n.º 11
0
        public static void BuildMinuteDayNodes(ThreadControl tc)
        {
            // this should be called AFTER updated yesterday's ticks AND data tracker no data days updated


            List <string> symbols = new List <string>(Global.State.AllSymbols);

            symbols.Shuffle();

            symbols.Remove("spy");
            symbols.Remove("aapl");
            symbols.Add("spy");
            symbols.Add("aapl");
            symbols.Reverse();



            ZonedDateTime ie = SystemClock.Instance.GetCurrentInstant().InZone(UCDT.TimeZones.Eastern);

            // set the current date to yesterday via eastern timezone just to be safe
            DateTime dt = new DateTime(ie.Year, ie.Month, ie.Day, 0, 0, 0, DateTimeKind.Unspecified).AddDays(-20);


            DateTime firstDataDay = Global.State.DataTracker.DataDays[0].DT;

            while (dt > firstDataDay && tc.CheckNotStopped())
            {
                FD fd = new FD(dt);

                Parallel.For(0, symbols.Count, new ParallelOptions {
                    MaxDegreeOfParallelism = 20
                }, n =>
                {
                    if (DataMethods.DayNodesDataCacheable(symbols[n], fd))
                    {
                        Stopwatch sw = new Stopwatch();
                        sw.Start();
                        NodesData nodes = DataMethods.GetCachedDayNodesData(symbols[n], fd, Interval.HalfSecond, computeNodes: false, justCache: true);
                        sw.Stop();
                        tc.Log.AddLine("[" + symbols[n] + "] " + fd.ToString() + " Done. Took " + UC.MillisecondsToSeconds(sw.ElapsedMilliseconds, 2) + " sec(s)");
                    }
                    else
                    {
                        tc.Log.AddLine("[" + symbols[n] + "] " + fd.ToString() + ". Not cacheable.");
                    }
                });

                dt = dt.AddDays(-1);
            }
        }
Exemplo n.º 12
0
        public async Task shoot(IUser User = null)
        {
            if (User == null)
            {
                await Context.Channel.SendMessageAsync($"Who were you trying to shoot, {Context.User.Mention}?");

                return;
            }

            await Context.Channel.SendMessageAsync($"*{Context.User.Mention} shoots {User.Mention} with a gun! BLAM!*  :gun:");

            await DataMethods.SaveAttack(Context.User.Id, User.Id, "shoot");

            return;
        }
Exemplo n.º 13
0
        public async Task Spank(IUser User = null)
        {
            if (User == null)
            {
                await Context.Channel.SendMessageAsync($"Who were you trying to spank, {Context.User.Mention}?");

                return;
            }

            await Context.Channel.SendMessageAsync($"*{Context.User.Mention} spanks {User.Mention} right on the butt! YOWCH!*  :clap:");

            await DataMethods.SaveAttack(Context.User.Id, User.Id, "spank");

            return;
        }
Exemplo n.º 14
0
        /// <summary>
        /// Creates a new instance of Core
        /// </summary>
        /// <param name="Settings"></param>
        /// <param name="metadata"></param>
        /// <param name="SecurityRoles"></param>
        /// <param name="Workflows"></param>
        public Core(XrmMockupSettings Settings, MetadataSkeleton metadata, List <Entity> Workflows, List <SecurityRole> SecurityRoles)
        {
            this.dataMethods    = new DataMethods(this, metadata, SecurityRoles);
            this.ServiceFactory = new MockupServiceProviderAndFactory(this);
            this.settings       = Settings;
            this.InitRequestMap();
            this.pluginManager   = new PluginManager(Settings.BasePluginTypes, metadata.EntityMetadata, metadata.Plugins);
            this.workflowManager = new WorkflowManager(Settings.CodeActivityInstanceTypes, Settings.IncludeAllWorkflows, Workflows, metadata.EntityMetadata);

            var tracingService = new TracingService();
            var factory        = new MockupServiceProviderAndFactory(this, null, tracingService);
            var service        = factory.CreateOrganizationService(null, new MockupServiceSettings(false, true, MockupServiceSettings.Role.SDK));

            dataMethods.SetWorkflowServices(tracingService, factory, service);
        }
Exemplo n.º 15
0
        public async Task Whip(IUser User = null)
        {
            if (User == null)
            {
                await Context.Channel.SendMessageAsync($"Who were you trying to whip, {Context.User.Mention}?");

                return;
            }

            await Context.Channel.SendMessageAsync($"*{Context.User.Mention} lashes {User.Mention} with a whip! CRACK!*");

            await DataMethods.SaveAttack(Context.User.Id, User.Id, "whip");

            return;
        }
Exemplo n.º 16
0
        /// <summary>
        /// When simulating, this method will load all of the needed nodes for simulating a live feed/stream.
        /// </summary>
        private void PrepareSimDayNodes()
        {
            if (AlgoTraderState.IsSim)
            {
                // load up today's nodes for StreamManager to pretend to add nodes by using today's nodes

                int       amount = 100;
                Stopwatch sw     = new Stopwatch();
                sw.Start();

                object lockObj = new object();

                for (int m = 0; m < Global.State.AllSymbols.Count; m += amount)
                {
                    Parallel.For(0, amount, new ParallelOptions {
                        MaxDegreeOfParallelism = 30
                    }, n =>
                    {
                        if (m + n < Global.State.AllSymbols.Count)
                        {
                            // NodesData nodes = null;
                            NodesData nodes = DataMethods.GetCachedDayNodesData(Global.State.AllSymbols[m + n], AlgoTraderState.CurrentDay, Interval.HalfSecond, justCache: false);

                            // NodesData nodesData = DataMethods.GetCachedDayNodesData(Global.State.AllSymbols[m + n], CurrentDay, Interval.HalfSecond, computeNodes: true, justCache: false);

                            // no need to ComputeGaps because it's 1 day... trusting well formatted data
                            lock (lockObj)
                            {
                                AlgoTraderShared.SimDayNodes.Add(Global.State.AllSymbols[m + n], nodes);

                                //nodes.Add(Global.State.AllSymbols[m + n], DataMethods.GetCachedDayNodesData(Global.State.AllSymbols[m + n], CurrentDay, Interval.HalfSecond, computeNodes: true, justCache: false));
                            }
                            TC.Log.AddLine("Loaded " + Global.State.AllSymbols[m + n] + " stock nodes for stream manager");
                        }
                    });

                    if (!TC.CheckNotStopped())
                    {
                        break;
                    }
                }

                sw.Stop();

                TC.Log.AddLine("Finished loading sim nodes for stream manager in " + UC.MillisecondsToSeconds(sw.ElapsedMilliseconds, 3) + " sec(s). That's " + ((decimal)Global.State.AllSymbols.Count / UC.MillisecondsToSeconds(sw.ElapsedMilliseconds, 3)) + " per sec.");
            }
        }
Exemplo n.º 17
0
        public async Task GroupKinks(params string[] parameters)
        {
            if (parameters.Length < 2)
            {
                await Context.Channel.SendMessageAsync("Insufficient data, quitting!");

                return;
            }

            List <string> kinkList  = parameters.ToList();
            string        groupName = kinkList[0];

            kinkList.RemoveAt(0);



            KinkGroup groupToJoin = DataMethods.GetGroup(groupName);

            if (groupToJoin == null)
            {
                await Context.Channel.SendMessageAsync("Invalid group, quitting!");

                return;
            }

            string adding = "Adding kinks to " + groupToJoin.KinkGroupName + "\n";

            foreach (string kinkName in kinkList)
            {
                bool kinkFound = await DataMethods.AddKinkToGroup(groupToJoin.KinkGroupID, kinkName, Context.Guild.Id);

                if (kinkFound)
                {
                    adding += kinkName + " added\n";
                }
                else
                {
                    adding += kinkName + " is not a valid kink\n";
                }
            }


            await Context.Channel.SendMessageAsync(adding);
        }
Exemplo n.º 18
0
        public async Task KinkRemover(SocketReaction reaction)
        {
            var reactedMenu = Vars.groupMenus.Where
                              (
                x => x.KinkMsgID == reaction.MessageId ||
                x.LimitMsgID == reaction.MessageId
                              ).FirstOrDefault();

            bool isLimit = false;

            if (reactedMenu.LimitMsgID == reaction.MessageId)
            {
                isLimit = true;
            }

            ulong kinkIDToAdd = DataMethods.GetKinkFromMenu(reactedMenu, reaction.Emote);

            await DataMethods.RemoveUserKink(reaction.UserId, kinkIDToAdd, isLimit);
        }
Exemplo n.º 19
0
        public static List <Trade> GetHistoricTradesFull(string symbol, int year, int month, int day, long startTimestamp = -1)
        {
            List <Trade> result = new List <Trade>();

            List <Trade> items;

            items = GetHistoricTrades(symbol, year, month, day, -1, startTimestamp);

            result.AddRange(items);

            while (items.Count != 0)
            {
                items = GetHistoricTrades(symbol, year, month, day, -1, items[items.Count - 1].Timestamp + 1);
                result.AddRange(items);
            }

            result = result.OrderBy(t => t.Timestamp).ToList();

            DataMethods.DeDupeTrades(result);

            return(result);
        }
Exemplo n.º 20
0
        private void btnGuardar_Click(object sender, RoutedEventArgs e)
        {
            User usuario = new User();

            usuario.Email       = txtCorreo.Text;
            usuario.FirstName   = txtFirtsName.Text;
            usuario.LastName    = txtLastName.Text;
            usuario.Names       = txtName.Text;
            usuario.Password    = txtPassword.ToString();
            usuario.Nick        = txtNick.Text;
            usuario.DateOfBirth = (DateTime)dtFecha.Value;
            usuario.Sexo        = sexoActual;


            MessageBox.Show(usuario.Nick);
            if (usuario.sexo != -1 && !usuario.Email.Equals("") && !usuario.FirstName.Equals("") && !usuario.LastName.Equals("") &&
                !usuario.Names.Equals("") && !usuario.Password.Equals("") && !usuario.Nick.Equals(""))
            {
                MessageBoxResult result;
                {
                    result = MessageBox.Show("Sure to keep your information, then could not modify",
                                             "Warning",
                                             MessageBoxButton.OKCancel);

                    if (result == MessageBoxResult.OK)
                    {
                        DataMethods.Register(usuario.Email, usuario.Password, usuario.Nick, usuario.FirstName, usuario.LastName, usuario.Names, usuario.Sexo, usuario.PhysicalComplexion, usuario.LevelActivity, usuario.Weight, usuario.Height, usuario.DateOfBirth);
                        NavigationService.Navigate(new Uri("/Views/Information.xaml", UriKind.Relative));
                    }
                }
            }
            else
            {
                MessageBox.Show("Missing data");
            }

            //ACA DEBERIA GUARDAR EL USUARIO CON SU INFORMACION Y ENVIAR EN NAVEGACION MI NICK Y PASSWORD PARA LUEGO ACTUALIZAR INFO
            //Metodos.AgregarDatosUsuario(nuevoDatosUsuario);
        }
Exemplo n.º 21
0
        public void PopulateDataTableTest()
        {
            var csvFilePath = @"C:\stocklist.CSV";

            var fileIO = new FileIO();

            var textFieldParser = fileIO.ReturnCSVData(csvFilePath);

            var dataTabe = DataMethods.GetInstance().PopulateDataTable(textFieldParser, _csvHeader);

            var rowCount = dataTabe.Rows.Count;

            var columnCount = dataTabe.Columns.Count;

            var rowColumnIntArray = new int[] { rowCount, columnCount };

            var compareIntArray = new int[] { 40, 4 };

            Console.WriteLine("Row count {0}", rowCount);
            Console.WriteLine("Column count {0}", columnCount);

            CollectionAssert.AreEqual(rowColumnIntArray, compareIntArray);
        }
Exemplo n.º 22
0
        public void CompareCurrentCountsTablesTest()
        {
            // Class Lists for testing
            var user1 = new AppUser {
                UserName = "******", Password = "******"
            };
            var user2 = new AppUser {
                UserName = "******", Password = "******"
            };

            var userList1 = new List <AppUser> {
                user1, user2
            };
            var userList2 = new List <AppUser> {
                user1, user2
            };

            var userList3 = new List <AppUser> {
                new AppUser {
                    UserName = "******", Password = "******"
                },
                new AppUser {
                    UserName = "******", Password = "******"
                }
            };

            // Primitive Lists for testing
            var testColArray1 = new string[] { "A0001", "A0002", "A0003", "A0004" };


            var dataMethods = DataMethods.GetInstance();
            var isEqual     = dataMethods.CompareCurrentCountsTables <string>(_colArray1, testColArray1);

            //var isEqual = dataMethods.CompareCurrentCountsTables<AppUser>(userList1, userList3);

            Assert.AreEqual(isEqual, true);
        }
Exemplo n.º 23
0
        public async Task EditGroupData(SocketCommandContext Context)
        {
            ulong userID = Context.User.Id;

            Command groupCommand = Vars.activeCommands.Where(x => x.ActorID == userID).FirstOrDefault();

            Console.WriteLine(" we've got our group command ");


            KinkGroup groupToEdit = Vars.tableEntries.Where(x => x.GetType().Name == "KinkGroup").ToList().Cast <KinkGroup>().ToList().Where(x => x.KinkGroupID.ToString() == groupCommand.CommandData).FirstOrDefault();

            Console.WriteLine(" we've got our group to edit ");



            if (groupCommand.CommandData == "start")
            {
                string groupName = Context.Message.Content;


                KinkGroup groupFromDB = DataMethods.GetGroup(groupName);


                if (groupFromDB == null)
                {
                    ulong msgEndID = groupCommand.MessageID;

                    var msgEnd = (RestUserMessage)await Context.Channel.GetMessageAsync(msgEndID);

                    string endMessage = "Welcome " + Context.User.Mention + "\n" +
                                        "Group not found, quitting!";

                    await msgEnd.ModifyAsync(x => x.Content = endMessage);

                    Vars.activeCommands.RemoveAll(x => x.ActorID == Context.User.Id);


                    await Context.Message.DeleteAsync();

                    return;
                }

                Vars.tableEntries.Add(groupFromDB);

                groupCommand.CommandData = groupFromDB.KinkGroupID.ToString();
                groupCommand.CommandStep = 1;

                string newMessage = "Welcome " + Context.User.Mention + "\n" +
                                    "Edit Group Step 1: Enter New Name, or Fartz to skip";

                ulong msgToEditID = groupCommand.MessageID;

                var msgToEdit = (RestUserMessage)await Context.Channel.GetMessageAsync(msgToEditID, CacheMode.AllowDownload);

                await msgToEdit.ModifyAsync(x => x.Content = newMessage);

                await Context.Message.DeleteAsync();
            }

            else if (groupToEdit != null && groupCommand.CommandStep == 1)
            {
                string newGroupName = Context.Message.Content;

                if (!newGroupName.Equals("fartz", StringComparison.OrdinalIgnoreCase))
                {
                    groupToEdit.KinkGroupName = newGroupName;

                    KinkGroup kinkToCheck = Vars.tableEntries.Where(x => x.GetType().Name == "KinkGroup").ToList().Cast <KinkGroup>().ToList().Where(x => x.KinkGroupID.ToString() == groupCommand.CommandData).FirstOrDefault();

                    if (groupToEdit.KinkGroupName != kinkToCheck.KinkGroupName)
                    {
                        Console.WriteLine("Kink in edit list not updating");
                    }
                }

                groupCommand.CommandStep = 2;

                string newMessage = "Welcome " + Context.User.Mention + "\n" +
                                    "Edit Kink Step 2: Enter New Description, or Fartz to skip";

                ulong msgToEditID = groupCommand.MessageID;

                var msgToEdit = (RestUserMessage)await Context.Channel.GetMessageAsync(msgToEditID, CacheMode.AllowDownload);

                await msgToEdit.ModifyAsync(x => x.Content = newMessage);

                await Context.Message.DeleteAsync();
            }

            else if (groupToEdit != null && groupCommand.CommandStep == 2)
            {
                string newKinkDescrip = Context.Message.Content;
                if (!newKinkDescrip.Equals("fartz", StringComparison.OrdinalIgnoreCase))
                {
                    groupToEdit.KinkGroupDescrip = newKinkDescrip;

                    KinkGroup kinkToCheck = Vars.tableEntries.Where(x => x.GetType().Name == "KinkGroup").ToList().Cast <KinkGroup>().ToList().Where(x => x.KinkGroupID.ToString() == groupCommand.CommandData).FirstOrDefault();

                    if (groupToEdit.KinkGroupDescrip != kinkToCheck.KinkGroupDescrip)
                    {
                        Console.WriteLine("Kink in edit list not updating");
                    }
                }

                await Context.Message.DeleteAsync();


                string newMessage = "Welcome " + Context.User.Mention + "\n" +
                                    "Now updating entry with new Name and Description: \n"
                                    + "Name: " + groupToEdit.KinkGroupName + "\n"
                                    + "Desc: " + groupToEdit.KinkGroupDescrip + "\n";


                ulong msgToEditID = groupCommand.MessageID;

                var msgToEdit = (RestUserMessage)await Context.Channel.GetMessageAsync(msgToEditID, CacheMode.AllowDownload);

                await msgToEdit.ModifyAsync(x => x.Content = newMessage);

                await DataMethods.EditGroup(groupToEdit.KinkGroupID, groupToEdit.KinkGroupName, groupToEdit.KinkGroupDescrip);


                await Task.Delay(1000);

                newMessage += "\n.";
                await msgToEdit.ModifyAsync(x => x.Content = newMessage);

                await Task.Delay(1000);

                newMessage += ".";
                await msgToEdit.ModifyAsync(x => x.Content = newMessage);

                await Task.Delay(1000);

                newMessage += ".";
                await msgToEdit.ModifyAsync(x => x.Content = newMessage);

                await Task.Delay(1000);

                newMessage += " Done.";
                await msgToEdit.ModifyAsync(x => x.Content = newMessage);

                Vars.activeCommands.RemoveAll(x => x.ActorID == Context.User.Id);

                Vars.tableEntries.RemoveAll(x => x.GetType().Name == "KinkGroup" && (x as KinkGroup).KinkGroupID == groupToEdit.KinkGroupID);
            }
        }
Exemplo n.º 24
0
        public async Task AddKink(params string[] kinkdata)
        {
            if (kinkdata != null && kinkdata.Length > 1)
            {
                string replyString = "Adding kink" + "\n"
                                     + "Name: - " + kinkdata[0] + "\n"
                                     + "Descrption: - " + kinkdata[1] + "\n";
                var replyMessage = await Context.Channel.SendMessageAsync(replyString);

                bool kinkAdded = await DataMethods.AddKink(kinkdata[0], kinkdata[1]);

                if (kinkAdded)
                {
                    replyString += "Kink added successfully!" + "\n";
                }
                else
                {
                    replyString += "Kink already in database, not added!" + "\n";
                }

                await replyMessage.ModifyAsync(x => x.Content = replyString);


                return;
            }

            string initMessage = "Welcome " + Context.User.Mention + "\n" +
                                 "New Kink Creation Step 1 - Enter Kink Name:";
            var replymessage = await Context.Channel.SendMessageAsync(initMessage);


            if (Vars.activeCommands.Where(x => x.ActorID == Context.User.Id).Count() > 0)
            {
                // eventually delete the old posts here too

                Vars.activeCommands.RemoveAll(x => x.ActorID == Context.User.Id);
            }


            var newCommand = new Command
            {
                CommandName = "addkink",
                CommandData = "start",
                ActorID     = Context.User.Id,
                ChannelID   = Context.Channel.Id,
                MessageID   = replymessage.Id,
            };

            Vars.activeCommands.Add(newCommand);

            /*
             * if (Vars.usersAddingKinks.Count > 0 && Vars.usersAddingKinks.Exists(x => x == Context.User.Id))
             * {
             *  Vars.usersAddingKinks.RemoveAll(x => x == Context.User.Id);
             * }
             *
             *
             * Vars.usersAddingKinks.Add(Context.User.Id);
             *
             *
             *
             *
             *
             *
             *
             * await DataMethods.RemoveKinkAdder(Context.User.Id);
             * await DataMethods.AddKinkAdder(replymessage.Id, Context.User.Id, Context.Channel.Id);
             */
        }
Exemplo n.º 25
0
 public Vector2D()
 {
     // Ensure that data is numerical
     DataMethods.EnsureIsNumeric(typeof(T));
 }
Exemplo n.º 26
0
        public async Task Sins([Remainder] string userNameAndNums)
        {
            if (userNameAndNums == null || userNameAndNums.Length < 6)
            {
                await CommandStatus("Invalid Username", "Sins");

                return;
            }


            string strBegin = userNameAndNums.Substring(0, 2);
            string strEnd   = userNameAndNums.Substring(userNameAndNums.Length - 1, 1);

            if (strBegin == "<@" && strEnd == ">")
            {
                string toSend = "Do not ping using this command.\n"
                                + "Instead, use the person's user name and numbers without the @. Like [!!sins username#3838] or [!!sins multi word user name#9999]";

                await CommandStatus(toSend, "Sins");


                return;
            }



            string userName = userNameAndNums.Substring(0, userNameAndNums.Length - 5);

            string userNumString = userNameAndNums.Substring(userNameAndNums.Length - 4, 4);


            var user = Context.Guild.Users.Where(x => x.Username == userName && x.Discriminator == userNumString).FirstOrDefault();

            if (user == null)
            {
                await CommandStatus("No such user on this server.", "Sins - " + userNameAndNums);

                return;
            }

            if (user.Roles.Any(x => x.Name == "DMs Closed" || x.Name == "Non Searchable"))
            {
                await CommandStatus("That user's info is private.", "Sins - " + userNameAndNums);

                return;
            }


            ulong userID = user != null ? user.Id : 0;

            var userKinks = DataMethods.GetUserKinksAndLimits(userID);

            if (userKinks == null)
            {
                await CommandStatus("User appears to have no kinks or limits.", "Sins - " + userNameAndNums);

                return;
            }

            string dmString = "​\n" + "**" + userName + "\'s Kinks:" + "\n━━━━━━━" + "**" + "\n\n​";

            foreach (var gk in userKinks.Where(x => !x.isLimit))
            {
                dmString += gk.Group.KinkGroupName + "\n━━━━━━━" + "\n\n​";

                foreach (var k in gk.KinksForGroup)
                {
                    dmString += k.KinkName /*+ " - " + k.KinkDesc*/ + "\n";
                }

                dmString += "\n​";
            }

            dmString += "​\n" + "**" + userName + "\'s Limits:" + "\n━━━━━━━" + "**" + "\n\n​";

            foreach (var gk in userKinks.Where(x => x.isLimit))
            {
                dmString += gk.Group.KinkGroupName + "\n━━━━━━━" + "\n\n​";

                foreach (var k in gk.KinksForGroup)
                {
                    dmString += k.KinkName /*+ " - " + k.KinkDesc*/ + "\n";
                }

                dmString += "\n​";
            }
            await DmSplit(dmString);


            await CommandStatus("DM Sent", "Sins - " + userNameAndNums);
        }
Exemplo n.º 27
0
        public async Task MySins(params string[] text)
        {
            // var userKinks = DataMethods.GetUserKinks(Context.User.Id);
            // var userLimits = DataMethods.GetUserLimits(Context.User.Id);

            var userKinks = DataMethods.GetUserKinksAndLimits(Context.User.Id);


            if (userKinks == null)
            {
                await CommandStatus("You appear to have no kinks or limits", "MySins");

                return;
            }

            string dmString = "​\n" + "**" + "Your Kinks:" + "\n━━━━━━━" + "**" + "\n\n​";

            foreach (var gk in userKinks.Where(x => !x.isLimit))
            {
                dmString += gk.Group.KinkGroupName + "\n━━━━━━━" + "\n\n​";

                foreach (var k in gk.KinksForGroup)
                {
                    dmString += k.KinkName /*+ " - " + k.KinkDesc*/ + "\n";
                }

                dmString += "\n​";
            }

            dmString += "​\n" + "**" + "Your Limits:" + "\n━━━━━━━" + "**" + "\n\n​";

            foreach (var gk in userKinks.Where(x => x.isLimit))
            {
                dmString += gk.Group.KinkGroupName + "\n━━━━━━━" + "\n\n​";

                foreach (var k in gk.KinksForGroup)
                {
                    dmString += k.KinkName /*+ " - " + k.KinkDesc*/ + "\n";
                }

                dmString += "\n​";
            }

            await DmSplit(dmString);


            await CommandStatus("DM Sent", "MySins");


            /*
             * var dmSentMsg = await Context.Channel.SendMessageAsync("DM Sent");
             *
             * await Task.Delay(1500);
             * // if this is NOT a dm, we want to try to delete the messages
             *
             *
             * if (Context.Message.Channel.GetType() != typeof(SocketDMChannel))
             * {
             *
             *
             *  await Context.Message.DeleteAsync();
             *  await Context.Channel.DeleteMessageAsync(dmSentMsg);
             * }
             */
        }
Exemplo n.º 28
0
        public async Task SinSearch(params string[] text)
        {
            if ((text == null || text.Length < 1))
            {
                await CommandStatus("No search terms given", "Sinsearch");

                return;
            }

            string termsString = string.Join(",", text);


            (string[] isAKink, string[] isNotAKink) = DataMethods.ValidateKinkNames(text);

            Console.WriteLine(" Completing the validate kink names method ");

            List <ulong> listOfUserIDs = new List <ulong>();

            if (isAKink != null && isAKink.Length > 0)
            {
                listOfUserIDs = DataMethods.GetUserIDsFromKinknames(isAKink);
            }

            Console.WriteLine(" Completing the user IDs from kinknames method ");

            List <string> listOfDiscordTags = new List <string>();

            if (isNotAKink != null && isNotAKink.Length > 0)
            {
                listOfDiscordTags = isNotAKink.ToList();
            }

            Console.WriteLine(" Completed setting discord tags to list ");


            if ((listOfUserIDs == null || listOfUserIDs.Count < 1) && (listOfDiscordTags == null || listOfDiscordTags.Count < 1))
            {
                await CommandStatus("No users found", "Sinsearch - " + termsString);

                return;
            }

            Console.WriteLine(" Completing the check for whether either list is null or zero ");

            string reslut2 = "​\nYour search terms:\n━━━━━━━\n\n";

            foreach (string term in text)
            {
                reslut2 += term + ", ";
            }

            reslut2  = reslut2.Remove(reslut2.LastIndexOf(","));
            reslut2 += "\n\n";



            List <SocketGuildUser> userList = new List <SocketGuildUser>();
            string noDMs     = "DMs Closed";
            string nonSearch = "Non Searchable";
            string askDM     = "Ask to DM";

            if (listOfUserIDs != null && listOfUserIDs.Count > 0)
            {
                userList = Context.Guild.Users.Where(user => listOfUserIDs.Any(dbUserID => user.Id == dbUserID)).ToList();

                /*
                 * foreach (ulong userIdent in listOfUserIDs)
                 * {
                 *  if (Context.Guild.GetUser(userIdent) != null)
                 *  {
                 *      userList.Add(Context.Guild.GetUser(userIdent));
                 *  }
                 *
                 * }
                 */
            }

            Console.WriteLine("Completed getting users from userlist by dbtags");


            if ((isAKink == null || isAKink.Length < 1) && (listOfDiscordTags != null && listOfDiscordTags.Count() > 0))
            {
                Console.WriteLine("entering the discord tag if get");

                Console.WriteLine("discord tag array zero position - " + listOfDiscordTags[0]);
                userList = Context.Guild.Users.Where(user => user.Roles.Any(userRoles => userRoles.Name.Equals(listOfDiscordTags[0], StringComparison.OrdinalIgnoreCase))).ToList();

                Console.WriteLine("completed filling userlist");
                listOfDiscordTags.RemoveAt(0);
                Console.WriteLine("completed removing tag from userlist");
            }

            Console.WriteLine("Completed getting users from userlist by discord tags");

            if (listOfDiscordTags != null && listOfDiscordTags.Count() > 0)
            {
                if (userList != null && userList.Count() > 0)
                {
                    userList = userList.Where(aUser => listOfDiscordTags.All(discordTag => aUser.Roles.Any(userRole => userRole.Name.Equals(discordTag, StringComparison.OrdinalIgnoreCase)))).ToList();
                }
            }

            int resultCount = userList.Count();

            Console.WriteLine("Completed flushing users from userlist by discord tags");



            if (userList != null && userList.Count() > 0)
            {
                userList.RemoveAll(x => x.Roles.Any(y => y.Name.Equals(noDMs, StringComparison.OrdinalIgnoreCase)));
                userList.RemoveAll(x => x.Roles.Any(y => y.Name.Equals(nonSearch, StringComparison.OrdinalIgnoreCase)));
            }

            int resultMinusExcludes = userList.Count();

            reslut2 += "Search Resluts:\n" + "━━━━━━━\n";
            reslut2 += "Total - " + resultCount + ", Total minus nodm/nosearch - " + resultMinusExcludes + "\n";
            reslut2 += "Note: please respect the Ask to DM tag by asking users who have it in the #Ask to DM channel before you DM them.\n\n";

            Console.WriteLine("Completed flushing users from userlist by exclusion tags");


            if (userList.Count() > 0)
            {
                foreach (SocketGuildUser userFound in userList)
                {
                    reslut2 += userFound.Username;
                    reslut2 += "#";
                    reslut2 += userFound.Discriminator;



                    //reslut2 += userFound.Mention;

                    if (userFound.Roles.Any(x => x.Name.Equals(askDM, StringComparison.OrdinalIgnoreCase)))
                    {
                        reslut2 += " - Ask to DM";
                    }

                    reslut2 += "\n";
                }
            }
            else
            {
                await CommandStatus("No resluts found", "Sinsearch - " + termsString);

                return;
            }


            reslut2 += "\n​";

            await DmSplit(reslut2);

            await CommandStatus("DM sent.", "Sinsearch - " + termsString);
        }
Exemplo n.º 29
0
        /// <summary>
        ///     This method is called when PixelMap load is requested, if you return a PixelMap
        ///     it will return it from the user else it will keep trying all the other PixelMapLoaders
        ///     until it does get one
        /// </summary>
        /// <param name="file">File path of the image to load.</param>
        /// <returns>A PixelMap or NULL if this factory can't load the given image file.</returns>
        protected override PixelMap RequestLoad(object path)
        {
            Stream stream = StreamFactory.RequestStream(path, StreamMode.Open);

            if (stream == null)
            {
                return(null);
            }
            BinaryReader reader = new BinaryReader(stream);

            #region Header Parsing

            // Cheak the 8 byte identifier header at the start to make
            // sure this really is a PNG file.
            byte[] correctHeader = new byte[8] {
                137, 80, 78, 71, 13, 10, 26, 10
            };
            byte[] header = reader.ReadBytes(8);

            for (int i = 0; i < correctHeader.Length; i++)
            {
                if (correctHeader[i] != header[i])
                {
                    reader.Close();
                    return(null);
                }
            }

            #endregion

            // Declare chunk releated local variables
            #region Local variables

            int      chunkIndex = 0;
            int      width = 0, height = 0;
            byte     bitDepth = 0, colorType = 0, compressionMethod = 0;
            byte     filterMethod = 0, interlaceMethod = 0;
            bool     readingChunks = true;
            byte[]   pixelData = null;
            int      bytesPerPixel = 0, bitsPerPixel = 0;
            int      dataSize = 0;
            PixelMap pixelMap = null;

            #endregion

            // Read in every chunk till we find the end of file chunk or
            // we read past the end of the stream.
            #region Chunk reading
            while (readingChunks)
            {
                // Read in chunk's data
                int    chunkLength    = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                byte[] chunkTypeChars = reader.ReadBytes(4);
                string chunkType      = ((char)chunkTypeChars[0]).ToString() + ((char)chunkTypeChars[1]).ToString() +
                                        ((char)chunkTypeChars[2]).ToString() + ((char)chunkTypeChars[3]).ToString();

                #region Chunk parsing
                switch (chunkType)
                {
                // Image header chunk, it MUST come first.
                case "IHDR":

                    if (chunkIndex != 0)
                    {
                        throw new Exception("Found out of sequence IHDR chunk while loading PNG file.");
                    }
                    width             = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                    height            = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                    bitDepth          = reader.ReadByte();
                    colorType         = reader.ReadByte();
                    compressionMethod = reader.ReadByte();
                    filterMethod      = reader.ReadByte();
                    interlaceMethod   = reader.ReadByte();

                    pixelMap = new PixelMap(width, height);

                    break;

                // Pallete chunk.

                /*
                 * case "PLTE":
                 *
                 * if (gotPallete == true || (colorType == 0 && gotData == false) || (colorType == 4 && gotData == false))
                 *      throw new Exception("Found out of sequence or unexpected PLTE pallete chunk while loading PNG image.");
                 *
                 * for (int i = 0; i < chunkLength / 3; i++)
                 * {
                 *      pallete[(i * 3)]	 = reader.ReadByte();
                 *      pallete[(i * 3) + 1] = reader.ReadByte();
                 *      pallete[(i * 3) + 2] = reader.ReadByte();
                 * }
                 *
                 * gotPallete = true;
                 *
                 * break;
                 */

                // Image data chunk.
                case "IDAT":

                    // Read in the new data and append it to the compressed
                    // data array for future use.
                    int index = pixelData == null ? 0 : pixelData.Length;

                    if (pixelData != null)
                    {
                        Array.Resize(ref pixelData, pixelData.Length + chunkLength);
                    }
                    else
                    {
                        pixelData = new byte[chunkLength];
                    }

                    stream.Read(pixelData, index, chunkLength);
                    dataSize += chunkLength;

                    break;

                // End of chunks chunk.
                case "IEND":

                    readingChunks = false;

                    break;

                /*
                 * // Transparencry chunk.
                 * case "tRNS":
                 *
                 *      break;
                 *
                 * // Image gamma chunk.
                 * case "gAMA":
                 *
                 *      gamma = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                 *
                 *      break;
                 *
                 * ///Primary chromaticities chunk.
                 * case "cHRM":
                 *
                 *      whitePointX = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                 *      whitePointY = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                 *      redX	    = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                 *      redY		= EndianSwapMethods.SwapEndian(reader.ReadInt32());
                 *      greenX		= EndianSwapMethods.SwapEndian(reader.ReadInt32());
                 *      greenY		= EndianSwapMethods.SwapEndian(reader.ReadInt32());
                 *      blueX		= EndianSwapMethods.SwapEndian(reader.ReadInt32());
                 *      blueY		= EndianSwapMethods.SwapEndian(reader.ReadInt32());
                 *
                 *      break;
                 *
                 * // Standard RGB color space chunk.
                 * case "sRGB":
                 *
                 *      renderingIntent = reader.ReadByte();
                 *
                 *      break;
                 *
                 * // Embedded ICCP chunk.
                 * case "iCCP":
                 *
                 *      break;
                 *
                 *
                 * // Internation textural infomation chunk
                 * case "iTXt":
                 *
                 *      break;
                 *
                 * // Textural infomation chunk.
                 * case "tEXt":
                 *
                 *      // Get the keyword
                 *      string keyword = "";
                 *      int	   keyAsc = 0;
                 *      while(true)
                 *      {
                 *              keyAsc = reader.ReadByte();
                 *              if (keyAsc == 0) break;
                 *              keyword += ((char)keyAsc).ToString();
                 *      }
                 *
                 *      // Read the text
                 *      string text = "";
                 *      int	   textLength = chunkLength - keyword.Length - 1;
                 *      for (int i = 0; i < textLength; i++)
                 *              text += ((char)reader.ReadByte()).ToString();
                 *
                 *      break;
                 *
                 * // Compressed textural infomation chunk.
                 * case "zTXt":
                 *
                 *      break;
                 *
                 * // Default background color chunk.
                 * case "bKGD":
                 *
                 *      break;
                 *
                 * // Physical pixel dimensions chunk.
                 * case "pHYs":
                 *
                 *      break;
                 *
                 * // Bit chunk.
                 * case "sBit":
                 *
                 *      break;
                 *
                 * // Suggested pallete chunk.
                 * case "sPLT":
                 *
                 *      break;
                 *
                 * // Pallete histogram chunk.
                 * case "hIST":
                 *
                 *      break;
                 *
                 * // Last modification time chunk.
                 * case "tIME":
                 */

                default:

                    // Check the chunk is not critical if it is, this file
                    // is probably corrupt or the chunk is not implemented in this
                    // loader so throw up an exception.
                    if ((((byte)chunkTypeChars[0]) & 32) == 0)
                    {
                        throw new Exception("Found unknown or unsupported but critical chunk while reading PNG file.");
                    }

                    stream.Position += chunkLength;

                    break;
                }
                #endregion

                // We shall just ignore the CRC for now :)
                int CRC = EndianSwapMethods.SwapEndian(reader.ReadInt32());

                chunkIndex++;
            }
            #endregion

            // Check the expect size is the same as the actual size.
            if (dataSize != pixelData.Length)
            {
                throw new Exception("An error occured while reading in pixel data, data size is not the same as expect size.");
            }

            // Work out how many bytes are used by each pixel
            #region Pixel size calculations
            switch (colorType)
            {
            case 0: bitsPerPixel = bitDepth;         break;                 // Grey

            case 2: bitsPerPixel = bitDepth * 3; break;                     // RGB

            case 3: bitsPerPixel = bitDepth;         break;                 // Pallete indexed

            case 4: bitsPerPixel = bitDepth * 2; break;                     // Grey and alpha.

            case 6: bitsPerPixel = bitDepth * 4; break;                     // RGB and alpha.
            }
            bytesPerPixel = (int)Math.Round(bitsPerPixel / 8.0, MidpointRounding.AwayFromZero);
            #endregion

            // Decompress data array.
            #region Decompression

            byte[] pixelDataWithoutHeader = new byte[pixelData.Length - 2];
            Array.Copy(pixelData, 2, pixelDataWithoutHeader, 0, pixelData.Length - 2);
            pixelData = DataMethods.Inflate(pixelDataWithoutHeader);

            #endregion

            // Remove filter.
            #region Filter removal

            switch (filterMethod)
            {
            case 0:                     // No filter.

                byte[] filteredData  = new byte[pixelData.Length - height];
                int    scanlineWidth = (width * bytesPerPixel);

                byte[] scanlineData = null;
                for (int scanline = 0; scanline < height; scanline++)
                {
                    int    priorScanlineIndex = ((scanlineWidth + 1) * (scanline - 1)) + 1;
                    int    scanlineIndex      = ((scanlineWidth + 1) * scanline) + 1;
                    byte   slFilterMethod     = pixelData[scanlineIndex - 1];
                    byte[] priorScanlineData  = scanline == 0 ? new byte[scanlineWidth] : scanlineData;
                    scanlineData = new byte[scanlineWidth];
                    Array.Copy(pixelData, scanlineIndex, scanlineData, 0, scanlineWidth);

                    // Check what kind of filter is attached to this scanline.
                    switch (slFilterMethod)
                    {
                    case 0:                                     // None
                        break;

                    case 1:                                     // Left
                        for (int pixel = 0; pixel < scanlineData.Length; pixel++)
                        {
                            int left = pixel - bytesPerPixel < 0 ? (byte)0 : scanlineData[pixel - bytesPerPixel];
                            scanlineData[pixel] = (byte)((scanlineData[pixel] + left) % 256);
                        }
                        break;

                    case 2:                                     // Up
                        for (int pixel = 0; pixel < scanlineData.Length; pixel++)
                        {
                            byte prior = priorScanlineData[pixel];
                            scanlineData[pixel] = (byte)((scanlineData[pixel] + prior) % 256);
                        }
                        break;

                    case 3:                                     // Average
                        for (int pixel = 0; pixel < scanlineData.Length; pixel++)
                        {
                            float p     = pixel - bytesPerPixel < 0 ? (byte)0 : scanlineData[pixel - bytesPerPixel];
                            float prior = priorScanlineData[pixel];
                            scanlineData[pixel] = (byte)(scanlineData[pixel] + Math.Floor((p + prior) / 2));
                        }
                        break;

                    case 4:                                     // Paeth
                        for (int pixel = 0; pixel < scanlineData.Length; pixel++)
                        {
                            int l  = pixel - bytesPerPixel < 0 ? (byte)0 : scanlineData[pixel - bytesPerPixel];
                            int u  = priorScanlineData[pixel];
                            int ul = pixel - bytesPerPixel < 0 ? (byte)0 : priorScanlineData[pixel - bytesPerPixel];
                            scanlineData[pixel] = (byte)((scanlineData[pixel] + PaethPredictor((byte)l, (byte)u, (byte)ul)) % 256);
                        }
                        break;

                    default:
                        throw new Exception("PNG Factory encountered file with invalid or unsupported scanline filter while reading file.");
                    }

                    // Place the scanline data into the filtered data.
                    Array.Copy(scanlineData, 0, filteredData, scanline * scanlineWidth, scanlineWidth);
                }

                pixelData = filteredData;

                break;

            default:

                stream.Close();
                throw new Exception("PNG Factory encountered file with invalid or unsupported filter method while reading file.");
            }

            #endregion

            // Remove interlacing.
            #region Interlace removal
            switch (interlaceMethod)
            {
            case 0:                     // No interlace.

                // *whistles* may as well ignore this, sorter pointless it even
                // being here.

                break;

            default:

                stream.Close();
                throw new Exception("PNG Factory encountered file with invalid or unsupported interlace method while reading file.");
            }
            #endregion

            // Store decompressed data in pixelmap.
            #region PixelMap building
            switch (colorType)
            {
            case 2:                     // RGB

                for (int i = 0; i < (width * height); i++)
                {
                    int pixelIndex = i * bytesPerPixel;
                    pixelMap[i] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, pixelData[pixelIndex], pixelData[pixelIndex + 1], pixelData[pixelIndex + 2], 255);
                }

                break;

            case 6:                     // RGB with alpha.

                for (int i = 0; i < (width * height); i++)
                {
                    int pixelIndex = i * bytesPerPixel;
                    pixelMap[i] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, pixelData[pixelIndex], pixelData[pixelIndex + 1], pixelData[pixelIndex + 2], pixelData[pixelIndex + 3]);
                }

                break;

            // Sherlock, somethings amiss!
            default:

                stream.Close();
                throw new Exception("PNG Factory encountered an invalid or unsupported image type while loading an image.");
            }
            #endregion

            // Return pixelmap and close stream
            stream.Close();
            return(pixelMap);
        }
Exemplo n.º 30
0
        public async Task PurgeIntros()
        {
            int interval = 50;

            Console.WriteLine("interval set");


            // check if command user is administrator

            SocketGuildUser ServerUser = Context.User as SocketGuildUser;

            if (!ServerUser.GuildPermissions.Administrator)
            {
                await Context.Channel.SendMessageAsync($":x: You don't have administrator permissions in this discord server! Ask an administrator or the owner to execute this command!");

                return;
            }

            Console.WriteLine("Trying to delete messages lol");
            await Context.Channel.SendMessageAsync("Trying to delete messages!");

            Console.WriteLine("Trying to delete messages lol 2");


            var GuildUsers = Context.Guild.Users;

            int messagesScanned = 0;
            int messagesDeleted = 0;

            //string[] channelNamesToPurge = serverSettings.introChannels.ToArray();

            ulong[] channelsToPurge = DataMethods.GetIntroChannelIDs(Context.Guild.Id);


            foreach (ulong channelToPurge in channelsToPurge)
            {
                int messagesScannedThisChannel = 0;
                int messagesDeletedThisChannel = 0;

                SocketTextChannel scannedChannel = Context.Guild.TextChannels.Where(x => x.Id == channelToPurge).FirstOrDefault();

                var MessagesFromChannel = await Context.Guild.TextChannels.Where(x => x.Id == channelToPurge).FirstOrDefault().GetMessagesAsync(interval).FlattenAsync();

                ulong lastMsgID = 0;
                //IMessage bombTest = await Context.Guild.TextChannels.Where(x => x.Name == channelNameToPurge).FirstOrDefault().GetMessageAsync(lastID);

                //int msgCount = MessagesFromChannel.Count();

                //await Context.Channel.SendMessageAsync($"First messages from #{channelNameToPurge} supposedly loaded! Message count: {msgCount}");

                foreach (IMessage CurrentMsg in MessagesFromChannel)
                {
                    //await Context.Channel.SendMessageAsync($"Looping message!");
                    //bool userFound = false;

                    lastMsgID = CurrentMsg.Id;
                    messagesScanned++;
                    messagesScannedThisChannel++;

                    //await Context.Channel.SendMessageAsync($"Looping message - ID {lastID}!");

                    /*
                     * foreach (SocketGuildUser CurrentUser in GuildUsers)
                     * {
                     *  if (CurrentMsg.Author.Id == CurrentUser.Id)
                     *  {
                     *      userFound = true;
                     *  }
                     * }
                     */

                    SocketGuildUser msgAuthor = Context.Guild.GetUser(CurrentMsg.Author.Id);

                    //if (!userFound)
                    if (msgAuthor == null)
                    {
                        await CurrentMsg.DeleteAsync();

                        messagesDeleted++;
                        messagesDeletedThisChannel++;
                    }
                }

                //await Context.Channel.SendMessageAsync($"First messages scanned in #{channelNameToPurge}!");


                while (true)
                {
                    IMessage currMessage = await Context.Guild.TextChannels.Where(x => x.Id == channelToPurge).FirstOrDefault().GetMessageAsync(lastMsgID);

                    //await Context.Channel.SendMessageAsync("We're in the while loop!");

                    if (currMessage == null)
                    {
                        var mgsToCount = await Context.Guild.TextChannels.Where(x => x.Id == channelToPurge).FirstOrDefault().GetMessagesAsync(limit: 1, fromMessageId: lastMsgID, dir: Direction.Before).FlattenAsync();

                        int theCount = mgsToCount.Count();

                        //await Context.Channel.SendMessageAsync("currMessage is returning null!");

                        if (theCount < 1)
                        {
                            break;
                        }
                    }
                    else
                    {
                        //messagesScanned--;
                        //messagesScannedThisChannel--;

                        var mgsToCount = await Context.Guild.TextChannels.Where(x => x.Id == channelToPurge).FirstOrDefault().GetMessagesAsync(limit: 2, fromMessageId: lastMsgID, dir: Direction.Before).FlattenAsync();

                        int theCount = mgsToCount.Count();


                        //await Context.Channel.SendMessageAsync($"currMessage is not returning null! count = {theCount}");

                        if (theCount < 2)
                        {
                            break;
                        }
                    }

                    //await Context.Channel.SendMessageAsync($"Deleting from message ID: {lastID}");
                    MessagesFromChannel = await Context.Guild.TextChannels.Where(x => x.Id == channelToPurge).FirstOrDefault().GetMessagesAsync(limit: interval, fromMessageId: lastMsgID, dir: Direction.Before).FlattenAsync();

                    foreach (IMessage CurrentMsg in MessagesFromChannel)
                    {
                        //bool userFound = false;

                        lastMsgID = CurrentMsg.Id;
                        messagesScanned++;
                        messagesScannedThisChannel++;
                        SocketGuildUser msgAuthor = Context.Guild.GetUser(CurrentMsg.Author.Id);

                        /*
                         * foreach (SocketGuildUser CurrentUser in GuildUsers)
                         * {
                         *  if (CurrentMsg.Author.Id == CurrentUser.Id)
                         *  {
                         *      userFound = true;
                         *  }
                         * }
                         */

                        //if (!userFound)
                        if (msgAuthor == null)
                        {
                            await CurrentMsg.DeleteAsync();

                            messagesDeleted++;
                            messagesDeletedThisChannel++;
                        }
                    }
                }

                await Context.Channel.SendMessageAsync($"All messages scanned from {scannedChannel.Mention}! Channel total: {messagesScannedThisChannel} messages scanned, {messagesDeletedThisChannel} messages deleted!");
            }



            await Context.Channel.SendMessageAsync($"All messages scanned! Total: {messagesScanned} messages scanned, {messagesDeleted} messages deleted!");
        }