Пример #1
0
        /// DUUUUUUUUZO NIEPOTRZEBNEJ REDUNDANCJI KODU
        #region
        ///Checking  every 8 directions
        private bool DirectionX(int how_far = 2)
        {
            int numberOfFindedcorrectfields = 0;
            int start_index  = columns - how_far + 1;
            int ending_index = columns + how_far - 1;

            if (start_index < 0)
            {
                start_index = 0;
            }
            if (ending_index >= FieldsToCheck.Count())    /// sprawdz potem czy to jest dobrze
            {
                ending_index = FieldsToCheck.Count() - 1; // -1 bo indeks a nie ilosc elementow
            }
            for (int i = start_index; i <= ending_index; i++)
            {
                if (FieldsToCheck[rows, i]._pattern == WinningPattern)
                {
                    numberOfFindedcorrectfields++;
                }
                else
                {
                    numberOfFindedcorrectfields = 0;
                }
                if (numberOfFindedcorrectfields >= how_far)
                {
                    return(true);
                }
            }
            return(false);
        }
Пример #2
0
        ///Checking  every 8 directions
        private int EvaluationX(Fields FieldsToCheck, int column, int rows, Pattern WinningPattern)
        {
            int correctfieldsL = 0, correctfieldsR = 0;
            int oppositefieldsL = 0, oppositefieldsR = 0;
            int L = column - how_far_to_win + 1;///Przesuniecie sie w lewo po osi X o tyle ile trzeba wygrac plus "horyzont
            int P = column + how_far_to_win - 1;

            if (L < 0)
            {
                L = 0;
            }
            if (P >= FieldsToCheck.Count())    /// sprawdz potem czy to jest dobrze
            {
                P = FieldsToCheck.Count() - 1; // -1 bo indeks a nie ilosc elementow
            }
            for (int i = L; i < column; i++)   //< albo <= to samo nizej
            {
                if (FieldsToCheck[rows, i]._pattern == WinningPattern)
                {
                    correctfieldsL++;
                    oppositefieldsL = 0;
                }

                else if (FieldsToCheck[rows, i]._pattern == Pattern.None)
                {
                    ;
                }
                else
                {
                    oppositefieldsL++;
                    correctfieldsL = 0;
                }
            }
            for (int i = P; i > column; i--)
            {
                if (FieldsToCheck[rows, i]._pattern == WinningPattern)
                {
                    oppositefieldsR = 0;
                    correctfieldsR++;
                }
                else if (FieldsToCheck[rows, i]._pattern == Pattern.None)
                {
                    ;
                }
                else
                {
                    oppositefieldsR++;
                    correctfieldsR = 0;
                }
            }
            if (oppositefieldsR + oppositefieldsL == how_far_to_win - 1)
            {
                return(100000);
            }
            // int opposite = (oppositefieldsL + oppositefieldsR) / 2;

            return(correctfieldsL + correctfieldsR);// +opposite;
        }
Пример #3
0
        private int EvaluationY(Fields FieldsToCheck, int column, int rows, Pattern WinningPattern)
        {
            int correctFieldsT = 0, correctfieldsB = 0;
            int oppositefieldsB = 0, oppositefieldsT = 0;
            int T = column - how_far_to_win + 1;  ///Przesuniecie sie w lewo po osi X o tyle ile trzeba wygrac plus "horyzont
            int B = column + how_far_to_win - 1;

            if (T < 0)
            {
                T = 0;
            }
            if (B >= FieldsToCheck.Count())    /// sprawdz potem czy to jest dobrze
            {
                B = FieldsToCheck.Count() - 1; // -1 bo indeks a nie ilosc elementow
            }
            for (int i = T; i < rows; i++)     //< albo <= to samo nizej
            {
                if (FieldsToCheck[i, column]._pattern == WinningPattern)
                {
                    correctFieldsT++;
                    oppositefieldsT = 0;
                }
                else if (FieldsToCheck[i, column]._pattern == Pattern.None)
                {
                    ;
                }
                else
                {
                    correctFieldsT = 0;
                    oppositefieldsT++;
                }
            }
            for (int i = B; i > rows; i--)
            {
                if (FieldsToCheck[i, column]._pattern == WinningPattern)
                {
                    correctfieldsB++;
                    oppositefieldsB = 0;
                }
                else if (FieldsToCheck[rows, i]._pattern == Pattern.None)
                {
                    ;
                }
                else
                {
                    correctfieldsB = 0;
                    oppositefieldsB++;
                }
            }
            if (oppositefieldsB + oppositefieldsT == how_far_to_win - 1)
            {
                return(100000);
            }
            // int opposite = (oppositefieldsB + oppositefieldsT) / 2;

            return(correctfieldsB + correctFieldsT);// + opposite;
        }
Пример #4
0
        public override ResultMap Execute(Dictionary <string, object> parameters)
        {
            //Build FieldSQL for parameters
            string fieldSQL = FieldSQL;

            if (fieldSQL == null && Fields != null && Fields.Count() > 0)
            {
                foreach (string field in Fields)
                {
                    if (fieldSQL == null)
                    {
                        FieldSQL = MySQLConnection.FieldEscape(field);
                        continue;
                    }

                    fieldSQL += ", " + MySQLConnection.FieldEscape(field);
                }
            }
            else
            {
                fieldSQL = "*";
            }

            if (base.Conditions.Count() < 1)
            {
                Console.WriteLine(String.Format("SELECT {0} FROM {1}", fieldSQL, Table));
                return(Database.ExecuteQuery(String.Format("SELECT {0} FROM {1}", fieldSQL, Table)));
            }

            string query = String.Format("SELECT {0} FROM {1} WHERE {2}", fieldSQL, Table,
                                         Database.BuildConditionSQL(base.Conditions, ref parameters));

            return(Database.ExecuteQuery(query, parameters));
        }
Пример #5
0
        public GraphQLQuery(GraphQLService graphQLService, EntityService entityService)
        {
            Name = "Query";
            var schemas = entityService.GetCollectionSchemas();

            foreach (var metaColl in schemas)
            {
                if (Fields.Count(x => x.Name == metaColl.CollectionName) == 0)
                {
                    JObjectRawType type     = new JObjectRawType(this, graphQLService, metaColl, entityService);
                    ListGraphType  listType = new ListGraphType(type);

                    AddField(new FieldType
                    {
                        Name         = metaColl.CollectionName,
                        Type         = listType.GetType(),
                        ResolvedType = listType,
                        Resolver     = new JObjectFieldResolver(graphQLService, entityService),
                        Arguments    = new QueryArguments(
                            type.TableArgs
                            )
                    });
                }
            }
        }
Пример #6
0
        public async Task LoadTransactionsAsync(string path)
        {
            _transactions = new List <Model.Transaction>();
            using (var sr = new StreamReader(path))
            {
                while (!sr.EndOfStream)
                {
                    // skip header
                    sr.ReadLine();

                    var transaction = new Model.Transaction();
                    var fields      = new Fields();
                    var line        = (await sr.ReadLineAsync())?.Split(';');
                    if (line != null && line.Length >= fields.Count())
                    {
                        foreach (var field in fields)
                        {
                            field.WriteTo(transaction, line[field.Index]);
                        }

                        _transactions.Add(transaction);
                    }
                }
            }
        }
Пример #7
0
        public IEnumerable <TpsObject> Parse(byte[] record)
        {
            if (record == null)
            {
                throw new ArgumentNullException(nameof(record));
            }

            var rx     = new RandomAccess(record);
            var values = new List <TpsObject>(Fields.Count());

            foreach (var field in Fields)
            {
                if (field.IsArray)
                {
                    int fieldSize = RecordLength / field.ElementCount;

                    for (int i = 0; i < field.ElementCount; i++)
                    {
                        values.Add(ParseField(field.Type, fieldSize, field, rx));
                    }
                }
                else
                {
                    values.Add(ParseField(field.Type, field.Length, field, rx));
                }
            }

            return(values);
        }
Пример #8
0
        protected void ImportVisitorsButton_Click(object sender, EventArgs e)
        {
            if (ImportVisitorsFileUploadControl.PostedFile.ContentType == "text/csv" || ImportVisitorsFileUploadControl.PostedFile.ContentType == "application/vnd.ms-excel")
            {
                string fileName = Path.Combine(Server.MapPath("~/Uploaded"), "visitors" + ".csv");
                try
                {
                    ImportVisitorsFileUploadControl.PostedFile.SaveAs(fileName);

                    string[] Lines = File.ReadAllLines(fileName);
                    string[] Fields;

                    //Remove Header line
                    Lines = Lines.Skip(1).ToArray();
                    List <VisitorWrapper> visitors = new List <VisitorWrapper>();
                    foreach (var line in Lines)
                    {
                        Fields = line.Split(new char[] { ',' });
                        if (Fields.Count() != VisitorNumOfFields)
                        {
                            throw new System.InvalidOperationException("Invalid number of fields");
                        }
                        visitors.Add(
                            new VisitorWrapper
                        {
                            Visitor = new Visitor
                            {
                                LastName     = Fields[0].Replace("\"", ""), // removed ""
                                FirstName    = Fields[1].Replace("\"", ""),
                                CompanyName  = Fields[2].Replace("\"", ""),
                                EmailAddress = Fields[3].Replace("\"", ""),
                                PhoneNumber  = Fields[4].Replace("\"", ""),
                                HostId       = Fields[5].Replace("\"", "")
                            },
                            Id = Fields[6].Replace("\"", "")
                        });
                    }

                    // Update database data
                    using (var dc = new VisitContext())
                    {
                        foreach (var i in visitors)
                        {
                            var v = dc.Visitors.Where(a => a.Id == i.Id).FirstOrDefault();
                            if (v == null)
                            {
                                dc.Visitors.Add(i);
                            }
                        }
                        dc.SaveChanges();
                    }
                    UpdateVisitorList();
                    UpdateVisitorDropDownList();
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
Пример #9
0
 public override string Render()
 {
     if (Fields.Count(o => o.Visiable) == 0)
     {
         return(string.Empty);
     }
     return(base.Render());
 }
Пример #10
0
        public Boolean PostJsonToSql([FromBody] object JsonData)
        {
            try
            {
                JObject JsonObject = (JObject)JsonConvert.DeserializeObject(JsonData.ToString());
                string  TableName;
                foreach (JToken token in JsonObject.SelectToken(""))
                {
                    foreach (JToken Fields in token)
                    {
                        int LastIndex = 0;
                        if (Fields.Type.ToString() == "Array")
                        {
                            LastIndex = Fields.Count() - 1;
                        }


                        for (int i = 0; i <= LastIndex; i++)
                        {
                            JToken WorkFields;
                            if (Fields.Type.ToString() == "Array")
                            {
                                WorkFields = Fields.ToArray()[i];
                            }
                            else
                            {
                                WorkFields = Fields;
                            }
                            JsonInputSection PcrSection = new JsonInputSection();
                            foreach (JToken Field in WorkFields.Children())
                            {
                                var Property = Field as JProperty;
                                PcrSection[Property.Name] = Property.Value.ToString();
                            }
                            TableName = token.Path.ToString();
                            if (TableName.Contains("."))
                            {
                                TableName = TableName.Remove(0, TableName.IndexOf(".") + 1);
                            }
                            Assembly Asm            = Assembly.Load(Assembly.GetExecutingAssembly().FullName);
                            Type     PCRSectionType = Asm.GetTypes().First(t => token.Path.ToUpper().EndsWith(t.Name.ToUpper()));
                            dynamic  objSectionOut  = Activator.CreateInstance(PCRSectionType, TableName, PcrSection);
                            objSectionOut.HandleRecord();
                        }
                    }
                }
                Logger.LogAction(JsonObject.ToString(), "JSON_Posts");
                return(true);
            }
            catch (Exception ex) { Logger.LogException(ex); return(false); }
        }
Пример #11
0
 /// <summary>
 /// W zalozeniu ta funkcja ma wypelnic ostatni poziom grafu
 /// </summary>
 /// <param name="fields"></param>
 /// <param name="currentPattern"></param>
 /// <param name="node"></param>
 /// <param name="deepOfRecursion"></param>
 public void FillNode(Fields fields, Pattern currentPattern, Node node, int deepOfRecursion)
 {
     if (deepOfRecursion > 0)
     {
         for (int i = 0; i < fields.Count(); i++)
         {
             for (int j = 0; j < fields.Count(); j++)       //Przejdz po wszystkich wezlach
             {
                 if (fields[i, j]._pattern == Pattern.None) //jezeli pole jest mozliwe do uzycia
                 {
                     fields[i, j]._pattern = currentPattern;
                     node.sons.Add(new Node(currentPattern, i, j, node));
                     FillNode(fields, currentPattern, node.sons[node.sons.Count - 1], deepOfRecursion - 1);
                     fields[i, j].ClearVirtualPattern();//Bez tego ostatnie pole nie mialoby zadnego ruchu
                 }
             }
         }
     }
     else
     {
         node.weight = evaluation(fields, node.i, node.j, currentPattern); /// Jestem na samym dole drzewa
     }
 }
Пример #12
0
        public bool IsValid()
        {
            var msg = new StringBuilder();

            if (Models == null && Models.Count() == 0)
            {
                msg.AppendLine("Data Model can't be empty");
            }
            if (Fields == null && Fields.Count() == 0)
            {
                msg.AppendLine("Field Template can't be empty");
            }
            ErrorMessage = msg.ToString();
            return(msg.Length == 0);
        }
Пример #13
0
        public void CreateProgressions()
        {
            int n = Fields.Count();

            Progressions = new List <List <int> >();
            for (int i = 1; i <= n - K + 1; i++)
            {
                for (int r = 1; r <= n / (K - 1) && i + r * (K - 1) <= n; r++)
                {
                    var nowyciag = new List <int>();
                    for (int j = 0; j < K; j++)
                    {
                        nowyciag.Add(i + r * j - 1);
                    }
                    Progressions.Add(nowyciag);
                }
            }
        }
Пример #14
0
        public QueryOutFields(string outFieldsText)
        {
            outFieldsText = outFieldsText?.Trim();

            if (String.IsNullOrEmpty(outFieldsText))
            {
                // do nothing
            }
            else if (outFieldsText.Contains(";"))
            {
                // Parse, Lexer
                if (!outFieldsText.EndsWith(";"))
                {
                    outFieldsText = $"{ outFieldsText };";
                }

                var lexicalAnalyser = new LexicalAnalyser(new LuceneServerOutFieldsSyntax());
                var tokens          = lexicalAnalyser.Tokenize(outFieldsText);

                Fields = tokens.GetStatements()
                         .Select(s => new QueryOutField(s))
                         .ToArray();
            }
            else
            {
                // Simple
                Fields = outFieldsText.Split(',')
                         .Select(f => f.Trim())
                         .Select(f => new QueryOutField(f))
                         .ToArray();
            }

            _names = this.Fields?.Select(f => f.Name).ToArray() ?? new string[0];

            if (this.Fields == null || Fields.Count() == 0)
            {
                this.Fields = new QueryOutField[]
                {
                    new QueryOutField("*")
                }
            }
            ;
        }
Пример #15
0
        public override SourceCode GenerateHandler(CodeContext context)
        {
            var code = new SourceCode();

            if (Fields.Count(field => field is RefField) == 0)
            {
                return(code);
            }

            var listAccessor = GetVarAccessor(context);
            var iteratorName = context.StartIterator();

            code.Append(CodeUtil.ForEachCode(TypeName, listAccessor, iteratorName, true));
            code.IndentRight();
            Fields.ForEach(field => code.Append(field.GenerateHandler(context)));
            code.BracketEnd();
            context.EndIterator();
            return(code);
        }
Пример #16
0
        public async Task New(string Name, int Ranks, params string[] Fields)
        {
            User  User  = Utils.GetUser(Context.User.Id);
            Actor Actor = User.Active;

            if (Actor == null)
            {
                await ReplyAsync("You have no active characters. Set one using the `Character` command or create one using the `Create` command");

                return;
            }

            if (Fields.Any(x => x.Length > 1024))
            {
                await ReplyAsync(Context.User.Mention + ", Each Merit field cannot exceed more than 1024 characters!");

                return;
            }
            if (Fields.Count() > 20)
            {
                await ReplyAsync(Context.User.Mention + ", You can only have 20 fields!");

                return;
            }
            if (Fields.Length > 5900)
            {
                await ReplyAsync(Context.User.Mention + ", You can only have a total of 5900 characters!");

                return;
            }
            var merit = new Merit()
            {
                Name        = Name,
                Ranks       = Ranks,
                Description = Fields
            };

            Actor.Merits.Add(merit);
            Utils.UpdateActor(Actor);

            await ReplyAsync(Context.User.Mention + ", Added Merit **" + Name + "** to " + Actor.Name + "'s merits with " + Ranks + " dots into this new merit.");
        }
Пример #17
0
 public override string Render()
 {
     if (Fields.Count(o => o.Visiable) == 0)
     {
         return(string.Empty);
     }
     if (FormLayoutType == FoxOne.Controls.FormLayoutType.Horizontal)
     {
         CssClass     = "search";
         FormCssClass = "form-list";
     }
     else
     {
         if (CssClass.Equals("search", StringComparison.OrdinalIgnoreCase))
         {
             CssClass = "search pt10 pl10";
         }
     }
     return(base.Render());
 }
Пример #18
0
        public async Task New(string Name, params string[] Fields)
        {
            User  User  = Utils.GetUser(Context.User.Id);
            Actor Actor = User.Active;

            if (Actor == null)
            {
                await ReplyAsync("You have no active characters. Set one using the `Character` command or create one using the `Create` command");

                return;
            }

            if (Fields.Any(x => x.Length > 1024))
            {
                await ReplyAsync(Context.User.Mention + ", Each item field cannot exceed more than 1024 characters!");

                return;
            }
            if (Fields.Count() > 20)
            {
                await ReplyAsync(Context.User.Mention + ", You can only have 20 fields!");

                return;
            }
            if (Fields.Length > 5900)
            {
                await ReplyAsync(Context.User.Mention + ", You can only have a total of 5900 characters!");

                return;
            }
            var Rote = new Item()
            {
                Name        = Name,
                Description = Fields
            };

            Actor.Inventory.Add(Rote);
            Utils.UpdateActor(Actor);

            await ReplyAsync(Context.User.Mention + ", Added Item **" + Name + "** to " + Actor.Name + "/" + Actor.Name2 + "'s Inventory.");
        }
Пример #19
0
        public void RunSingleTest()
        {
            Random randomizer = new Random();

            string selectedColour = randomizer.Next(1, 2) == 1 ? "Black" : "Red";

            int randomResult = randomizer.Next(1, Fields.Count());

            decimal runprofit = stake;

            SelectableField resultField = Fields.Where(x => x.ID == randomResult).First();

            if (resultField.Color == selectedColour || resultField.Color == "White")
            {
                runprofit -= (stake * resultField.stakeMultiplier);
            }

            Results.Add(new TestResult
            {
                testNum = Results.Count == 0 ? 1 : Results.Max(x => x.testNum) + 1,
                profit  = runprofit
            });
        }
Пример #20
0
        public void GetDebugInfo(XmlWriter file)
        {
            file.WriteStartElement("debug");
            file.WriteAttributeString("name", this.Name);
            file.WriteAttributeString("fields", Fields.Count().ToString());

            file.WriteAttributeString("template", IsTemplate.ToString());
            if (AddressTree == null)
            {
                file.WriteAttributeString("address", Address.ToString("X"));
            }
            else
            {
                file.WriteAttributeString("address", string.Concat(AddressTree.Select(x => x.ToString("X") + ", ")));
            }
            file.WriteAttributeString("size", Size.ToString("X"));
            file.WriteAttributeString("offset", Offset.ToString("X"));

            foreach (var field in Fields)
            {
                file.WriteStartElement("debug-field");
                file.WriteAttributeString("name", field.Value.Name);
                file.WriteAttributeString("address", field.Value.Address.ToString());
                file.WriteAttributeString("size", field.Value.Size.ToString());
                file.WriteAttributeString("offset", field.Value.Offset.ToString());
                file.WriteAttributeString("type", field.Value.ValueType.ToString());
                file.WriteEndElement();
            }
            foreach (var pool in Pools)
            {
                pool.Value.GetDebugInfo(file);
            }

            file.WriteEndElement();

            //return string.Format("Type:{0}, Fields: {1}, IsTemplate: {2}, Address: 0x{3:X}, Offset: 0x{4:X}, Size: 0x{5:X}", AddressType, Fields.Count(), IsTemplate, Address, Offset, Size);
        }
Пример #21
0
        public string GetInfo()
        {
            var builder = new StringBuilder();

            builder.AppendLine("Type Summary");
            builder.Append(Environment.NewLine);
            builder.AppendLine(string.Format("Name: {0}", Name));
            builder.AppendLine(string.Format("TypeCode: {0}", TypeDefinition.KnownTypeCode));
            builder.AppendLine(string.Format("Methods: {0}", Methods.Count()));
            builder.AppendLine(string.Format("Fields: {0}", Fields.Count()));
            builder.AppendLine(string.Format("Nested types: {0}", NestedTypes.Count()));
            builder.AppendLine(string.Format("Base types: {0}", BaseTypes.Count()));
            // more to come

            builder.Append(Environment.NewLine);

//			if (TypeDefinition.IsAbstract)
//				builder.AppendLine("IsAbstract");
//			if (TypeDefinition.
//			if (IsInternal)
//				builder.AppendLine("IsInternal");
//			if (IsNestedPrivate)
//				builder.AppendLine("IsNestedPrivate");
//			if (IsNestedProtected)
//				builder.AppendLine("IsNestedProtected");
//			if (IsNestedPublic)
//				builder.AppendLine("IsNestedPublic");
//			if (IsPublic)
//				builder.AppendLine("IsPublic");
//			if (IsSealed)
//				builder.AppendLine("IsSealed");
//			if (IsStruct)
//				builder.AppendLine("IsStruct");

            return(builder.ToString());
        }
Пример #22
0
 public override string ToString()
 {
     return(String.Format("{0} Fields, {1} Frames", Fields.Count(), Frames.Count()));
 }
Пример #23
0
        /// <inheritdoc/>
        public void Validate()
        {
            foreach (var definition in Definitions.Values)
            {
                if (Definitions.Values.Count(d => d.Name.Equals(definition.Name, StringComparison.OrdinalIgnoreCase)) > 1)
                {
                    throw new MultipleDefinitionsException(definition);
                }
                if (ReservedWords.Identifiers.Contains(definition.Name))
                {
                    throw new ReservedIdentifierException(definition.Name, definition.Span);
                }
                if (definition is TopLevelDefinition td && td.OpcodeAttribute != null)
                {
                    if (!td.OpcodeAttribute.TryValidate(out var opcodeReason))
                    {
                        throw new InvalidOpcodeAttributeValueException(td, opcodeReason);
                    }
                    if (Definitions.Values.Count(d => d is TopLevelDefinition td2 && td2.OpcodeAttribute != null && td2.OpcodeAttribute.Value.Equals(td.OpcodeAttribute.Value)) > 1)
                    {
                        throw new DuplicateOpcodeException(td);
                    }
                }
                if (definition is FieldsDefinition fd)
                {
                    foreach (var field in fd.Fields)
                    {
                        if (ReservedWords.Identifiers.Contains(field.Name))
                        {
                            throw new ReservedIdentifierException(field.Name, field.Span);
                        }
                        if (field.DeprecatedAttribute != null && fd is StructDefinition)
                        {
                            throw new InvalidDeprecatedAttributeUsageException(field);
                        }
                        if (fd.Fields.Count(f => f.Name.Equals(field.Name, StringComparison.OrdinalIgnoreCase)) > 1)
                        {
                            throw new DuplicateFieldException(field, fd);
                        }
                        switch (fd)
                        {
                        case StructDefinition when field.Type is DefinedType dt && fd.Name.Equals(dt.Name):
                        {
                            throw new InvalidFieldException(field, "Struct contains itself");
                        }

                        case MessageDefinition when fd.Fields.Count(f => f.ConstantValue == field.ConstantValue) > 1:
                        {
                            throw new InvalidFieldException(field, "Message index must be unique");
                        }

                        case MessageDefinition when field.ConstantValue <= 0:
                        {
                            throw new InvalidFieldException(field, "Message member index must start at 1");
                        }

                        case MessageDefinition when field.ConstantValue > fd.Fields.Count:
                        {
                            throw new InvalidFieldException(field, "Message index is greater than field count");
                        }

                        default:
                            break;
                        }
                    }
                }
                if (definition is EnumDefinition ed)
                {
                    HashSet <uint>   values = new HashSet <uint>();
                    HashSet <string> names  = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                    foreach (var field in ed.Members)
                    {
                        if (values.Contains(field.ConstantValue))
                        {
                            throw new InvalidFieldException(field, "Enum value must be unique");
                        }
                        if (names.Contains(field.Name))
                        {
                            throw new DuplicateFieldException(field, ed);
                        }
                        values.Add(field.ConstantValue);
                        names.Add(field.Name);
                    }
                }
            }
        }
Пример #24
0
        private int EvaluationYX(Fields FieldsToCheck, int columns, int rows, Pattern WinningPattern)
        {
            int CorrectFields1 = 0, CorrectFields2 = 0;
            int oppositefields1 = 0, oppositefields2 = 0;
            int rowsB    = rows + how_far_to_win;
            int rowsT    = rows - how_far_to_win;
            int columnsL = columns - how_far_to_win;
            int columnsR = columns + how_far_to_win;

            while (rowsB >= FieldsToCheck.Count())
            {
                rowsB--;
                columnsL++;
            }

            while (rowsT < 0)
            {
                /// sprawdz potem czy to jest dobrze
                rowsT++;// -1 bo indeks a nie ilosc elementow
                columnsR--;
            }
            while (columnsL < 0)
            {
                columnsL++;
                rowsB--;
            }
            while (columnsR >= FieldsToCheck.Count())
            {
                /// sprawdz potem czy to jest dobrze
                columnsR--;
                rowsT++;// -1 bo indeks a nie ilosc elementow
            }
            for (int i = rowsB, j = columnsL; i > rows && j < columns; j++, i--)
            {
                if (FieldsToCheck[i, j]._pattern == WinningPattern)
                {
                    oppositefields1 = 0;
                    CorrectFields1++;
                }
                else if (FieldsToCheck[i, j]._pattern == Pattern.None)
                {
                    ;
                }
                else
                {
                    oppositefields1++;
                    CorrectFields1 = 0;
                }
            }
            for (int i = rowsT, j = columnsR; i < rows && j > columns; j--, i++)
            {
                if (FieldsToCheck[i, j]._pattern == WinningPattern)
                {
                    CorrectFields2++;
                    oppositefields2 = 0;
                }
                else if (FieldsToCheck[i, j]._pattern == Pattern.None)
                {
                    ;
                }
                else
                {
                    oppositefields2++;
                    CorrectFields2 = 0;
                }
            }

            if (oppositefields1 + oppositefields2 == how_far_to_win - 1)
            {
                return(100000);
            }
            /// int opposite = (oppositefields1 + oppositefields2) / 2;

            return(CorrectFields1 + CorrectFields2);// + opposite;
        }
Пример #25
0
        private int EvaluationXY(Fields FieldsToCheck, int column, int rows, Pattern WinningPattern)
        {
            int correctFields1 = 0, correctFields2 = 0;
            int oppositefields1 = 0, oppositefields2 = 0;
            int RowT    = rows - how_far_to_win;
            int RowB    = rows + how_far_to_win;
            int ColumnL = column - how_far_to_win;
            int ColumnP = column + how_far_to_win;

            /// Zasadniczo jest dobrze ale nie na krowaedziach, zmieniejsz rzad i kolumne az nie beda nieujemne
            while (RowT < 0)
            {
                ColumnL++;
                RowT++;
            }
            while (ColumnL < 0)
            {
                ColumnL++;
                RowT++;
            }
            while (RowB >= FieldsToCheck.Count())
            {                                        /// sprawdz potem czy to jest dobrze
                ColumnP--;
                RowB--;                              // -1 bo indeks a nie ilosc elementow
            }
            while (ColumnP >= FieldsToCheck.Count()) /// sprawdz potem czy to jest dobrze
            {                                        /// sprawdz potem czy to jest dobrze
                ColumnP--;
                RowB--;                              // -1 bo indeks a nie ilosc elementow
            }
            for (int i = RowT, j = ColumnL; i < rows && j < column; j++, i++)
            {
                if (FieldsToCheck[i, j]._pattern == WinningPattern)
                {
                    correctFields1++;
                    oppositefields1 = 0;
                }
                else if (FieldsToCheck[i, j]._pattern == Pattern.None)
                {
                    ;
                }
                else
                {
                    oppositefields1++;
                    correctFields1 = 0;
                }
            }
            for (int i = RowB, j = ColumnP; i > rows && j > column; j--, i--)
            {
                if (FieldsToCheck[i, j]._pattern == WinningPattern)
                {
                    oppositefields2 = 0;
                    correctFields2++;
                }
                else if (FieldsToCheck[i, j]._pattern == Pattern.None)
                {
                    ;
                }
                else
                {
                    oppositefields2++;
                    correctFields2 = 0;
                }
            }
            if (oppositefields1 + oppositefields2 == how_far_to_win - 1)
            {
                return(100000);
            }
            // int opposite = (oppositefields1 + oppositefields2) / 2;

            return(correctFields1 + correctFields2);// + opposite;
        }
Пример #26
0
        /// <inheritdoc/>
        public void Validate()
        {
            foreach (var definition in Definitions.Values)
            {
                if (Definitions.Values.Count(d => d.Name.Equals(definition.Name)) > 1)
                {
                    throw new MultipleDefinitionsException(definition);
                }
                if (ReservedWords.Identifiers.Contains(definition.Name))
                {
                    throw new ReservedIdentifierException(definition.Name, definition.Span);
                }
                if (definition.IsReadOnly && !definition.IsStruct())
                {
                    throw new InvalidReadOnlyException(definition);
                }
                if (definition.OpcodeAttribute != null)
                {
                    if (definition.IsEnum())
                    {
                        throw new InvalidOpcodeAttributeUsageException(definition);
                    }
                    if (!definition.OpcodeAttribute.TryValidate(out var opcodeReason))
                    {
                        throw new InvalidOpcodeAttributeValueException(definition, opcodeReason);
                    }
                    if (Definitions.Values.Count(d => d.OpcodeAttribute != null && d.OpcodeAttribute.Value.Equals(definition.OpcodeAttribute.Value)) > 1)
                    {
                        throw new DuplicateOpcodeException(definition);
                    }
                }
                foreach (var field in definition.Fields)
                {
                    if (ReservedWords.Identifiers.Contains(field.Name))
                    {
                        throw new ReservedIdentifierException(field.Name, field.Span);
                    }
                    if (field.DeprecatedAttribute != null && definition.IsStruct())
                    {
                        throw new InvalidDeprecatedAttributeUsageException(field);
                    }
                    switch (definition.Kind)
                    {
                    case AggregateKind.Enum when field.ConstantValue < 0:
                    {
                        throw new InvalidFieldException(field, "Enum values must start at 0");
                    }

                    case AggregateKind.Enum when definition.Fields.Count(f => f.ConstantValue == field.ConstantValue) > 1:
                    {
                        throw new InvalidFieldException(field, "Enum value must be unique");
                    }

                    case AggregateKind.Struct when field.Type is DefinedType dt && definition.Name.Equals(dt.Name):
                    {
                        throw new InvalidFieldException(field, "Struct contains itself");
                    }

                    case AggregateKind.Message when definition.Fields.Count(f => f.ConstantValue == field.ConstantValue) > 1:
                    {
                        throw new InvalidFieldException(field, "Message index must be unique");
                    }

                    case AggregateKind.Message when field.ConstantValue <= 0:
                    {
                        throw new InvalidFieldException(field, "Message member index must start at 1");
                    }

                    case AggregateKind.Message when field.ConstantValue > definition.Fields.Count:
                    {
                        throw new InvalidFieldException(field, "Message index is greater than field count");
                    }

                    default:
                        break;
                    }
                }
            }
        }
Пример #27
0
        public override string RenderContent()
        {
            if (Fields.Count == 0)
            {
                throw new FoxOneException("Fields不能为空");
            }
            var request = HttpContext.Current.Request;

            if (FormService != null)
            {
                if (Key.IsNullOrEmpty())
                {
                    Key = request[NamingCenter.PARAM_KEY_NAME];
                }

                //当FORM指定的服务类不为空,且当前的请求中带有KEY的URL参数,
                //则尝试去获取表单数据,如果不为空,则为编辑状态
                if (!Key.IsNullOrEmpty())
                {
                    var tempData = FormService.Get(Key);
                    if (!tempData.IsNullOrEmpty())
                    {
                        if (FormMode != FormMode.View)
                        {
                            FormMode = FormMode.Edit;
                        }
                        Data = tempData;
                    }
                    if (request != null && request.QueryString[NamingCenter.PARAM_FORM_VIEW_MODE] != null && request.QueryString[NamingCenter.PARAM_FORM_VIEW_MODE].Equals(FormMode.View.ToString(), StringComparison.OrdinalIgnoreCase))
                    {
                        FormMode = FormMode.View;
                    }
                }
            }
            IDictionary <string, object> formData = null;

            if (Data != null)
            {
                formData = Data as Dictionary <string, object>;
                if (formData.IsNullOrEmpty())
                {
                    formData = Data.ToDictionary();
                }
            }
            StringBuilder result = new StringBuilder();
            ///隐藏域和按钮属于特殊群体放在表单的指定位置
            StringBuilder hiddenResult = new StringBuilder();
            StringBuilder buttonResult = new StringBuilder();

            if (!Buttons.IsNullOrEmpty() && FormMode != FormMode.View)
            {
                foreach (var button in Buttons)
                {
                    buttonResult.AppendLine(button.Render());
                }
            }
            var formModeHidden = new HiddenField()
            {
                Id = NamingCenter.PARAM_FORM_VIEW_MODE, Value = request[NamingCenter.PARAM_FORM_VIEW_MODE].IsNullOrEmpty() ? FormMode.ToString() : request[NamingCenter.PARAM_FORM_VIEW_MODE], Name = NamingCenter.PARAM_FORM_VIEW_MODE
            };

            hiddenResult.Append(formModeHidden.Render());
            var formTemplate = TemplateGenerator.GetDefaultFormTemplate();
            var renderQuerystringFinished = false;

            if (AppendQueryString && !renderQuerystringFinished)
            {
                foreach (var r in request.QueryString.AllKeys)
                {
                    if (!r.Equals(NamingCenter.PARAM_FORM_VIEW_MODE, StringComparison.OrdinalIgnoreCase) && Fields.Count(o => o.Id.Equals(r, StringComparison.CurrentCultureIgnoreCase)) == 0)
                    {
                        hiddenResult.AppendLine(new HiddenField()
                        {
                            Id = r, Name = r, Value = request.QueryString[r]
                        }.Render());
                    }
                }
                renderQuerystringFinished = true;
            }
            var renderFields = new List <FormControlBase>();

            foreach (var field in Fields.OrderBy(o => o.Rank))
            {
                if ((FormMode == FormMode.Edit && !field.CanModity) || FormMode == FormMode.View)
                {
                    //如果当前Form的模式为编辑模式,而字段又不允许修改,则改为不可用。
                    field.Enable = false;
                }
                if (field.Name.IsNullOrEmpty())
                {
                    field.Name = field.Id;
                }
                if (!formData.IsNullOrEmpty())
                {
                    if (formData.Keys.Contains(field.Id))
                    {
                        field.Value = (formData[field.Id] == null) ? "" : formData[field.Id].ToString();
                    }
                }
                else
                {
                    if (!request.QueryString[field.Id].IsNullOrEmpty())
                    {
                        //如果URL参数中含有与当前控件ID一致的键值,则以URL参数的值赋初始值
                        field.Value = request.QueryString[field.Id];
                    }
                    else
                    {
                        /// 当字段的值存在的时候从环境变量将值格式化
                        if (field.Value != null)
                        {
                            field.Value = Env.Parse(field.Value.ToString());
                        }
                    }
                }
                if (field is HiddenField)
                {
                    hiddenResult.AppendLine(field.Render());
                }
                else
                {
                    if (field.ContainerTemplate.IsNullOrEmpty())
                    {
                        field.ContainerTemplate = TemplateGenerator.GetFormFieldTemplate();
                    }
                    renderFields.Add(field);
                }
            }
            string groupTemplate = TemplateGenerator.GetFormGroupTemplate();

            for (int i = 0; i < renderFields.Count; i++)
            {
                if (!renderFields[i].EditColSpan && ((i + 1) < renderFields.Count) && !renderFields[i + 1].EditColSpan)
                {
                    result.Append(groupTemplate.FormatTo(renderFields[i].Render() + renderFields[++i].Render()));
                }
                else
                {
                    result.Append(groupTemplate.FormatTo(renderFields[i].Render()));
                }
            }
            return(formTemplate.FormatTo(PostUrl, FormCssClass, hiddenResult.ToString(), result.ToString(), buttonResult.ToString()));
        }
Пример #28
0
        private void HandleTimer()
        {
            System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                lastFarmID     = "-1";
                lastProducerID = "-1";
                lastFieldID    = "-1";

                var selProducerID = (SelectedProducer != null) ? SelectedProducer.ID : "";
                var selFarmID     = (SelectedFarm != null) ? SelectedFarm.ID : "";
                var selFieldID    = (SelectedField != null) ? SelectedField.ID : "";
                var selItemID     = "";

                if (SelectedItem != null)
                {
                    selItemID = SelectedItem.ListID;
                }

                refresh();

                //restore selections
                int producerIndex = 0;
                for (producerIndex = 0; producerIndex < Producers.Count(); producerIndex++)
                {
                    if (Producers[producerIndex].ID == selProducerID)
                    {
                        break;
                    }
                }
                if (producerIndex >= Producers.Count())
                {
                    producerIndex = 0;
                }

                if (Producers.Count() > 0)
                {
                    SelectedProducer = Producers[producerIndex];
                }

                int farmIndex = 0;
                for (farmIndex = 0; farmIndex < Farms.Count(); farmIndex++)
                {
                    if (Farms[farmIndex].ID == selFarmID)
                    {
                        break;
                    }
                }
                if (farmIndex >= Farms.Count())
                {
                    farmIndex = 0;
                }

                if (Farms.Count() > 0)
                {
                    SelectedFarm = Farms[farmIndex];
                }

                int fieldIndex = 0;
                for (fieldIndex = 0; fieldIndex < Fields.Count(); fieldIndex++)
                {
                    if (Fields[fieldIndex].ID == selFieldID)
                    {
                        break;
                    }
                }
                if (fieldIndex >= Fields.Count())
                {
                    fieldIndex = 0;
                }

                if (Fields.Count() > 0)
                {
                    SelectedField = Fields[fieldIndex];
                }

                var item = Lists.SingleOrDefault(l => l.ListID == selItemID);
                if (item != null)
                {
                    SelectedItem = item;
                }
                else if (Lists.Count() > 0)
                {
                    SelectedItem = Lists[0];
                }
                else
                {
                    SelectedItem = null;
                }
            }));
        }
Пример #29
0
        public EntityClass(
            EntityClass parent,
            entitySpec entitySpec,
            Type type,
            LinkedFieldInfo fieldInfo,
            Action <string> log,
            bool throwOnCircularReference)
            : base(entitySpec)
        {
            log?.Invoke(
                $"EntityClass ctor: {entitySpec.name}/{entitySpec.fields?.Count ?? 0} - {type?.Name} - {fieldInfo?.FieldType} - {fieldInfo?.IEnumerable?.Name}");

            TableName = parent != null && Spec.externalname == null
                ? string.Join("_", parent.TableName, ExternalName)
                : ExternalName;

            FieldInfo = fieldInfo;
            FieldType = fieldInfo?.FieldType;

            if (!Spec.Any() || isStarExpansionAndNoRealSubProperties(type))
            {
                // not sure if this should be allowed...
                Fields.Add(new EntitySolitaire(type));
            }

            breakDownSubEntities(type, log, throwOnCircularReference);

            // move the nosave fields to always be at the end of the list
            var noSaveFields = Fields.Where(_ => _.NoSave).ToList();

            Fields.RemoveAll(_ => _.NoSave);
            SaveableFieldCount = Fields.Count;
            Fields.AddRange(noSaveFields);

            // this is temporary - to be able to serialze a contract with "*" since it was digging up so much garbage...
            // need to investigae each "garbage" occurrence and handle it more elegantly
            Fields.RemoveAll(_ => _ is EntityPlainField && SqlHelpers.Field2Sql(_.NameAndType.Name, _.NameAndType.Type, false, 0, true) == null);
            Lists.RemoveAll(_ => !_.Fields.Any() && !_.Lists.Any());

            if (Fields.Count(_ => _.Spec.primarykey) > 1)
            {
                throw new Exception("There may be no more than one primary key field");
            }
            PrimaryKeyIndex = Fields.FindIndex(_ => _.Spec.primarykey);

            EffectiveFieldCount = Fields.Count + 1;
            for (var fi = 0; fi < Fields.Count; fi++)
            {
                Fields[fi].ParentInitialized(this, fi);
            }
            for (var li = 0; li < Lists.Count; li++)
            {
                Lists[li].ParentInitialized(this, li);
            }

            for (var i = 0; i < Fields.Count; i++)
            {
                Fields[i].ResultSetIndex = i;
            }

            var fieldsThenFormulas = Fields.Where(_ => !(_ is EntityAggregation)).ToList();

            SortWithFormulasLast(fieldsThenFormulas);
            _fieldsThenNonAggregatedFormulas = fieldsThenFormulas.Where(_ => !_.IsBasedOnAggregation).ToArray();
            _aggregatedFormulas = fieldsThenFormulas.Where(_ => _.IsBasedOnAggregation).ToArray();

            if (!string.IsNullOrEmpty(Spec.where))
            {
                _whereClause = new WhereClause(Spec.where, Fields, _fieldsThenNonAggregatedFormulas);
            }

            if (PrimaryKeyIndex >= 0 && Fields[PrimaryKeyIndex].IsBasedOnAggregation)
            {
                throw new Exception($"The primary key must not be based on an aggregation (table '{TableName}')");
            }
        }
Пример #30
0
        private IEnumerable <IStatement> ParseMethodExecutions(IEnumerable <string> lines)
        {
            var result = new List <IStatement>();

            int controlsequenceDepth = 0;

            foreach (string line in lines.Select(entry => entry.Trim()))
            {
                if (IsLineIgnored(line))
                {
                    continue;
                }

                if (line == "{")
                {
                    continue;
                }

                if (line == "}")
                {
                    if (controlsequenceDepth > 0)
                    {
                        result.Add(new ControlStatementEnd());
                        controlsequenceDepth--;
                    }

                    continue;
                }

                IStatement statement;

                if (Regex.IsMatch(line, ControlStatement.Pattern))
                {
                    statement = ControlStatement.Parse(line);
                    controlsequenceDepth++;
                }

                else if (Regex.IsMatch(line, AssignationStatement.Pattern))
                {
                    statement = AssignationStatement.Parse(line);
                }

                else if (Regex.IsMatch(line, InvokeExpression.Pattern))
                {
                    statement = InvokeExpression.Parse(line);
                    if (!string.IsNullOrEmpty((statement as InvokeExpression).ReturnVariableAssignation) &&
                        string.IsNullOrEmpty((statement as InvokeExpression).Preffix) &&
                        Fields.Count(entry => entry.Name == ((InvokeExpression)statement).ReturnVariableAssignation) > 0)
                    {
                        (statement as InvokeExpression).Preffix = "(" +
                                                                  Fields.Where(
                            entry =>
                            entry.Name ==
                            ((InvokeExpression)statement).
                            ReturnVariableAssignation).First().Type + ")";                                                                                                                      // cast
                    }

                    // cast to generic type
                    if (!string.IsNullOrEmpty((statement as InvokeExpression).Target) &&
                        (statement as InvokeExpression).Name == "Add" &&
                        Fields.Count(entry => entry.Name == ((InvokeExpression)statement).Target.Split('.').Last()) > 0)
                    {
                        string generictype =
                            Fields.Where(entry => entry.Name == ((InvokeExpression)statement).Target.Split('.').Last()).
                            First().Type.Split('<').Last().Split('>').First();

                        (statement as InvokeExpression).Args[0] = "(" + generictype + ")" +
                                                                  (statement as InvokeExpression).Args[0];
                    }
                }

                else
                {
                    statement = new UnknownStatement
                    {
                        Value = line
                    }
                };

                result.Add(statement);
            }

            return(result);
        }