public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var expression = value as BindingExpression;
            if (expression == null)
            {
                // TODO: Can't handle this
                return ValidationResult.ValidResult;
            }

            var sourceItem = typeof(BindingExpression).GetProperty("SourceItem", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(expression, null);
            if (sourceItem == null || sourceItem.GetType().Name == "NullDataItem" || sourceItem.GetType() == previousSourceItemType)
            {
                return ValidationResult.ValidResult;
            }
            previousSourceItemType = sourceItem.GetType();

            var propertyName = (string)typeof(BindingExpression).GetProperty("SourcePropertyName", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(expression, null);
            if (propertyName == null)
            {
                return ValidationResult.ValidResult;
            }

            var properties = TypeDescriptor.GetProperties(sourceItem);
            var property = properties.Find(propertyName, true);
            if (property == null)
            {
                // TODO: Can't handle this
                return ValidationResult.ValidResult;
            }

            var context = new FieldContext(field, editorBinding, sourceItem, propertyName, property);
            fieldBuilder.Configure(context);

            return ValidationResult.ValidResult;
        }
 public override IFieldContext NewFieldContext(string id)
 {
     FieldContext field = new FieldContext();
     field.ID = id;
     field.MessageSource = this.MessageSource;
     return field;
 }
 public void DeleteOneMetadataFromInside(FieldContext fc)
 {
     MetadataContext mc = new MetadataContext(fc.FieldId, fc.FieldInfo.FieldName, fc.Values[0].TextContext.Text, fc.Document.DocumentId);
     listOfMetadata = ReadAllFields().ToList();
     var metadataContext = listOfMetadata.First(l => l.Id.Equals(mc.Id));
     listOfMetadata.Remove(metadataContext);
     WriteJsonFile(listOfMetadata);
 }
        /// <summary>
        /// Creates the appropriate editor from the context. If the return value is null, another
        /// <see cref="IEditorStrategy"/> will be asked. The returned value should be fully configured
        /// and bound.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>
        /// A control that will be used for editing the field, or null if this strategy cannot be
        /// used for this field.
        /// </returns>
        public object CreateEditor(FieldContext context)
        {
            var textBox = new TextBox { Width = 200 };
            context.WhenHasAttribute<StringLengthAttribute>(sl => textBox.MaxLength = sl.MaximumLength);

            BindingOperations.SetBinding(textBox, TextBox.TextProperty, context.Binding);
            return textBox;
        }
Beispiel #5
0
        private static PartialResults CheckDiagonals(FourInARowState state)
        {
            PartialResults summary = new PartialResults();

            //// from left bottom to right top

            for (Int32 startY = 0, mStartY = FourInARowState.RowCount - WinningCount + 1; startY < mStartY; startY++)
            {
                FieldContext context = new FieldContext();

                for (Int32 x = 0, y = startY, my = FourInARowState.RowCount, mx = FourInARowState.ColumnCount; y < my && x < mx /* && y < state.LastEmptyRow */; x++, y++)
                {
                    ProcessField(state, x, y, context);
                }

                summary.Add(context.PartialResults);
            }

            for (Int32 startX = 1, mStartX = FourInARowState.ColumnCount - WinningCount + 1; startX < mStartX; startX++)
            {
                FieldContext context = new FieldContext();

                for (Int32 x = startX, y = 0, my = FourInARowState.RowCount, mx = FourInARowState.ColumnCount; y < my && x < mx /* && y < state.LastEmptyRow */; x++, y++)
                {
                    ProcessField(state, x, y, context);
                }

                summary.Add(context.PartialResults);
            }

            //// from right bottom to left top

            for (Int32 startY = 0, mStartY = FourInARowState.RowCount - WinningCount + 1; startY < mStartY; startY++)
            {
                FieldContext context = new FieldContext();

                for (Int32 x = FourInARowState.ColumnCount - 1, y = startY, my = FourInARowState.RowCount; y < my && x >= 0 /* && y < state.LastEmptyRow */; x--, y++)
                {
                    ProcessField(state, x, y, context);
                }

                summary.Add(context.PartialResults);
            }

            for (Int32 sStartX = FourInARowState.ColumnCount - 2, mStartX = WinningCount - 1; sStartX >= mStartX; sStartX--)
            {
                FieldContext context = new FieldContext();

                for (Int32 x = sStartX, y = 0, my = FourInARowState.RowCount; y < my && x >= 0 /* && y < state.LastEmptyRow */; x--, y++)
                {
                    ProcessField(state, x, y, context);
                }

                summary.Add(context.PartialResults);
            }

            return(summary);
        }
Beispiel #6
0
        /// <summary>
        /// 起こりうる最大連鎖回数を分析します
        /// </summary>
        /// <returns>起こりうる最大連鎖回数</returns>
        /// <param name="context">フィールド状態</param>
        /// <param name="player">プレイヤ</param>
        public int Analyze(FieldContext context, Player.Index player)
        {
            int maxChain = 0;

            // 移動可能パターンを取得
            var movePatterns = CompleteReadingHelper.GetAllMovePatterns();

            // 分析対象の移動可能スライムを生成
            var usingSlimes   = context.UsingSlimes;
            var slimePatterns = new List <Slime[]>();

            slimePatterns.Add(new[] { usingSlimes[0], usingSlimes[1] });
            slimePatterns.Add(new[] { usingSlimes[2], usingSlimes[3] });

            // 自動移動機能を生成
            var updater = DiProvider.GetContainer().GetInstance <AutoMoveAndDropUpdater>();

            updater.Inject(context.UsingSlimes);

            // 各移動可能スライムの全パターンを試していく
            foreach (var slimePattern in slimePatterns)
            {
                var _context = context.DeepCopy();
                // 移動可能スライムを書き換える
                for (var movable = 0; movable < MovableSlime.Length; movable++)
                {
                    var org   = _context.MovableSlimes[player.ToInt()][(int)movable];
                    var valid = (org.Index == FieldContextConfig.MaxHiddenUnitIndex &&
                                 org.Position == FieldContextConfig.MovableSlimeInitialShiftAfterDroped + (FieldContextConfig.OneLineBitCount * (int)movable));
                    if (!valid)
                    {
                        return(0);
                    }

                    // 元の移動可能スライムを消す
                    _context.SlimeFields[player.ToInt()][org.Slime][org.Index] &= ~(1u << org.Position);

                    // 色を書き換える
                    org.Slime = slimePattern[(int)movable];
                }

                // 自動移動を実行
                foreach (var movePattern in movePatterns)
                {
                    var _movedContext = _context.DeepCopy();
                    var param         = new AutoMoveAndDropUpdater.Param()
                    {
                        Pattern = movePattern,
                    };

                    updater.Update(_movedContext, player, param);
                    maxChain = Math.Max(maxChain, param.Chain);
                }
            }

            // 試行内の最大連鎖数を返却
            return(maxChain);
        }
 /// <summary>
 /// Checks whether a field with the specified Id has already been defined.
 /// </summary>
 /// <param name="container">The field container to search.</param>
 /// <param name="fieldId">The field Id to check for.</param>
 /// <param name="node">The field being defined.</param>
 /// <returns>
 /// true if the field Id has already been defined, false otherwise.
 /// </returns>
 public static bool IsFieldIdAlreadyDefined(
     this IFieldContainer container,
     int fieldId,
     FieldContext node)
 {
     return(container.Fields
            .Where(item => item.FieldId == fieldId)
            .FirstOrDefault().Node != node);
 }
 /// <summary>
 /// Checks whether the field has already been defined.
 /// </summary>
 /// <param name="container">The field container to search.</param>
 /// <param name="name">The name of the field.</param>
 /// <param name="node">The field being defined.</param>
 /// <returns>
 /// true if the field name has already been defined, false otherwise.
 /// </returns>
 public static bool IsFieldNameAlreadyDefined(
     this IFieldContainer container,
     string name,
     FieldContext node)
 {
     return(container.Fields
            .Where(item => item.Name == name)
            .FirstOrDefault().Node != node);
 }
        public static T AddGraphQlError <T>(this T exception, string errorCode, FieldContext fieldContext)
            where T : Exception
        {
            var error = new GraphQlError(errorCode);

            error.Fixup(fieldContext);
            exception.Data[errorKey] = new[] { error };
            return(exception);
        }
Beispiel #10
0
        public bool SaveNode(Node node, dynamic rawdata, List <Field> fields = null)
        {
            if (fields != null)
            {
                throw new Exception("SaveNodeData is not consumed in the right way!");
                foreach (var field in fields)
                {
                    try
                    {
                        var value = rawdata[field.Id.ToString()];
                        //raw data has to be processed before saving to database
                        var fieldtype = _fieldrepository.GetFieldType(field);

                        var          type     = System.Type.GetType(fieldtype.ClassPath);
                        FieldContext _context = new FieldContext(field.Id, fieldtype.Id, field.FieldName);
                        _context.RawData  = value;
                        _context.OldValue = null;
                        var fieldobj = Activator.CreateInstance(type, _context);
                        var mi       = type.GetMethod("GetValue");
                        var data     = mi.Invoke(fieldobj, null).ToString();

                        _currentrepository.SaveNodeData(node, field, data);
                    }
                    catch (Exception e) { }
                }
            }
            else
            {
                var list = ((INodeRepository)_currentrepository).GetNodeFieldMapData(node);
                foreach (var nodefield in list)
                {
                    try
                    {
                        var value = rawdata[nodefield.Id.ToString()];
                        //raw data has to be processed before saving to database
                        var          fieldtype = _fieldrepository.GetFieldType(nodefield.Field);
                        var          type      = System.Type.GetType(fieldtype.ClassPath);
                        FieldContext _context  = new FieldContext(nodefield.Field.Id, fieldtype.Id, nodefield.Field.FieldName);
                        _context.RawData  = value;
                        _context.OldValue = nodefield.NodeData;
                        var fieldobj = Activator.CreateInstance(type, _context);
                        //invoke GetValue to get the processed value.
                        var mi   = type.GetMethod("GetValue");
                        var data = mi.Invoke(fieldobj, null).ToString();
                        //call SaveValue to save addition information.
                        mi = type.GetMethod("SaveValue");
                        mi.Invoke(fieldobj, null);

                        nodefield.NodeData = data;
                        _currentrepository.SaveNodeData(nodefield);
                    }
                    catch (Exception e) { }
                }
            }

            return(true);
        }
Beispiel #11
0
        /// <inheritdoc/>
        public Field FindSymbolForNode(FieldContext node)
        {
            if (this.FindSymbolForNode((IParseTree)node) is Field field)
            {
                return(field);
            }

            return(null);
        }
Beispiel #12
0
        public void TestBuildFieldContext_Struct()
        {
            string   testSrcML = "<struct>struct <name>foo</name> <block>{<public type=\"default\"><decl_stmt><decl><type><name>int</name></type> <name>a</name></decl>;</decl_stmt></public>}</block>;</struct>";
            XElement xml       = XElement.Parse(string.Format(srcMLFormat, testSrcML), LoadOptions.PreserveWhitespace);

            FieldContext fc1 = new FieldContext("int", true, "foo");
            FieldContext fc2 = ContextBuilder.BuildFieldContext(xml.Descendants(SRC.Declaration).First());

            Assert.IsTrue(FieldContextsAreEqual(fc1, fc2));
        }
Beispiel #13
0
        public void TestBuildFieldContext_Global()
        {
            string   testSrcML = "<decl_stmt><decl><type><name>int</name></type> <name>a</name> =<init> <expr><lit:literal type=\"number\">42</lit:literal></expr></init></decl>;</decl_stmt>";
            XElement xml       = XElement.Parse(string.Format(srcMLFormat, testSrcML), LoadOptions.PreserveWhitespace);

            FieldContext fc1 = new FieldContext("int", true, "");
            FieldContext fc2 = ContextBuilder.BuildFieldContext(xml.Descendants(SRC.Declaration).First());

            Assert.IsTrue(FieldContextsAreEqual(fc1, fc2));
        }
Beispiel #14
0
        /// <summary>
        /// 評価値を取得する
        /// </summary>
        /// <returns></returns>
        protected override double GetEvaluate(FieldContext context)
        {
            StopWatchLogger.StartEventWatch("SearchBestPointer-GetEvaluate");
            var score = this.Evaluator.Evaluate(context);

            StopWatchLogger.StopEventWatch("SearchBestPointer-GetEvaluate");
            FileHelper.WriteLine($"score:{score} direction:{context.OperationDirection}");

            return(score * this.GetParity(context));
        }
 public void DeleteOneContextFromInside(FieldContext fc)
 {
     string hashName = CalculateMD5Hash(fc.FieldInfo.FieldName + fc.Document.DocumentId);
     string hashPath = GetFilePathUsingFullNameOfFile(hashName);
     if (hashPath != null)
     {
         File.Delete(hashPath);
         MetadataStorage.DeleteOneMetadataFromInside(fc);
     }
 }
        /// <summary>
        /// Creates the appropriate editor from the context. If the return value is null, another
        /// <see cref="IEditorStrategy"/> will be asked. The returned value should be fully configured
        /// and bound.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>
        /// A control that will be used for editing the field, or null if this strategy cannot be
        /// used for this field.
        /// </returns>
        public object CreateEditor(FieldContext context)
        {
            var textBox = new TextBox {
                Width = 200
            };

            context.WhenHasAttribute <StringLengthAttribute>(sl => textBox.MaxLength = sl.MaximumLength);

            BindingOperations.SetBinding(textBox, TextBox.TextProperty, context.Binding);
            return(textBox);
        }
 public void AddMetadata(FieldContext fc)
 {
     MetadataContext mc = new MetadataContext(fc.FieldId, fc.FieldInfo.FieldName, fc.Values[0].TextContext.Text, fc.Document.DocumentId);
     List<string> listOfMetadataHashId = GetListOfMetadataHashId();
     string hash = CalculateMD5Hash(mc.Id);
     if (!listOfMetadataHashId.Contains(hash + ".json"))
     {
         listOfMetadata.Add(mc);
         WriteJsonFile(listOfMetadata);
     }
 }
Beispiel #18
0
        public void TestConstructSwum()
        {
            string testSrcML = "<class>class <name>foo</name> <block>{<private type=\"default\"><decl_stmt><decl><type><name>int</name></type> <name>a</name></decl>;</decl_stmt></private>}</block>;</class>";
            XElement xml = XElement.Parse(string.Format(srcMLFormat, testSrcML), LoadOptions.PreserveWhitespace);
            FieldContext fc = ContextBuilder.BuildFieldContext(xml.Descendants(SRC.Declaration).First());

            FieldDeclarationNode fdn = new FieldDeclarationNode("a", fc);
            FieldRule rule = new FieldRule(posData, tagger, splitter);
            rule.ConstructSwum(fdn);
            Console.WriteLine(fdn.ToString());
        }
Beispiel #19
0
        /// <summary>
        /// 指定したバージョンのベクトルを取得します。
        /// </summary>
        /// <param name="version">ベクトルバージョン</param>
        /// <param name="context">フィールド状態</param>
        /// <returns>ベクトル</returns>
        public SparseVector <double> GetVector(AiPlayer.Version version, FieldContext context)
        {
            if (!this.VectorGens.ContainsKey(version))
            {
                throw new ArgumentException("ベクトル種別が不正です");
            }

            var vector = this.GetVector(this.VectorGens[version], context);

            return(vector);
        }
Beispiel #20
0
 /// <summary>
 /// TODO:勝ったプレイヤを取得します。
 /// </summary>
 /// <param name="context">フィールド状態</param>
 /// <returns>勝ったプレイヤ</returns>
 private static Player.Index GetWinPlayer(FieldContext context)
 {
     if (LastWinCount[(int)Player.Index.First] != context.WinCount[(int)Player.Index.First])
     {
         return(Player.Index.First);
     }
     else
     {
         return(Player.Index.Second);
     }
 }
Beispiel #21
0
 /// <summary>
 /// Asks each <see cref="IEditorStrategy">editor strategy</see> in the list whether it can create a
 /// control for editing the given field, returning the first non-null result. If none of the editors
 /// can provide an editor, the fallback editor is asked.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <returns></returns>
 public object GetEditor(FieldContext context)
 {
     foreach (var selector in this)
     {
         var editor = selector.CreateEditor(context);
         if (editor != null)
         {
             return(editor);
         }
     }
     return(fallback.CreateEditor(context));
 }
Beispiel #22
0
        protected Field SetupField(FieldContext fieldNode, Struct @struct, int?fieldId = null, string name = null)
        {
            var field = new FieldBuilder()
                        .SetNode(fieldNode)
                        .SetFieldId(fieldId)
                        .SetName(name)
                        .Build();

            this.binderProvider.GetBinder(fieldNode).Returns(this.fieldBinder);
            this.fieldBinder.Bind <Field>(fieldNode, @struct).Returns(field);

            return(field);
        }
Beispiel #23
0
        /// <summary>
        /// パターンを生成します。
        /// </summary>
        /// <param name="context">フィールド状態</param>
        /// <returns>現在のフィールド状態のパターンリスト</returns>
        public SparseVector <double> GetNext(FieldContext context)
        {
            Debug.Assert(this.HasInjected, "依存性の注入が完了していません");

            int maxIndex = 0;
            var dic      = new Dictionary <int, double>();

            for (var i = 0; i < Player.Length; i++)
            {
                var player = (Player.Index)i;
                if (!this.MyConfig.BothPlayer && player != context.OperationPlayer)
                {
                    // 片方のみ対象の場合は、操作対象プレイヤのみを対象にする
                    continue;
                }

                var colorSlimeFields = context.SlimeFields[player.ToInt()].
                                       Where(f => context.UsingSlimes.Contains(f.Key)).
                                       Select(f => f.Value.Skip(FieldContextConfig.MinDisplayUnitIndex).ToArray()).ToArray();
                var obsSlimeFields = context.SlimeFields[player.ToInt()].
                                     Where(f => f.Key == Slime.Obstruction).
                                     Select(f => f.Value.Skip(FieldContextConfig.MinDisplayUnitIndex).ToArray()).ToArray();

                foreach (var pattern in this.MyConfig.Patterns)
                {
                    foreach (var fields in colorSlimeFields)
                    {
                        this.AddPatternCount(fields, pattern, maxIndex, dic);
                    }
                    maxIndex += (int)pattern.MaxIndex + 1;

                    if (!this.MyConfig.ContainsObstructionSlime)
                    {
                        // おじゃまスライムを含めない場合はスキップ
                        continue;
                    }

                    foreach (var fields in obsSlimeFields)
                    {
                        this.AddPatternCount(fields, pattern, maxIndex, dic);
                    }
                    maxIndex += (int)pattern.MaxIndex + 1;
                }
            }
            var vector = new SparseVector <double>(maxIndex, dic, this.MyConfig.SparseValue);

            return(vector);
        }
Beispiel #24
0
        private object ArrayToOutputRec(FieldContext context, TypeRef typeRef, object value)
        {
            if (value == null)
            {
                return(null);
            }
            var list        = value as IList;
            var result      = new object[list.Count];
            var elemTypeRef = typeRef.Inner;

            for (int i = 0; i < result.Length; i++)
            {
                result[i] = ToOutputRec(context, elemTypeRef, list[i]);
            }
            return(result);
        }
Beispiel #25
0
        /// <summary>
        /// フレーム毎に実行される更新処理を行います。
        /// </summary>
        private static void Update()
        {
            if (IsEnd(Context))
            {
                Console.WriteLine(string.Format("{0}Pの勝ちです。", (int)GetWinPlayer(Context) + 1));
                return;
            }

            // 移動方向無コマンドの実行
            Context.OperationDirection = Direction.None;
            var c = ConsoleClientDiProvider.GetContainer().GetInstance <NativeCommand>();

            c.Command = Command.Move;
            c.Context = Context.DeepCopy();
            c.Context.OperationPlayer = NoneMovePlayer;
            NoneMovePlayer            = Player.GetOppositeIndex(NoneMovePlayer);
            FileHelper.WriteLine("----- 移動方向無コマンドの実行 -----");
            FileHelper.WriteLine(Sender.Send(Context));
            Context = Receiver.Receive(c);

            // 入力を受け付けたコマンドの実行
            IsBlockedKeyInfo = true;
            var keys = KeyInfos.Select(k => k).ToList();

            KeyInfos.Clear();
            IsBlockedKeyInfo = false;

            foreach (var key in keys)
            {
                if (!KeyMap.ContainsKey(key.Key))
                {
                    continue;
                }

                Context.OperationPlayer    = KeyMap.GetPlayer(key.Key);
                Context.OperationDirection = KeyMap.GetDirection(key.Key);
                c         = ConsoleClientDiProvider.GetContainer().GetInstance <NativeCommand>();
                c.Command = Command.Move;
                c.Context = Context.DeepCopy();
                FileHelper.WriteLine("----- 入力を受け付けたコマンドの実行 -----");
                FileHelper.WriteLine(Sender.Send(Context));
                Context = Receiver.Receive(c);
            }

            // 画面描画
            FieldContextWriter.Write(Context);
        }
Beispiel #26
0
        public FieldContext field()
        {
            FieldContext _localctx = new FieldContext(_ctx, State);

            EnterRule(_localctx, 4, RULE_field);
            try {
                State = 27;
                _errHandler.Sync(this);
                switch (_input.La(1))
                {
                case TEXT:
                    EnterOuterAlt(_localctx, 1);
                    {
                        State = 24; Match(TEXT);
                    }
                    break;

                case STRING:
                    EnterOuterAlt(_localctx, 2);
                    {
                        State = 25; Match(STRING);
                    }
                    break;

                case T__0:
                case T__1:
                case T__2:
                    EnterOuterAlt(_localctx, 3);
                    {
                    }
                    break;

                default:
                    throw new NoViableAltException(this);
                }
            }
            catch (RecognitionException re) {
                _localctx.exception = re;
                _errHandler.ReportError(this, re);
                _errHandler.Recover(this, re);
            }
            finally {
                ExitRule();
            }
            return(_localctx);
        }
        /// <summary>
        /// Creates the appropriate editor from the context. If the return value is null, another
        /// <see cref="IEditorStrategy"/> will be asked. The returned value should be fully configured
        /// and bound.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>
        /// A control that will be used for editing the field, or null if this strategy cannot be
        /// used for this field.
        /// </returns>
        public object CreateEditor(FieldContext context)
        {
            if (context.PropertyDescriptor.PropertyType != typeof (bool))
            {
                return null;
            }
            
            // Hide the header:
            context.Field.Header = "";

            var displayName = context.PropertyDescriptor.Attributes.OfType<DisplayNameAttribute>().FirstOrDefault();

            var checkBox = new CheckBox();
            checkBox.Content = displayName == null ? context.PropertyName : displayName.DisplayName;
            BindingOperations.SetBinding(checkBox, ToggleButton.IsCheckedProperty, context.Binding);
            return checkBox;
        }
Beispiel #28
0
        public FieldContext field()
        {
            FieldContext _localctx = new FieldContext(Context, State);

            EnterRule(_localctx, 4, RULE_field);
            try {
                State = 28;
                switch (TokenStream.La(1))
                {
                case TEXT:
                    EnterOuterAlt(_localctx, 1);
                    {
                        State = 25; Match(TEXT);
                    }
                    break;

                case String:
                    EnterOuterAlt(_localctx, 2);
                    {
                        State = 26; Match(String);
                    }
                    break;

                case T__0:
                case T__1:
                case COMMA:
                    EnterOuterAlt(_localctx, 3);
                    {
                    }
                    break;

                default:
                    throw new NoViableAltException(this);
                }
            }
            catch (RecognitionException re) {
                _localctx.exception = re;
                ErrorHandler.ReportError(this, re);
                ErrorHandler.Recover(this, re);
            }
            finally {
                ExitRule();
            }
            return(_localctx);
        }
Beispiel #29
0
        private static PartialResults CheckColumns(FourInARowState state)
        {
            PartialResults summary = new PartialResults();

            for (Int32 x = 0, mx = FourInARowState.ColumnCount; x < mx; x++)
            {
                FieldContext context = new FieldContext();

                for (Int32 y = 0, my = FourInARowState.RowCount; y < my /* && y < state.LastEmptyRow */; y++)
                {
                    ProcessField(state, x, y, context);
                }

                summary.Add(context.PartialResults);
            }

            return(summary);
        }
Beispiel #30
0
        /// <summary>
        /// 指定した種別の評価値を取得します。
        /// </summary>
        /// <param name="version">バージョン</param>
        /// <param name="context">フィールド状態</param>
        /// <returns>評価値</returns>
        public double GetEval(AiPlayer.Version version, FieldContext context)
        {
            double ev = 0.0d;

            switch (version)
            {
            case AiPlayer.Version.V1_0:
            case AiPlayer.Version.V2_0:
                ev  = this.LinearRegressionEvaluators[version].Evaluate(context);
                ev += this.AliveEvaluators[version].Sum(e => e.Evaluate(context));
                ev += this.RandomEvaluator.Evaluate(this.RandomParams[version]);
                break;

            default:
                throw new ArgumentException("バージョンが不正です");
            }
            return(ev);
        }
        /// <summary>
        /// Creates the appropriate editor from the context. If the return value is null, another
        /// <see cref="IEditorStrategy"/> will be asked. The returned value should be fully configured
        /// and bound.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>
        /// A control that will be used for editing the field, or null if this strategy cannot be
        /// used for this field.
        /// </returns>
        public object CreateEditor(FieldContext context)
        {
            if (context.PropertyDescriptor.PropertyType != typeof(bool))
            {
                return(null);
            }

            // Hide the header:
            context.Field.Header = "";

            var displayName = context.PropertyDescriptor.Attributes.OfType <DisplayNameAttribute>().FirstOrDefault();

            var checkBox = new CheckBox();

            checkBox.Content = displayName == null ? context.PropertyName : displayName.DisplayName;
            BindingOperations.SetBinding(checkBox, ToggleButton.IsCheckedProperty, context.Binding);
            return(checkBox);
        }
Beispiel #32
0
 private bool FieldContextsAreEqual(FieldContext fc1, FieldContext fc2)
 {
     if (fc1 == null && fc2 == null)
     {
         return(true);
     }
     if ((fc1 == null) ^ (fc2 == null))
     {
         return(false);
     }
     if (fc1.DeclaringClass != fc2.DeclaringClass ||
         fc1.IdType != fc2.IdType ||
         fc1.IdTypeIsPrimitive != fc2.IdTypeIsPrimitive)
     {
         return(false);
     }
     return(true);
 }
Beispiel #33
0
        protected Field SetupField(
            FieldContext fieldNode,
            Exception exception,
            int?fieldId = null,
            string name = null,
            FieldRequiredness requiredness = FieldRequiredness.Default)
        {
            var field = new FieldBuilder()
                        .SetNode(fieldNode)
                        .SetFieldId(fieldId)
                        .SetRequiredness(requiredness)
                        .SetName(name)
                        .Build();

            this.binderProvider.GetBinder(fieldNode).Returns(this.fieldBinder);
            this.fieldBinder.Bind <Field>(fieldNode, exception).Returns(field);

            return(field);
        }
Beispiel #34
0
 // Recursive method, for high-rank arrays
 private object ToOutputRec(FieldContext context, TypeRef typeRef, object value)
 {
     if (value == null)
     {
         return(null);
     }
     if (typeRef.Kind == TypeKind.NonNull)
     {
         typeRef = typeRef.Inner;
     }
     if (Handler.IsFlagSet && typeRef.Rank == 1)
     {
         return(Handler.ConvertFlagsEnumValueToOutputStringList(value));
     }
     if (typeRef.IsList)
     {
         return(ArrayToOutputRec(context, typeRef, value));
     }
     return(Handler.ConvertEnumValueToOutputString(value));
 }
Beispiel #35
0
        /// <summary>
        /// 自動移動を実行します。
        /// </summary>
        /// <param name="context">フィールド状態</param>
        /// <param name="player">プレイヤ</param>
        /// <param name="param">パラメータ</param>
        public void Update(FieldContext context, Player.Index player, Param param)
        {
            Debug.Assert(this.HasInjected, "依存性の注入が完了していません");
            if (!(context.FieldEvent[(int)context.OperationPlayer] == FieldEvent.None || context.FieldEvent[(int)context.OperationPlayer] == FieldEvent.End))
            {
                return;
            }
#if DEBUG
            for (var i = 0; i < context.UsingSlimes.Length; i++)
            {
                Debug.Assert(context.UsingSlimes[i] == this.UsingSlimes[i], "使用スライムが不正です");
            }
#endif

            // 回転と横移動
            foreach (var p in param.Pattern)
            {
                context.OperationDirection = p;
                context = this.Game.Update(context);
            }

            // 最後まで落下させる
            while (!context.Ground[(int)player] && context.FieldEvent[(int)player] != FieldEvent.End)
            {
                context.OperationDirection = Direction.Down;
                context = this.Game.Update(context);
            }

            // 接地したら即設置完了にする
            context.BuiltRemainingTime[(int)player] = -1;
            context.OperationDirection = Direction.None;
            context = this.Game.Update(context);

            // イベント終了 or ゲーム終了まで更新する
            while (context.FieldEvent[(int)player] != FieldEvent.None && context.FieldEvent[(int)player] != FieldEvent.End)
            {
                context     = this.Game.Update(context);
                param.Chain = Math.Max(param.Chain, context.Chain[player.ToInt()]);
            }
            Debug.Assert(context.FieldEvent[(int)player] == FieldEvent.None || context.FieldEvent[(int)player] == FieldEvent.End, "イベント発生中はありえません");
        }
Beispiel #36
0
        public Label Parse(IEnumerable <Token> tokens)
        {
            var label = new Label();

            FieldContext = new FieldContext(new Font("A", Orientation.Normal, 5, 9));
            foreach (var token in tokens)
            {
                Execute(token, label);
            }
            if (_unSupported.Count <= 0)
            {
                return(label);
            }
            var sb = new StringBuilder();

            foreach (var token in _unSupported.GroupBy(p => p.Command).Select(g => g.First()).ToList())
            {
                sb.Append(token.Command + Environment.NewLine);
            }
            throw new ArgumentException(sb.ToString());
        }
Beispiel #37
0
    public FieldContext field()
    {
        FieldContext _localctx = new FieldContext(Context, State);

        EnterRule(_localctx, 8, RULE_field);
        try {
            EnterOuterAlt(_localctx, 1);
            {
                State = 74; Match(IDENTIFIER);
            }
        }
        catch (RecognitionException re) {
            _localctx.exception = re;
            ErrorHandler.ReportError(this, re);
            ErrorHandler.Recover(this, re);
        }
        finally {
            ExitRule();
        }
        return(_localctx);
    }
        /// <summary>
        /// Creates the appropriate editor from the context. If the return value is null, another
        /// <see cref="IEditorStrategy"/> will be asked. The returned value should be fully configured
        /// and bound.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>
        /// A control that will be used for editing the field, or null if this strategy cannot be
        /// used for this field.
        /// </returns>
        public object CreateEditor(FieldContext context)
        {
            if (!context.PropertyDescriptor.PropertyType.IsEnum)
                return null;

            var enumType = context.PropertyDescriptor.PropertyType;
            var items = new List<EnumOption>();
            foreach (var value in Enum.GetValues(enumType))
            {
                var displayName = enumType.GetField(value.ToString()).GetCustomAttributes(typeof(EnumDisplayNameAttribute), true).OfType<EnumDisplayNameAttribute>().FirstOrDefault();
                var item = new EnumOption();
                item.DisplayName = displayName == null ? value.ToString() : displayName.DisplayName;
                item.Value = value;
                items.Add(item);
            }

            var comboBox = new ComboBox();
            comboBox.SelectedValuePath = "Value";
            comboBox.DisplayMemberPath = "DisplayName";
            comboBox.ItemsSource = items;
            BindingOperations.SetBinding(comboBox, Selector.SelectedValueProperty, context.Binding);
            return comboBox;
        }
Beispiel #39
0
 public DynamicNodeValue(FieldContext _context)
 {
     context = _context;
 }
 public void AddOneContextFromInside(FieldContext fc)
 {
     TryCreateFolderIfNotExist(storagePath);
     WriteJsonFile(fc);
     MetadataStorage.AddOneMetadataFromInside(fc);
 }
 private void WriteJsonFile(FieldContext fc)
 {
     string hashName = CalculateMD5Hash(fc.FieldInfo.FieldName + fc.Document.DocumentId);
     string filePath = storagePath + hashName + ".json";
     VerifyFileExistenceAndRemoveIfExists(filePath);
     using (TextWriter textWriter = File.CreateText(filePath))
     {
         var context = JsonConvert.SerializeObject(fc, Formatting.Indented);
         textWriter.Write(context);
     }
 }
Beispiel #42
0
 public virtual string TransformValue(FieldContext field, StaticNodeValue sv)
 {
     return QuoteStr(sv.Value);
 }
Beispiel #43
0
        protected virtual string RenderField(StringBuilder sb, FieldContext field)
        {
            if(field.Value == null)
                throw new ApplicationException("Field has no value: " + field.Name);

            List<TerminalNodeValue> vals = new List<TerminalNodeValue>(field.Value.Terminals);

            if(vals.Count == 0)
                throw new ApplicationException("Field has no value: " + field.Name);

            if(vals.Count == 1 && vals[0] is StaticNodeValue)
                return TransformValue(field, (StaticNodeValue)vals[0]);

            StringBuilder valStr = new StringBuilder();

            int c = 0;
            foreach(TerminalNodeValue tsv in vals) {
                if(tsv is NullNodeValue)
                    return "NULL";

                else if(field.ObjectClassField.Atts["DataType"] != "string") {
                    if(c > 0)
                        throw new ApplicationException("Cannot have compound values for datatype: " + field.ObjectClassField.Atts["DataType"]);

                    if(tsv is StaticNodeValue) {
                        if(field.ObjectClassField.Atts["DataType"] == "int")
                            valStr.Append(Convert.ToString(Convert.ToInt32(((StaticNodeValue)tsv).Value)));
                        else
                            valStr.Append(QuoteStr(((StaticNodeValue)tsv).Value));
                    }
                    else if(tsv is DynamicNodeValue)
                        valStr.Append("@" + ((DynamicNodeValue)tsv).Context.Name);
                }
                else {
                    if(c++ > 0)
                        valStr.Append(" + ");

                    if(tsv is StaticNodeValue)
                        valStr.Append(QuoteStr(((StaticNodeValue)tsv).Value));
                    else if(tsv is DynamicNodeValue)
                        valStr.AppendFormat("cast(@{0} as varchar)", ((DynamicNodeValue)tsv).Context.Name);
                }
            }

            return valStr.ToString();
        }
 public void AddContext(FieldContext fc)
 {
     TryCreateFolderIfNotExist(storagePath);
     WriteJsonFile(fc);
     MetadataStorage.AddMetadata(fc);
 }
 /// <summary>
 /// Creates a new FieldDeclarationNode.
 /// </summary>
 /// <param name="name">The name of the declared field.</param>
 /// <param name="context">The surrounding context of the field.</param>
 public FieldDeclarationNode(string name, FieldContext context)
     : base(name) {
     this.Context = context;
 }