text:
using Database.Entity;
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Data_Access_Layer
{
    public class DLDatabase
    {
        private DLDatabase() { }

        private static readonly string DB_FILE = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\RemindMe\\RemindMeDatabase.db";

        //The neccesary query to execute to create the table Reminder
        private const string TABLE_REMINDER = "CREATE TABLE [Reminder] ([Id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, [Deleted] bigint DEFAULT(0) NOT NULL, [Name] text NOT NULL, [Date] text NOT NULL, [RepeatType] text NOT NULL, [Note] text NOT NULL, [Enabled] bigint NOT NULL, [DayOfMonth]bigint NULL, [EveryXCustom] bigint NULL, [RepeatDays] text NULL, [SoundFilePath] text NULL, [PostponeDate] text NULL, [Hide] bigint DEFAULT(0) NULL, [Corrupted] bigint DEFAULT(0) NULL, [EnableAdvancedReminder] bigint DEFAULT(1) NOT NULL, [UpdateTime] bigint DEFAULT(0) NOT NULL);";

        //The neccesary query to execute to create the table Settings
        private const string TABLE_SETTINGS = "CREATE TABLE [Settings] ([Id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, [PopupType] text NOT NULL, [StickyForm] bigint NOT NULL, [EnableReminderCountPopup] bigint DEFAULT(1) NOT NULL, [EnableHourBeforeReminder] bigint DEFAULT(1) NOT NULL, [HideReminderConfirmation] bigint DEFAULT(0) NULL, [EnableQuickTimer] bigint DEFAULT(1) NOT NULL, [LastVersion] text NULL, [DefaultTimerSound] text NULL, [EnableAdvancedReminders] bigint NULL, [UniqueString] text NULL, [RemindMeTheme] text DEFAULT('Default') NOT NULL, [DrawerUseColors] bigint DEFAULT(0) NULL, [DrawerHighlight] bigint DEFAULT(1) NULL, [DrawerBackground] bigint DEFAULT(0) NULL, [CurrentTheme] bigint DEFAULT(-1) NULL, [MaterialDesign] bigint DEFAULT(1) NULL, [AutoUpdate] bigint DEFAULT(1) NOT NULL, [TimerVolume] bigint DEFAULT(100) NOT NULL);";

        //The neccesary query to execute to create the table Songs
        private const string TABLE_SONGS = "CREATE TABLE [Songs] ( [Id] INTEGER NOT NULL, [SongFileName]text NOT NULL, [SongFilePath]text NOT NULL, CONSTRAINT[sqlite_master_PK_Songs] PRIMARY KEY([Id]));";

        //The neccesary query to execute to create the table PopupDimensions
        private const string TABLE_POPUP_DIMENSIONS = "CREATE TABLE [PopupDimensions] ([Id] INTEGER NOT NULL, [FormWidth]bigint NOT NULL, [FormHeight]bigint NOT NULL, [FontTitleSize]bigint NOT NULL, [FontNoteSize]bigint NOT NULL, CONSTRAINT[sqlite_master_PK_PopupDimensions] PRIMARY KEY([Id]));";

        //The neccesary query to execute to create the table Listview_Column_sizes
        private const string TABLE_LISTVIEW_COLUMN_SIZES = "CREATE TABLE[ListviewColumnSizes] ([Id]INTEGER NOT NULL, [Title]bigint NOT NULL, [Date]bigint NOT NULL, [Repeating]bigint NOT NULL, [Enabled]bigint NOT NULL, CONSTRAINT[sqlite_master_PK_ListviewColumnSizes] PRIMARY KEY([Id]));";

        //The neccesary query to execute to create the table Listview_Column_sizes
        private const string TABLE_HOTKEYS = "CREATE TABLE [Hotkeys] ([Id] INTEGER NOT NULL, [Name]text NOT NULL, [Key]text NOT NULL, [Modifiers]text NOT NULL, CONSTRAINT[sqlite_master_PK_Hotkeys] PRIMARY KEY([Id]));";

        //AVR = Advanced reminder. Table contains advanced reminder properties. Has a foreign key to TABLE_REMINDER
        private const string TABLE_AVR_PROPERTIES = "CREATE TABLE [AdvancedReminderProperties] ([Id] INTEGER NOT NULL, [Remid]bigint NOT NULL, [BatchScript]text NULL, [ShowReminder] bigint DEFAULT 1  NULL, CONSTRAINT[sqlite_master_PK_AdvancedReminderProperties] PRIMARY KEY([Id]));";

        //Contains the files/folders and their actions, example: delete folder x. open file x. Has a foreign key to TABLE_REMINDER
        private const string TABLE_AVR_FILES_FOLDERS = "CREATE TABLE [AdvancedReminderFilesFolders] ([Id] INTEGER NOT NULL, [Remid]bigint NOT NULL, [Path]text NOT NULL, [Action]text NOT NULL, CONSTRAINT[sqlite_master_PK_AdvancedReminderFilesFolders] PRIMARY KEY([Id]));";

        //The neccesary query to execute to create the table ReadMessages
        private const string TABLE_READ_MESSAGES = "CREATE TABLE [ReadMessages] ([Id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, [ReadMessageId] bigint NOT NULL, [ReadDate] text NOT NULL, [MessageText] text NULL);";

        //The neccesary query to execute to create the table ButtonSpaces
        private const string TABLE_BUTTONSPACES = "CREATE TABLE [ButtonSpaces] ([Id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, [Reminders] bigint DEFAULT(5) NOT NULL, [Timer] bigint DEFAULT(5) NOT NULL, [BackupImport] bigint DEFAULT(5) NOT NULL, [Settings] bigint DEFAULT(5) NOT NULL, [SoundEffects] bigint DEFAULT(5) NOT NULL, [ResizePopup] bigint DEFAULT(5) NOT NULL, [MessageCenter] bigint DEFAULT(5) NOT NULL, [DebugMode] bigint DEFAULT(5) NOT NULL);";

        //The neccesary query to execute to create the table ButtonSpaces
        private const string TABLE_THEMES = "CREATE TABLE [Themes] ([Id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, [Primary] bigint DEFAULT(0) NOT NULL, [DarkPrimary] bigint DEFAULT(0) NOT NULL, [LightPrimary] bigint DEFAULT(0) NOT NULL, [Accent] bigint DEFAULT(0) NOT NULL, [TextShade] bigint DEFAULT(0) NOT NULL, [Mode] bigint DEFAULT(0) NULL, [ThemeName] text NULL, [IsDefault] bigint DEFAULT(0) NOT NULL);";

        //The neccesary query to execute to create the table HttpRequests
        private const string TABLE_HTTP = "CREATE TABLE [HttpRequests] ([Id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, [reminderId] bigint NOT NULL, [URL] text NOT NULL, [Type] text NOT NULL, [AcceptHeader] text NOT NULL, [ContentTypeHeader] text NOT NULL, [OtherHeaders] text NOT NULL, [Body] text NOT NULL, [Interval] bigint NOT NULL, [AfterPopup] text DEFAULT('Stop') NOT NULL);";

        //The neccesary query to execute to create the table HttpRequestCondition
        private const string TABLE_HTTP_CONDITION = "CREATE TABLE [HttpRequestCondition] ([Id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, [RequestId] bigint NOT NULL, [Condition] text NOT NULL, [DataType] text NOT NULL, [Property] text NOT NULL, [Operator] text NOT NULL, [Value] text NOT NULL);";

        //The neccesary query to execute to create the table RemindMeColorThemes, used to give RemindMe multiple color scheme
        //private const string TABLE_REMINDME_COLOR_SCHEMES = "CREATE TABLE [RemindMeColorScheme] ([Id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, [ThemeName] text NOT NULL, [PrimaryBottomLeft] text NOT NULL, [PrimaryBottomRight] text NOT NULL, [PrimaryTopLeft] text NOT NULL, [PrimaryTopRight] text NOT NULL, [SecondaryBottomLeft] text NOT NULL, [SecondaryBottomRight] text NOT NULL, [SecondaryTopLeft] text NOT NULL, [SecondaryTopRight] text NOT NULL);";

        /// <summary>
        /// Creates the database with associated tables
        /// </summary>
        public static void CreateDatabase()
        {
            SQLiteConnection conn = new SQLiteConnection();
            conn.ConnectionString = "data source = " + DB_FILE;
            conn.Open();

            SQLiteCommand tableReminder = new SQLiteCommand();
            SQLiteCommand tableSettings = new SQLiteCommand();
            SQLiteCommand tableSongs = new SQLiteCommand();
            SQLiteCommand tablePopupDimensions = new SQLiteCommand();
            SQLiteCommand tableListviewColumnSizes = new SQLiteCommand();
            SQLiteCommand tableHotkeys = new SQLiteCommand();
            SQLiteCommand tableAvrProperties = new SQLiteCommand();
            SQLiteCommand tableAvrFilesFolders = new SQLiteCommand();
            SQLiteCommand tableReadMessages = new SQLiteCommand();
            SQLiteCommand tableButtonSpaces = new SQLiteCommand();
            SQLiteCommand tableThemes = new SQLiteCommand();
            SQLiteCommand tableHttp = new SQLiteCommand();
            SQLiteCommand tableHttpCon = new SQLiteCommand();
            //SQLiteCommand tableRemindMeColorSchemes = new SQLiteCommand();

            tableReminder.CommandText = TABLE_REMINDER;
            tableSettings.CommandText = TABLE_SETTINGS;
            tableSongs.CommandText = TABLE_SONGS;
            tablePopupDimensions.CommandText = TABLE_POPUP_DIMENSIONS;
            tableListviewColumnSizes.CommandText = TABLE_LISTVIEW_COLUMN_SIZES;
            tableHotkeys.CommandText = TABLE_HOTKEYS;
            tableAvrProperties.CommandText = TABLE_AVR_PROPERTIES;
            tableAvrFilesFolders.CommandText = TABLE_AVR_FILES_FOLDERS;
            tableReadMessages.CommandText = TABLE_READ_MESSAGES;
            tableButtonSpaces.CommandText = TABLE_BUTTONSPACES;
            tableThemes.CommandText = TABLE_THEMES;
            tableHttp.CommandText = TABLE_HTTP;
            tableHttpCon.CommandText = TABLE_HTTP_CONDITION;
            //tableRemindMeColorSchemes.CommandText = TABLE_REMINDME_COLOR_SCHEMES;

            tableReminder.Connection = conn;
            tableSettings.Connection = conn;
            tableSongs.Connection = conn;
            tablePopupDimensions.Connection = conn;
            tableListviewColumnSizes.Connection = conn;
            tableHotkeys.Connection = conn;
            tableAvrProperties.Connection = conn;
            tableAvrFilesFolders.Connection = conn;
            tableReadMessages.Connection = conn;
            tableButtonSpaces.Connection = conn;
            tableThemes.Connection = conn;
            tableHttp.Connection = conn;
            tableHttpCon.Connection = conn;
            //tableRemindMeColorSchemes.Connection = conn;

            tableReminder.ExecuteNonQuery();
            tableSettings.ExecuteNonQuery();
            tableSongs.ExecuteNonQuery();
            tablePopupDimensions.ExecuteNonQuery();
            tableListviewColumnSizes.ExecuteNonQuery();
            tableHotkeys.ExecuteNonQuery();
            tableAvrProperties.ExecuteNonQuery();
            tableAvrFilesFolders.ExecuteNonQuery();
            tableReadMessages.ExecuteNonQuery();
            tableButtonSpaces.ExecuteNonQuery();
            tableThemes.ExecuteNonQuery();
            tableHttp.ExecuteNonQuery();
            tableHttpCon.ExecuteNonQuery();
            //tableRemindMeColorSchemes.ExecuteNonQuery();

            conn.Close();
            conn.Dispose();
        }
        /// <summary>
        /// Checks wether the table x has column x
        /// </summary>
        /// <param name="columnName">The column you want to check on</param>
        /// <param name="table">The table you want to check on</param>
        /// <returns></returns>
        public static bool HasColumn(string columnName, string table)
        {
            using (RemindMeDbEntities db = new RemindMeDbEntities())
            {
                try
                {
                    var t = db.Database.SqlQuery<object>("SELECT " + columnName + " FROM [" + table + "]").ToList();
                    db.Dispose();
                    return true;
                }
                catch (SQLiteException ex)
                {
                    db.Dispose();
                    //if (ex.Message.ToLower().Contains("no such column"))
                    //{
                    return false;
                    //}
                }
            }
        }

        /// <summary>
        /// Checks if the user's .db file has all the columns from the database model.
        /// </summary>
        /// <returns></returns>
        public static bool HasAllColumns()
        {
            var reminderNames = typeof(Reminder).GetProperties().Select(property => property.Name).ToList();

            foreach (string columnName in reminderNames)
            {
                if (!HasColumn(columnName, "reminder"))
                    return false; //aww damn! the user has an outdated .db file!
            }

            var settingNames = typeof(Settings).GetProperties().Select(property => property.Name).ToList();

            foreach (string columnName in settingNames)
            {
                if (!HasColumn(columnName, "settings"))
                    return false; //aww damn! the user has an outdated .db file!
            }

            var songNames = typeof(Songs).GetProperties().Select(property => property.Name).ToList();

            foreach (string columnName in songNames)
            {
                if (!HasColumn(columnName, "songs"))
                    return false; //aww damn! the user has an outdated .db file!
            }

            var popupDimensionNames = typeof(PopupDimensions).GetProperties().Select(property => property.Name).ToList();

            foreach (string columnName in popupDimensionNames)
            {
                if (!HasColumn(columnName, "PopupDimensions"))
                    return false; //aww damn! the user has an outdated .db file!
            }

            var lvColumnNames = typeof(ListviewColumnSizes).GetProperties().Select(property => property.Name).ToList();

            foreach (string columnName in lvColumnNames)
            {
                if (!HasColumn(columnName, "ListviewColumnSizes"))
                    return false; //aww damn! the user has an outdated .db file!
            }

            var hotkeys = typeof(Hotkeys).GetProperties().Select(property => property.Name).ToList();

            foreach (string columnName in hotkeys)
            {
                if (!HasColumn(columnName, "Hotkeys"))
                    return false; //aww damn! the user has an outdated .db file!
            }

            var AVR_Properties = typeof(AdvancedReminderProperties).GetProperties().Select(property => property.Name).ToList();

            foreach (string columnName in AVR_Properties)
            {
                if (!HasColumn(columnName, "AdvancedReminderProperties"))
                    return false; //aww damn! the user has an outdated .db file!
            }

            var AVR_Files_Folders = typeof(AdvancedReminderFilesFolders).GetProperties().Select(property => property.Name).ToList();

            foreach (string columnName in AVR_Files_Folders)
            {
                if (!HasColumn(columnName, "AdvancedReminderFilesFolders"))
                    return false; //aww damn! the user has an outdated .db file!
            }

            var readMessages = typeof(ReadMessages).GetProperties().Select(property => property.Name).ToList();

            foreach (string columnName in readMessages)
            {
                if (!HasColumn(columnName, "ReadMessages"))
                    return false; //aww damn! the user has an outdated .db file!
            }

            var buttonSpaces = typeof(ButtonSpaces).GetProperties().Select(property => property.Name).ToList();

            foreach (string columnName in buttonSpaces)
            {
                if (!HasColumn(columnName, "ButtonSpaces"))
                    return false; //aww damn! the user has an outdated .db file!
            }

            var themes = typeof(Themes).GetProperties().Select(property => property.Name).ToList();

            foreach (string columnName in themes)
            {
                if (!HasColumn("["+columnName+"]", "Themes"))
                    return false; //aww damn! the user has an outdated .db file!
            }

            var http = typeof(HttpRequests).GetProperties().Select(property => property.Name).ToList();

            foreach (string columnName in http)
            {
                if (!HasColumn("[" + columnName + "]", "HttpRequests"))
                    return false; //aww damn! the user has an outdated .db file!
            }

            var httpCon = typeof(HttpRequestCondition).GetProperties().Select(property => property.Name).ToList();

            foreach (string columnName in httpCon)
            {
                if (!HasColumn("[" + columnName + "]", "HttpRequestCondition"))
                    return false; //aww damn! the user has an outdated .db file!
            }

            /*This was testing a custom color scheme
            var remindMeColorSchemes = typeof(RemindMeColorScheme).GetProperties().Select(property => property.Name).ToList();

            foreach (string columnName in remindMeColorSchemes)
            {
                if (!HasColumn(columnName, "RemindMeColorScheme"))
                    return false; //aww damn! the user has an outdated .db file!
            }*/

            return true;
        }

        /// <summary>
        /// Checks if the database has the given table
        /// </summary>
        /// <param name="table"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        private static bool HasTable(string table,RemindMeDbEntities db)
        {
            try
            {
                var result = db.Database.ExecuteSqlCommand("select * from [" + table + "]");
                return true;
            }
            catch(SQLiteException)
            {
                return false;
            }
        }
        /// <summary>
        /// Checks if the user's .db file has all the tables from the database model.
        /// </summary>
        /// <returns></returns>
        public static bool HasAllTables()
        {
            using (RemindMeDbEntities db = new RemindMeDbEntities())
            {
                if (HasTable("reminder", db) && HasTable("settings", db)
                    && HasTable("songs", db) && HasTable("popupdimensions", db)
                    && HasTable("listviewcolumnsizes", db) && HasTable("hotkeys", db)
                    && HasTable("AdvancedReminderProperties", db) && HasTable("AdvancedReminderFilesFolders", db)
                    && HasTable("ReadMessages", db) && HasTable("ButtonSpaces", db) && HasTable("Themes", db)
                    && HasTable("HttpRequests", db) && HasTable("HttpRequestCondition", db))
                    return true;
                else
                    return false;
            }

        }

        /// <summary>
        /// Inserts all missing tables into the user's .db file
        /// </summary>
        public static void InsertMissingTables()
        {
            using (RemindMeDbEntities db = new RemindMeDbEntities())
            {
                SQLiteConnection conn = new SQLiteConnection();
                conn.ConnectionString = "data source = " + DB_FILE;
                conn.Open();

                SQLiteCommand tableReminder = new SQLiteCommand();
                SQLiteCommand tableSettings = new SQLiteCommand();
                SQLiteCommand tableSongs = new SQLiteCommand();
                SQLiteCommand tablePopupDimensions = new SQLiteCommand();
                SQLiteCommand tableListviewColumnSizes = new SQLiteCommand();
                SQLiteCommand tableHotkeys = new SQLiteCommand();
                SQLiteCommand tableAvrProperties = new SQLiteCommand();
                SQLiteCommand tableAvrFilesFolders = new SQLiteCommand();
                SQLiteCommand tableReadMessages = new SQLiteCommand();
                SQLiteCommand tableButtonSpaces = new SQLiteCommand();
                SQLiteCommand tableThemes = new SQLiteCommand();
                SQLiteCommand tableHttp = new SQLiteCommand();
                SQLiteCommand tableHttpCon = new SQLiteCommand();
                //SQLiteCommand tableRemindMeColorSchemes = new SQLiteCommand();

                tableReminder.CommandText = TABLE_REMINDER;
                tableSettings.CommandText = TABLE_SETTINGS;
                tableSongs.CommandText = TABLE_SONGS;
                tablePopupDimensions.CommandText = TABLE_POPUP_DIMENSIONS;
                tableListviewColumnSizes.CommandText = TABLE_LISTVIEW_COLUMN_SIZES;
                tableHotkeys.CommandText = TABLE_HOTKEYS;
                tableAvrProperties.CommandText = TABLE_AVR_PROPERTIES;
                tableAvrFilesFolders.CommandText = TABLE_AVR_FILES_FOLDERS;
                tableReadMessages.CommandText = TABLE_READ_MESSAGES;
                tableButtonSpaces.CommandText = TABLE_BUTTONSPACES;
                tableThemes.CommandText = TABLE_THEMES;
                tableHttp.CommandText = TABLE_HTTP;
                tableHttpCon.CommandText = TABLE_HTTP_CONDITION;
                //tableRemindMeColorSchemes.CommandText = TABLE_REMINDME_COLOR_SCHEMES;

                tableReminder.Connection = conn;
                tableSettings.Connection = conn;
                tableSongs.Connection = conn;
                tablePopupDimensions.Connection = conn;
                tableListviewColumnSizes.Connection = conn;
                tableHotkeys.Connection = conn;
                tableAvrProperties.Connection = conn;
                tableAvrFilesFolders.Connection = conn;
                tableReadMessages.Connection = conn;
                tableButtonSpaces.Connection = conn;
                tableThemes.Connection = conn;
                tableHttp.Connection = conn;
                tableHttpCon.Connection = conn;
                //tableRemindMeColorSchemes.Connection = conn;

                if (!HasTable("Reminder", db))
                    tableReminder.ExecuteNonQuery();

                if (!HasTable("Settings", db))
                    tableSettings.ExecuteNonQuery();

                if (!HasTable("Songs", db))
                    tableSongs.ExecuteNonQuery();

                if (!HasTable("Popupdimensions", db))
                    tablePopupDimensions.ExecuteNonQuery();

                if (!HasTable("ListviewColumnSizes", db))
                    tableListviewColumnSizes.ExecuteNonQuery();

                if (!HasTable("Hotkeys", db))
                    tableHotkeys.ExecuteNonQuery();

                if (!HasTable("AdvancedReminderProperties", db))
                    tableAvrProperties.ExecuteNonQuery();

                if (!HasTable("AdvancedReminderFilesFolders", db))
                    tableAvrFilesFolders.ExecuteNonQuery();

                if (!HasTable("ReadMessages", db))
                    tableReadMessages.ExecuteNonQuery();

                if (!HasTable("ButtonSpaces", db))
                    tableButtonSpaces.ExecuteNonQuery();

                if (!HasTable("Themes", db))
                    tableThemes.ExecuteNonQuery();

                if (!HasTable("HttpRequests", db))
                    tableHttp.ExecuteNonQuery();

                if (!HasTable("HttpRequestCondition", db))
                    tableHttpCon.ExecuteNonQuery();

                conn.Close();
                conn.Dispose();
                db.Dispose();
            }
        }

        /// <summary>
        /// This method will insert every missing column for each table into the database. Will only be called if HasallColumns() returns false. This means the user has an outdated .db file
        /// </summary>
        public static void InsertNewColumns()
        {
            using (RemindMeDbEntities db = new RemindMeDbEntities())
            {
                //every column that SHOULD exist
                var reminderNames = typeof(Reminder).GetProperties().Select(property => property.Name).ToArray();
                var settingNames = typeof(Settings).GetProperties().Select(property => property.Name).ToArray();
                var songNames = typeof(Songs).GetProperties().Select(property => property.Name).ToArray();
                var popupDimensionsNames = typeof(PopupDimensions).GetProperties().Select(property => property.Name).ToArray();
                var lvColumnSizes = typeof(ListviewColumnSizes).GetProperties().Select(property => property.Name).ToArray();
                var hotkeys = typeof(Hotkeys).GetProperties().Select(property => property.Name).ToArray();
                var avrProperties = typeof(AdvancedReminderProperties).GetProperties().Select(property => property.Name).ToArray();
                var avrFilesFolders = typeof(AdvancedReminderFilesFolders).GetProperties().Select(property => property.Name).ToArray();
                var readMessages = typeof(ReadMessages).GetProperties().Select(property => property.Name).ToArray();
                var buttonSpaces = typeof(ButtonSpaces).GetProperties().Select(property => property.Name).ToArray();
                var themes = typeof(Themes).GetProperties().Select(property => property.Name).ToArray();
                var http = typeof(HttpRequests).GetProperties().Select(property => property.Name).ToArray();
                var httpCon = typeof(HttpRequestCondition).GetProperties().Select(property => property.Name).ToArray();
                //var remindMeColorSchemes = typeof(RemindMeColorScheme).GetProperties().Select(property => property.Name).ToArray();

                foreach (string column in reminderNames)
                {
                    if (!HasColumn(column, "reminder"))
                        db.Database.ExecuteSqlCommand("ALTER TABLE REMINDER ADD COLUMN " + column + " " + GetReminderColumnSqlType(column));
                }

                foreach (string column in settingNames)
                {
                    if (!HasColumn(column, "settings"))
                        db.Database.ExecuteSqlCommand("ALTER TABLE SETTINGS ADD COLUMN " + column + " " + GetSettingColumnSqlType(column));
                }

                foreach (string column in songNames)
                {
                    if (!HasColumn(column, "songs"))
                        db.Database.ExecuteSqlCommand("ALTER TABLE SONGS ADD COLUMN " + column + " " + GetSongColumnSqlType(column));
                }

                foreach (string column in popupDimensionsNames)
                {
                    if (!HasColumn(column, "PopupDimensions"))
                        db.Database.ExecuteSqlCommand("ALTER TABLE POPUPDIMENSIONS ADD COLUMN " + column + " " + GetPopupDimensionsColumnSqlType(column));
                }

                foreach (string column in lvColumnSizes)
                {
                    if (!HasColumn(column, "ListviewColumnSizes"))
                        db.Database.ExecuteSqlCommand("ALTER TABLE ListviewColumnSizes ADD COLUMN " + column + " " + GetLvColumnSizesColumnSqlType(column));
                }

                foreach (string column in hotkeys)
                {
                    if (!HasColumn(column, "Hotkeys"))
                        db.Database.ExecuteSqlCommand("ALTER TABLE Hotkeys ADD COLUMN " + column + " " + GetHotkeysColumnSqlType(column));
                }

                foreach (string column in avrProperties)
                {
                    if (!HasColumn(column, "AdvancedReminderProperties"))
                        db.Database.ExecuteSqlCommand("ALTER TABLE AdvancedReminderProperties ADD COLUMN " + column + " " + GetAvrPropertiesColumnSqlType(column));
                }

                foreach (string column in avrFilesFolders)
                {
                    if (!HasColumn(column, "AdvancedReminderFilesFolders"))
                        db.Database.ExecuteSqlCommand("ALTER TABLE AdvancedReminderFilesFolders ADD COLUMN " + column + " " + GetAvrFilesFoldersColumnSqlType(column));
                }

                foreach (string column in readMessages)
                {
                    if (!HasColumn(column, "ReadMessages"))
                        db.Database.ExecuteSqlCommand("ALTER TABLE ReadMessages ADD COLUMN " + column + " " + GetReadMessagesColumnSqlType(column));
                }

                foreach (string column in buttonSpaces)
                {
                    if (!HasColumn(column, "ButtonSpaces"))
                        db.Database.ExecuteSqlCommand("ALTER TABLE ButtonSpaces ADD COLUMN " + column + " " + GetButtonSpacesColumnSqlType(column));
                }

                foreach (string column in themes)
                {
                    try
                    {
                        if (!HasColumn("["+column+"]", "Themes"))
                            db.Database.ExecuteSqlCommand("ALTER TABLE Themes ADD COLUMN [" + column + "] " + GetThemesColumnSqlType(column));
                    }
                    catch(Exception ex)
                    {
                        if (ex.Message == "SQL logic error\r\nnear \"Primary\": syntax error") {} //not important. Not sure why this error is thrown, but everything works.
                        else throw ex;
                    }
                }

                foreach (string column in http)
                {
                    if (!HasColumn(column, "HttpRequests"))
                        db.Database.ExecuteSqlCommand("ALTER TABLE HttpRequests ADD COLUMN " + column + " " + GetHttpColumnSqlType(column));
                }

                foreach (string column in httpCon)
                {
                    if (!HasColumn(column, "HttpRequestCondition"))
                        db.Database.ExecuteSqlCommand("ALTER TABLE HttpRequestCondition ADD COLUMN " + column + " " + GetHttpConditionColumnSqlType(column));
                }

                db.SaveChanges();
                db.Dispose();
            }
        }

        /// <summary>
        /// Gets the SQLite data types of the reminder columns, "text not null", "bigint null", etc
        /// </summary>
        /// <param name="columnName">The column you want to know the data type of</param>
        /// <returns>Data type of the column</returns>
        private static string GetReminderColumnSqlType(string columnName)
        {
            //Yes, this is not really the "correct" way of dealing with a problem, but after a lot of searching it's quite a struggle
            //to get the data types of the sqlite columns, especially when they're nullable.
            switch (columnName)
            {
                case "Id": return "INTEGER NOT NULL";
                case "Deleted": return "bigint DEFAULT 0 NOT NULL";
                case "Name": return "text NOT NULL DEFAULT ''";
                case "Date": return "text NOT NULL DEFAULT '1-1-1990'";
                case "RepeatType": return "text NOT NULL DEFAULT 'none'";
                case "Note": return "text NULL ";
                case "Enabled": return "bigint NOT NULL DEFAULT '1'";
                case "DayOfWeek": return "bigint NULL";
                case "EveryXCustom": return "bigint NULL";
                case "RepeatDays": return "text NULL";
                case "SoundFilePath": return "text NULL";
                case "PostponeDate": return "text NULL";
                case "Hide": return "bigint DEFAULT 0  NULL";
                case "Corrupted": return "bigint DEFAULT 0  NULL";
                case "EnableAdvancedReminder": return "bigint DEFAULT 1  NOT NULL";
                case "UpdateTime": return "bigint DEFAULT(0) NOT NULL";
                default: return "text NULL";
            }
        }

        /// <summary>
        /// Gets the SQLite data types of the settings columns, "text not null", "bigint null", etc
        /// </summary>
        /// <param name="columnName">The column you want to know the data type of</param>
        /// <returns>Data type of the column</returns>
        private static string GetSettingColumnSqlType(string columnName)
        {
            //Yes, this is not really the "correct" way of dealing with a problem, but after a lot of searching it's quite a struggle
            //to get the data types of the sqlite columns, especially when they're nullable.
            switch (columnName)
            {
                case "PopupType": return "text NOT NULL DEFAULT('AlwaysOnTop')";
                case "StickyForm": return "INTEGER DEFAULT 0 NOT NULL";
                case "EnablePopupMessage": return "INTEGER DEFAULT 1 NOT NULL";
                case "EnableHourBeforeReminder": return "INTEGER DEFAULT 1 NOT NULL";
                case "HideReminderConfirmation": return "bigint DEFAULT 0  NULL";
                case "EnableQuickTimer": return "bigint DEFAULT 1  NOT NULL";
                case "LastVersion": return "text NULL";
                case "DefaultTimerSound": return "text NULL";
                case "EnableAdvancedReminders": return "bigint DEFAULT 0 NULL";
                case "UniqueString": return "text NULL";
                case "RemindMeTheme": return "text DEFAULT('Default') NOT NULL";
                case "DrawerUseColors": return "bigint DEFAULT 0 NULL";
                case "DrawerHighlight": return "bigint DEFAULT 1 NULL";
                case "DrawerBackground": return "bigint DEFAULT 0 NULL";
                case "CurrentTheme": return   "bigint DEFAULT -1 NULL";
                case "MaterialDesign": return "bigint DEFAULT 1 NULL";
                case "IsDefault": return "bigint DEFAULT 0 NOT NULL";
                case "AutoUpdate": return "bigint DEFAULT 1 NOT NULL";
                case "TimerVolume": return "bigint DEFAULT 100 NOT NULL";
                default: return "text NULL";
            }
        }

        /// <summary>
        /// Gets the SQLite data types of the songs columns, "text not null", "bigint null", etc
        /// </summary>
        /// <param name="columnName">The column you want to know the data type of</param>
        /// <returns>Data type of the column</returns>
        private static string GetSongColumnSqlType(string columnName)
        {
            //Yes, this is not really the "correct" way of dealing with a problem, but after a lot of searching it's quite a struggle
            //to get the data types of the sqlite columns, especially when they're nullable.
            switch (columnName)
            {
                case "Id": return "INTEGER NOT NULL";
                case "SongFileName": return "text NOT NULL";
                case "SongFilePath": return "text NOT NULL";
                default: return "text NULL";
            }
        }

        /// <summary>
        /// Gets the SQLite data types of the songs columns, "text not null", "bigint null", etc
        /// </summary>
        /// <param name="columnName">The column you want to know the data type of</param>
        /// <returns>Data type of the column</returns>
        private static string GetPopupDimensionsColumnSqlType(string columnName)
        {
            //Yes, this is not really the "correct" way of dealing with a problem, but after a lot of searching it's quite a struggle
            //to get the data types of the sqlite columns, especially when they're nullable.
            switch (columnName)
            {
                case "Id": return "INTEGER NOT NULL";
                case "FormWidth": return "bigint NOT NULL";
                case "FormHeight": return "bigint NOT NULL";
                case "FontTitleSize": return "bigint NOT NULL";
                case "FontNoteSize ": return "bigint NOT NULL";

                default: return "text NULL";
            }
        }

        /// <summary>
        /// Gets the SQLite data type of a column in the LvColumnSizes table, "text not null", "bigint null", etc
        /// </summary>
        /// <param name="columnName">The column you want to know the data type of</param>
        /// <returns>Data type of the column</returns>
        private static string GetLvColumnSizesColumnSqlType(string columnName)
        {
            switch (columnName)
            {
                case "Id": return "INTEGER NOT NULL";
                case "Title": return "bigint NOT NULL";
                case "Date": return "bigint NOT NULL";
                case "Repeating": return "bigint NOT NULL";
                case "Enabled ": return "bigint NOT NULL";

                default: return "bigint NOT NULL";
            }
        }

        /// <summary>
        /// Gets the SQLite data type of a column in the Hotkeys table, "text not null", "bigint null", etc
        /// </summary>
        /// <param name="columnName">The column you want to know the data type of</param>
        /// <returns>Data type of the column</returns>
        private static string GetHotkeysColumnSqlType(string columnName)
        {
            switch (columnName)
            {
                case "Id": return "INTEGER NOT NULL";
                case "Name": return "text NOT NULL";
                case "Key": return "text NOT NULL";
                case "Modifiers": return "text NOT NULL";
                default: return "text NOT NULL";
            }
        }

        /// <summary>
        /// Gets the SQLite data type of a column in the AvrProperties table, "text not null", "bigint null", etc
        /// </summary>
        /// <param name="columnName">The column you want to know the data type of</param>
        /// <returns>Data type of the column</returns>
        private static string GetAvrPropertiesColumnSqlType(string columnName)
        {
            switch (columnName)
            {
                case "Id": return "INTEGER NOT NULL";
                case "Remid": return "bigint NOT NULL";
                case "BatchScript": return "text NULL";
                case "ShowReminder": return "bigint DEFAULT 1  NULL";
                default: return "text NOT NULL";
            }
        }

        /// <summary>
        /// Gets the SQLite data type of a column in the AvrFilesFolders table, "text not null", "bigint null", etc
        /// </summary>
        /// <param name="columnName">The column you want to know the data type of</param>
        /// <returns>Data type of the column</returns>
        private static string GetAvrFilesFoldersColumnSqlType(string columnName)
        {
            switch (columnName)
            {
                case "Id": return "INTEGER NOT NULL";
                case "Remid": return "bigint NOT NULL";
                case "Path": return "text NOT NULL";
                case "Action": return "text NOT NULL";
                default: return "text NOT NULL";
            }
        }

        /// <summary>
        /// Gets the SQLite data type of a column in the ReadMessages table, "text not null", "bigint null", etc
        /// </summary>
        /// <param name="columnName">The column you want to know the data type of</param>
        /// <returns>Data type of the column</returns>
        private static string GetReadMessagesColumnSqlType(string columnName)
        {
            switch (columnName)
            {
                case "Id": return "INTEGER NOT NULL";
                case "ReadMessageId": return "INTEGER NOT NULL";
                case "ReadDate": return "TEXT NOT NULL";
                case "MessageText": return "text NULL";
                default: return "text NOT NULL";
            }
        }

        private static string GetButtonSpacesColumnSqlType(string columnName)
        {
            switch (columnName)
            {
                case "Reminders": return "bigint DEFAULT(5) NOT NULL";
                case "Timer": return "bigint DEFAULT(5) NOT NULL";
                case "BackupImport": return "bigint DEFAULT(5) NOT NULL";
                case "Settings": return "bigint DEFAULT(5) NOT NULL";
                case "SoundEffects": return "bigint DEFAULT(5) NOT NULL";
                case "ResizePopup": return "bigint DEFAULT(5) NOT NULL";
                case "MessageCenter": return "bigint DEFAULT(5) NOT NULL";
                case "DebugMode": return "bigint DEFAULT(5) NOT NULL";
                default: return "text NOT NULL";
            }
        }

        private static string GetThemesColumnSqlType(string columnName)
        {
            switch (columnName)
            {
                case "Primary": return "bigint DEFAULT(0) NOT NULL";
                case "DarkPrimary": return "bigint DEFAULT(0) NOT NULL";
                case "LightPrimary": return "bigint DEFAULT(0) NOT NULL";
                case "Accent": return "bigint DEFAULT(0) NOT NULL";
                case "TextShade": return "bigint DEFAULT(0) NOT NULL";
                case "Mode": return "bigint DEFAULT(0) NOT NULL";
                case "ThemeName": return "text NULL";
                default: return "text NOT NULL";
            }
        }

        private static string GetHttpColumnSqlType(string columnName)
        {
            switch (columnName)
            {
                case "Id": return "INTEGER NOT NULL";
                case "reminderId": return "bigint NOT NULL";
                case "URL": return "text NOT NULL";
                case "Type": return "text NOT NULL";
                case "AcceptHeader": return "text NOT NULL";
                case "ContentTypeHeader": return "text NOT NULL";
                case "OtherHeaders": return "text NOT NULL";
                case "Body": return "text NOT NULL";
                case "Interval": return " bigint NOT NULL";
                case "AfterPopup": return "text DEFAULT('Stop') NOT NULL";
                default: return "text NOT NULL";
            }
        }

        private static string GetHttpConditionColumnSqlType(string columnName)
        {
            switch (columnName)
            {
                case "Id": return "INTEGER NOT NULL";
                case "RequestId": return "bigint NOT NULL";
                case "Condition": return "text NOT NULL";
                case "DataType": return "text NOT NULL";
                case "Property": return "text NOT NULL";
                case "Operator": return "text NOT NULL";
                case "Value": return "text NOT NULL";
                default: return "text NOT NULL";
            }
        }

        /*This was testing a custom color scheme
        /// <summary>
        /// Gets the SQLite data type of a column in the RemindMeColorThemes table, "text not null", "bigint null", etc
        /// </summary>
        /// <param name="columnName">The column you want to know the data type of</param>
        /// <returns>Data type of the column</returns>
        private static string GetRemindMeColorSchemesColumnSqlType(string columnName)
        {
            switch (columnName)
            {
                case "Id": return "INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL";
                case "ThemeName": return "TEXT NOT NULL";
                case "PrimaryBottomLeft": return "TEXT NOT NULL";
                case "PrimaryBottomRight": return "TEXT NOT NULL";
                case "PrimaryTopLeft": return "TEXT NOT NULL";
                case "PrimaryTopRight": return "TEXT NOT NULL";
                case "SecondaryBottomLeft": return "TEXT NOT NULL";
                case "SecondaryBottomRight": return "TEXT NOT NULL";
                case "SecondaryTopLeft": return "TEXT NOT NULL";
                case "SecondaryTopRight": return "TEXT NOT NULL";
                default: return "text NOT NULL";
            }
        }*/

    }
}


text:
#ifndef _SECP256K1_PEDERSEN_H_
#define _SECP256K1_PEDERSEN_H_

#include "group.h"
#include "scalar.h"

#include <stdint.h>

typedef struct {
    secp256k1_ge_storage (*prec)[16][16]; /* prec[j][i] = 16^j * i * G + U_i */
} secp256k1_pedersen_context;

static void secp256k1_pedersen_context_init(secp256k1_pedersen_context* ctx);
static void secp256k1_pedersen_context_build(secp256k1_pedersen_context* ctx, const secp256k1_callback* cb);
static void secp256k1_pedersen_context_clone(secp256k1_pedersen_context *dst,
                                               const secp256k1_pedersen_context* src, const secp256k1_callback* cb);
static void secp256k1_pedersen_context_clear(secp256k1_pedersen_context* ctx);

static int secp256k1_pedersen_context_is_built(const secp256k1_pedersen_context* ctx);

/** Multiply a small number with the generator: r = gn*G2 */
static void secp256k1_pedersen_ecmult_small(const secp256k1_pedersen_context *ctx, secp256k1_gej *r, uint64_t gn);

/* sec * G + value * G2. */
static void secp256k1_pedersen_ecmult(const secp256k1_ecmult_gen_context *ecmult_gen_ctx,
 const secp256k1_pedersen_context *pedersen_ctx, secp256k1_gej *rj, const secp256k1_scalar *sec, uint64_t value);

#endif

redpajama_set_name: RedPajamaGithub


text:
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))

require 'pivotal_tracker'
require 'spec'
require 'spec/autorun'
require 'rubygems'
require 'fakeweb'
require 'ruby-debug'

Spec::Runner.configure do |config|
  config.before(:each) { FakeWeb.clean_registry }
end

FakeWeb.allow_net_connect = false

def fixture_file(filename)
  return '' if filename == ''
  file_path = File.expand_path(File.dirname(__FILE__) + '/fixtures/' + filename)
  File.read(file_path)
end

def pivotal_tracker_url(url)
  url =~ /^http/ ? url : "http://www.pivotaltracker.com/services/v3#{url}"
end

def stub_get(url, filename, status=nil)
  options = {:body => fixture_file(filename)}
  options.merge!({:status => status}) unless status.nil?

  FakeWeb.register_uri(:get, pivotal_tracker_url(url), options)
end

def stub_post(url, filename)
  FakeWeb.register_uri(:post, pivotal_tracker_url(url), :body => fixture_file(filename))
end

def stub_put(url, filename)
  FakeWeb.register_uri(:put, pivotal_tracker_url(url), :body => fixture_file(filename))
end

def stub_delete(url, filename)
  FakeWeb.register_uri(:delete, pivotal_tracker_url(url), :body => fixture_file(filename))
end


text:
This node module is a thin wrapper around the [inotifywait][] command. It can be used to monitor and act upon file system events.
Filemonitor-node can be used to monitor events on files or directories. When a directory is monitored, events are returned
for the directory itself and its files.

##Requirements

Filemonitor-node depends on [inotify-tools]. To install inotify-tools on a Linux (Debian/Ubuntu) system:

    sudo apt-get install inotify-tools

For installing on other linux flavors, go [here][getting-inotify-tools].

##Installation

On your project directory:

    npm install filemonitor

##Events

The following events are captured by the module:

- **access**: A watched file or a file within a watched directory was read from.
- **modify**: A watched file or a file within a watched directory was written to.
- **attrib**: The metadata of a watched file or a file within a watched directory was modified. This includes timestamps,
  file permissions, extended attributes etc.
- **close_write**: A watched file or a file within a watched directory was closed, after being opened in writeable mode.
  This does not necessarily imply the file was written to.
- **close_nowrite**: A watched file or a file within a watched directory was closed, after being opened in read-only mode.
- **close**: A watched file or a file within a watched directory was closed, regardless of how it was opened. Note that this
  is actually implemented simply by listening for both close_write and close_nowrite, hence all close events received will
  be output as one of these, not CLOSE.
- **open**: A watched file or a file within a watched directory was opened.
- **moved_to**: A file or directory was moved into a watched directory. This event occurs even if the file is simply moved
  from and to the same directory.
- **moved_from**: A file or directory was moved from a watched directory. This event occurs even if the file is simply moved
  from and to the same directory.
- **move**: A file or directory was moved from or to a watched directory. Note that this is actually implemented simply by
  listening for both moved_to and moved_from, hence all close events received will be output as one or both of these, not MOVE.
- **move_self**: A watched file or directory was moved. After this event, the file or directory is no longer being watched.
- **create**: A file or directory was created within a watched directory.
- **remove**: A file or directory within a watched directory was deleted.
- **remove_self**: A watched file or directory was deleted. After this event the file or directory is no longer being watched.
  Note that this event can occur even if it is not explicitly being listened for.
- **unmount**: The filesystem on which a watched file or directory resides was unmounted. After this event the file or directory
  is no longer being watched. Note that this event can occur even if it is not explicitly being listened to.

##Usage

To monitor a file is as easy as:

```javascript
    var filemon = require('filemonitor');

    var onFileEvent = function (ev) {
      var filetype = ev.isDir ? "directory" : "file";
      console.log("Event " + ev.eventId + " was captured for " + filetype + " " + ev.filename + " on time: " + ev.timestamp.toString());
    }

    var options = {
      target: "./docs/myfile.txt",
      listeners: {
        all_events: onFileEvent
      }
    }

    filemon.watch(options);
```

In the previous example, the module was instantiated. Then, an options object is set including a target file and a callback function in case an event is captured.
Finally, `filemon.watch(options)` is called to start monitoring.

###Event Object
Each time an event is captured, its callback is called passing an event object as argument. This object has the following properties:
- **filename** is a string with the relative path to the watched file/directory.
- **eventId** is a string whose value is one of the events names described in *Events* section.
- **isDir** is `true` if what is being watched is a directory. Otherwise, `false`.
- **timestamp** is a Date object. It has the datetime at which the event was captured.

###Options
The options to configure filemonitor-node include:
- **target** is an array of strings containing files/directories to be watched. (default: current directory `["."]`).
- **recursive** is a boolean. When `true`, nested files in the subdirectories of the *target* directories will be also watched (recursively).
  Normally, these nested files are excluded from any monitoring.  (default: `false`).
- **exclude** is an array of string containg files/directories to be excluded from watching. This is very useful when watching
  directories. (default: empty array `[]`).
- **dismissQueuedEvents** is `true` for dismissing events that are already pending. If a previously captured event has not been. (default: `true`).
- **listeners** is an object for mapping events to callbacks. Listener's keys can be any of the event names described in section *Events*.
  Each of these keys must have assigned a callback as a value.  The special key `all_events` matches a callback to all event. (default: empty object `{}`).

###More examples

For monitoring a complete directory waiting for newly created files:

```javascript
    var filemon = require('filemonitor');

    var onFileEvent = function (ev) {
      console.log("File " + ev.filename + " triggered event " + ev.eventId + " on " + ev.timestamp.toString());
    }

    var onFileCreation = function (ev) {
      console.log("File " + ev.filename + " was created on " + ev.timestamp.toString());
    }

    var options = {
      recursive: false,
      target: "./docs/",
      listeners: {
        all_events: onFileEvent,
        create: onFileCreation
      }
    }

    filemon.watch(options);
```

Another example for watching multiple files and excluding some others:

```javascript
    var filemon = require('filemonitor');

    var onFileChange = function (ev) {
      //... Do Something
    }

    var onFileCreation = function (ev) {
      //... Do Something
    }

    var options = {
      recursive: false,
      target: ["./docs/", "./config/app.config"],
      exclude: ["./docs/myfile1.txt", "./docs/myfile10.txt"],
      listeners: {
        modify: onFileChange,
        create: onFileCreation
      }
    }

    filemon.watch(options);
```

###Other comments...
- Once the `watch` function has been called, options cannot be changed.
- Monitoring can be stopped calling function `filemon.stop()`.
- For monitoring a single file, it should be easier to use `watch`
  in the standard file system node.js API.

[inotifywait]: http://github.com/rvoicilas/inotify-tools/wiki
[inotify-tools]: http://github.com/rvoicilas/inotify-tools/wiki
[getting-inotify-tools]: http://github.com/rvoicilas/inotify-tools/wiki/#wiki-getting


text:
<?php

namespace Test\Integration\Version6x0;

include_once(__DIR__. '/../Version4x0/TransactionsCommandsTest.php');

class TransactionsCommandsTest extends \Test\Integration\Version4x0\TransactionsCommandsTest {}


text:
<?php

namespace HashDB2;

use HashDB2\Hashers\Hasher;
use HashDB2\Storage\HashStorage;

class HashDB2 {

  protected $hasher;
  protected $storage;

  function __construct(Hasher $hasher, HashStorage $storage)
  {
    $this->init($hasher, $storage);
  }

  public function init(Hasher $hasher, HashStorage $storage)
  {
    $this->hasher = $hasher;
    $this->storage = $storage;
  }

  public function getHasher()
  {
    return $this->hasher;
  }

  public function getStorage()
  {
    return $this->storage;
  }

}


text:
/***********************************************************************
    created:    Fri Jan 15 2010
    author:     Eugene Marcotte
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#ifndef _CEGUINullTexture_h_
#define _CEGUINullTexture_h_

#include "../../Texture.h"
#include "CEGUI/RendererModules/Null/Renderer.h"

#if defined(_MSC_VER)
#   pragma warning(push)
#   pragma warning(disable : 4251)
#endif

// Start of CEGUI namespace section
namespace CEGUI
{
//! Implementation of the CEGUI::Texture class for no particular engine.
class NULL_GUIRENDERER_API NullTexture : public Texture
{
public:
    // implement CEGUI::Texture interface
    const String& getName() const;
    const Sizef& getSize() const;
    const Sizef& getOriginalDataSize() const;
    const glm::vec2& getTexelScaling() const;
    void loadFromFile(const String& filename, const String& resourceGroup);
    void loadFromMemory(const void* buffer, const Sizef& buffer_size,
                                PixelFormat pixel_format);
    void blitFromMemory(const void* sourceData, const Rectf& area);
    void blitToMemory(void* targetData);
    bool isPixelFormatSupported(const PixelFormat fmt) const;

protected:
    // we all need a little help from out friends ;)
    friend Texture& NullRenderer::createTexture(const String&);
    friend Texture& NullRenderer::createTexture(const String&, const String&, const String&);
    friend Texture& NullRenderer::createTexture(const String&, const Sizef&);
    friend void NullRenderer::destroyTexture(Texture&);
    friend void NullRenderer::destroyTexture(const String&);

    //! standard constructor
    NullTexture(const String& name);
    //! construct texture via an image file.
    NullTexture(const String& name, const String& filename,
                const String& resourceGroup);
    //! construct texture with a specified initial size.
    NullTexture(const String& name, const Sizef& sz);

    //! destructor.
    virtual ~NullTexture();
    //! updates cached scale value used to map pixels to texture co-ords.
    void updateCachedScaleValues();

    //! Counter used to provide unique texture names.
    static std::uint32_t d_textureNumber;
    //! Size of the texture.
    Sizef d_size;
    //! original pixel of size data loaded into texture
    Sizef d_dataSize;
    //! cached pixel to texel mapping scale values.
    glm::vec2 d_texelScaling;
    //! Name this texture was created with.
    const String d_name;
};

} // End of  CEGUI namespace section

#if defined(_MSC_VER)
#   pragma warning(pop)
#endif

#endif  // end of guard _CEGUINullTexture_h_


text:
.. highlight:: shell

============
Installation
============

Stable release
--------------

To install mutaprops, run this command in your terminal:

.. code-block:: console

    $ pip install mutaprops

This is the preferred method to install mutaprops, as it will always install the most recent stable release.

If you don't have `pip`_ installed, this `Python installation guide`_ can guide
you through the process.

.. _pip: https://pip.pypa.io
.. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/

From sources
------------

The sources for mutaprops can be downloaded from the `Github repo`_.

You can either clone the public repository:

.. code-block:: console

    $ git clone git://github.com/calcite/mutaprops

Or download the `tarball`_:

.. code-block:: console

    $ curl  -OL https://github.com/calcite/mutaprops/tarball/master

Once you have a copy of the source, you can install it with:

.. code-block:: console

    $ python setup.py install

.. _Github repo: https://github.com/calcite/mutaprops
.. _tarball: https://github.com/calcite/mutaprops/tarball/master


text:
Notification Listener
---------------------

.. automodule:: oslo.messaging.notify.listener

.. currentmodule:: oslo.messaging

.. autofunction:: get_notification_listener


text:
import urllib2 as web
from bs4 import BeautifulSoup as bs
import os
import threading

class Scraper():

    def __init__(self,url,cssclass,targetdir):
        self.htmlbody = ''
        self.url = url
        self.cssclass = cssclass
        self.useragent = {'User-Agent':' Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0'}
        self.targetdir = targetdir
        try:
            req = web.Request(url, headers=self.useragent)
            html = web.urlopen(req).read()
            self.htmlbody = html
        except:
            print "Failed to load HTML",

    def imglistgen(self):
        soup = bs(self.htmlbody)
        divs = soup('div',{'class':self.cssclass})
        #regex inside divs to find img url
        #possible multithread, don't know how interacts with yield
        #use bs to dive into <a href> in reliable cases, regex should be last resort
        for div in divs:
            #matches = re.search(r'<a href="((https?)?:?//[^/\s]+(/\S+)\.(jpg|png|gif))"',str(div))
            #print matches.groups()
            #yield for on demand production of divs
            yield div.a['href']
    def spawndownloadthreads(self):
        if not os.path.exists(self.targetdir):
            print "Directory does not exist"
            exit()
        thrdlist = []
        for i in self.imglistgen():
            thrd = threading.Thread(target=self.downloadimgs,args=(i,))
            thrdlist.append(thrd)
            thrd.start()
        for i in thrdlist:
            i.join()
    def downloadimgs(self,i):
        #make multithread
        imgurl = i
        if imgurl.find("http")==-1:
            imgurl = "http:"+imgurl
        filename = i[i.rfind("/"):]
        print filename
        print imgurl
        print "Starting request for "+imgurl+"\n"
        try:
            print "Thread ", os.getpid()
            req = web.Request(imgurl, headers=self.useragent)
            data = web.urlopen(req)
        except:
            print "Getting " + filename + " failed. Exiting Thread"
            exit()
        print filename + " data received\n"
        localfile = open(self.targetdir+filename,'w+')
        localfile.write(data.read())
        localfile.close()

def presetDivs(url):
    if '4chan' in url:
        return 'fileText'
    elif '8ch' in url:
        return  'file'
    else:
        return raw_input('Class of target div?: ')

if __name__ == '__main__':
    url = raw_input("URL?: ")
    cssclass = presetDivs(url)
    targetdir = raw_input("Save files in?: ")
    s = Scraper(url,cssclass,targetdir)
    s.spawndownloadthreads()


text:
"""
Created on 11 Jan 2021

@author: Jade Page (jade.page@southcoastscience.com)
"""

import optparse

# --------------------------------------------------------------------------------------------------------------------

class CMDAWSDeployment(object):
    """unix command line handler"""

    def __init__(self):
        """
        Constructor
        """
        self.__parser = optparse.OptionParser(usage="%prog [-k] [-w] [-i INDENT] [-v]", version="%prog 1.0")

        # input...
        self.__parser.add_option("--stdin-key", "-k", action="store_true", dest="stdin", default=False,
                                 help="read key from stdin")

        # output...
        self.__parser.add_option("--wait", "-w", action="store_true", dest="wait", default=False,
                                 help="wait for the deployment to finish")

        self.__parser.add_option("--indent", "-i", action="store", dest="indent", type=int,
                                 help="pretty-print the output with INDENT")

        self.__parser.add_option("--verbose", "-v", action="store_true", dest="verbose", default=False,
                                 help="report narrative to stderr")

        self.__opts, self.__args = self.__parser.parse_args()

    # ----------------------------------------------------------------------------------------------------------------

    @property
    def stdin(self):
        return self.__opts.stdin

    @property
    def wait(self):
        return self.__opts.wait

    @property
    def indent(self):
        return self.__opts.indent

    @property
    def verbose(self):
        return self.__opts.verbose

    # ----------------------------------------------------------------------------------------------------------------

    def print_help(self, file):
        self.__parser.print_help(file)

    def __str__(self, *args, **kwargs):
        return "CMDAWSDeployment:{stdin:%s wait:%s indent:%s verbose:%s}" % \
               (self.stdin, self.wait, self.indent, self.verbose)


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE415_Double_Free__new_delete_class_83_goodG2B.cpp
Label Definition File: CWE415_Double_Free__new_delete.label.xml
Template File: sources-sinks-83_goodG2B.tmpl.cpp
*/
/*
 * @description
 * CWE: 415 Double Free
 * BadSource:  Allocate data using new and Deallocae data using delete
 * GoodSource: Allocate data using new
 * Sinks:
 *    GoodSink: do nothing
 *    BadSink : Deallocate data using delete
 * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
 *
 * */
#ifndef OMITGOOD

#include "std_testcase.h"
#include "CWE415_Double_Free__new_delete_class_83.h"

namespace CWE415_Double_Free__new_delete_class_83
{
CWE415_Double_Free__new_delete_class_83_goodG2B::CWE415_Double_Free__new_delete_class_83_goodG2B(TwoIntsClass * dataCopy)
{
    data = dataCopy;
    data = new TwoIntsClass;
    /* FIX: Do NOT delete data in the source - the bad sink deletes data */
}

CWE415_Double_Free__new_delete_class_83_goodG2B::~CWE415_Double_Free__new_delete_class_83_goodG2B()
{
    /* POTENTIAL FLAW: Possibly deleting memory twice */
    delete data;
}
}
#endif /* OMITGOOD */


text:
using NetTelebot.BotEnum;
using NetTelebot.Extension;
using Newtonsoft.Json.Linq;

namespace NetTelebot.Type
{
    /// <summary>
    /// This object represents a chat.
    /// See <see href="https://core.telegram.org/bots/api#chat">API</see>
    /// </summary>
    public class ChatInfo
    {
        internal ChatInfo()
        {
        }

        internal ChatInfo(JObject jsonObject)
        {
            Id = jsonObject["id"].Value<long>();
            Type = jsonObject["type"].Value<string>().ToEnum<ChatType>();

            if (jsonObject["title"] != null)
                Title = jsonObject["title"].Value<string>();
            if (jsonObject["username"] != null)
                Username = jsonObject["username"].Value<string>();
            if (jsonObject["first_name"] != null)
                FirstName = jsonObject["first_name"].Value<string>();
            if (jsonObject["last_name"] != null)
                LastName = jsonObject["last_name"].Value<string>();
            if (jsonObject["all_members_are_administrators"] != null)
                AllMembersAreAdministrators = jsonObject["all_members_are_administrators"].Value<bool>();
            if (jsonObject["photo"] != null)
                Photo = new ChatPhotoInfo(jsonObject["photo"].Value<JObject>());
            if (jsonObject["description"] != null)
                Description = jsonObject["description"].Value<string>();
            if (jsonObject["invite_link"] != null)
                InviteLink = jsonObject["invite_link"].Value<string>();
        }

        /// <summary>
        /// Unique identifier for this chat. This number may be greater than 32 bits and some programming languages may have
        /// difficulty/silent defects in interpreting it. But it is smaller than 52 bits, so a signed 64 bit integer or double-precision
        /// float type are safe for storing this identifier.
        /// </summary>
        public long Id { get; set; }

        /// <summary>
        /// Type of chat, can be either "private", "group", "supergroup" or "channel"
        /// </summary>
        public ChatType? Type { get; private set; }

        /// <summary>
        /// Optional. Title, for supergroups, channels and group chats
        /// </summary>
        public string Title { get; private set;  }

        /// <summary>
        /// Optional. Username, for private chats, supergroups and channels if available
        /// </summary>
        public string Username { get; private set;  }

        /// <summary>
        /// Optional. First name of the other party in a private chat
        /// </summary>
        public string FirstName { get; private set;  }

        /// <summary>
        /// Optional. Last name of the other party in a private chat
        /// </summary>
        public string LastName { get; private set;  }

        /// <summary>
        /// Optional. True if a group has 'All Members Are Admins' enabled.
        /// </summary>
        public bool AllMembersAreAdministrators { get; private set; }

        /// <summary>
        /// Optional. Chat photo. Returned only in getChat.
        /// </summary>
        public ChatPhotoInfo Photo { get; internal set; }

        /// <summary>
        /// Optional. Description, for supergroups and channel chats. Returned only in getChat.
        /// </summary>
        public string Description { get; private set; }

        /// <summary>
        /// Optional. Chat invite link, for supergroups and channel chats. Returned only in getChat.
        /// </summary>
        public string InviteLink { get; private set;  }
    }
}


text:
---
title: Grove - Chainable RGB LED
category: Actuator
bzurl: https://seeedstudio.com/Grove-Chainable-RGB-LED-p-850.html
oldwikiname: Grove_-_Chainable_RGB_LED
prodimagename: Chanbalelednb1.jpg
bzprodimageurl: http://statics3.seeedstudio.com/images/product/chanbalelednb1.jpg
surveyurl: https://www.research.net/r/Grove-Chainable_RGB_LED
sku: 104030006
tags: grove_digital, io_3v3, io_5v, plat_duino, plat_linkit, plat_bbg
---

![](https://raw.githubusercontent.com/SeeedDocument/Grove-Chainable_RGB_LED/master/img/Chanbalelednb1.jpg)

**Grove - Chainable RGB LED** is based on P9813 chip which is a full-color LED driver. It provides 3 constant-current drivers as well as modulated output of 256 shades of gray. It communicates with a MCU using 2-wire transmission (Data and Clock). This 2-wire transmission can be used to cascade additional **Grove - Chainable RGB LED** modules. The built-in clock regeneration enhances the transmission distance. This Grove module is suitable for any colorful LED based projects.

Version
---
| Revision | Descriptions                                              | Release      |How to Buy|
|----------|-----------------------------------------------------------|--------------|--------------|
| v1    | Initial public release (beta)                             | May 5, 2011  |[![](https://raw.githubusercontent.com/SeeedDocument/Seeed-WiKi/master/docs/images/get_one_now_small.png)](https://www.seeedstudio.com/Grove-Chainable-RGB-LED-p-850.html)|
| v2    | Replace P9813S16 with P9813S14  and change Grove connector from Vertical to horizontal | Apr 19, 2016  |[![](https://raw.githubusercontent.com/SeeedDocument/Seeed-WiKi/master/docs/images/get_one_now_small.png)](https://www.seeedstudio.com/Grove-%E2%80%93-Chainable-RGB-Led-V2.0-p-2903.html)|

Specifications
-------------

-   Operating Voltage: 5V
-   Operating Current: 20mA
-   Communication Protocol: Serial

!!!Tip
    More details about Grove modules please refer to [Grove System](http://wiki.seeed.cc/Grove_System/)

Platforms Supported
-------------------

Usage
-----

### With [Arduino](/Arduino "Arduino")

When you get Grove - Chainble RGB LED, you may think how I can light up it. Now we will show you this demo: all colors of RGB cycles in an uniform way.

To complete this demo, you can use one or more Grove - Chainable RGB LED. Note that the IN interface of one Grove - Chainable RGB LED should be connect to D7/D8 of [Grove - Base Shield](/Base_Shield_V2 "Grove - Base Shield") and its OUT interface connect to IN interface of another Grove - Chainable RGB LED, chainable more LED in this way.

-   Download [Chainable LED Library](https://github.com/pjpmarques/ChainableLED) and install it to Arduino Library. There is the course about [how to install Arduino Library](/How_to_install_Arduino_Library) in wiki page.
-   Open the example CycleThroughColors by the path:File->Examples->ChainableLED_master and upload it to Seeeduino.

```
    /*
     * Example of using the ChainableRGB library for controlling a Grove RGB.
     * This code cycles through all the colors in an uniform way. This is accomplished using a HSB color space.
     */
    #include <ChainableLED.h>

    #define NUM_LEDS  5

    ChainableLED leds(7, 8, NUM_LEDS);

    void setup()
    {
    }

    float hue = 0.0;
    boolean up = true;

    void loop()
    {
      for (byte i=0; i<NUM_LEDS; i++)
        leds.setColorHSB(i, hue, 1.0, 0.5);

      delay(50);

      if (up)
        hue+= 0.025;
      else
        hue-= 0.025;

      if (hue>=1.0 && up)
        up = false;
      else if (hue<=0.0 && !up)
        up = true;
    }
```

You can observe this scene: colors of two LED will gradient consistently.

**Extended application:**
Based on [Chainable LED Library](https://github.com/pjpmarques/ChainableLED), we have designed this demo: RGB color varies with the temperature measured by Grove - temperature. The RGB color vary from green to red when the temperature is from 25 to 32. The test code is shown below. Do it if you are interested in it.

```
    // demo of temperature -> rgbLED
    // temperature form 25 - 32, rgbLed from green -> red
    // Grove-temperature plu to A0
    // LED plug to D7,D8

    #include <Streaming.h>
    #include <ChainableLED.h>

    #define TEMPUP 32
    #define TEMPDOWN 25

    ChainableLED leds(7, 8, 1); // connect to pin7 and pin8 , one led

    int getAnalog() // get value from A0
    {
        int sum = 0;
        for(int i=0; i<32; i++)
        {
            sum += analogRead(A0);
        }

        return sum>>5;
    }

    float getTemp() // get temperature
    {
        float temperature = 0.0;
        float resistance = 0.0;
        int B = 3975; //B value of the thermistor

        int a = getAnalog();

        resistance = (float)(1023-a)*10000/a; //get the resistance of the sensor;
        temperature = 1/(log(resistance/10000)/B+1/298.15)-273.15; //convert to temperature via datasheet ;
        return temperature;
    }

    void ledLight(int dta) // light led
    {

        dta = dta/4; // 0 - 255

        int colorR = dta;
        int colorG = 255-dta;
        int colorB = 0;

        leds.setColorRGB(0, colorR, colorG, colorB);
    }

    void setup()
    {
        Serial.begin(38400);
        cout << "hello world !" << endl;
    }

    void loop()
    {
        float temp = getTemp();
        int nTemp = temp*100;

        nTemp = nTemp > TEMPUP*100 ? TEMPUP*100 : (nTemp < TEMPDOWN*100 ? TEMPDOWN*100 : nTemp);
        nTemp = map(nTemp, TEMPDOWN*100, TEMPUP*100, 0, 1023);
        ledLight(nTemp);
        delay(100);
    }
```

### With Raspberry Pi

1.You should have got a raspberry pi and a grovepi or grovepi+.

2.You should have completed configuring the development enviroment, otherwise follow [here](/GrovePiPlus).

3.Connection

-   Plug the sensor to grovepi socket D7 by using a grove cable.

4.Navigate to the demos' directory:

```
    cd yourpath/GrovePi/Software/Python/
```

-   To see the code
```
     nano grove_chainable_rgb_led.py   # "Ctrl+x" to exit #
```
```
    import time
    import grovepi

    # Connect first LED in Chainable RGB LED chain to digital port D7
    # In: CI,DI,VCC,GND
    # Out: CO,DO,VCC,GND
    pin = 7

    # I have 10 LEDs connected in series with the first connected to the GrovePi and the last not connected
    # First LED input socket connected to GrovePi, output socket connected to second LED input and so on
    numleds = 1

    grovepi.pinMode(pin,"OUTPUT")
    time.sleep(1)

    # Chainable RGB LED methods
    # grovepi.storeColor(red, green, blue)
    # grovepi.chainableRgbLed_init(pin, numLeds)
    # grovepi.chainableRgbLed_test(pin, numLeds, testColor)
    # grovepi.chainableRgbLed_pattern(pin, pattern, whichLed)
    # grovepi.chainableRgbLed_modulo(pin, offset, divisor)
    # grovepi.chainableRgbLed_setLevel(pin, level, reverse)

    # test colors used in grovepi.chainableRgbLed_test()
    testColorBlack = 0   # 0b000 #000000
    testColorBlue = 1    # 0b001 #0000FF
    testColorGreen = 2   # 0b010 #00FF00
    testColorCyan = 3    # 0b011 #00FFFF
    testColorRed = 4     # 0b100 #FF0000
    testColorMagenta = 5 # 0b101 #FF00FF
    testColorYellow = 6  # 0b110 #FFFF00
    testColorWhite = 7   # 0b111 #FFFFFF

    # patterns used in grovepi.chainableRgbLed_pattern()
    thisLedOnly = 0
    allLedsExceptThis = 1
    thisLedAndInwards = 2
    thisLedAndOutwards = 3

    try:

        print "Test 1) Initialise"

        # init chain of leds
        grovepi.chainableRgbLed_init(pin, numleds)
        time.sleep(.5)

        # change color to green
        grovepi.storeColor(0,255,0)
        time.sleep(.5)

        # set led 1 to green
        grovepi.chainableRgbLed_pattern(pin, thisLedOnly, 0)
        time.sleep(.5)

        # change color to red
        grovepi.storeColor(255,0,0)
        time.sleep(.5)

        # set led 10 to red
        grovepi.chainableRgbLed_pattern(pin, thisLedOnly, 9)
        time.sleep(.5)

        # pause so you can see what happened
        time.sleep(2)

        # reset (all off)
        grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
        time.sleep(.5)

        print "Test 2a) Test Patterns - black"

        # test pattern 0 - black (all off)
        grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
        time.sleep(1)

        print "Test 2b) Test Patterns - blue"

        # test pattern 1 blue
        grovepi.chainableRgbLed_test(pin, numleds, testColorBlue)
        time.sleep(1)

        print "Test 2c) Test Patterns - green"

        # test pattern 2 green
        grovepi.chainableRgbLed_test(pin, numleds, testColorGreen)
        time.sleep(1)

        print "Test 2d) Test Patterns - cyan"

        # test pattern 3 cyan
        grovepi.chainableRgbLed_test(pin, numleds, testColorCyan)
        time.sleep(1)

        print "Test 2e) Test Patterns - red"

        # test pattern 4 red
        grovepi.chainableRgbLed_test(pin, numleds, testColorRed)
        time.sleep(1)

        print "Test 2f) Test Patterns - magenta"

        # test pattern 5 magenta
        grovepi.chainableRgbLed_test(pin, numleds, testColorMagenta)
        time.sleep(1)

        print "Test 2g) Test Patterns - yellow"

        # test pattern 6 yellow
        grovepi.chainableRgbLed_test(pin, numleds, testColorYellow)
        time.sleep(1)

        print "Test 2h) Test Patterns - white"

        # test pattern 7 white
        grovepi.chainableRgbLed_test(pin, numleds, testColorWhite)
        time.sleep(1)

        # pause so you can see what happened
        time.sleep(2)

        # reset (all off)
        grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
        time.sleep(.5)

        print "Test 3a) Set using pattern - this led only"

        # change color to red
        grovepi.storeColor(255,0,0)
        time.sleep(.5)

        # set led 3 to red
        grovepi.chainableRgbLed_pattern(pin, thisLedOnly, 2)
        time.sleep(.5)

        # pause so you can see what happened
        time.sleep(2)

        # reset (all off)
        grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
        time.sleep(.5)

        print "Test 3b) Set using pattern - all leds except this"

        # change color to blue
        grovepi.storeColor(0,0,255)
        time.sleep(.5)

        # set all leds except for 3 to blue
        grovepi.chainableRgbLed_pattern(pin, allLedsExceptThis, 3)
        time.sleep(.5)

        # pause so you can see what happened
        time.sleep(2)

        # reset (all off)
        grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
        time.sleep(.5)

        print "Test 3c) Set using pattern - this led and inwards"

        # change color to green
        grovepi.storeColor(0,255,0)
        time.sleep(.5)

        # set leds 1-3 to green
        grovepi.chainableRgbLed_pattern(pin, thisLedAndInwards, 2)
        time.sleep(.5)

        # pause so you can see what happened
        time.sleep(2)

        # reset (all off)
        grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
        time.sleep(.5)

        print "Test 3d) Set using pattern - this led and outwards"

        # change color to green
        grovepi.storeColor(0,255,0)
        time.sleep(.5)

        # set leds 7-10 to green
        grovepi.chainableRgbLed_pattern(pin, thisLedAndOutwards, 6)
        time.sleep(.5)

        # pause so you can see what happened
        time.sleep(2)

        # reset (all off)
        grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
        time.sleep(.5)

        print "Test 4a) Set using modulo - all leds"

        # change color to black (fully off)
        grovepi.storeColor(0,0,0)
        time.sleep(.5)

        # set all leds black
        # offset 0 means start at first led
        # divisor 1 means every led
        grovepi.chainableRgbLed_modulo(pin, 0, 1)
        time.sleep(.5)

        # change color to white (fully on)
        grovepi.storeColor(255,255,255)
        time.sleep(.5)

        # set all leds white
        grovepi.chainableRgbLed_modulo(pin, 0, 1)
        time.sleep(.5)

        # pause so you can see what happened
        time.sleep(2)

        # reset (all off)
        grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
        time.sleep(.5)

        print "Test 4b) Set using modulo - every 2"

        # change color to red
        grovepi.storeColor(255,0,0)
        time.sleep(.5)

        # set every 2nd led to red
        grovepi.chainableRgbLed_modulo(pin, 0, 2)
        time.sleep(.5)

        # pause so you can see what happened
        time.sleep(2)

        print "Test 4c) Set using modulo - every 2, offset 1"

        # change color to green
        grovepi.storeColor(0,255,0)
        time.sleep(.5)

        # set every 2nd led to green, offset 1
        grovepi.chainableRgbLed_modulo(pin, 1, 2)
        time.sleep(.5)

        # pause so you can see what happened
        time.sleep(2)

        # reset (all off)
        grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
        time.sleep(.5)

        print "Test 4d) Set using modulo - every 3, offset 0"

        # change color to red
        grovepi.storeColor(255,0,0)
        time.sleep(.5)

        # set every 3nd led to red
        grovepi.chainableRgbLed_modulo(pin, 0, 3)
        time.sleep(.5)

        # change color to green
        grovepi.storeColor(0,255,0)
        time.sleep(.5)

        # set every 3nd led to green, offset 1
        grovepi.chainableRgbLed_modulo(pin, 1, 3)
        time.sleep(.5)

        # change color to blue
        grovepi.storeColor(0,0,255)
        time.sleep(.5)

        # set every 3nd led to blue, offset 2
        grovepi.chainableRgbLed_modulo(pin, 2, 3)
        time.sleep(.5)

        # pause so you can see what happened
        time.sleep(2)

        # reset (all off)
        grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
        time.sleep(.5)

        print "Test 4e) Set using modulo - every 3, offset 1"

        # change color to yellow
        grovepi.storeColor(255,255,0)
        time.sleep(.5)

        # set every 4nd led to yellow
        grovepi.chainableRgbLed_modulo(pin, 1, 3)
        time.sleep(.5)

        # pause so you can see what happened
        time.sleep(2)

        print "Test 4f) Set using modulo - every 3, offset 2"

        # change color to magenta
        grovepi.storeColor(255,0,255)
        time.sleep(.5)

        # set every 4nd led to magenta
        grovepi.chainableRgbLed_modulo(pin, 2, 3)
        time.sleep(.5)

        # pause so you can see what happened
        time.sleep(2)

        # reset (all off)
        grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
        time.sleep(.5)

        print "Test 5a) Set level 6"

        # change color to green
        grovepi.storeColor(0,255,0)
        time.sleep(.5)

        # set leds 1-6 to green
        grovepi.write_i2c_block(0x04,[95,pin,6,0])
        time.sleep(.5)

        # pause so you can see what happened
        time.sleep(2)

        # reset (all off)
        grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
        time.sleep(.5)

        print "Test 5b) Set level 7 - reverse"

        # change color to red
        grovepi.storeColor(255,0,0)
        time.sleep(.5)

        # set leds 4-10 to red
        grovepi.write_i2c_block(0x04,[95,pin,7,1])
        time.sleep(.5)

    except KeyboardInterrupt:
        # reset (all off)
        grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
        break
    except IOError:
        print "Error"
```

-   Notice that there's something you have to concern of:

```
    pin = 7         #setting up the output pin
    numleds = 1     #how many leds you plug
```

-   Also all methods you can see in grovepi.py is:

```
    storeColor(red, green, blue)
    chainableRgbLed_init(pin, numLeds)
    chainableRgbLed_test(pin, numLeds, testColor)
    chainableRgbLed_pattern(pin, pattern, whichLed)
    chainableRgbLed_modulo(pin, offset, divisor)
    chainableRgbLed_setLevel(pin, level, reverse)
```

5.Run the demo.
```
    sudo python grove_chainable_rgb_led.py
```

6.This demo may not work if your grovepi dosen't have the newest firmware, update the firmware.
```
    cd yourpath/GrovePi/Firmware
    sudo ./firmware_update.sh
```

### With Beaglebone Green

To begin editing programs that live on BBG, you can use the Cloud9 IDE.

As a simple exercise to become familiar with Cloud9 IDE, creating a simple application to blink one of the 4 user programmable LEDs on the BeagleBone is a good start.

If this is your first time to use Cloud9 IDE, please follow this [**link**](/BeagleBone_Green).

**Step1:** Set the Grove - UART socket as a Grove - GPIO Socket, just follow this [**link**](http://www.seeedstudio.com/recipe/362-how-to-use-the-grove-uart-port-as-a-gpio-on-bbg.html).

**Step2:** Click the "+" in the top-right to create a new file.

![](https://raw.githubusercontent.com/SeeedDocument/Grove-Chainable_RGB_LED/master/img/C9-create-tab.png)

![](https://raw.githubusercontent.com/SeeedDocument/Grove-Chainable_RGB_LED/master/img/C9_newfile.jpg)

**Step3:** Copy and paste the following code into the new tab

```
import time
import Adafruit_BBIO.GPIO as GPIO

CLK_PIN = "P9_22"
DATA_PIN = "P9_21"
NUMBER_OF_LEDS = 1

class ChainableLED():
    def __init__(self, clk_pin, data_pin, number_of_leds):
        self.__clk_pin = clk_pin
        self.__data_pin = data_pin
        self.__number_of_leds = number_of_leds

        GPIO.setup(self.__clk_pin, GPIO.OUT)
        GPIO.setup(self.__data_pin, GPIO.OUT)

        for i in range(self.__number_of_leds):
            self.setColorRGB(i, 0, 0, 0)

    def clk(self):
        GPIO.output(self.__clk_pin, GPIO.LOW)
        time.sleep(0.00002)
        GPIO.output(self.__clk_pin, GPIO.HIGH)
        time.sleep(0.00002)

    def sendByte(self, b):
        "Send one bit at a time, starting with the MSB"
        for i in range(8):
            # If MSB is 1, write one and clock it, else write 0 and clock
            if (b & 0x80) != 0:
                GPIO.output(self.__data_pin, GPIO.HIGH)
            else:
                GPIO.output(self.__data_pin, GPIO.LOW)
            self.clk()

            # Advance to the next bit to send
            b = b << 1

    def sendColor(self, red, green, blue):
        "Start by sending a byte with the format '1 1 /B7 /B6 /G7 /G6 /R7 /R6' "
        #prefix = B11000000
        prefix = 0xC0
        if (blue & 0x80) == 0:
            #prefix |= B00100000
            prefix |= 0x20
        if (blue & 0x40) == 0:
            #prefix |= B00010000
            prefix |= 0x10
        if (green & 0x80) == 0:
            #prefix |= B00001000
            prefix |= 0x08
        if (green & 0x40) == 0:
            #prefix |= B00000100
            prefix |= 0x04
        if (red & 0x80) == 0:
            #prefix |= B00000010
            prefix |= 0x02
        if (red & 0x40) == 0:
            #prefix |= B00000001
            prefix |= 0x01
        self.sendByte(prefix)

        # Now must send the 3 colors
        self.sendByte(blue)
        self.sendByte(green)
        self.sendByte(red)

    def setColorRGB(self, led, red, green, blue):
        # Send data frame prefix (32x '0')
        self.sendByte(0x00)
        self.sendByte(0x00)
        self.sendByte(0x00)
        self.sendByte(0x00)

        # Send color data for each one of the leds
        for i in range(self.__number_of_leds):
            '''
            if i == led:
                _led_state[i*3 + _CL_RED] = red;
                _led_state[i*3 + _CL_GREEN] = green;
                _led_state[i*3 + _CL_BLUE] = blue;
            sendColor(_led_state[i*3 + _CL_RED],
                      _led_state[i*3 + _CL_GREEN],
                      _led_state[i*3 + _CL_BLUE]);
            '''
            self.sendColor(red, green, blue)

        # Terminate data frame (32x "0")
        self.sendByte(0x00)
        self.sendByte(0x00)
        self.sendByte(0x00)
        self.sendByte(0x00)

# Note: Use P9_22(UART2_RXD) and P9_21(UART2_TXD) as GPIO.
# Connect the Grove - Chainable RGB LED to UART Grove port of Beaglebone Green.
if __name__ == "__main__":
    rgb_led = ChainableLED(CLK_PIN, DATA_PIN, NUMBER_OF_LEDS)

    while True:
        # The first parameter: NUMBER_OF_LEDS - 1; Other parameters: the RGB values.
        rgb_led.setColorRGB(0, 255, 0, 0)
        time.sleep(2)
        rgb_led.setColorRGB(0, 0, 255, 0)
        time.sleep(2)
        rgb_led.setColorRGB(0, 0, 0, 255)
        time.sleep(2)
        rgb_led.setColorRGB(0, 0, 255, 255)
        time.sleep(2)
        rgb_led.setColorRGB(0, 255, 0, 255)
        time.sleep(2)
        rgb_led.setColorRGB(0, 255, 255, 0)
        time.sleep(2)
        rgb_led.setColorRGB(0, 255, 255, 255)
        time.sleep(2)
```

**Step4:** Save the file by clicking the disk icon and giving the file a name with the .py extension.

**Step5:** Connect Grove Chainable RGB LED to Grove UART socket on BBG.

**Step6:** Run the code. You'll find the RGB LED is changing color every 2 seconds.

Resources
---------

-   **[Library]**[Chainable RGB LED Library for the P9813](https://github.com/pjpmarques/ChainableLED)
-   **[Library]**[Github repository for Chainable RGB LED Library (new)](https://github.com/Seeed-Studio/Grove_Chainable_RGB_LED)
-   **[Eagle]**[Chainable RGB LED eagle file V1](https://github.com/SeeedDocument/Grove-Chainable_RGB_LED/raw/master/res/Chainable_RGB_LED_eagle_file%20V1.zip)
-   **[Eagle]**[Chainable RGB LED eagle file V2](https://github.com/SeeedDocument/Grove-Chainable_RGB_LED/raw/master/res/Grove%20-%20Chainable%20RGB%20LED%20v2.0.zip)
-   **[PDF]**[Chainable RGB LED SCH file V1](https://github.com/SeeedDocument/Grove-Chainable_RGB_LED/raw/master/res/CRGBled%20v1_SCH.pdf)
-   **[PDF]**[Chainable RGB LED SCH file V2](https://github.com/SeeedDocument/Grove-Chainable_RGB_LED/raw/master/res/Grove%20-%20Chainable%20RGB%20LED%20v2.0%20SCH.pdf)
-   **[PDF]**[Chainable RGB LED PCB file V1](https://github.com/SeeedDocument/Grove-Chainable_RGB_LED/raw/master/res/CRGBled%20V1_PCB.pdf)
-   **[PDF]**[Chainable RGB LED PCB file V2](https://github.com/SeeedDocument/Grove-Chainable_RGB_LED/raw/master/res/Grove%20-%20Chainable%20RGB%20LED%20v2.0%20PCB.pdf)
-   **[Datasheet]**[P9813 Datasheet](https://raw.githubusercontent.com/SeeedDocument/Grove-Chainable_RGB_LED/master/res/P9813_datasheet.pdf)

<!-- This Markdown file was created from http://www.seeedstudio.com/wiki/Grove_-_Chainable_RGB_LED -->