An object used for storing minions under the control of a specific player
        /// <summary>
        /// Gets the raw string (xml) from the broker db by URL
        /// </summary>
        /// <param name="Url">URL of the page</param>
        /// <returns>String with page xml or empty string if no page was found</returns>
        public string GetContentByUrl(string Url)
        {
            Page page = new Page();
            page.Title = Randomizer.AnyString(15);
            page.Id = Randomizer.AnyUri(64);
            page.Filename = Randomizer.AnySafeString(8) + ".html";

            PageTemplate pt = new PageTemplate();
            pt.Title = Randomizer.AnyString(20);
            Field ptfieldView = new Field();
            ptfieldView.Name = "view";
            ptfieldView.Values.Add("Standard");
            pt.MetadataFields = new FieldSet();
            pt.MetadataFields.Add(ptfieldView.Name, ptfieldView);

            page.PageTemplate = pt;

            Schema schema = new Schema();
            schema.Title = Randomizer.AnyString(10);

            Component component = new Component();
            component.Title = Randomizer.AnyString(30);
            component.Id = Randomizer.AnyUri(16);
            component.Schema = schema;

            Field field1 = Randomizer.AnyTextField(6, 120, true);
            Field field2 = Randomizer.AnyTextField(8, 40, false);

            FieldSet fieldSet = new FieldSet();
            fieldSet.Add(field1.Name, field1);
            fieldSet.Add(field2.Name, field2);
            component.Fields = fieldSet;

            ComponentTemplate ct = new ComponentTemplate();
            ct.Title = Randomizer.AnyString(20);
            Field fieldView = new Field();
            fieldView.Name = "view";
            fieldView.Values.Add("DefaultComponentView");
            ct.MetadataFields = new FieldSet();
            ct.MetadataFields.Add(fieldView.Name, fieldView);

            ComponentPresentation cp = new ComponentPresentation();
            cp.Component = component;
            cp.ComponentTemplate = ct;

            page.ComponentPresentations = new List<ComponentPresentation>();
            page.ComponentPresentations.Add(cp);

            FieldSet metadataFields = new FieldSet();
            page.MetadataFields = metadataFields;

            var serializer = new XmlSerializer(typeof(Page));
            StringBuilder builder = new StringBuilder();
            StringWriter writer = new StringWriter(builder);
            //XmlTextWriter writer = new XmlTextWriter(page.Filename, Encoding.UTF8);
            //serializer.Serialize(writer, page);
            serializer.Serialize(writer, page);
            string pageAsString = builder.ToString();
            return pageAsString;
        }
        /// <summary>
        /// Sets the field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="value">The value.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <exception cref="Glass.Mapper.MapperException">No item with ID {0}. Can not update File Item field.Formatted(newId)</exception>
        public override void SetField(Field field, object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            File file = value as File;

            var item = field.Item;

            FileField fileField = new FileField(field);

            if (file == null)
            {
                fileField.Clear();
                return;
            }

            if (fileField.MediaID.Guid != file.Id)
            {
                if (file.Id == Guid.Empty)
                {
                    ItemLink link = new ItemLink(item.Database.Name, item.ID, fileField.InnerField.ID, fileField.MediaItem.Database.Name, fileField.MediaID, fileField.MediaItem.Paths.FullPath);
                    fileField.RemoveLink(link);
                }
                else
                {
                    ID newId = new ID(file.Id);
                    Item target = item.Database.GetItem(newId);
                    if (target != null)
                    {
                        fileField.MediaID = newId;
                        ItemLink link = new ItemLink(item.Database.Name, item.ID, fileField.InnerField.ID, target.Database.Name, target.ID, target.Paths.FullPath);
                        fileField.UpdateLink(link);
                    }
                    else throw new MapperException("No item with ID {0}. Can not update File Item field".Formatted(newId));
                }
            }
        }
Example #3
0
 public static string FilterDisplayName(Field filter)
 {
     switch (filter)
     {
         case Field.CompanyName:
             return "Company";
         case Field.Date:
             return "Date";
         case Field.EducationCode:
             return "Education Code";
         case Field.FieldOfStudy:
             return "Field of Study";
         case Field.JobTitle:
             return "Job Title";
         case Field.Keyword:
             return "Keyword";
         case Field.Location:
             return "Location";
         case Field.Salary:
             return "Salary";
         case Field.Source:
             return "Source";
         case Field.JobType:
             return "Job Type";
         default:
             return filter.ToString();
     }
 }
Example #4
0
        public FieldWrapper(Field field)
        {
            Sitecore.Diagnostics.Assert.ArgumentNotNull(field, "field");

            _modified = false;
            _field = field;
        }
        protected override void CustomFieldTypeValidation(AssertPair<FieldDefinition, Field> assert, Field spObject, FieldDefinition definition)
        {
            var typedObject = spObject.Context.CastTo<FieldLookup>(spObject);
            var typedDefinition = definition.WithAssertAndCast<LookupFieldDefinition>("model", value => value.RequireNotNull());

            // https://github.com/SubPointSolutions/spmeta2/issues/310
            // AllowMultipleValues - TRUE - LookupMulti
            // AllowMultipleValues - FALSE - Lookup
            assert.ShouldBeEqual((p, s, d) =>
            {
                var srcProp = s.GetExpressionValue(m => m.FieldType);
                var dstProp = d.GetExpressionValue(m => d.TypeAsString);

                var isValid = typedDefinition.AllowMultipleValues
                    ? typedObject.TypeAsString == "LookupMulti"
                    : typedObject.TypeAsString == "Lookup";

                return new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    Dst = dstProp,
                    IsValid = isValid
                };
            });
        }
        public FieldSetup_Rules_Combat(Field d)
            : base(0, 0)
        {
            Handeling = d;

            Closable = true;
            Dragable = true;
            Resizable = false;

            AddBackground(219, 238, 172, 179, 9300);
            AddLabel(245, 244, 70, @"Combat Ability Rules");

            AddCheck(225, 265, 210, 211, Handeling.CombatAbilities, 1);
            AddLabel(255, 265, 54, @"Combat Abilities");
            AddCheck(225, 290, 210, 211, Handeling.Stun, 2);
            AddLabel(255, 290, 54, @"Stun");
            AddCheck(225, 315, 210, 211, Handeling.Disarm, 3);
            AddLabel(255, 315, 54, @"Disarm");
            AddCheck(225, 340, 210, 211, Handeling.ConcussionBlow, 4);
            AddLabel(255, 340, 54, @"Concussion Blow");
            AddCheck(225, 365, 210, 211, Handeling.CrushingBlow, 5);
            AddLabel(255, 365, 54, @"Crushing Blow");
            AddCheck(225, 390, 210, 211, Handeling.ParalyzingBlow, 6);
            AddLabel(255, 390, 54, @"Paralyzing Blow");
        }
        private void CustomizeCompomentForKeywordField(Component component)
        {
            component.Schema.RootElementName = "hasKeyword";
            Field headingField = new Field() { Name = "heading", Values = new List<string> { "some heading" } };

            FieldSet metadataFields = new FieldSet();
            metadataFields.Add(headingField.Name, headingField);


            Field keywordField = new Field()
            {
                Name = "keyword",
                KeywordValues = new List<Keyword>() 
                {
                    new Keyword()
                    {
                        MetadataFields = metadataFields,
                        Id = Randomizer.AnyUri(1024),
                        Title = Randomizer.AnyString(33),
                        Description = Randomizer.AnyString(33)
                    }                        
                }
            };
            component.Fields.Add(keywordField.Name, keywordField);
        }
 internal TextRegion(int start, Field field)
     : this()
 {
     this.Field = field;
     this.Start = start;
     this.Length = field.PlaceholderText.Length;
 }
Example #9
0
        public override bool VisitFieldDecl(Field field)
        {
            if (!VisitDeclaration(field))
                return false;

            var type = field.Type;

            Declaration decl;
            type.TryGetDeclaration(out decl);
            string msg = "internal";
            if (decl == null || (decl.GenerationKind != GenerationKind.Internal && !HasInvalidType(type, out msg)))
                return false;

            field.GenerationKind = GenerationKind.Internal;

            var @class = (Class)field.Namespace;

            var cppTypePrinter = new CppTypePrinter();
            var typeName = type.Visit(cppTypePrinter);

            Log.Debug("Field '{0}::{1}' was ignored due to {2} type '{3}'",
                @class.Name, field.Name, msg, typeName);

            return true;
        }
		public FieldSetup_Pending(Field d) : base(0, 0)
		{
            Handeling = d;

			Closable = false;
			Dragable = true;
			Resizable = false;

            int bh = (PlayerCount() * 38);
			AddBackground( 212, 177, 251, bh, 9250 );
			AddBackground( 219, 185, 235, (bh - 15), 9350 );

            int y = 190;
            IEnumerator key = Handeling.Teams.Keys.GetEnumerator();
            for (int i = 0; i < Handeling.Teams.Count; ++i)
            {
                key.MoveNext();
                Field_Team d_team = (Field_Team)Handeling.Teams[(int)key.Current];

                for (int i2 = 0; i2 < d_team.Players.Count; ++i2)
                {
                    object o = (object)d_team.Players[i2];
                    if (o is PlayerMobile)
                    {
                        PlayerMobile pm = (PlayerMobile)o;
                        AddLabel(250, y, 0, String.Format("{0}", pm.Name));
                        AddImage(225, y, ImageID((bool)d_team.Accepted[pm]));
                        y += 30;
                    }
                }
            }
		}
 /// <summary>
 /// Gets the nearest set ancestor that has the field with a value
 /// </summary>
 /// <param name="field">The field.</param>
 /// <returns></returns>
 private Item GetFallbackItem(Field field)
 {
     using (new SecurityDisabler())
     {
         return field.Item.Axes.GetAncestors().Where(ancestor => DoesItemHaveFieldWithValue(ancestor, field.ID, true)).LastOrDefault();
     }
 }
Example #12
0
    public MenuInGame(FSM parentFsm, UIManager2 panel1, UIManager2 panel2)
        : base(parentFsm, panel1, panel2, "MenuInGame.fsm")
    {
        timeClient = TimeManager.Instance.Create();

        InitUI();

        int stageId = (int)parentFsm.Variables["stageId"];

        /*
        // ddong
        if (stageId < 2000)
        {
            stageId += 2000;
        }
        */

        InitStage(stageId, out stageEntity, out gameEntity);

        Rect fieldArea = UI.GetFieldArea();
        field = CreateField(stageEntity, fieldArea, timeClient, fsm);

        // ddong
        int subClassCode = 11;
        int level = 1;
        int trainLevel = 1;

        this.subClassEntity = TableLoader.GetTable<SubClassEntity>().Get(subClassCode);
        ClassLevelEntity levelEntity = TableLoader.GetTable<ClassLevelEntity>().Get(subClassEntity.classCode, level);
        TrainLevelEntity trainLevelEntity = TableLoader.GetTable<TrainLevelEntity>().Get(subClassEntity.classCode, trainLevel);
        FieldObjectEntity objectField = TableLoader.GetTable<FieldObjectEntity>().Get(subClassEntity.objectCode);

        Rect puzzleArea = UI.GetPuzzleArea();
        CreatePuzzle(puzzleArea, timeClient, subClassCode, out puzzleRecord, out puzzlePanel);

        user = CreateUser(stageEntity, UI, fsm);
        heroCharacter = CreateCharacter(objectField, levelEntity, trainLevelEntity, subClassEntity, user, puzzlePanel, itemDropManager, UI.AddBuffIcon, UI.RemoveBuffIcon, fsm);
        itemDropManager = new ConsumableSpawn(stageEntity.gameModeCode, levelEntity.consumableTier);

        Func<float> getLifeDrainRate = (() => gameEntity.defaultHP);
        new PlayerCharacter(user, heroCharacter, getLifeDrainRate, fsm);
        /*
        heroCharacter.Status.RegisterOnChangeEvent(HeroCharacter.Character.HP, OnCharacterHPChanged);
        heroCharacter.Status.RegisterOnChangeEvent(HeroCharacter.Character.HP, UI.ChangeHP);
        heroCharacter.Status.RegisterOnChangeEvent(HeroCharacter.Character.MP, UI.ChangeMana);
        heroCharacter.Status.RegisterOnChangeEvent(HeroCharacter.Character.Armor, UI.ChangeShield);
        */

        UI.InitCommendSlots(fsm, heroCharacter);

        field.AddPlayerCharacter(heroCharacter);
        field.FocusOnForced(heroCharacter, 0);
        puzzlePanel.SetQueue(user.commandQueue);

        var screenPosTable = TableLoader.GetTable<ScreenPositionEntity2>();
        var hpToPos = screenPosTable.Values.Select(x => new KeyValuePair<float, float>(x.hp, x.screenPos));
        convertHPRatioToScreenPos = new RangeConvertor(hpToPos).Convert;

        SetFocusTarget(heroCharacter);
    }
        public Fields Read(AbstractConnection connection, string process, string prefix, string name, string schema, bool isMaster = false) {
            var fields = new Fields();

            using (var cn = connection.GetConnection()) {
                cn.Open();
                var sql = PrepareSql();
                connection.Logger.EntityDebug(name, sql);

                var results = cn.Query(sql, new { name, schema });

                foreach (var result in results) {
                    var columnName = result.COLUMN_NAME;
                    var type = GetSystemType(result.DATA_TYPE);
                    var length = result.CHARACTER_MAXIMUM_LENGTH == "0" || result.CHARACTER_MAXIMUM_LENGTH == "-1" ? "64" : result.CHARACTER_MAXIMUM_LENGTH;
                    var fieldType = (bool)result.IS_PRIMARY_KEY ? (isMaster ? FieldType.MasterKey : FieldType.PrimaryKey) : FieldType.NonKey;
                    var field = new Field(type, length, fieldType, true, string.Empty) {
                        Name = columnName,
                        Entity = name,
                        Process = process,
                        Index = Convert.ToInt16(result.ORDINAL_POSITION - 1),
                        Schema = schema,
                        Input = true,
                        Precision = result.NUMERIC_PRECISION,
                        Scale = result.NUMERIC_SCALE,
                        Alias = prefix + columnName
                    };
                    fields.Add(field);
                }
            }

            return fields;
        }
Example #14
0
        private object[] ConvertArguments(MethodInfo methodInfo, IRequest request, Field[] args)
        {
            var methodParams = methodInfo.GetParameters();

            if (methodParams.Length != args.Length)
                throw new InvalidOperationException();		// TODO: support the case of the Unbounded parameters

            var values = new object[args.Length];
            for (int i = 0; i < args.Length; i++) {
                var paramType = methodParams[i].ParameterType;
                if ((paramType == typeof (ISession) ||
                    paramType == typeof(IRequest) ||
                    paramType == typeof(IQuery)) &&
                    i > 0)
                        throw new InvalidOperationException("The request parameter must be the first in method signature.");

                object arg;

                if (paramType == typeof (ISession)) {
                    arg = request.Query.Session;
                } else if (paramType == typeof (IQuery)) {
                    arg = request.Query;
                } else if (paramType == typeof(IRequest)) {
                    arg = request.CreateBlock();
                } else {
                    var sqlType = PrimitiveTypes.FromType(paramType);
                    arg = sqlType.ConvertTo(args[i].Value, paramType);
                }

                values[i] = arg;
            }

            return values;
        }
		private void Draw(Field field, FileInfo file)
		{
			var xMax = 10;
			var yMax = field.RowCount;

			var image = new Bitmap(xMax * BlockSize, yMax * BlockSize);

			for (var y = 0; y < yMax; y++)
			{
				var row = field[y];

				for (var x = 0; x < xMax; x++)
				{
					if ((Row.Flag[x] & row) != 0)
					{
						DrawPixel(image, x, y, Color.Red);
					}
					else
					{
						DrawPixel(image, x, y, Color.White);
					}
				}
			}
			image.Save(file.FullName, ImageFormat.Png);
		}
Example #16
0
 public void TestLevel2Description()
 {
     var field = new Field(2, 5, 2, 1);
     Assert.That(field.GetSequence(), Is.EqualTo(new[] {6, 7, 8, 9, 10, 5, 4, 3, 2, 1}));
     field = new Field(5, 2, 5, 2);
     Assert.That(field.GetSequence(), Is.EqualTo(new[] {10, 9, 7, 8, 6, 5, 3, 4, 2, 1}));
 }
Example #17
0
 public void TestLevel3Description()
 {
     var field = new Field(3, 4, 1, 1, 'S');
     Assert.That(field.GetSequence(), Is.EqualTo(new[] {1, 5, 9, 10, 6, 2, 3, 7, 11, 12, 8, 4}));
     field = new Field(5, 2, 5, 2, 'N');
     Assert.That(field.GetSequence(), Is.EqualTo(new[] {10, 8, 6, 4, 2, 1, 3, 5, 7, 9}));
 }
Example #18
0
        public void Test_CanMoveLeft_WhenAtTheLeftEdge_ReturnsFalse()
        {
            Field subject = new Field(10, 10);
            subject.SetBlock(new BlockHelper.MockBlock(2, 1), new Vector2(0, 5));

            Assert.That(subject.CanMoveLeft(), Is.False);
        }
Example #19
0
        public int TransformCell(Field pastF, int x, int y)
        {
            int centerCell = pastF.GetCell(x, y);
            // Possible check for -1 value of cell in case of addition all cell's neighbors to array
            //int[] Neighbors = f.GetNeighborsInAllDirections(x, y);
            int northWestCell = pastF.GetCellAtDirection(x, y, Directions.NorthWest);
            int northEastCell = pastF.GetCellAtDirection(x, y, Directions.NorthEast);
            int northCell = pastF.GetCellAtDirection(x, y, Directions.North);
            int southWestCell = pastF.GetCellAtDirection(x, y, Directions.SouthWest);
            int southEastCell = pastF.GetCellAtDirection(x, y, Directions.SouthEast);
            int southCell = pastF.GetCellAtDirection(x, y, Directions.South);
            int westCell = pastF.GetCellAtDirection(x, y, Directions.West);
            int eastCell = pastF.GetCellAtDirection(x, y, Directions.East);

            int[] Neighbors = { northWestCell, northCell, northEastCell, eastCell, southEastCell, southCell, southWestCell, westCell };
            for (int i = 0; i < Neighbors.Length; i++)
            {
                if (Neighbors[i] < 0)
                    Neighbors[i] = 0;
            }

            if (centerCell == 0)
                return 2 * ((northWestCell % 2) ^ (northEastCell % 2)) + northCell % 2;
            else if (centerCell == 1)
                return 2 * ((northWestCell % 2) ^ (southWestCell % 2)) + westCell % 2;
            else if (centerCell == 2)
                return 2 * ((southWestCell % 2) ^ (southEastCell % 2)) + southCell % 2;
            else
                return 2 * ((southEastCell % 2) ^ (northEastCell % 2)) + eastCell % 2;
        }
        public FileInformation Read(FileInfo fileInfo) {

            var fileInformation = new FileInformation(fileInfo);
            var names = new List<string>();

            var stream = System.IO.File.Open(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            var isXml = fileInfo.Extension.Equals(".xlsx", StringComparison.OrdinalIgnoreCase);

            var excelReader = isXml ? ExcelReaderFactory.CreateOpenXmlReader(stream) : ExcelReaderFactory.CreateBinaryReader(stream);
            excelReader.Read();
            for (var i = 0; i < excelReader.FieldCount; i++) {
                var name = excelReader.GetString(i);
                if (name != null)
                    names.Add(name);
            }

            excelReader.Close();
            foreach (var name in names) {
                var field = new Field("string", _request.DefaultLength, FieldType.NonKey, true, string.Empty) {
                    Name = name
                };
                fileInformation.Fields.Add(field);
            }

            return fileInformation;
        }
 public string GetMarketData(string bland, Field field)
 {
     if (!m_marketData.ContainsKey(bland) || !m_marketData[bland].ContainsKey(field))
         return bland + " is now loading.";
     else
         return m_marketData[bland][field];
 }
		public Field[] GetMoves(Field field, bool IsRed)
		{
			var moves = new Field[7];

			var occupied = field.Occupied;

			for (var col = 0; col < 7; col++)
			{
				var test = (occupied >> col) & RowMask;
				var row = 0;

				switch (test)
				{
					case 0x000000000000: break;
					case 0x000000000001: row = 1; break;
					case 0x000000000101: row = 2; break;
					case 0x000000010101: row = 3; break;
					case 0x000001010101: row = 4; break;
					case 0x000101010101: row = 5; break;
					case 0x010101010101: row = 6; break;
					default: break;
				}
				if (row != 6)
				{
					var move = 1UL << ((row << 3) | col);
					moves[col] = IsRed ? field.MoveRed(move) : field.MoveYellow(move);
				}
			}
			return moves;
		}
        /// <summary>
        /// Gets the raw string (xml) from the broker db by URL
        /// </summary>
        /// <param name="Url">URL of the page</param>
        /// <returns>String with page xml or empty string if no page was found</returns>
        public string GetContentByUrl(string Url)
        {
            Page page = new Page();
            page.Title = Randomizer.AnyString(15);
            page.Id = Randomizer.AnyUri(64);
            page.Filename = Randomizer.AnySafeString(8) + ".html";

            PageTemplate pt = new PageTemplate();
            pt.Title = Randomizer.AnyString(20);
            Field ptfieldView = new Field();
            ptfieldView.Name = "view";
            ptfieldView.Values.Add("Standard");
            pt.MetadataFields = new FieldSet();
            pt.MetadataFields.Add(ptfieldView.Name, ptfieldView);

            page.PageTemplate = pt;

            page.ComponentPresentations = new List<ComponentPresentation>();

            string cpString = ComponentPresentationProvider.GetContent("");
            page.ComponentPresentations.Add(SerializerService.Deserialize<ComponentPresentation>(cpString));

            FieldSet metadataFields = new FieldSet();
            page.MetadataFields = metadataFields;

            return SerializerService.Serialize<Page>(page);
        }
Example #24
0
 public void BadBlockPlacementTest( int x, int y )
 {
     Field field = new Field( 2, 10 );
     IBlock block = new Block();
     block.Grid [ 2 ] [ 2 ] = Color.Tomato;
     field.SetBlock( block, new Point( x, y ) );
 }
Example #25
0
 public PartialViewResult GetFilterView(Field targetField, string filterString)
 {
     FilterBag fb = FilterBag.createFromURLQuery(Request.QueryString.ToString());
     ViewBag.FilterString = fb.JsonEncode();
     ViewBag.inputID = Guid.NewGuid();
     return PartialView("_FilterEditPartial", targetField);
 }
 public HttpResponseMessage Post(HttpRequestMessage request, CreateFieldCommand command)
 {
     var repository = new FieldRepository();
     var field = new Field(command.Name, command.Description, command.DataType, command.FieldType);
     repository.AddField(field);
     return request.CreateResponse(HttpStatusCode.Created, new FieldViewModel(field));
 }
Example #27
0
 public void BadBigBlockPlacementTest( int x, int y )
 {
     Field field = new Field( 5, 10 );
     IBlock block = new Block();
     createBigBlock( block );
     field.SetBlock( block, new Point( x, y ) );
 }
Example #28
0
        private object GetField(Field field)
        {
            if (_fields.ContainsKey(field))
                return _fields[field];

            return null;
        }
Example #29
0
 public Batch(int id, double amountOfFruit, string team, double sellAbleAmount, Field field)
 {
     Id = id;
     AmountOfFruit = amountOfFruit;
     SellAbleAmount = sellAbleAmount;
     Field = field;
 }
 public FieldViewModel(Field field)
 {
     Name = field.Name;
     Description = field.Description;
     DataType = field.DataType;
     FieldType = field.FieldType;
 }
        public virtual void TestEmptyIndexWithVectors()
        {
            Directory rd1 = NewDirectory();
            {
                if (VERBOSE)
                {
                    Console.WriteLine("\nTEST: make 1st writer");
                }
                IndexWriter iw      = new IndexWriter(rd1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
                Document    doc     = new Document();
                Field       idField = NewTextField("id", "", Field.Store.NO);
                doc.Add(idField);
                FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
                customType.StoreTermVectors = true;
                doc.Add(NewField("test", "", customType));
                idField.StringValue = "1";
                iw.AddDocument(doc);
                doc.Add(NewTextField("test", "", Field.Store.NO));
                idField.StringValue = "2";
                iw.AddDocument(doc);
                iw.Dispose();

                IndexWriterConfig dontMergeConfig = (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))).SetMergePolicy(NoMergePolicy.COMPOUND_FILES);
                if (VERBOSE)
                {
                    Console.WriteLine("\nTEST: make 2nd writer");
                }
                IndexWriter writer = new IndexWriter(rd1, dontMergeConfig);

                writer.DeleteDocuments(new Term("id", "1"));
                writer.Dispose();
                IndexReader ir = DirectoryReader.Open(rd1);
                Assert.AreEqual(2, ir.MaxDoc);
                Assert.AreEqual(1, ir.NumDocs);
                ir.Dispose();

                iw = new IndexWriter(rd1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode_e.APPEND));
                iw.ForceMerge(1);
                iw.Dispose();
            }

            Directory rd2 = NewDirectory();
            {
                IndexWriter iw  = new IndexWriter(rd2, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
                Document    doc = new Document();
                iw.AddDocument(doc);
                iw.Dispose();
            }

            Directory rdOut = NewDirectory();

            IndexWriter          iwOut = new IndexWriter(rdOut, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
            DirectoryReader      reader1, reader2;
            ParallelAtomicReader pr = new ParallelAtomicReader(SlowCompositeReaderWrapper.Wrap(reader1 = DirectoryReader.Open(rd1)), SlowCompositeReaderWrapper.Wrap(reader2 = DirectoryReader.Open(rd2)));

            // When unpatched, Lucene crashes here with an ArrayIndexOutOfBoundsException (caused by TermVectorsWriter)
            iwOut.AddIndexes(pr);

            // ParallelReader closes any IndexReader you added to it:
            pr.Dispose();

            // assert subreaders were closed
            Assert.AreEqual(0, reader1.RefCount);
            Assert.AreEqual(0, reader2.RefCount);

            rd1.Dispose();
            rd2.Dispose();

            iwOut.ForceMerge(1);
            iwOut.Dispose();

            rdOut.Dispose();
        }
Example #32
0
 public abstract void Apply(
     Field field
     );
 public abstract void MigrateField(Field field);
 /// <summary>
 /// Initializes an instance of <see cref="NullExecutionNode"/> with the specified values.
 /// </summary>
 public NullExecutionNode(ExecutionNode parent, IGraphType graphType, Field field, FieldType fieldDefinition, int?indexInParentNode)
     : base(parent, graphType, field, fieldDefinition, indexInParentNode)
 {
     Result = null;
 }
 public NameValueListFieldWrapper(Field originalField)
     : base(originalField)
 {
 }
Example #36
0
 internal CachedCell(CellKey key, Field value)
 {
     Key   = key;
     Value = value;
 }
        internal static Dictionary <string, Field> ParseReplaceFields(string fileNameFormat, Row row, Field target)
        {
            if (fileNameFormat.IndexOf('|') < 0)
            {
                return(null);
            }

            var replaceFields = new Dictionary <string, Field>();

            int start = 0;

            while ((start = fileNameFormat.IndexOf('|', start)) >= 0)
            {
                var end = fileNameFormat.IndexOf('|', start + 1);
                if (end <= start + 1)
                {
                    throw new ArgumentException(String.Format(
                                                    "Field '{0}' on row type '{1}' has a UploadEditor attribute " +
                                                    "with invalid format string '{2}'!",
                                                    target.PropertyName ?? target.Name,
                                                    row.GetType().FullName,
                                                    fileNameFormat));
                }

                var fieldName  = fileNameFormat.Substring(start + 1, end - start - 1);
                var actualName = fieldName;
                var colon      = fieldName.IndexOf(":");
                if (colon >= 0)
                {
                    actualName = fieldName.Substring(0, colon);
                }

                var replaceField = row.FindFieldByPropertyName(actualName) ??
                                   row.FindField(actualName);

                if (ReferenceEquals(null, replaceField))
                {
                    throw new ArgumentException(String.Format(
                                                    "Field '{0}' on row type '{1}' has a UploadEditor attribute that " +
                                                    "references field '{2}', but no such field is found!'",
                                                    target.PropertyName ?? target.Name,
                                                    row.GetType().FullName,
                                                    actualName));
                }

                replaceFields['|' + fieldName + '|'] = replaceField;

                start = end + 1;
            }

            return(replaceFields);
        }
Example #38
0
        /// <summary>
        /// This generate function do same work as of reportProcessor generate function. But it is different from that generate function, as it will also used to generate multiline report, when taking values from purchase.
        /// </summary>
        /// <param name="field"></param>
        /// <param name="reportName"></param>
        /// <param name="saveFileName"></param>
        public void GenerateReport(Field field, string reportName, string saveFileName)
        {
            string     documentName = System.IO.Path.GetFileName(System.IO.Path.GetDirectoryName(reportName));
            FileStream fileStream   = new FileStream(reportName, FileMode.Open, FileAccess.Read);
            IWorkbook  workbook     = null;
            string     extension    = Utility.GetExtension(reportName);

            if (extension == ".xlsx")
            {
                workbook = new XSSFWorkbook(fileStream);
            }
            else if (extension == ".xls")
            {
                throw new DAOException(extension + " files are not supported. Please change them to .xlsx file format. \n Thanks");
            }
            else
            {
                throw new DAOException("File format " + extension + " not supported.");
            }
            ISheet sheet = null;

            if (sheet == null)
            {
                sheet = workbook.GetSheet("Invoice");
            }
            IRow  currRow;
            ICell cell;

            for (int i = 0, rowNum = 20; i < purchases.Count; i++)
            {
                Purchase p = purchases[i];
                currRow = sheet.GetRow(rowNum);
                cell    = currRow.GetCell(0);
                //SetValue(cell, "1", field);
                cell.SetCellValue(p.SNo);

                string[] strs = p.description.Split('\n');
                for (int j = 0; j < strs.Length; j++)
                {
                    currRow = sheet.GetRow(rowNum + j);
                    cell    = currRow.GetCell(1);
                    cell.SetCellValue(strs[j]);
                }

                currRow = sheet.GetRow(rowNum);
                cell    = currRow.GetCell(6);
                cell.SetCellValue(p.quantity);

                currRow = sheet.GetRow(rowNum);
                cell    = currRow.GetCell(8);
                cell.SetCellValue(p.amount);
                int count = p.description.Count(s => s == '\n') + 1;
                rowNum += count;
            }
            currRow = sheet.GetRow(40);
            cell    = currRow.GetCell(0);
            cell.SetCellValue(txtGSTAmountInWords.Text);

            currRow = sheet.GetRow(42);
            cell    = currRow.GetCell(0);
            cell.SetCellValue(txtTotalAmountInWords.Text);

            currRow = sheet.GetRow(38);
            cell    = currRow.GetCell(8);
            cell.SetCellValue(txtTotalAmount.Text);

            currRow = sheet.GetRow(39);
            cell    = currRow.GetCell(8);
            cell.SetCellValue(txtCGST.Text);

            currRow = sheet.GetRow(40);
            cell    = currRow.GetCell(8);
            cell.SetCellValue(txtSGST.Text);

            currRow = sheet.GetRow(41);
            cell    = currRow.GetCell(8);
            cell.SetCellValue(txtIGST.Text);

            currRow = sheet.GetRow(42);
            cell    = currRow.GetCell(8);
            cell.SetCellValue(txtGrandTotal.Text);

            OleDbConnection connection = DatabaseConnection.GetConnection();

            connection.Open();
            OleDbCommand command = new OleDbCommand("select * from qryDocumentFields where doctype_name=@DOCUMENT", connection);

            //Trace.WriteLine("Document Name " + documentName);
            command.Parameters.AddWithValue("@DOCUMENT", documentName);
            OleDbDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                if (sheet == null)
                {
                    sheet = workbook.GetSheet(reader["field_sheet"].ToString());
                }
                currRow = sheet.GetRow(int.Parse(reader["field_row"].ToString()) - 1);
                cell    = currRow.GetCell(int.Parse(reader["field_column"].ToString()) - 1);
                //Trace.WriteLine("Field Name "+reader["field_name"]);
                SetValue(cell, reader["field_name"].ToString(), field);
            }


            using (var fileData = new FileStream(saveFileName, FileMode.Create))
            {
                workbook.Write(fileData);
                workbook.Close();
            }
        }
Example #39
0
 internal override void RenderField(Field field, PropertyInfo property, object host, PaperContext ctx)
 {
     field.AddRequired(Required);
 }
Example #40
0
 public void SetValue(ICell cell, string fieldName, Field field)
 {
     if (fieldName.Equals("Ref No"))
     {
         cell.SetCellValue(field.refNo);
     }
     if (fieldName.Equals("Date"))
     {
         cell.SetCellValue(field.date);
     }
     if (fieldName.Equals("Company Name"))
     {
         cell.SetCellValue(field.companyName);
     }
     if (fieldName.Equals("Address 1"))
     {
         cell.SetCellValue(field.address1);
     }
     if (fieldName.Equals("Address 2"))
     {
         cell.SetCellValue(field.address2);
     }
     if (fieldName.Equals("Address 3"))
     {
         cell.SetCellValue(field.address3);
     }
     if (fieldName.Equals("City"))
     {
         cell.SetCellValue(field.city);
     }
     if (fieldName.Equals("Pincode"))
     {
         cell.SetCellValue(field.pincode);
     }
     if (fieldName.Equals("Address Block"))
     {
         cell.SetCellValue(field.address1 + "\n" + field.address2 + "," + field.address3 + "\n" + field.city + " - " + field.pincode + "\n" + field.state);
     }
     if (fieldName.Equals("Phone"))
     {
         cell.SetCellValue(field.phone);
     }
     if (fieldName.Equals("State"))
     {
         cell.SetCellValue(field.state);
     }
     if (fieldName.Equals("Contact Name"))
     {
         cell.SetCellValue(field.contactName);
     }
     if (fieldName.Equals("Contact Phone"))
     {
         cell.SetCellValue(field.contactPhone);
     }
     if (fieldName.Equals("Contact Email"))
     {
         cell.SetCellValue(field.contactEmail);
     }
     if (fieldName.Equals("State Code"))
     {
         cell.SetCellValue(field.stateCode);
     }
     if (fieldName.Equals("GST No"))
     {
         cell.SetCellValue(field.gstNo);
     }
     if (fieldName.Equals("Country"))
     {
         cell.SetCellValue(field.country);
     }
     if (fieldName.Equals("Service Invoice No"))
     {
         cell.SetCellValue(field.serviceInvoiceNo);
         string serviceNo           = field.serviceInvoiceNo;
         string newServiceInvoiceNo = Utility.IncreaseStringByOne(serviceNo);
         mainWindow.txtServiceInvoiceNo.Text = newServiceInvoiceNo;
         mainWindow.UpdateSettingsTable();
         field.serviceInvoiceNo = newServiceInvoiceNo;
     }
     if (field.Equals("Tax Invoice No"))
     {
         cell.SetCellValue(field.taxInvoiceNo);
         string taxInvoiceNo    = field.taxInvoiceNo;
         string newTaxInvoiceNo = Utility.IncreaseStringByOne(taxInvoiceNo);
         mainWindow.txtTaxInvoiceNo.Text = newTaxInvoiceNo;
         mainWindow.UpdateSettingsTable();
         field.taxInvoiceNo = newTaxInvoiceNo;
     }
 }
Example #41
0
        /// <summary>
        /// Inserts field value into item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="field">The field.</param>
        /// <param name="creatingNewItem">Whether the item under update is new or not (controls logging verbosity)</param>
        /// <exception cref="T:Sitecore.Data.Serialization.Exceptions.FieldIsMissingFromTemplateException"/>
        protected virtual bool PasteField(Item item, IItemFieldValue field, bool creatingNewItem)
        {
            if (!_fieldFilter.Includes(field.FieldId))
            {
                _logger.SkippedPastingIgnoredField(item, field);
                return(false);
            }

            Template template = AssertTemplate(item.Database, item.TemplateID, item.Paths.Path);

            if (template.GetField(new ID(field.FieldId)) == null)
            {
                item.Database.Engines.TemplateEngine.Reset();
                template = AssertTemplate(item.Database, item.TemplateID, item.Paths.Path);
            }

            if (template.GetField(new ID(field.FieldId)) == null)
            {
                throw new TemplateMissingFieldException(item.TemplateName, item.Database.Name + ":" + item.Paths.FullPath, field);
            }

            Field itemField = item.Fields[new ID(field.FieldId)];

            if (itemField.IsBlobField)
            {
                Guid existingBlobId;
                bool hasExistingId = Guid.TryParse(itemField.Value, out existingBlobId);

                // serialized blob has no value (media item with detached media)
                if (!field.BlobId.HasValue)
                {
                    if (!hasExistingId || existingBlobId == Guid.Empty)
                    {
                        return(false);                                                                    // no blob ID and none in DB either, so we're cool
                    }
                    // existing blob in DB but none in serialized
                    // so clear the blob and field value
                    ItemManager.RemoveBlobStream(existingBlobId, item.Database);
                    itemField.SetValue(string.Empty, true);
                    _logger.WroteBlobStream(item, field);

                    return(true);
                }

                // check if existing blob is here with the same ID; abort if so
                if (hasExistingId && existingBlobId == field.BlobId.Value)
                {
                    return(false);
                }

                byte[] buffer = Convert.FromBase64String(field.Value);

                // if an existing blob of a different ID exists, drop it from the database
                if (existingBlobId != default(Guid))
                {
                    ItemManager.RemoveBlobStream(existingBlobId, item.Database);
                }

                // write the new blob to the database
                ItemManager.SetBlobStream(new MemoryStream(buffer, false), field.BlobId.Value, item.Database);

                // set the value of the blob field to the correct blob ID
                itemField.SetValue(MainUtil.GuidToString(field.BlobId.Value), true);

                if (!creatingNewItem)
                {
                    _logger.WroteBlobStream(item, field);
                }

                return(true);
            }

            if (field.Value != null && !field.Value.Equals(itemField.GetValue(false, false)))
            {
                var oldValue = itemField.Value;
                itemField.SetValue(field.Value, true);

                if (!creatingNewItem)
                {
                    _logger.UpdatedChangedFieldValue(item, field, oldValue);
                }

                return(true);
            }

            return(false);
        }
Example #42
0
        public static Index CreateTestIndex()
        {
            string indexName = SearchTestUtilities.GenerateName();

            var index = new Index()
            {
                Name   = indexName,
                Fields = new[]
                {
                    Field.New("hotelId", DataType.String, isKey: true, isSearchable: false, isFilterable: true, isSortable: true, isFacetable: true),
                    Field.New("hotelName", DataType.String, isSearchable: true, isFilterable: true, isSortable: true, isFacetable: false),
                    Field.NewSearchableString("description", AnalyzerName.EnLucene, isKey: false, isFilterable: false, isSortable: false, isFacetable: false),
                    Field.NewSearchableString("descriptionFr", AnalyzerName.FrLucene, isFilterable: false, isSortable: false, isFacetable: false),
                    Field.New("description_custom", DataType.String, isSearchable: true, isFilterable: false, isSortable: false, isFacetable: false, searchAnalyzerName: AnalyzerName.Stop, indexAnalyzerName: AnalyzerName.Stop),
                    Field.New("category", DataType.String, isSearchable: true, isFilterable: true, isSortable: true, isFacetable: true),
                    Field.New("tags", DataType.Collection(DataType.String), isSearchable: true, isFilterable: true, isSortable: false, isFacetable: true),
                    Field.New("parkingIncluded", DataType.Boolean, isFilterable: true, isSortable: true, isFacetable: true),
                    Field.New("smokingAllowed", DataType.Boolean, isFilterable: true, isSortable: true, isFacetable: true),
                    Field.New("lastRenovationDate", DataType.DateTimeOffset, isFilterable: true, isSortable: true, isFacetable: true),
                    Field.New("rating", DataType.Int32, isFilterable: true, isSortable: true, isFacetable: true),
                    Field.NewComplex("address", isCollection: false, fields: new[]
                    {
                        Field.New("streetAddress", DataType.String, isSearchable: true),
                        Field.New("city", DataType.String, isSearchable: true, isFilterable: true, isSortable: true, isFacetable: true),
                        Field.New("stateProvince", DataType.String, isSearchable: true, isFilterable: true, isSortable: true, isFacetable: true),
                        Field.New("country", DataType.String, isSearchable: true, isFilterable: true, isSortable: true, isFacetable: true),
                        Field.New("postalCode", DataType.String, isSearchable: true, isFilterable: true, isSortable: true, isFacetable: true)
                    }),
                    Field.New("location", DataType.GeographyPoint, isFilterable: true, isSortable: true, isFacetable: false, isRetrievable: true),
                    Field.NewComplex("rooms", isCollection: true, fields: new[]
                    {
                        Field.NewSearchableString("description", AnalyzerName.EnLucene),
                        Field.NewSearchableString("descriptionFr", AnalyzerName.FrLucene),
                        Field.New("type", DataType.String, isSearchable: true, isFilterable: true, isFacetable: true),
                        Field.New("baseRate", DataType.Double, isKey: false, isSearchable: false, isFilterable: true, isFacetable: true),
                        Field.New("bedOptions", DataType.String, isSearchable: true, isFilterable: true, isFacetable: true),
                        Field.New("sleepsCount", DataType.Int32, isFilterable: true, isFacetable: true),
                        Field.New("smokingAllowed", DataType.Boolean, isFilterable: true, isFacetable: true),
                        Field.New("tags", DataType.Collection(DataType.String), isSearchable: true, isFilterable: true, isSortable: false, isFacetable: true)
                    }),
                    Field.New("totalGuests", DataType.Int64, isFilterable: true, isSortable: true, isFacetable: true, isRetrievable: false),
                    Field.New("profitMargin", DataType.Double)
                },
                ScoringProfiles = new[]
                {
                    new ScoringProfile("MyProfile")
                    {
                        FunctionAggregation = ScoringFunctionAggregation.Average,
                        Functions           = new ScoringFunction[]
                        {
                            new MagnitudeScoringFunction(
                                "rating",
                                boost: 2.0,
                                boostingRangeStart: 1,
                                boostingRangeEnd: 4,
                                shouldBoostBeyondRangeByConstant: true,
                                interpolation: ScoringFunctionInterpolation.Constant),
                            new DistanceScoringFunction(
                                "location",
                                boost: 1.5,
                                referencePointParameter: "loc",
                                boostingDistance: 5,
                                interpolation: ScoringFunctionInterpolation.Linear),
                            new FreshnessScoringFunction(
                                "lastRenovationDate",
                                boost: 1.1,
                                boostingDuration: TimeSpan.FromDays(365),   //aka.ms/sre-codescan/disable
                                interpolation: ScoringFunctionInterpolation.Logarithmic)
                        },
                        TextWeights = new TextWeights()
                        {
                            Weights = new Dictionary <string, double>()
                            {
                                { "description", 1.5 }, { "category", 2.0 }
                            }
                        }
                    },
                    new ScoringProfile("ProfileTwo")
                    {
                        FunctionAggregation = ScoringFunctionAggregation.Maximum,
                        Functions           = new[]
                        {
                            new TagScoringFunction(
                                "tags",
                                boost: 1.5,
                                tagsParameter: "mytags",
                                interpolation: ScoringFunctionInterpolation.Linear)
                        }
                    },
                    new ScoringProfile("ProfileThree")
                    {
                        FunctionAggregation = ScoringFunctionAggregation.Minimum,
                        Functions           = new[]
                        {
                            // Set ShouldBoostBeyondRangeByConstant explicitly to false. The API returns the default (false) if you pass in null, so we
                            // need to do this to ensure that comparisons work after round trips.
                            new MagnitudeScoringFunction("rating", 3.0, new MagnitudeScoringParameters(0, 10)
                            {
                                ShouldBoostBeyondRangeByConstant = false
                            })
                            {
                                Interpolation = ScoringFunctionInterpolation.Quadratic
                            }
                        }
                    },
                    new ScoringProfile("ProfileFour")
                    {
                        FunctionAggregation = ScoringFunctionAggregation.FirstMatching,
                        Functions           = new[]
                        {
                            // Set ShouldBoostBeyondRangeByConstant explicitly to false. The API returns the default (false) if you pass in null, so we
                            // need to do this to ensure that comparisons work after round trips.
                            new MagnitudeScoringFunction("rating", 3.14, new MagnitudeScoringParameters(1, 5)
                            {
                                ShouldBoostBeyondRangeByConstant = false
                            })
                            {
                                Interpolation = ScoringFunctionInterpolation.Constant
                            }
                        }
                    }
                },
                DefaultScoringProfile = "MyProfile",
                CorsOptions           = new CorsOptions()
                {
                    AllowedOrigins  = new[] { "http://tempuri.org", "http://localhost:80" },
                    MaxAgeInSeconds = 60
                },
                Suggesters = new[]
                {
                    new Suggester("FancySuggester", "hotelName")
                }
            };

            return(index);
        }
Example #43
0
 public override bool VisitFieldDecl(Field field)
 {
     return(true);
 }
        public virtual void Test()
        {
            Directory         dir = NewDirectory();
            RandomIndexWriter w   = new RandomIndexWriter(Random(), dir, Similarity, TimeZone);

            long startTime = Environment.TickCount;

            // TODO: replace w/ the @nightly test data; make this
            // into an optional @nightly stress test
            Document doc  = new Document();
            Field    body = NewTextField("body", "", Field.Store.NO);

            doc.Add(body);
            StringBuilder sb = new StringBuilder();

            for (int docCount = 0; docCount < NUM_DOCS; docCount++)
            {
                int numTerms = Random().Next(10);
                for (int termCount = 0; termCount < numTerms; termCount++)
                {
                    sb.Append(Random().NextBoolean() ? "aaa" : "bbb");
                    sb.Append(' ');
                }
                body.StringValue = sb.ToString();
                w.AddDocument(doc);
                sb.Remove(0, sb.Length);
            }
            IndexReader r = w.Reader;

            w.Dispose();

            long endTime = Environment.TickCount;

            if (VERBOSE)
            {
                Console.WriteLine("BUILD took " + (endTime - startTime));
            }

            IndexSearcher s = NewSearcher(r);

            AtomicBoolean failed    = new AtomicBoolean();
            AtomicLong    netSearch = new AtomicLong();

            ThreadClass[] threads = new ThreadClass[NUM_SEARCH_THREADS];
            for (int threadID = 0; threadID < NUM_SEARCH_THREADS; threadID++)
            {
                threads[threadID] = new ThreadAnonymousInnerClassHelper(this, s, failed, netSearch);
                threads[threadID].SetDaemon(true);
            }

            foreach (ThreadClass t in threads)
            {
                t.Start();
            }

            foreach (ThreadClass t in threads)
            {
                t.Join();
            }

            if (VERBOSE)
            {
                Console.WriteLine(NUM_SEARCH_THREADS + " threads did " + netSearch.Get() + " searches");
            }

            r.Dispose();
            dir.Dispose();
        }
 protected override void OnInit()
 {
     Register(config => config.Named("user2")
              .ReturnsType(PrimitiveTypes.String())
              .WhenExecute(context => context.Result(Field.String(context.Request.User().Name))));
 }
        void DrawField(Field field, bool withOverride)
        {
            int indentLevel = attributes[field.field].indentLevel;

            if (indentLevel == 0)
            {
                --EditorGUI.indentLevel;    //alignment provided by the space for override checkbox
            }
            else
            {
                for (int i = indentLevel - 1; i > 0; --i)
                {
                    ++EditorGUI.indentLevel;
                }
            }
            bool enabled = field.IsOverrideableWithDependencies(serializedFrameSettings, defaultFrameSettings);

            withOverride &= enabled & GUI.enabled;
            bool shouldBeDisabled = withOverride || !enabled || !GUI.enabled;

            const int k_IndentPerLevel         = 15;
            const int k_CheckBoxWidth          = 15;
            const int k_CheckboxLabelSeparator = 5;
            const int k_LabelFieldSeparator    = 2;
            float     indentValue = k_IndentPerLevel * EditorGUI.indentLevel;

            Rect lineRect     = GUILayoutUtility.GetRect(1, EditorGUIUtility.singleLineHeight);
            Rect overrideRect = lineRect;

            overrideRect.width = k_CheckBoxWidth;
            Rect labelRect = lineRect;

            labelRect.x    += k_CheckBoxWidth + k_CheckboxLabelSeparator;
            labelRect.width = EditorGUIUtility.labelWidth - indentValue;
            Rect fieldRect = lineRect;

            fieldRect.x      = labelRect.xMax + k_LabelFieldSeparator;
            fieldRect.width -= fieldRect.x - lineRect.x;

            if (withOverride)
            {
                int currentIndent = EditorGUI.indentLevel;
                EditorGUI.indentLevel = 0;

                bool mixedValue    = serializedFrameSettings.HaveMultipleOverride(field.field);
                bool originalValue = serializedFrameSettings.GetOverrides(field.field) && !mixedValue;
                overrideRect.yMin += 4f;

                // MixedValueState is handled by style for small tickbox for strange reason
                //EditorGUI.showMixedValue = mixedValue;
                bool modifiedValue = EditorGUI.Toggle(overrideRect, overrideTooltip, originalValue, mixedValue ? CoreEditorStyles.smallMixedTickbox : CoreEditorStyles.smallTickbox);
                //EditorGUI.showMixedValue = false;

                if (originalValue ^ modifiedValue)
                {
                    serializedFrameSettings.SetOverrides(field.field, modifiedValue);
                }

                shouldBeDisabled      = !modifiedValue;
                EditorGUI.indentLevel = currentIndent;
            }

            using (new SerializedFrameSettings.TitleDrawingScope(labelRect, field.label, serializedFrameSettings))
            {
                HDEditorUtils.HandlePrefixLabelWithIndent(lineRect, labelRect, field.label);
            }

            using (new EditorGUI.DisabledScope(shouldBeDisabled))
            {
                EditorGUI.showMixedValue = serializedFrameSettings.HaveMultipleValue(field.field) || field.hasMixedValues;
                using (new EditorGUILayout.VerticalScope())
                {
                    //the following block will display a default value if provided instead of actual value (case if(true))
                    if (shouldBeDisabled)
                    {
                        if (field.overridedDefaultValue == null)
                        {
                            switch (attributes[field.field].type)
                            {
                            case FrameSettingsFieldAttribute.DisplayType.BoolAsCheckbox:
                                DrawFieldShape(fieldRect, defaultFrameSettings.IsEnabled(field.field));
                                break;

                            case FrameSettingsFieldAttribute.DisplayType.BoolAsEnumPopup:
                                //shame but it is not possible to use Convert.ChangeType to convert int into enum in current C#
                                //rely on string parsing for the moment
                                var oldEnumValue = Enum.Parse(attributes[field.field].targetType, defaultFrameSettings.IsEnabled(field.field) ? "1" : "0");
                                DrawFieldShape(fieldRect, oldEnumValue);
                                break;

                            case FrameSettingsFieldAttribute.DisplayType.Others:
                                var oldValue = field.customGetter();
                                DrawFieldShape(fieldRect, oldValue);
                                break;

                            default:
                                throw new ArgumentException("Unknown FrameSettingsFieldAttribute");
                            }
                        }
                        else
                        {
                            DrawFieldShape(fieldRect, field.overridedDefaultValue);
                        }
                    }
                    else
                    {
                        switch (attributes[field.field].type)
                        {
                        case FrameSettingsFieldAttribute.DisplayType.BoolAsCheckbox:
                            bool oldBool = serializedFrameSettings.IsEnabled(field.field) ?? false;
                            bool newBool = (bool)DrawFieldShape(fieldRect, oldBool);
                            if (oldBool ^ newBool)
                            {
                                Undo.RecordObject(serializedFrameSettings.serializedObject.targetObject, "Changed FrameSettings " + field.field);
                                serializedFrameSettings.SetEnabled(field.field, newBool);
                            }
                            break;

                        case FrameSettingsFieldAttribute.DisplayType.BoolAsEnumPopup:
                            //shame but it is not possible to use Convert.ChangeType to convert int into enum in current C#
                            //Also, Enum.Equals and Enum operator!= always send true here. As it seams to compare object reference instead of value.
                            var    oldBoolValue    = serializedFrameSettings.IsEnabled(field.field);
                            int    oldEnumIntValue = -1;
                            int    newEnumIntValue;
                            object newEnumValue;
                            if (oldBoolValue.HasValue)
                            {
                                var oldEnumValue = Enum.GetValues(attributes[field.field].targetType).GetValue(oldBoolValue.Value ? 1 : 0);
                                newEnumValue    = Convert.ChangeType(DrawFieldShape(fieldRect, oldEnumValue), attributes[field.field].targetType);
                                oldEnumIntValue = ((IConvertible)oldEnumValue).ToInt32(System.Globalization.CultureInfo.CurrentCulture);
                                newEnumIntValue = ((IConvertible)newEnumValue).ToInt32(System.Globalization.CultureInfo.CurrentCulture);
                            }
                            else     //in multi edition, do not assume any previous value
                            {
                                newEnumIntValue = EditorGUI.Popup(fieldRect, -1, Enum.GetNames(attributes[field.field].targetType));
                                newEnumValue    = newEnumIntValue < 0 ? null : Enum.GetValues(attributes[field.field].targetType).GetValue(newEnumIntValue);
                            }
                            if (oldEnumIntValue != newEnumIntValue)
                            {
                                Undo.RecordObject(serializedFrameSettings.serializedObject.targetObject, "Changed FrameSettings " + field.field);
                                serializedFrameSettings.SetEnabled(field.field, Convert.ToInt32(newEnumValue) == 1);
                            }
                            break;

                        case FrameSettingsFieldAttribute.DisplayType.Others:
                            var oldValue = field.customGetter();
                            EditorGUI.BeginChangeCheck();
                            var newValue = DrawFieldShape(fieldRect, oldValue);
                            // We need an extensive check here, otherwise in some case with boxing or polymorphism
                            // the != operator won't be accurate. (This is the case for enum types).
                            var valuesAreEquals = oldValue == null && newValue == null || oldValue != null && oldValue.Equals(newValue);
                            // If the UI reported a change, we also assign values.
                            // When assigning to a multiple selection, the equals check may fail while there was indeed a change.
                            if (EditorGUI.EndChangeCheck() || !valuesAreEquals)
                            {
                                Undo.RecordObject(serializedFrameSettings.serializedObject.targetObject, "Changed FrameSettings " + field.field);
                                field.customSetter(newValue);
                            }
                            break;

                        default:
                            throw new ArgumentException("Unknown FrameSettingsFieldAttribute");
                        }
                    }
                }
                EditorGUI.showMixedValue = false;
            }

            if (indentLevel == 0)
            {
                ++EditorGUI.indentLevel;
            }
            else
            {
                for (int i = indentLevel - 1; i > 0; --i)
                {
                    --EditorGUI.indentLevel;
                }
            }
        }
Example #47
0
        public static ExecutionNode BuildExecutionNode(ExecutionNode parent, IGraphType graphType, Field field, FieldType fieldDefinition, string[] path = null)
        {
            path = path ?? AppendPath(parent.Path, field.Name);

            if (graphType is NonNullGraphType nonNullFieldType)
            {
                graphType = nonNullFieldType.ResolvedType;
            }

            switch (graphType)
            {
            case ListGraphType listGraphType:
                return(new ArrayExecutionNode(parent, graphType, field, fieldDefinition, path));

            case IObjectGraphType objectGraphType:
                return(new ObjectExecutionNode(parent, graphType, field, fieldDefinition, path));

            case IAbstractGraphType abstractType:
                return(new ObjectExecutionNode(parent, graphType, field, fieldDefinition, path));

            case ScalarGraphType scalarType:
                return(new ValueExecutionNode(parent, graphType, field, fieldDefinition, path));

            default:
                throw new InvalidOperationException($"Unexpected type: {graphType}");
            }
        }
        //********************************************************************************************
        public Message_02()
        {
            _ObsFields = new ObservableCollection <Field>();
            Field xField;

            xField = new Field("QtitTran", FieldType.Numerical, 12, 1, "Traded quantity", "", "120", "");
            _ObsFields.Add(xField);

            xField = new Field("PTran", FieldType.QtmX, 14, 13, "Trade Price", "", "109", "");
            _ObsFields.Add(xField);

            xField = new Field("CIdAdhNSCAc", FieldType.Alphanumerical, 8, 27, "", "62", "", "");
            _ObsFields.Add(xField);

            xField = new Field("CIdAdhNSCVt", FieldType.Alphanumerical, 8, 35, "ID of NSC® Selling Member", "", "63", "");
            _ObsFields.Add(xField);

            xField = new Field("QTitNgJ", FieldType.Numerical, 12, 43, "Total traded quantity of the trading day", "", "119", "");
            _ObsFields.Add(xField);

            xField = new Field("IsensVarP", FieldType.Alphanumerical, 1, 55, "Last trade price variation as compared to the reference price", "", "87", "");
            _ObsFields.Add(xField);

            xField = new Field("Filler_1", FieldType.Alphanumerical, 5, 56, "", "", "", "");
            _ObsFields.Add(xField);

            xField = new Field("YCpteOmAc", FieldType.Alphanumerical, 1, 61, "Type of Clearing Account for the buyer Member in the Trade", "", "137", "");
            _ObsFields.Add(xField);

            xField = new Field("YCpteOmVt", FieldType.Alphanumerical, 1, 62, "Type of Clearing Account for the seller Member in the Trade", "", "138", "");
            _ObsFields.Add(xField);

            xField = new Field("PphSeaCotJ", FieldType.QtmX, 14, 63, "Highest trade price of the trading day", "", "108", "");
            _ObsFields.Add(xField);

            xField = new Field("PpbSeaCotJ", FieldType.QtmX, 14, 77, "Lowest trade price of the trading day", "", "107", "");
            _ObsFields.Add(xField);

            xField = new Field("IAnuTran", FieldType.Numerical, 2, 91, "Trade cancellation flag", "", "81", "");
            _ObsFields.Add(xField);

            xField = new Field("Filler_2", FieldType.Alphanumerical, 2, 93, "", "", "", "");
            _ObsFields.Add(xField);

            xField = new Field("ItranYApl", FieldType.Numerical, 1, 95, "Cross Trade Flag", "", "90", "");
            _ObsFields.Add(xField);

            xField = new Field("IfinTran", FieldType.Alphanumerical, 1, 96, "Flag indicating end of trades at the same price", "", "83", "");
            _ObsFields.Add(xField);

            xField = new Field("YOmOrgTran", FieldType.Numerical, 1, 97, "Type of orders at the origin of a trade", "", "142", "");
            _ObsFields.Add(xField);

            xField = new Field("YOmAc", FieldType.Alphanumerical, 1, 98, "Code for the technical origin of the buy order", "", "142", "");
            _ObsFields.Add(xField);

            xField = new Field("YOmVt", FieldType.Alphanumerical, 1, 99, "Code for the technicalorigin of the sell order", "", "142", "");
            _ObsFields.Add(xField);

            xField = new Field("CSensVarPTranPP", FieldType.Alphanumerical, 1, 100, "Sign of price variation as compared to the previous price", "", "69", "");
            _ObsFields.Add(xField);

            xField = new Field("NTran", FieldType.Numerical, 7, 101, "Trade number", "", "101", "");
            _ObsFields.Add(xField);

            xField = new Field("Filler_3", FieldType.Alphanumerical, 3, 108, "", "", "", "");
            _ObsFields.Add(xField);

            xField = new Field("YMarNSC", FieldType.Alphanumerical, 2, 111, "NSC® market segment", "", "141", "");
            _ObsFields.Add(xField);

            xField = new Field("Filler_4", FieldType.Alphanumerical, 86, 113, "", "", "", "");
            _ObsFields.Add(xField);

            xField = new Field("DHTran", FieldType.Numerical, 14, 199, "Trade Date and Time", "", "75", "");
            _ObsFields.Add(xField);

            xField = new Field("XQVarPJDrPRf", FieldType.QtmX, 14, 213, "Price Variation As Compared to Reference Price", "", "132", "");
            _ObsFields.Add(xField);

            xField = new Field("Filler_5", FieldType.Alphanumerical, 16, 227, "", "", "", "");
            _ObsFields.Add(xField);
        }
Example #49
0
            public override bool Equals(Field other)
            {
                var cast = (MiscData)other;

                return(Value == cast.Value && Weight == cast.Weight && Damage == cast.Damage);
            }
Example #50
0
 public override void AppendUserQuery(StringBuilder sb)
 {
     sb.Append(Field == null ? Value.ToUserQuery() : Field.ToTermString(Operator.PrimaryAlias, Value.ToUserQuery()));
 }
        public virtual void DoTestLongPostingsNoPositions(IndexOptions options)
        {
            // Don't use TestUtil.getTempDir so that we own the
            // randomness (ie same seed will point to same dir):
            Directory dir = NewFSDirectory(CreateTempDir("longpostings" + "." + Random.NextInt64()));

            int NUM_DOCS = AtLeast(2000);

            if (Verbose)
            {
                Console.WriteLine("TEST: NUM_DOCS=" + NUM_DOCS);
            }

            string s1 = GetRandomTerm(null);
            string s2 = GetRandomTerm(s1);

            if (Verbose)
            {
                Console.WriteLine("\nTEST: s1=" + s1 + " s2=" + s2);

                /*
                 * for(int idx=0;idx<s1.length();idx++) {
                 * System.out.println("  s1 ch=0x" + Integer.toHexString(s1.charAt(idx)));
                 * }
                 * for(int idx=0;idx<s2.length();idx++) {
                 * System.out.println("  s2 ch=0x" + Integer.toHexString(s2.charAt(idx)));
                 * }
                 */
            }

            FixedBitSet isS1 = new FixedBitSet(NUM_DOCS);

            for (int idx = 0; idx < NUM_DOCS; idx++)
            {
                if (Random.NextBoolean())
                {
                    isS1.Set(idx);
                }
            }

            IndexReader r;

            if (true)
            {
                IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetOpenMode(OpenMode.CREATE).SetMergePolicy(NewLogMergePolicy());
                iwc.SetRAMBufferSizeMB(16.0 + 16.0 * Random.NextDouble());
                iwc.SetMaxBufferedDocs(-1);
                RandomIndexWriter riw = new RandomIndexWriter(Random, dir, iwc);

                FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
                ft.IndexOptions = options;
                for (int idx = 0; idx < NUM_DOCS; idx++)
                {
                    Document doc   = new Document();
                    string   s     = isS1.Get(idx) ? s1 : s2;
                    Field    f     = NewField("field", s, ft);
                    int      count = TestUtil.NextInt32(Random, 1, 4);
                    for (int ct = 0; ct < count; ct++)
                    {
                        doc.Add(f);
                    }
                    riw.AddDocument(doc);
                }

                r = riw.GetReader();
                riw.Dispose();
            }
            else
            {
#pragma warning disable 162
                r = DirectoryReader.Open(dir);
#pragma warning restore 162
            }

            /*
             * if (VERBOSE) {
             * System.out.println("TEST: terms");
             * TermEnum termEnum = r.Terms();
             * while(termEnum.Next()) {
             *  System.out.println("  term=" + termEnum.Term() + " len=" + termEnum.Term().Text().length());
             *  Assert.IsTrue(termEnum.DocFreq() > 0);
             *  System.out.println("    s1?=" + (termEnum.Term().Text().equals(s1)) + " s1len=" + s1.length());
             *  System.out.println("    s2?=" + (termEnum.Term().Text().equals(s2)) + " s2len=" + s2.length());
             *  final String s = termEnum.Term().Text();
             *  for(int idx=0;idx<s.length();idx++) {
             *    System.out.println("      ch=0x" + Integer.toHexString(s.charAt(idx)));
             *  }
             * }
             * }
             */

            Assert.AreEqual(NUM_DOCS, r.NumDocs);
            Assert.IsTrue(r.DocFreq(new Term("field", s1)) > 0);
            Assert.IsTrue(r.DocFreq(new Term("field", s2)) > 0);

            int num = AtLeast(1000);
            for (int iter = 0; iter < num; iter++)
            {
                string term;
                bool   doS1;
                if (Random.NextBoolean())
                {
                    term = s1;
                    doS1 = true;
                }
                else
                {
                    term = s2;
                    doS1 = false;
                }

                if (Verbose)
                {
                    Console.WriteLine("\nTEST: iter=" + iter + " doS1=" + doS1 + " term=" + term);
                }

                DocsEnum docs;
                DocsEnum postings;

                if (options == IndexOptions.DOCS_ONLY)
                {
                    docs     = TestUtil.Docs(Random, r, "field", new BytesRef(term), null, null, DocsFlags.NONE);
                    postings = null;
                }
                else
                {
                    docs = postings = TestUtil.Docs(Random, r, "field", new BytesRef(term), null, null, DocsFlags.FREQS);
                    Debug.Assert(postings != null);
                }
                Debug.Assert(docs != null);

                int docID = -1;
                while (docID < DocIdSetIterator.NO_MORE_DOCS)
                {
                    int what = Random.Next(3);
                    if (what == 0)
                    {
                        if (Verbose)
                        {
                            Console.WriteLine("TEST: docID=" + docID + "; do next()");
                        }
                        // nextDoc
                        int expected = docID + 1;
                        while (true)
                        {
                            if (expected == NUM_DOCS)
                            {
                                expected = int.MaxValue;
                                break;
                            }
                            else if (isS1.Get(expected) == doS1)
                            {
                                break;
                            }
                            else
                            {
                                expected++;
                            }
                        }
                        docID = docs.NextDoc();
                        if (Verbose)
                        {
                            Console.WriteLine("  got docID=" + docID);
                        }
                        Assert.AreEqual(expected, docID);
                        if (docID == DocIdSetIterator.NO_MORE_DOCS)
                        {
                            break;
                        }

                        if (Random.Next(6) == 3 && postings != null)
                        {
                            int freq = postings.Freq;
                            Assert.IsTrue(freq >= 1 && freq <= 4);
                        }
                    }
                    else
                    {
                        // advance
                        int targetDocID;
                        if (docID == -1)
                        {
                            targetDocID = Random.Next(NUM_DOCS + 1);
                        }
                        else
                        {
                            targetDocID = docID + TestUtil.NextInt32(Random, 1, NUM_DOCS - docID);
                        }
                        if (Verbose)
                        {
                            Console.WriteLine("TEST: docID=" + docID + "; do advance(" + targetDocID + ")");
                        }
                        int expected = targetDocID;
                        while (true)
                        {
                            if (expected == NUM_DOCS)
                            {
                                expected = int.MaxValue;
                                break;
                            }
                            else if (isS1.Get(expected) == doS1)
                            {
                                break;
                            }
                            else
                            {
                                expected++;
                            }
                        }

                        docID = docs.Advance(targetDocID);
                        if (Verbose)
                        {
                            Console.WriteLine("  got docID=" + docID);
                        }
                        Assert.AreEqual(expected, docID);
                        if (docID == DocIdSetIterator.NO_MORE_DOCS)
                        {
                            break;
                        }

                        if (Random.Next(6) == 3 && postings != null)
                        {
                            int freq = postings.Freq;
                            Assert.IsTrue(freq >= 1 && freq <= 4, "got invalid freq=" + freq);
                        }
                    }
                }
            }
            r.Dispose();
            dir.Dispose();
        }
Example #52
0
            public override bool Equals(Field other)
            {
                var cast = (CriticalData)other;

                return(Damage == cast.Damage && Unknown == cast.Unknown && Multiplier == cast.Multiplier && Flags == cast.Flags && SpellEffect == cast.SpellEffect);
            }
Example #53
0
        public bool CreateIO(IIOFactory ioFactory, Dictionary <Field, IOContainer> ioContainers, Field field, bool isInput = true, bool isBinSized = false, int order = 0)
        {
            Type t = typeof(ISpread <>).MakeGenericType(field.FieldType);

            if (isBinSized)
            {
                t = typeof(ISpread <>).MakeGenericType(t);
            }

            if (ioContainers.ContainsKey(field))
            {
                ioContainers[field].SetOrder(order);
                return(false);
            }
            else
            {
                if (isInput)
                {
                    var inAttr = new InputAttribute(field.Name)
                    {
                        Order = order, BinOrder = order + 1, AutoValidate = false
                    };
                    inAttr.SetDefaultAttribute(field);
                    var ioCont = ioFactory.CreateIOContainer(t, inAttr);

                    ioContainers.Add(field, new IOContainer(ioCont, isInput, isBinSized, order));
                }
                else
                {
                    var outAttr = new OutputAttribute(field.Name)
                    {
                        Order = order, BinOrder = order + 1
                    };                                                                                     //, AutoFlush = false
                    var ioCont = ioFactory.CreateIOContainer(t, outAttr);
                    ioContainers.Add(field, new IOContainer(ioCont, isInput, isBinSized, order));
                    (ioContainers[field].RawIOObject as ISpread).SliceCount = 0;
                }
            }
            return(true);
        }
Example #54
0
 /// <summary>
 /// Equalses the specified other.
 /// </summary>
 /// <param name="other">The other.</param>
 /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
 protected bool Equals(Field other)
 {
     return(string.Equals(Name, other.Name) && string.Equals(Type, other.Type) && XmlType == other.XmlType && string.Equals(Namespace, other.Namespace) && string.Equals(XmlName, other.XmlName));
 }
Example #55
0
 protected virtual void WriteToIO <T>(Field field, ISpread <T> source, ISpread <T> destination)
 {
     destination.AssignFrom(source);
 }
Example #56
0
 public virtual void SetLength(Field field, IIOContainer ioContainer, int length)
 {
     (ioContainer.RawIOObject as ISpread).SliceCount = length;
 }
Example #57
0
 private void titleChanged(object sender, TextChangedEventArgs e)
 {
     lastFieldEditted            = Field.Title;
     suggestionsLstBx.Visibility = Visibility.Hidden;
 }
Example #58
0
        public virtual void NilToIOBin(Field field, IIOContainer ioContainer, int index = 0)
        {
            dynamic dest = ioContainer.RawIOObject;

            WriteSpread(null, dest, index);
        }
Example #59
0
 /// <summary>コンストラクタ</summary>
 public ChannelwiseConvolution(Field infield, Field kernelfield, Field outfield, int stride)
     : base(new Field[] { infield, kernelfield }, outfield)
 {
     this.Stride = stride;
 }
Example #60
0
 private void CategoryChanged(object sender, SelectionChangedEventArgs e)
 {
     lastFieldEditted            = Field.Category;
     suggestionsLstBx.Visibility = Visibility.Hidden;
 }