Beispiel #1
0
        public static void PropogateSingle(this Datatype dt, int correct, WriteToCMDLine write, string s, string s2 = null, double[] other = null, double[] img = null)
        {
            Sample entry = new Sample(dt);

            entry.TextInput = s;
            if (s2 != null)
            {
                entry.SecondaryText = s2;
            }
            if (other != null)
            {
                entry.ValInput = other;
            }
            if (img != null)
            {
                entry.ImgInput = img;
            }

            var      type     = typeof(INetworkPredUpdater);
            Assembly a        = type.Assembly;
            var      NetTypes = a.GetTypes().Where(y => !y.IsInterface).Where(x => type.IsAssignableFrom(x)).ToList();

            for (int i = 0; i < NetTypes.Count(); i++)
            {
                var Network = (INetworkPredUpdater)Activator.CreateInstance(NetTypes[i], entry);
                if (Network.datatype == dt)
                {
                    entry.DesiredOutput          = new double[Network.Network.Layers.Last().Biases.Count()];
                    entry.DesiredOutput[correct] = 1;
                    Network.Propogate(entry, write);
                    break;
                }
            }
        }
Beispiel #2
0
        public bool Equals(TagMetadataDefinition input)
        {
            if (input == null)
            {
                return(false);
            }

            return
                ((
                     Description == input.Description ||
                     (Description != null && Description.Equals(input.Description))
                     ) &&
                 (
                     Order == input.Order ||
                     (Order.Equals(input.Order))
                 ) &&
                 (
                     Items == input.Items ||
                     (Items != null && Items.SequenceEqual(input.Items))
                 ) &&
                 (
                     Datatype == input.Datatype ||
                     (Datatype != null && Datatype.Equals(input.Datatype))
                 ) &&
                 (
                     Name == input.Name ||
                     (Name != null && Name.Equals(input.Name))
                 ) &&
                 (
                     IsRequired == input.IsRequired ||
                     (IsRequired != null && IsRequired.Equals(input.IsRequired))
                 ));
        }
Beispiel #3
0
        public static int PredictSingle(this Datatype dt, string s, string s2 = null, double[] other = null, double[] img = null)
        {
            Sample entry = new Sample(dt);

            entry.TextInput = s;
            if (s2 != null)
            {
                entry.SecondaryText = s2;
            }
            if (other != null)
            {
                entry.ValInput = other;
            }
            if (img != null)
            {
                entry.ImgInput = img;
            }

            var      type       = typeof(INetworkPredUpdater);
            Assembly a          = type.Assembly;
            var      NetTypes   = a.GetTypes().Where(y => !y.IsInterface).Where(x => type.IsAssignableFrom(x)).ToList();
            int      prediction = -1;

            for (int i = 0; i < NetTypes.Count(); i++)
            {
                var Network = (INetworkPredUpdater)Activator.CreateInstance(NetTypes[i], entry);
                if (Network.datatype == dt)
                {
                    var output = Network.Predict(entry);
                    prediction = output.ToList().IndexOf(output.Max());
                    break;
                }
            }
            return(prediction);
        }
        public static void CreateTTDData(this Datatype dt, string name, string value)
        {
            string Directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string Datafile  = Directory + "\\" + dt.ToString() + "_CollectedData.csv";
            string Datapoint = name + "," + value;

            if (File.Exists(Datafile))
            {
                string[] lines    = File.ReadAllLines(Datafile);
                string[] newlines = new string[lines.Length + 1];
                for (int i = 0; i < lines.Length; i++)
                {
                    newlines[i] = lines[i];
                }
                newlines[newlines.Length - 1] = Datapoint;
                File.WriteAllLines(Datafile, newlines);
            }
            if (!File.Exists(Datafile))
            {
                string[] lines = new string[1] {
                    Datapoint
                };
                File.WriteAllLines(Datafile, lines);
            }
        }
Beispiel #5
0
        public Characteristic(string name, string value, Datatype datatype, string length, string decimals, string description, string status)
        {
            _name = name;

            _length     = length;
            _decimals   = decimals;
            Description = description;
            Status      = status;
            Value       = value;
            switch (datatype)
            {
            case Datatype.CHAR:
                DataType = "CHAR";
                break;

            case Datatype.NUM:
                DataType = "NUM";
                break;

            case Datatype.DATE:
                DataType = "DATE";
                break;

            case Datatype.CURR:
                DataType = "CURR";
                break;

            case Datatype.TIME:
                DataType = "TIME";
                break;
            }
        }
Beispiel #6
0
        public static CSVData CreateData(this Datatype dt, string name, string datapt)
        {
            CSVData data = new CSVData(dt, name, datapt);

            data.Write();
            return(data);
        }
Beispiel #7
0
 public Sample(Datatype dt)
 {
     this.Datatype   = dt.ToString();
     this.GUID       = Guid.NewGuid().ToString();
     this.TextOutput = new double[1] {
         0
     };
     this.SecondaryTextOutput = new double[1] {
         0
     };
     this.TertiaryTextOutput = new double[1] {
         0
     };
     this.TextInput     = "";
     this.SecondaryText = "";
     this.TertiaryText  = "";
     this.ValInput      = new double[1] {
         0
     };
     this.ImgInput = new double[1] {
         0
     };
     this.MktVals       = new double[1, 1];
     this.DesiredOutput = new double[1] {
         0
     };
     this.MktOutput = new double[1];
 }
Beispiel #8
0
        public void SaveTxt(Datatype dt)
        {
            string folder = "ValueSets".GetMyDocs();

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            var subfolder = folder + "\\" + dt.ToString();

            if (!Directory.Exists(subfolder))
            {
                Directory.CreateDirectory(subfolder);
            }
            string filename = subfolder + "\\" + guid.ToString() + ".txt";

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

            Lines.Add("GUID : " + guid.ToString());
            Lines.Add("Increase : " + Increase);
            Lines.Add("Fin Value : " + GetValueText(FinValue));
            Lines.Add("Comp Value : " + GetValueText(CompValue));
            foreach (var val in Values)
            {
                Lines.Add(GetValueText(val));
            }
            File.WriteAllLines(filename, Lines);
            this.Save(dt);
        }
Beispiel #9
0
        /// <summary>
        /// Given Pixel Data, convert the data to inches, generate new statists based on them, and generate the report based on the new data.
        /// </summary>
        /// <param name="data">Data points in pixels.</param>
        /// <param name="stats">Statistics in pixels.</param>
        /// <param name="configReader"></param>
        public static void GenerateReport(Datatype.ImageData data, Datatype.Stats stats, ConfigReader configReader)
        {
            IList<Datatype.DoublePoint> newPoints = convertToInches(data, stats);
            newPoints = verticallyFlip(newPoints);
            newPoints = translatePoints(newPoints);

            //To test the GenerateReport Class, add points from a known set of statistics into the
            //following field.  Then any report generated will be from this set.
            /*newPoints = new List<Datatype.DoublePoint>();
            newPoints.Add(new Datatype.DoublePoint(-6, 1.5));
            newPoints.Add(new Datatype.DoublePoint(0, -1.4));
            newPoints.Add(new Datatype.DoublePoint(-0.3, 1.6));
            newPoints.Add(new Datatype.DoublePoint(-3.6, -4.2));
            newPoints.Add(new Datatype.DoublePoint(1.1, -1.5));
            newPoints.Add(new Datatype.DoublePoint(-3.4, 0.2));
            newPoints.Add(new Datatype.DoublePoint(0.7, -2.4));
            newPoints.Add(new Datatype.DoublePoint(-3.8, 3.6));
            newPoints.Add(new Datatype.DoublePoint(-0.5, -3.2));
            newPoints.Add(new Datatype.DoublePoint(2.7, -2.4));

            newPoints = translatePoints(newPoints);*/

            Datatype.Stats newStats = Stats.GenerateStatistics(newPoints);

            try
            {
                ExcelReportGenerator.GenerateReport(newPoints, data, newStats, configReader);
            }
            catch (System.InvalidOperationException)
            {
                //Do nothing for now.
            }
        }
Beispiel #10
0
        public ValueSet[] ReadValues(Datatype dt, int Count = 16)
        {
            string fname  = "Valuesets";
            string folder = fname.GetMyDocs();

            if (Directory.Exists(folder))
            {
                string subfolder = folder + "\\" + dt.ToString();
                if (Directory.Exists(subfolder))
                {
                    var Files = Directory.GetFiles(subfolder).Where(x => x.EndsWith(".bin")).ToList();
                    if (Files.Any())
                    {
                        Random     r      = new Random();
                        ValueSet[] output = new ValueSet[(Count > (Files.Count() + 1))? (Files.Count() + 1) : Count];
                        output[0] = this;
                        for (int i = 1; i < output.Count(); i++)
                        {
                            output[i] = Files[r.Next(Files.Count())].ReadFromBinaryFile <ValueSet>();
                        }
                        return(output);
                    }
                }
            }
            return(new ValueSet[1] {
                this
            });
        }
        public static int Count(this Datatype datatype)
        {
            int value = (int)datatype / 1000;
            int fin   = value % 10;

            return(fin);
        }
Beispiel #12
0
        internal AlphaContext(Datatype dt, WriteToCMDLine write, int numb = 0)
        {
            datatype = dt;
            switch (numb)
            {
            default:
            case 0: Network = Datatype.AlphaContextPrimary.LoadNetwork(write, dt); break;

            case 1: Network = Datatype.AlphaContextSecondary.LoadNetwork(write, dt); break;

            case 2: Network = Datatype.AlphaContextTertiary.LoadNetwork(write, dt); break;
            }
            if (Network.Datatype == Datatype.None)
            {
                switch (numb)
                {
                default:
                case 0: Network = new NeuralNetwork(Datatype.AlphaContextPrimary); break;

                case 1: Network = new NeuralNetwork(Datatype.AlphaContextSecondary); break;

                case 2: Network = new NeuralNetwork(Datatype.AlphaContextTertiary); break;
                }
                Network.Layers.Add(new Layer(1, CharSet.CharCount * (1 + (2 * SearchRange)), Activation.Linear));
            }
        }
    private void binddata()
    {
        DBFunctions db = new DBFunctions();
        Programtxt.DataSource = db.getprogramslist();
        Programtxt.DataValueField = "ID";
        Programtxt.DataTextField = "ProgramName";
        Programtxt.DataBind();

        Sectiontxt.DataSource = db.getformSectionlist();
        Sectiontxt.DataTextField = "Section";
        Sectiontxt.DataValueField = "ID";
        Sectiontxt.DataBind();

        Datatype dt=new Datatype();
        Datatypetxt.DataSource = dt.datatypelist;
        Datatypetxt.DataTextField = "type";
        Datatypetxt.DataValueField = "type";
        Datatypetxt.DataBind();


        Controltxt.DataSource = dt.controllist;
        //Controltxt.DataSource = dt.datatypelist;
        Controltxt.DataTextField = "type";
        Controltxt.DataValueField = "type";
        Controltxt.DataBind();
    }
Beispiel #14
0
        public static Alpha2 LoadAlpha(this Datatype datatype, WriteToCMDLine write)
        {
            string fn = "AlphaNetwork";

            fn += ".bin";
            string Folder = "NeuralNets".GetMyDocs();

            if (Directory.Exists(Folder))
            {
                string[] Files = Directory.GetFiles(Folder);
                if (Files.Any(x => x.Contains(fn)))
                {
                    var doc = Files.Where(x => x.Contains(fn)).First();
                    write("Alpha read from My Docs");
                    return(ReadFromBinaryFile <Alpha2>(doc));
                }
            }
            var assembly = typeof(ReadWriteNeuralNetwork).GetTypeInfo().Assembly;

            if (assembly.GetManifestResourceNames().Any(x => x.Contains(fn)))
            {
                string name = assembly.GetManifestResourceNames().Where(x => x.Contains(fn)).First();
                using (Stream stream = assembly.GetManifestResourceStream(name))
                {
                    var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    write("Alpha Read from Assembly");
                    return((Alpha2)binaryFormatter.Deserialize(stream));
                }
            }

            write("Alpha Not Found. New Network Created");
            return(new Alpha2(write));
        }
    private void binddata()
    {
        DBFunctions db = new DBFunctions();

        Programtxt.DataSource     = db.getprogramslist();
        Programtxt.DataValueField = "ID";
        Programtxt.DataTextField  = "ProgramName";
        Programtxt.DataBind();

        Sectiontxt.DataSource     = db.getformSectionlist();
        Sectiontxt.DataTextField  = "Section";
        Sectiontxt.DataValueField = "ID";
        Sectiontxt.DataBind();

        Datatype dt = new Datatype();

        Datatypetxt.DataSource     = dt.datatypelist;
        Datatypetxt.DataTextField  = "type";
        Datatypetxt.DataValueField = "type";
        Datatypetxt.DataBind();


        Controltxt.DataSource = dt.controllist;
        //Controltxt.DataSource = dt.datatypelist;
        Controltxt.DataTextField  = "type";
        Controltxt.DataValueField = "type";
        Controltxt.DataBind();
    }
Beispiel #16
0
 public Tick(string ticker, Datatype datatype, DateTime timestamp, double value, double volume)
 {
     Ticker    = ticker;
     Type      = datatype;
     Timestamp = timestamp;
     Value     = value;
     Volume    = volume;
 }
Beispiel #17
0
        public DatabaseObjectVariable(T databaseObject, string name, Datatype datatype)
        {
            DatabaseObject = databaseObject;
            Name           = name;
            Datatype       = datatype;

            SqlName = GetSqlName(name);
        }
Beispiel #18
0
 public CSVData(Datatype dt, string n, string s)
 {
     this.ID       = Guid.NewGuid().ToString();
     this.datatype = dt;
     this.Name     = n;
     this.Data     = s;
     this.Time     = DateTime.Now.ToString("yyyyMMddhhmmss");
 }
Beispiel #19
0
        public RNPointFieldMsg(JSONNode node)
        {
            name   = node["name"];
            offset = node["offset"].AsInt;
            count  = node["count"].AsInt;

            switch (node["datatype"].AsInt)
            {
            case PointFieldMsg.INT8:
                datatype   = Datatype.INT8;
                byteLength = 1;
                break;

            case PointFieldMsg.UINT8:
                datatype   = Datatype.UINT8;
                byteLength = 1;
                break;

            case PointFieldMsg.INT16:
                datatype   = Datatype.INT16;
                byteLength = 2;
                break;

            case PointFieldMsg.UINT16:
                datatype   = Datatype.UINT16;
                byteLength = 2;
                break;

            case PointFieldMsg.INT32:
                datatype   = Datatype.INT32;
                byteLength = 4;
                break;

            case PointFieldMsg.UINT32:
                datatype   = Datatype.UINT32;
                byteLength = 4;
                break;

            case 7:
                datatype   = Datatype.INT64;
                byteLength = 8;
                break;

            case PointFieldMsg.FLOAT32 + 1:
                datatype   = Datatype.FLOAT32;
                byteLength = 4;
                break;

            case PointFieldMsg.FLOAT64 + 1:
                datatype   = Datatype.FLOAT64;
                byteLength = 4;
                break;

            default:
                break;
            }
        }
        public static void SelectSet(string filepath, Datatype datatype)
        {
            currentFilePath = filepath;
            currentDataType = datatype;

            Thread thread = new Thread(new ThreadStart(CreateFeatureVectors));

            thread.Start();
        }
Beispiel #21
0
        public static void Sort(this Datatype dt)
        {
            if (dt == Datatype.Masterformat)
            {
                OpenFileDialog ofd = new OpenFileDialog()
                {
                    FileName = "Select a csv file",
                    Filter   = "CSV files (*.csv)|*.csv",
                    Title    = "Open csv file"
                };
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    var filepath = ofd.FileName;
                    var lines    = File.ReadAllLines(filepath).ToList();
                    List <List <string> > LineSets = new List <List <string> >();
                    for (int i = 0; i < 40; i++)
                    {
                        List <string> l = new List <string>();
                        for (int j = 0; j < lines.Count(); j++)
                        {
                            int k = int.Parse(lines[j].Split(',').Last());
                            if (k == i)
                            {
                                l.Add(lines[j]);
                            }
                        }
                        if (l.Any())
                        {
                            LineSets.Add(l);
                        }
                    }

                    int Max = 0;
                    for (int i = 0; i < LineSets.Count(); i++)
                    {
                        int j = LineSets[i].Count();
                        if (j > Max)
                        {
                            Max = j;
                        }
                    }
                    Program.Write("Max is : " + Max);
                    Program.Write("LineSet Count is : " + LineSets.Count());
                    Random r = new Random();
                    for (int i = 0; i < LineSets.Count(); i++)
                    {
                        for (int j = LineSets[i].Count(); j < Max; j++)
                        {
                            lines.Add(LineSets[i].OrderBy(x => r.Next()).First());
                        }
                    }

                    var NewLines = lines.OrderBy(x => int.Parse(x.Split(',').Last()));
                    File.WriteAllLines(filepath, NewLines);
                }
            }
        }
Beispiel #22
0
 internal ValueExp(Datatype dt, object value)
     : base(dt.GetHashCode() * dt.ValueHashCode(value) * HASH_VALUE, false)
 {
     // TODO: probably the epsilon reducibility is wrong.
     // can we treat epsilon-reducibility as an approximation?
     // rather than the precise value?
     this.dt    = dt;
     this.value = value;
 }
 internal ValueExp( Datatype dt, object value )
     : base(dt.GetHashCode()*dt.ValueHashCode(value)*HASH_VALUE, false)
 {
     // TODO: probably the epsilon reducibility is wrong.
     // can we treat epsilon-reducibility as an approximation?
     // rather than the precise value?
     this.dt = dt;
     this.value = value;
 }
Beispiel #24
0
 public AddToDataDefinition(uint defineId, string datumName, string unitsName, Datatype datumType, float fEpsilon, uint datumId)
 {
     this.defineId  = defineId;
     this.datumName = datumName;
     this.unitsName = unitsName;
     this.datumType = datumType;
     this.fEpsilon  = fEpsilon;
     this.datumId   = datumId;
 }
Beispiel #25
0
        public static string WithSqlSyntax(this string importValue, Datatype datatype)
        {
            importValue = string.IsNullOrEmpty(importValue)? string.Empty : importValue.Trim();
            switch (datatype)
            {
            case Datatype.Numeric:

                return(string.IsNullOrEmpty(importValue) ? "NULL" : importValue.RemoveInvalidCharacters());

            case Datatype.Dynamic:
                return(importValue);

            case Datatype.DateTime:
                return(string.IsNullOrEmpty(importValue) ? "NULL" : "'" + importValue.Replace("'", "''") + "'");

            case Datatype.String:
                return("'" + importValue.Replace("'", "''") + "'");

            case Datatype.Bit:
                string val;
                if (BooleanValues.TryGetValue(importValue.ToUpperInvariant(), out val))
                {
                    return(val);
                }
                else
                {
                    if (string.IsNullOrEmpty(importValue))
                    {
                        return("NULL");
                    }
                    else
                    {
                        return("INVALID");
                    }
                }

            case Datatype.Intolerance:
                string intolVal;
                if (IntoleranceValues.TryGetValue(importValue.ToUpperInvariant(), out intolVal))
                {
                    return(intolVal);
                }
                else
                {
                    if (string.IsNullOrEmpty(importValue))
                    {
                        return("NULL");
                    }
                    else
                    {
                        return("INVALID");
                    }
                }
            }
            return(importValue);
        }
Beispiel #26
0
 internal DataExp(Datatype _dt, Expression _except, string _name)
     : base(_dt.GetHashCode() * HASH_DATA, false)
 {
     // TODO: probably the epsilon reducibility is wrong.
     // can we treat epsilon-reducibility as an approximation?
     // rather than the precise value?
     this.except = _except;
     this.dt     = _dt;
     this.name   = _name;
 }
        public static string CreateFolder(this Datatype dt, WriteToCMDLine wo)
        {
            string folder = dt.ToString().GetMyDocs(wo);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            return(folder);
        }
 public StonkContext(Datatype dt)
 {
     datatype = dt;
     Network  = Datatype.StonkContext.LoadNetwork(CMDLibrary.WriteNull, dt);
     if (Network.Datatype == Datatype.None)
     {
         Network = new NeuralNetwork(Datatype.StonkContext);
         Network.Layers.Add(new Layer(1, 8, Activation.Linear));
     }
 }
Beispiel #29
0
        public static void CreateTTDData(this string obj, string id, string value, Datatype dt)
        {
            string[] lines = new string[4] {
                DateTime.Now.ToString("yyyyMMddhhmmss"), obj, id, value
            };
            string folder = dt.CreateFolder(new WriteToCMDLine(Write));
            string file   = folder + "\\" + Guid.NewGuid().ToString("N") + ".txt";

            File.WriteAllLines(file, lines);
        }
Beispiel #30
0
        public CSVData(string fn)
        {
            string[] lines = File.ReadAllLines(fn);
            this.ID   = fn;
            this.Time = lines[0];
            Datatype dt = (Datatype)Enum.Parse(typeof(Datatype), lines[1]);

            this.Name = lines[2];
            this.Data = lines[3];
        }
 internal DataExp( Datatype _dt, Expression _except, string _name )
     : base(_dt.GetHashCode()*HASH_DATA, false)
 {
     // TODO: probably the epsilon reducibility is wrong.
     // can we treat epsilon-reducibility as an approximation?
     // rather than the precise value?
     this.except = _except;
     this.dt = _dt;
     this.name = _name;
 }
Beispiel #32
0
        public DatatypeBuilder CreateDatatypeBuilder(string name)
        {
            Datatype dt = CreateDatatype(name);

            if (dt == null)
            {
                throw new DatatypeException();
            }
            return(new DatatypeBuilderImpl(dt));
        }
        public Datatype CreateDatatype(string name)
        {
            Datatype dt = (Datatype)builtinTypes[name];

            if (dt != null)
            {
                return(dt);
            }

            // TODO: localization
            throw new DatatypeException("undefined datatype: " + name);
        }
        public void Test_NameValidNamespaceContainsInternalSpaceAndSpecialCharacter()
        {
            Datatype datatype = Datatype.BuildCustomDatatype("asdasd", "asd asd#");

            List <string> errors = datatype.ValidationErrors().ToList();

            errors.Contains(ErrorMessages.DatatypeIsRequired).ShouldBeFalse();
            errors.Contains(ErrorMessages.NameCannotContainAnInternalSpace).ShouldBeFalse();
            errors.Contains(ErrorMessages.NameCannotContainSpecialCharacters).ShouldBeFalse();
            errors.Contains(ErrorMessages.NamespaceCannotContainAnInternalSpace).ShouldBeTrue();
            errors.Contains(ErrorMessages.NamespaceIsNotValid).ShouldBeTrue();
        }
Beispiel #35
0
        /// <summary>
        /// Given a set of datapoints, convert them to inches and return the points.
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private static IList<Datatype.DoublePoint> convertToInches(Datatype.ImageData data, Datatype.Stats stats)
        {
            Point oldX = data.scale.horizontal;
            Point oldY = data.scale.vertical;
            Point oldOrigin = data.scale.middle;

            //Change so oldX and oldY are in reference to origin of (0, 0)
            oldX = pointSubtract(oldX, oldOrigin);
            oldY = pointSubtract(oldY, oldOrigin);

            //Declare new points.  Data.scale.___length is the scale and origin of (0,0)
            Datatype.DoublePoint inchesX = new Datatype.DoublePoint(data.scale.horizontalLength, 0);
            Datatype.DoublePoint inchesY = new Datatype.DoublePoint(0, data.scale.verticalLength);
            Datatype.DoublePoint inchesOrigin = new Datatype.DoublePoint(0, 0);

            inchesX = pointSubtract(inchesX, inchesOrigin);
            inchesY = pointSubtract(inchesY, inchesOrigin);

            //Convert by using transformation matrix A:
            //A * oldPoint = newPoint
            //A = [ a  b
            //      c  d ]

            //Assuming oldX, oldY, newX, and newY are all measured from an origin of 0:
            double a = (double)inchesX.X / (double)oldX.X;
            double b = (double)inchesX.Y / (double)oldX.X;
            double c = (double)inchesY.X / ((double)oldY.Y - ((double)oldY.X / (double)oldX.X) * (double)oldX.Y);
            double d = (double)inchesY.Y / ((double)oldY.Y - ((double)oldY.X / (double)oldX.X) * (double)oldX.Y);

            //Convert each point by multiplying by matrix A:
            // [a b  *  [oldX  = [newX
            //  c d]     oldY]    newY]
            Datatype.DoublePoint doublePoint = new Datatype.DoublePoint();
            IList<Datatype.DoublePoint> newPoints = new List<Datatype.DoublePoint>();

            for (int point = 0; point < data.points.Count; point++)
            {
                doublePoint.X = a * data.points[point].X + c * data.points[point].Y;
                doublePoint.Y = b * data.points[point].X + d * data.points[point].Y;
                newPoints.Add(doublePoint);
            }

            return newPoints;
        }
Beispiel #36
0
        /// <summary>
        /// Adds a caliber unit to the database.
        /// </summary>
        /// <param name="caliberUnit">The <c>CaliberUnit</c> to add to the database.</param>
        /// <param name="configReader">The <c>ConfigReader</c> with the path to the database.</param>
        /// <exception cref="OleDbException">A connection-level error occurred while opening the connection.</exception>
        /// <exception cref="InvalidOperationException">The INSERT INTO Caliber command failed.</exception>
        public static void AddCaliberUnit(Datatype.CaliberUnit caliberUnit, ConfigReader configReader)
        {
            using (OleDbConnection conn = new OleDbConnection(configReader.getValue("Database Location")))
            {
                openConnection(conn);

                using (OleDbCommand command = new OleDbCommand()) {
                    command.Connection = conn;
                    command.CommandText = "INSERT INTO Caliber (UnitName, UnitsPerInch) VALUES (?, ?)";
                    command.Prepare();
                    setStringParameter(command, "UnitName", caliberUnit.unitName);
                    command.Parameters.Add("UnitsPerInch", OleDbType.Double).Value = caliberUnit.unitsPerInch;

                    try {
                        command.ExecuteNonQuery();
                    } catch (InvalidOperationException e) {
                        Log.LogError("Could not perform INSERT INTO Caliber.", "SQL", command.CommandText);
                        throw e;
                    }
                }
            }
        }
Beispiel #37
0
        /** Decodes data transitions. */
        private static Transition.Data decodeDTr( string encStates, string encDTr, State.Single[] states, int s, Transition.Data next, Datatype[] datatypes )
        {
            int start = encStates[ s*sizeOfState+3 ];
            int end = (s!=states.Length-1)?encStates[ (s+1)*sizeOfState+3 ]:encDTr.Length;

            for( int i=end-sizeOfDTr; i>=start; i-=sizeOfDTr ) {
                next = new Transition.Data(
                    datatypes[ encDTr[ i+2 ] ],
                    states[encDTr[i+0]],
                    states[encDTr[i+1]],
                    next );
            }

            return next;
        }
Beispiel #38
0
        /**
        * @param nameLiterals
        *      Name literals encoded into a string as
        *      "[stateId1][uri1]\u0000[local1]\u0000[stateid2][uri2]\u0000 ..."
        * @param defaultNameCode
        *      The name code assigned to literals that are not described in the above
        *      dictionary.
        * @param encStates
        *      encoded state information.
        * @param encATr, encDTr, encETr, encITr, encLTr, encNTr, encVTr
        *      encoded transition tables (per alphabet type.)
        * @param datatypes
        *      Datatype objects used in this schema.
        * @param values
        *      Values used by &lt;value/> patterns.
        */
        public Schema(
            string nameLiterals,
            int defaultNameCode,
            string encStates,
            string encATr,
            string encDTr,
            string encETr,
            string encITr,
            string encLTr,
            string encNTr,
            string encVTr,
            Datatype[] datatypes,
            object[] values)
        {
            // decode name literals
            while(nameLiterals.Length!=0) {
                int code = decodeInt(nameLiterals,0);   // name code
                nameLiterals = nameLiterals.Substring(2);

                int idx;

                idx = nameLiterals.IndexOf('\u0000');
                string uri = nameLiterals.Substring(0,idx);
                nameLiterals = nameLiterals.Substring(idx+1);

                idx = nameLiterals.IndexOf('\u0000');
                string local = nameLiterals.Substring(0,idx);
                nameLiterals = nameLiterals.Substring(idx+1);

                this.nameLiterals.Add( new StringPair(uri,local), code );
            }

            this.defaultNameCode = defaultNameCode;

            {// decode state and transition table
                string es;
                State.Single[] states = new State.Single[ encStates.Length/sizeOfState ];

                // build basic state objects
                es=encStates;
                for( int idx=0; es.Length!=0; idx++,es=es.Substring(sizeOfState) ) {
                    char bitFlags = es[0];
                    states[idx] = new State.Single( (bitFlags&2)!=0, (bitFlags&1)!=0, idx );
                }

                bool[] decoded = new bool[states.Length];

                // bare stack.
                int[] stack = new int[16];
                int stackPtr=0;

                // decode transition table
                for( int idx=states.Length-1; idx>=0; idx-- ) {

                    int s = idx;
                    while( s!=65535 && !decoded[s] ) {
                        // this state needs to be decoded -- push this state
                        if( stack.Length==stackPtr ) {
                            // extend the stack
                            int[] newBuf = new int[stack.Length*2];
                            stack.CopyTo( newBuf,0 );
                            stack = newBuf;
                        }
                        stack[stackPtr++] = s;
                        decoded[s] = true;

                        // decode next state
                        s = encStates[ s*sizeOfState+1 ];
                    }

                    while( stackPtr!=0 ) {
                        // decode transitions from state 's'.
                        s = stack[--stackPtr];
                        State.Single current = states[s];

                        // next state
                        int nextStateIdx = encStates[ s*sizeOfState+1 ];
                        State.Single nextState = (nextStateIdx==65535)?null:states[nextStateIdx];

                        // decode transitions

                        current.aTr = decodeATr( encStates, encATr, states, s, nextState==null?null:nextState.aTr );
                        current.dTr = decodeDTr( encStates, encDTr, states, s, nextState==null?null:nextState.dTr, datatypes );
                        current.eTr = decodeETr( encStates, encETr, states, s, nextState==null?null:nextState.eTr );
                        current.iTr = decodeITr( encStates, encITr, states, s, nextState==null?null:nextState.iTr );
                        current.lTr = decodeLTr( encStates, encLTr, states, s, nextState==null?null:nextState.lTr );
                        current.nTr = decodeNTr( encStates, encNTr, states, s, nextState==null?null:nextState.nTr );
                        current.vTr = decodeVTr( encStates, encVTr, states, s, nextState==null?null:nextState.vTr, datatypes, values );
                    }
                }

                InitialState = states[0];
            }
        }
Beispiel #39
0
 private static Datatype[] createDatatypes( DatatypeLibraryFactory factory, object[] encodedDatatypes )
 {
     Datatype[] datatypes = new Datatype[encodedDatatypes.Length/3];
     for( int i=0; i<datatypes.Length; i++ ) {
         datatypes[i] = createDatatype( factory,
             (string)encodedDatatypes[i*3],
             (string)encodedDatatypes[i*3+1],
             (object[])encodedDatatypes[i*3+2] );
     }
     return datatypes;
 }
Beispiel #40
0
 public Data( Datatype dt, State.Single left, State.Single right, Data next )
 {
     this.Datatype=dt;
     this.Left=left;
     this.Right=right;
     this.Next=next;
 }
Beispiel #41
0
 public Value( Datatype dt, object value, State.Single right, Value next )
 {
     this.Datatype=dt;
     this.Obj = value;
     this.Right=right;
     this.Next=next;
 }
        // Receive an update from either a client or the server, depending on where this method is called.
        public static object ReceiveMessage( NetIncomingMessage inc, Datatype messageType )
        {
            switch ( messageType )
            {
                case Datatype.UpdateDeck:
                {
                    return new Deck(ReadCards(inc));
                }

                case Datatype.UpdateDiscardPile:
                {
                    return ReadCards(inc);
                }

                case Datatype.UpdatePlayer:
                {
                    return ReadPlayer(inc);
                }

                case Datatype.UpdatePlayerList:
                {
                    return ReadPlayerList(inc);
                }

                case Datatype.RequestRent:
                {
                    return ReadRentRequest(inc);
                }

                case Datatype.GiveRent:
                {
                    return ReadRentResponse(inc);
                }

                case Datatype.RequestTheft:
                {
                    return ReadTheftRequest(inc);
                }

                case Datatype.ReplyToTheft:
                {
                    return ReadTheftResponse(inc);
                }

                case Datatype.LaunchGame:
                case Datatype.UpdateTurn:
                {
                    return ReadTurn(inc);
                }

                case Datatype.TimeToConnect:
                {
                    return inc.ReadString();
                }

                case Datatype.EndTurn:
                {
                    return ReadTurn(inc);
                }
            }

            return null;
        }
 internal DatatypeBuilderImpl( Datatype _type )
 {
     this.type = _type;
 }
Beispiel #44
0
 public RegisterValueNode(Datatype type)
     : base(type, StorageClass.RegisterValue)
 {
 }
Beispiel #45
0
 public Register(string mnemonic, Datatype datatype)
 {
     this.mnemonic = mnemonic;
     this.datatype = datatype;
 }
Beispiel #46
0
 public ValueNode(Datatype datatype, StorageClass storageClass)
 {
     this.datatype = datatype;
     this.storageClass = storageClass;
 }
Beispiel #47
0
 public TestRegisterNode(string id, Datatype type)
     : base(type)
 {
     this.id = id;
 }
Beispiel #48
0
        public static void GenerateReport(IList<Datatype.DoublePoint> newPoints, Datatype.ImageData data, Datatype.Stats stats, ConfigReader reader)
        {
            string imagePath = data.origFilename;
            string savePath = data.reportFilename;

            if (savePath == null)
            {
                throw new NullReferenceException("A save path must be provided in order for the report to save");
            }

            //Open Excel File
            ExcelFile excelFile = new ExcelFile();

            try
            {
                excelFile.LoadXlsx(reader.getValue("Template Location"),
                                  XlsxOptions.PreserveKeepOpen);
            }
            //Catch and report error if directory is not valid
            catch (System.IO.DirectoryNotFoundException)
            {
                MessageBox.Show("A report could not be generated.  Please check the configuration file for errors.  " +
                "The path to the default template contains a directory that doesn't seem to exist.", "Directory Not Found",
                MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                throw new System.InvalidOperationException("DirectoryNotFoundException");
            }
            //Catch and return error if file is not found.
            catch (System.IO.FileNotFoundException)
            {
                MessageBox.Show("A report could not be generated.  Please check the configuration file for errors.  " +
                "The file name given doesn't seem to exist.", "File Not Found",
                MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                throw new System.InvalidOperationException("FileNotFoundException");
            }
            //Catch and report error if the file is already opened and locked
            catch (System.IO.IOException)
            {
                MessageBox.Show("A report could not be generated because the template file is locked.  " +
                "Please close any application that may be using the file and try again.", "File Could Not Load",
                MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                throw new System.InvalidOperationException("FileLoadException");
            }
            ExcelWorksheet reportWorksheet = excelFile.Worksheets[0];
            ExcelWorksheet otherStatsWorksheet = excelFile.Worksheets[1];

            //Set row fill color.
            Color rowFillColor = Color.FromArgb(219, 229, 241);

            //Check that data.distance != 0
            if (data.distance == 0)
            {
                throw new DivideByZeroException("Data.distance cannot be 0");
            }

            //Determine minutes of angle factor.  If yards, use the literal data.distance; else convert to yards.
            if (data.distanceUnits == SANTA.Datatype.UnitsOfMeasure.Yard)
            {
                minutesOfAngleConverter = minutesOfAngleConversionFactor*100/data.distance;
            } else if (data.distanceUnits == SANTA.Datatype.UnitsOfMeasure.Meter)
            {
                minutesOfAngleConverter = minutesOfAngleConversionFactor*100/(data.distance*1.0936133);
            } else
            {
                //Should never get here, but exception will trigger if we do.
                throw new InstanceNotFoundException("Distance Units are not of a known datatype.");
            }

            // Column width of 8, 30, 16, 9, 9, 9, 9, 4 and 5 characters.
            reportWorksheet.Columns[0].Width = 285/7*256;
            reportWorksheet.Columns[1].Width = 107/7*256;
            reportWorksheet.Columns[2].Width = 12*(256 - 24);
            reportWorksheet.Columns[3].Width = 12*(256 - 24);
            reportWorksheet.Columns[4].Width = 12*(256 - 24);
            reportWorksheet.Columns[5].Width = 12*(256 - 24);
            reportWorksheet.Columns[6].Width = 12*(256 - 24);
            reportWorksheet.Columns[7].Width = 12*(256 - 24);

            // Fill in cell data

            placeValue(reportWorksheet, "Target Distance", data.distance);

            reportWorksheet.Cells[reader.getValue("Shooter Name")].Value = data.shooterFName + " " + data.shooterLName;
            reportWorksheet.Cells[reader.getValue("Shoot Date")].Value = data.dateTimeFired;
            reportWorksheet.Cells[reader.getValue("Shoot Date")].Style.NumberFormat = reader.getValue("Date Format");
            reportWorksheet.Cells[reader.getValue("Range Name")].Value = data.rangeLocation;
            reportWorksheet.Cells[reader.getValue("Temperature")].Value = Datatype.ImageData.tempDetails[(int) data.temperature];
            reportWorksheet.Cells[reader.getValue("Target Distance")].Value = data.distance + " " + data.distanceUnits;

            if (data.shotsFired == newPoints.Count)
            {
                reportWorksheet.Cells[reader.getValue("Shots Fired")].Value = data.shotsFired;
            }
            else
            {
                reportWorksheet.Cells[reader.getValue("Shots Fired")].Value = newPoints.Count.ToString() + " found of " + data.shotsFired.ToString() + " indicated";
            }

            reportWorksheet.Cells[reader.getValue("Weapon Name")].Value = data.weaponName;
            reportWorksheet.Cells[reader.getValue("Weapon Serial Number")].Value = data.serialNumber;
            reportWorksheet.Cells[reader.getValue("Ammo Caliber")].Value = data.caliberValue + " " + data.caliber.unitName;
            reportWorksheet.Cells[reader.getValue("Ammo Lot Number")].Value = data.lotNumber;
            reportWorksheet.Cells[reader.getValue("Ammo Mass")].Value = data.projectileMassGrains + " grains";

            reportWorksheet.Cells[reader.getValue("Target ID")].Value = "Target ID: " + data.targetID;
            reportWorksheet.Cells[reader.getValue("Weapon Notes")].Value = "Weapon Notes: " + data.weaponNotes;
            reportWorksheet.Cells[reader.getValue("Ammo Notes")].Value = "Ammo Notes: " + data.ammunitionNotes;

            //Fill in the shot records
            Random generator = new Random();

                for (int i = 0; i < newPoints.Count && i < 50; i++)
                {
                    //TODO: Set first point of x, y, z values (or specify each point)
                    insertPoints(reportWorksheet, "G" + (i + 15).ToString(), newPoints[i].X, reader);
                    insertPoints(reportWorksheet, "H" + (i + 15).ToString(), newPoints[i].Y, reader);

                    //Color every other row in the shot record table.
                    if (i % 2 == 1)
                    {
                        reportWorksheet.Cells["F" + (i + 15).ToString()].Style.FillPattern.SetSolid(rowFillColor);
                        reportWorksheet.Cells["G" + (i + 15).ToString()].Style.FillPattern.SetSolid(rowFillColor);
                        reportWorksheet.Cells["H" + (i + 15).ToString()].Style.FillPattern.SetSolid(rowFillColor);
                    }

                }

            //Fill in the color for
                for (int i = newPoints.Count; i < 50; i = i + 2)
            {
                //if the first time through, we are on an odd instead of an even, put us back on evens.
                if (i%2 == 0)
                {
                    i++;
                }
                reportWorksheet.Cells["F" + (i + 15).ToString()].Style.FillPattern.SetSolid(rowFillColor);
                reportWorksheet.Cells["G" + (i + 15).ToString()].Style.FillPattern.SetSolid(rowFillColor);
                reportWorksheet.Cells["H" + (i + 15).ToString()].Style.FillPattern.SetSolid(rowFillColor);
            }

            //Display stats
            insertStat(reportWorksheet, "Extreme Spread X", stats.extremeSpreadX, reader);
            insertStat(reportWorksheet, "Extreme Spread Y", stats.extremeSpreadY, reader);
            insertStat(reportWorksheet, "Extreme Spread", stats.extremeSpread, reader);
            insertStat(reportWorksheet, "Mean Radius", stats.meanRadius, reader);
            insertStat(reportWorksheet, "Sigma X", stats.sigmaX, reader);
            insertStat(reportWorksheet, "Sigma Y", stats.sigmaY, reader);
            insertStat(reportWorksheet, "Furthest Left", stats.furthestLeft, reader);
            insertStat(reportWorksheet, "Furthest Right", stats.furthestRight, reader);
            insertStat(reportWorksheet, "Highest Round", stats.highestRound, reader);
            insertStat(reportWorksheet, "Lowest Round", stats.lowestRound, reader);
            insertStat(reportWorksheet, "CEP", stats.CEPRadius, reader);

            //Add a small image of the pic in the upper right corner.
            Bitmap image = new Bitmap(imagePath);
            int width = image.Width;
            int height = image.Height;

            double aspectRatio = (double)width / (double)height;

            image.Dispose();

            if (aspectRatio > (double)reportImageWidth / (double)reportImageHeight)
            {
                double newHeight = (double)reportImageWidth / aspectRatio * 0.9; // The 0.9 is a fudge factor because GemBox doesn't know how to scale things properly.
                reportWorksheet.Pictures.Add(imagePath, new Rectangle(0, (int) ((reportImageHeight - newHeight) * 0.5), reportImageWidth, (int) (newHeight + 0.5)));
            }
            else
            {
                double newWidth = (double)reportImageHeight * aspectRatio / 0.9; // The 0.9 is a fudge factor because GemBox doesn't know how to scale things properly.
                reportWorksheet.Pictures.Add(imagePath, new Rectangle((int) ((reportImageWidth - newWidth) * 0.5), 0, (int) (newWidth + 0.5), reportImageHeight));
            }

            //Add CEP Data
            otherStatsWorksheet.Cells[reader.getValue("X Offset")].Value = stats.center.X;
            otherStatsWorksheet.Cells[reader.getValue("Y Offset")].Value = stats.center.Y;
            otherStatsWorksheet.Cells[reader.getValue("Mean X Offset")].Value = stats.center.X;
            otherStatsWorksheet.Cells[reader.getValue("Mean Y Offset")].Value = stats.center.Y;
            otherStatsWorksheet.Cells[reader.getValue("CEP Radius")].Formula = "=IF(Report!" + reader.getValue("CEP Toggle Cell") + " =\"CEP Off\", " + 0 + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in inches)\", " + stats.CEPRadius + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in centimeters)\", " + (stats.CEPRadius * 2.54) + ", " + (stats.CEPRadius * minutesOfAngleConverter) + ")))";
            otherStatsWorksheet.Cells[reader.getValue("Mean Radius Circle")].Formula = "=IF(Report!" + reader.getValue("Mean Radius Toggle Cell") + " =\"Mean Radius Off\", " + 0 + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in inches)\", " + stats.meanRadius + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in centimeters)\", " + (stats.meanRadius * 2.54) + ", " + (stats.meanRadius * minutesOfAngleConverter) + ")))";
            otherStatsWorksheet.Cells[reader.getValue("Extreme Spread x1")].Formula = "=IF(Report!" + reader.getValue("Extreme Spread Toggle Cell") + " =\"Extreme Spread Off\", " + 0 + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in inches)\", " + stats.extremePoints[0].X + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in centimeters)\", " + (stats.extremePoints[0].X * 2.54) + ", " + (stats.extremePoints[0].X * minutesOfAngleConverter) + ")))";
            otherStatsWorksheet.Cells[reader.getValue("Extreme Spread x2")].Formula = "=IF(Report!" + reader.getValue("Extreme Spread Toggle Cell") + " =\"Extreme Spread Off\", " + 0 + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in inches)\", " + stats.extremePoints[1].X + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in centimeters)\", " + (stats.extremePoints[1].X * 2.54) + ", " + (stats.extremePoints[1].X * minutesOfAngleConverter) + ")))";
            otherStatsWorksheet.Cells[reader.getValue("Extreme Spread y1")].Formula = "=IF(Report!" + reader.getValue("Extreme Spread Toggle Cell") + " =\"Extreme Spread Off\", " + 0 + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in inches)\", " + stats.extremePoints[0].Y + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in centimeters)\", " + (stats.extremePoints[0].Y * 2.54) + ", " + (stats.extremePoints[0].Y * minutesOfAngleConverter) + ")))";
            otherStatsWorksheet.Cells[reader.getValue("Extreme Spread y2")].Formula = "=IF(Report!" + reader.getValue("Extreme Spread Toggle Cell") + " =\"Extreme Spread Off\", " + 0 + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in inches)\", " + stats.extremePoints[1].Y + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in centimeters)\", " + (stats.extremePoints[1].Y * 2.54) + ", " + (stats.extremePoints[1].Y * minutesOfAngleConverter) + ")))";

            //Generate CEP Circle formula data
            for (int cell = 0; cell <= 39; cell++)
            {
                otherStatsWorksheet.Cells["B" + (cell + 9).ToString()].Formula = "=$B$3+A" + (cell + 9).ToString();
                otherStatsWorksheet.Cells["C" + (cell + 9).ToString()].Formula = "=SQRT(ABS(POWER($B$5,2)-POWER(B" + (cell + 9).ToString() + ",2))) +$B$4";
                otherStatsWorksheet.Cells["D" + (cell + 9).ToString()].Formula = "=$B$4 - SQRT(ABS(POWER($B$5,2)-POWER(B" + (cell + 9).ToString() + ",2)))";
            }

            //Generate Mean Circle formula data
            for (int cell = 0; cell <= 39; cell++)
            {
                otherStatsWorksheet.Cells["M" + (cell + 9).ToString()].Formula = "=$M$3+L" + (cell + 9).ToString();
                otherStatsWorksheet.Cells["N" + (cell + 9).ToString()].Formula = "=SQRT(ABS(POWER($M$5,2)-POWER(M" + (cell + 9).ToString() + ",2))) +$M$4";
                otherStatsWorksheet.Cells["O" + (cell + 9).ToString()].Formula = "=$M$4 - SQRT(ABS(POWER($M$5,2)-POWER(M" + (cell + 9).ToString() + ",2)))";
            }

            try
            {
                //Write Report
                excelFile.SaveXlsx(savePath);
            }
            catch (System.IO.IOException)
            {
                MessageBox.Show("A report could not be generated.  The file you attempted to save to is busy.  Please close all applications using  " + savePath +
                " and press ok to continue.", "File Open", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);

                throw new System.InvalidOperationException("DirectoryNotFoundException");
            }
            finally
            {
                //Close Report
                excelFile.ClosePreservedXlsx();
            }
            //Check to see what to do with report now
                switch (reader.getValue("Open Excel By Default").ToString())
                {
                    case "nothing":
                        break;
                    case "prompt":
                        DialogResult response = MessageBox.Show("Would you like to open the report you just created?", "Open report?",
                                        MessageBoxButtons.YesNo);
                        if (response == DialogResult.Yes)
                        {
                            openReportWithExcel(savePath);
                        }
                        break;
                    case "open":
                        openReportWithExcel(savePath);
                        break;
                }
        }
Beispiel #49
0
 public ConstantValueNode(Datatype type)
     : base(type, StorageClass.ConstantValue)
 {
 }
        // Send an update to either a client or the server, depending on where this method is called.
        public static void SendMessage( NetPeer netPeer, Datatype messageType, object updatedObject = null )
        {
            NetOutgoingMessage outmsg;

            // Create new message
            if ( netPeer is NetServer )
            {
                outmsg = (netPeer as NetServer).CreateMessage();
            }
            else
            {
                outmsg = (netPeer as NetClient).CreateMessage();
            }

            // Write the type of the message that is being sent.
            outmsg.Write((byte)messageType);

            if ( updatedObject != null )
            {
                switch ( messageType )
                {
                    case Datatype.UpdateDeck:
                    {
                        WriteCards(outmsg, (updatedObject as Deck).CardList);

                        break;
                    }

                    case Datatype.UpdateDiscardPile:
                    {
                        WriteCards(outmsg, (updatedObject as List<Card>));
                        break;
                    }

                    case Datatype.UpdatePlayer:
                    {
                        WritePlayer(outmsg, (updatedObject as Player));

                        break;
                    }

                    case Datatype.UpdatePlayerList:
                    {
                        WritePlayerList(outmsg, (updatedObject as List<Player>));
                        break;
                    }

                    case Datatype.RequestRent:
                    {
                        WriteRentRequest(outmsg, (updatedObject as ActionData.RentRequest));
                        break;
                    }

                    case Datatype.GiveRent:
                    {
                        WriteRentResponse(outmsg, (updatedObject as ActionData.RentResponse));
                        break;
                    }

                    case Datatype.RequestTheft:
                    {
                        WriteTheftRequest(outmsg, (updatedObject as ActionData.TheftRequest));
                        break;
                    }

                    case Datatype.ReplyToTheft:
                    {
                        WriteTheftResponse(outmsg, (updatedObject as ActionData.TheftResponse));
                        break;
                    }

                    case Datatype.LaunchGame:
                    case Datatype.UpdateTurn:
                    {
                        Turn currentTurn = (Turn)updatedObject;

                        WriteTurn(outmsg, currentTurn);

                        break;
                    }

                    case Datatype.TimeToConnect:
                    {
                        String playerToConnect = (String)updatedObject;
                        outmsg.Write(playerToConnect);

                        break;
                    }

                    case Datatype.EndTurn:
                    {
                        Turn currentTurn = (Turn)updatedObject;

                        WriteTurn(outmsg, currentTurn);

                        break;
                    }
                }
            }

            // Send it to the server or the clients.
            if ( netPeer is NetServer )
            {
                NetServer server = netPeer as NetServer;

                if ( server.Connections.Count > 0 )
                {
                    server.SendMessage(outmsg, server.Connections, NetDeliveryMethod.ReliableOrdered, 0);
                }
            }
            else
            {
                (netPeer as NetClient).SendMessage(outmsg, NetDeliveryMethod.ReliableOrdered);
            }
        }
Beispiel #51
0
        /** Decodes value transitions. */
        private static Transition.Value decodeVTr( string encStates, string encVTr, State.Single[] states, int s, Transition.Value next, Datatype[] datatypes, object[] values )
        {
            int start = encStates[ s*sizeOfState+8 ];
            int end = (s!=states.Length-1)?encStates[ (s+1)*sizeOfState+8 ]:encVTr.Length;

            for( int i=end-sizeOfVTr; i>=start; i-=sizeOfVTr ) {
                Datatype dt = datatypes[ encVTr[i+1] ];
                int vidx = encVTr[i+2]*2;
                next = new Transition.Value(
                    dt,
                    dt.CreateValue( (string)values[vidx], createContext((string[])values[vidx+1]) ),
                    states[encVTr[i+0]],
                    next );
            }

            return next;
        }
Beispiel #52
0
        private void PopulateFields(Datatype.ImageData imageData)
        {
            if (imageData == null)
            {
                EraseFields();
            }
            else
            {
                // General Information
                DateFired = imageData.dateTimeFired;
                ShooterFirstName = (imageData.shooterFName == null ? "" : imageData.shooterFName);
                ShooterLastName = (imageData.shooterLName == null ? "" : imageData.shooterLName);
                ShotsFired = imageData.shotsFired;

                // Range Information
                Place = (imageData.rangeLocation == null ? "" : imageData.rangeLocation);
                Distance = imageData.distance;
                DistanceUnits = imageData.distanceUnits;
                Temperature = imageData.temperature;

                // Weapon Information
                Nomenclature = (imageData.weaponName == null ? "" : imageData.weaponName);
                SerialNumber = (imageData.serialNumber == null ? "" : imageData.serialNumber);
                WeaponNotes = (imageData.weaponNotes == null ? "" : imageData.weaponNotes);

                // Ammunition Information
                Caliber = imageData.caliberValue;
                if (imageData.caliber == null)
                {
                    ammo_CaliberUnit.SelectedIndex = 0;
                }
                else
                {
                    for (int c = 0; c < _possibleCalibers.Length; c++)
                    {
                        if (imageData.caliber.caliberUnitID == _possibleCalibers[c].caliberUnitID)
                        {
                            ammo_CaliberUnit.SelectedIndex = c;
                            break;
                        }
                    }
                }
                LotNumber = (imageData.lotNumber == null ? "" : imageData.lotNumber);
                Mass = imageData.projectileMassGrains;
                AmmoNotes = (imageData.ammunitionNotes == null ? "" : imageData.ammunitionNotes);
            }
        }
Beispiel #53
0
        public static Instruction CreateRightTernaryInstruction(
            string mnemonic, OperationNode op1, OperationNode op2, int exUnit,
            ValueNode vres, RegisterSet vresRegs,
            ValueNode v1, RegisterSet v1Regs,
            ValueNode v2, RegisterSet v2Regs,
            Datatype iv1Type)
        {
            InstructionPattern ip = new InstructionPattern();

            ip.AddNode(op1);
            ip.AddNode(op2);
            ip.AddNode(vres);
            ip.AddNode(v1);
            ip.AddNode(v2);

            ValueNode iv1 = new RegisterValueNode(iv1Type);

            ip.AddNode(iv1);

            ip.AddEdge(v2, op1);
            ip.AddEdge(op1, iv1);
            ip.AddEdge(v1, op2);
            ip.AddEdge(iv1, op2);
            ip.AddEdge(op2, vres);

            ip.OperandValues.Add(v1);
            ip.OperandValues.Add(v2);
            ip.ResultValue = vres;

            Instruction i = new Instruction(mnemonic, ip);

            i.ExecutionUnit = exUnit;
            i.ResultRegisters = vresRegs;
            i.OperandsRegisters[0] = v1Regs;
            i.OperandsRegisters[1] = v2Regs;

            return i;
        }
Beispiel #54
0
 private static Datatype.DoublePoint pointSubtract(Datatype.DoublePoint minuend, Datatype.DoublePoint subtrahend)
 {
     return new Datatype.DoublePoint(minuend.X - subtrahend.X, minuend.Y - subtrahend.Y);
 }
Beispiel #55
0
        /// <summary>
        /// Sets the caliber units displayed on the details tab.
        /// </summary>
        /// <param name="calibers">The caliber units to display.</param>
        public void SetCalibers(Datatype.CaliberUnit[] calibers)
        {
            _possibleCalibers = calibers;

            ammo_CaliberUnit.Items.Clear();

            foreach (Datatype.CaliberUnit c in _possibleCalibers)
            {
                ammo_CaliberUnit.Items.Add(c.unitName);
            }

            ammo_CaliberUnit.SelectedIndex = 0;
        }
Beispiel #56
0
        /// <summary>
        /// Inserts an <c>ImageData</c> object into the <c>Target</c> table.
        /// </summary>
        /// <param name="imageData">The <c>ImageData</c> to insert.</param>
        /// <param name="configReader">The <c>ConfigReader</c> with the path to the database.</param>
        /// <exception cref="OleDbException">A connection-level error occurred while opening the connection.</exception>
        /// <exception cref="InvalidOperationException">The INSERT INTO Target command failed.</exception>
        /// <exception cref="ArgumentException">The caliber or weapon name was not found in the database.</exception>
        /// <returns>The <c>targetID</c> of the newly-inserted record.</returns>
        private static int InsertData(Datatype.ImageData imageData, ConfigReader configReader)
        {
            int targetID = -1;
            using (OleDbConnection conn = new OleDbConnection(configReader.getValue("Database Location"))) {
                openConnection(conn);

                if (!CaliberIDExists(imageData.caliber.caliberUnitID, configReader)) {
                    Log.LogError("Caliber to insert not found in database.", "unitID",
                        imageData.caliber.caliberUnitID.ToString(), "unitName", imageData.caliber.unitName,
                        "unitsPerInch", imageData.caliber.unitsPerInch.ToString());
                    throw new ArgumentException("Caliber to insert does not exist.", "caliber");
                }
                if (!WeaponExists(imageData.weaponName, configReader)) {
                    Log.LogError("Weapon name to insert not found in database.", "weaponName", imageData.weaponName);
                    throw new ArgumentException("Weapon name to insert not found in database.", "weaponName");
                }

                using (OleDbCommand command = new OleDbCommand()) {
                    command.Connection = conn;
                    command.CommandText = "INSERT INTO Target (OrigFilename, ReportFilename, DateTimeFired, DateTimeProcessed, ShooterLName, ShooterFName, RangeLocation, DistanceUnits, Distance, Temperature, WeaponName, SerialNumber, WeaponNotes, CaliberID, CaliberValue, LotNumber, ProjectileMassGrains, AmmunitionNotes, ShotsFired, ShotLocations, Scale, ROI) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    command.Prepare();
                    setStringParameter(command, "OrigFilename", imageData.origFilename);
                    setStringParameter(command, "ReportFilename", imageData.reportFilename);
                    command.Parameters.Add("DateTimeFired", OleDbType.Date).Value = imageData.dateTimeFired;
                    command.Parameters.Add("DateTimeProcessed", OleDbType.Date).Value = DateTime.Now;
                    setStringParameter(command, "ShooterLName", imageData.shooterLName);
                    setStringParameter(command, "ShooterFName", imageData.shooterFName);
                    setStringParameter(command, "RangeLocation", imageData.rangeLocation);
                    command.Parameters.Add("DistanceUnits", OleDbType.UnsignedTinyInt).Value = imageData.distanceUnits;
                    command.Parameters.Add("Distance", OleDbType.Integer).Value = imageData.distance;
                    command.Parameters.Add("Temperature", OleDbType.UnsignedTinyInt).Value = imageData.temperature;
                    setStringParameter(command, "WeaponName", imageData.weaponName);
                    setStringParameter(command, "SerialNumber", imageData.serialNumber);
                    command.Parameters.Add("WeaponNotes", OleDbType.LongVarWChar).Value = imageData.weaponNotes == null ? "" : imageData.weaponNotes;
                    command.Parameters.Add("CaliberID", OleDbType.Integer).Value = imageData.caliber.caliberUnitID;
                    command.Parameters.Add("CaliberValue", OleDbType.Double).Value = imageData.caliberValue;
                    setStringParameter(command, "LotNumber", imageData.lotNumber);
                    command.Parameters.Add("ProjectileMassGrains", OleDbType.Integer).Value = imageData.projectileMassGrains;
                    command.Parameters.Add("AmmunitionNotes", OleDbType.LongVarWChar).Value = imageData.ammunitionNotes == null ? "" : imageData.ammunitionNotes;
                    command.Parameters.Add("ShotsFired", OleDbType.Integer).Value = imageData.shotsFired;

                    StringBuilder pointStringBuilder = new StringBuilder();
                    foreach (Point point in imageData.points) {
                        pointStringBuilder.Append(point.X);
                        pointStringBuilder.Append(",");
                        pointStringBuilder.Append(point.Y);
                        pointStringBuilder.Append(",");
                    }
                    command.Parameters.Add("ShotLocations", OleDbType.LongVarWChar).Value = pointStringBuilder.ToString();

                    StringBuilder scaleStringBuilder = new StringBuilder();
                    scaleStringBuilder.Append(imageData.scale.horizontal.X);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.horizontal.Y);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.middle.X);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.middle.Y);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.vertical.X);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.vertical.Y);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.horizontalLength);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.verticalLength);
                    setStringParameter(command, "Scale", scaleStringBuilder.ToString());

                    StringBuilder ROIStringBuilder = new StringBuilder();
                    ROIStringBuilder.Append(imageData.regionOfInterest.topLeft.X);
                    ROIStringBuilder.Append(",");
                    ROIStringBuilder.Append(imageData.regionOfInterest.topLeft.Y);
                    ROIStringBuilder.Append(",");
                    ROIStringBuilder.Append(imageData.regionOfInterest.bottomRight.X);
                    ROIStringBuilder.Append(",");
                    ROIStringBuilder.Append(imageData.regionOfInterest.bottomRight.Y);
                    setStringParameter(command, "ROI", ROIStringBuilder.ToString());

                    try {
                        command.ExecuteNonQuery();
                    } catch (InvalidOperationException e) {
                        Log.LogError("Could not perform INSERT INTO Target.", "SQL", command.CommandText);
                        throw e;
                    }
                }

                using (OleDbCommand command = new OleDbCommand("SELECT MAX(TargetID) FROM Target", conn)) {
                    using (OleDbDataReader reader = command.ExecuteReader()) {
                        if (reader.Read()) {
                            targetID = reader.GetInt32(0);
                        } else {
                            Log.LogError("Unable to get the maximum TargetID.", "SQL", command.CommandText);
                        }
                    }
                }
            }

            return targetID;
        }
Beispiel #57
0
 protected virtual bool IsCoverableWithDatatype(Datatype datatype)
 {
     return this.Datatype == datatype;
 }
Beispiel #58
0
        /// <summary>
        /// Updates an existing <c>ImageData</c> object in the <c>Target</c> table.
        /// </summary>
        /// <param name="imageData">The <c>ImageData</c> to update.</param>
        /// <param name="configReader">The <c>ConfigReader</c> with the path to the database.</param>
        /// <exception cref="OleDbException">A connection-level error occurred while opening the connection.</exception>
        /// <exception cref="InvalidOperationException">The UPDATE Target command failed.</exception>
        /// <exception cref="ArgumentException">The caliber or weapon name was not found in the database.</exception>
        /// <returns>The <c>targetID</c> of the updated record.</returns>
        private static int UpdateData(Datatype.ImageData imageData, ConfigReader configReader)
        {
            using (OleDbConnection conn = new OleDbConnection(configReader.getValue("Database Location"))) {
                openConnection(conn);

                if (!CaliberIDExists(imageData.caliber.caliberUnitID, configReader)) {
                    Log.LogError("Caliber to insert not found in database.", "unitID",
                        imageData.caliber.caliberUnitID.ToString(), "unitName", imageData.caliber.unitName,
                        "unitsPerInch", imageData.caliber.unitsPerInch.ToString());
                    throw new ArgumentException("Caliber to insert does not exist.", "caliber");
                }
                if (!WeaponExists(imageData.weaponName, configReader)) {
                    Log.LogError("Weapon name to insert not found in database.", "weaponName", imageData.weaponName);
                    throw new ArgumentException("Weapon name to insert not found in database.", "weaponName");
                }

                using (OleDbCommand command = new OleDbCommand()) {
                    command.Connection = conn;
                    command.CommandText = "UPDATE Target SET OrigFilename = ?, ReportFilename = ?, DateTimeFired = ?, DateTimeProcessed = ?, ShooterLName = ?, ShooterFName = ?, RangeLocation = ?, DistanceUnits = ?, Distance = ?, Temperature = ?, WeaponName = ?, SerialNumber = ?, WeaponNotes = ?, CaliberID = ?, CaliberValue = ?, LotNumber = ?, ProjectileMassGrains = ?, AmmunitionNotes = ?, ShotsFired = ?, ShotLocations = ?, Scale = ?, ROI = ? WHERE TargetID = ?";
                    command.Prepare();
                    setStringParameter(command, "OrigFilename", imageData.origFilename);
                    setStringParameter(command, "ReportFilename", imageData.reportFilename);
                    command.Parameters.Add("DateTimeFired", OleDbType.Date).Value = imageData.dateTimeFired;
                    command.Parameters.Add("DateTimeProcessed", OleDbType.Date).Value = DateTime.Now;
                    setStringParameter(command, "ShooterLName", imageData.shooterLName);
                    setStringParameter(command, "ShooterFName", imageData.shooterFName);
                    setStringParameter(command, "RangeLocation", imageData.rangeLocation);
                    command.Parameters.Add("DistanceUnits", OleDbType.UnsignedTinyInt).Value = imageData.distanceUnits;
                    command.Parameters.Add("Distance", OleDbType.Integer).Value = imageData.distance;
                    command.Parameters.Add("Temperature", OleDbType.UnsignedTinyInt).Value = imageData.temperature;
                    setStringParameter(command, "WeaponName", imageData.weaponName);
                    setStringParameter(command, "SerialNumber", imageData.serialNumber);
                    command.Parameters.Add("WeaponNotes", OleDbType.LongVarWChar).Value = imageData.weaponNotes;
                    command.Parameters.Add("CaliberID", OleDbType.Integer).Value = imageData.caliber.caliberUnitID;
                    command.Parameters.Add("CaliberValue", OleDbType.Double).Value = imageData.caliberValue;
                    setStringParameter(command, "LotNumber", imageData.lotNumber);
                    command.Parameters.Add("ProjectileMassGrains", OleDbType.Integer).Value = imageData.projectileMassGrains;
                    command.Parameters.Add("AmmunitionNotes", OleDbType.LongVarWChar).Value = imageData.ammunitionNotes;
                    command.Parameters.Add("ShotsFired", OleDbType.Integer).Value = imageData.shotsFired;

                    StringBuilder pointStringBuilder = new StringBuilder();
                    foreach (Point point in imageData.points) {
                        pointStringBuilder.Append(point.X);
                        pointStringBuilder.Append(",");
                        pointStringBuilder.Append(point.Y);
                        pointStringBuilder.Append(",");
                    }
                    command.Parameters.Add("ShotLocations", OleDbType.LongVarWChar).Value = pointStringBuilder.ToString();

                    StringBuilder scaleStringBuilder = new StringBuilder();
                    scaleStringBuilder.Append(imageData.scale.horizontal.X);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.horizontal.Y);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.middle.X);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.middle.Y);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.vertical.X);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.vertical.Y);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.horizontalLength);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.verticalLength);
                    setStringParameter(command, "Scale", scaleStringBuilder.ToString());

                    StringBuilder ROIStringBuilder = new StringBuilder();
                    ROIStringBuilder.Append(imageData.regionOfInterest.topLeft.X);
                    ROIStringBuilder.Append(",");
                    ROIStringBuilder.Append(imageData.regionOfInterest.topLeft.Y);
                    ROIStringBuilder.Append(",");
                    ROIStringBuilder.Append(imageData.regionOfInterest.bottomRight.X);
                    ROIStringBuilder.Append(",");
                    ROIStringBuilder.Append(imageData.regionOfInterest.bottomRight.Y);
                    setStringParameter(command, "ROI", ROIStringBuilder.ToString());

                    command.Parameters.Add("TargetID", OleDbType.Integer).Value = imageData.targetID;

                    try {
                        command.ExecuteNonQuery();
                    } catch (InvalidOperationException e) {
                        Log.LogError("Could not perform UPDATE Target.", "SQL", command.CommandText);
                        throw e;
                    }
                }
            }

            return imageData.targetID;
        }
Beispiel #59
0
 /// <summary>
 /// Saves an <c>ImageData</c> object to the <c>Target</c> table.
 /// </summary>
 /// <param name="imageData">The <c>ImageData</c> to save.</param>
 /// <param name="configReader">The <c>ConfigReader</c> with the path to the database.</param>
 /// <exception cref="OleDbException">A connection-level error occurred while opening the connection.</exception>
 /// <exception cref="InvalidOperationException">The SQL command failed.</exception>
 /// <exception cref="ArgumentException">The caliber or weapon name was not found in the database.</exception>
 /// <returns>The <c>targetID</c> of the saved record.</returns>
 public static int SaveData(Datatype.ImageData imageData, ConfigReader configReader)
 {
     if (imageData.targetID == -1) {
         return InsertData(imageData, configReader);
     } else {
         return UpdateData(imageData, configReader);
     }
 }
Beispiel #60
0
 public MemoryValueNode(Datatype type, string id)
     : base(type, StorageClass.MemoryValue)
 {
     this.id = id;
 }