private bool checkItem(RawItem item) { bool accept = provider.CheckItem(item); //проверка по диапазону if (!accept) { incrementLims(); } if (accept) //если всё ещё подходит, то проверяем дату { accept &= !dates.ContainsKey(item.DateArgument); //проверка повтора даты if (!accept) { incrementRepeats(); } } if (item.DirectionRhumb == WindDirections16.Undefined || item.DirectionRhumb == WindDirections16.Variable) { incrementOther(); accept = false; } if (accept) { dates.TryAdd(item.DateArgument, 0); } return(accept); }
public static List <RawItem> getItems() { List <RawItem> items = new List <RawItem>(); while (fileReader.currentLine != null) { if (initialRx.Match(fileReader.currentLine).Success) { RawItem rawItem; string acumulator = ""; string whiteSpaces = getbeginingWhiteSpaces(); fileReader.getNextLine(); while (!endRx.Match(fileReader.currentLine).Success) { acumulator += fileReader.currentLine + "\n"; fileReader.getNextLine(); } rawItem = new RawItem { proprieties = getItemProprieties(acumulator, whiteSpaces) }; items.Add(rawItem); } fileReader.getNextLine(); } return(items); }
private void ProcessContentItem(RawItem rawItem, ContentRegistration registration) { var converter = ItemConverters.FirstOrDefault(x => x.Supports(rawItem.ContentType)); if (converter == null) { CopyUnconvertableFile(rawItem, registration); return; } var template = registration.DataSource is IFindTemplates templateSourcing ? templateSourcing.SelectTemplate(rawItem, SupportedTemplateEngines) : registration.TemplateFinder.SelectTemplate(rawItem, SupportedTemplateEngines); var templateEngine = SupportedTemplateEngines.TemplateEngineForTemplate(template); var item = converter.ConvertToItem(rawItem.Content); item.SourceKey = rawItem.SourceKey; var contentProcessingResult = templateEngine.Process(item, template); var outputPath = ProcessPath(contentProcessingResult.OutputName); var fullOutputPath = Path.Combine(registration.OutputPath, outputPath); Output.Save(fullOutputPath, contentProcessingResult); }
protected int PrintableCharacterCount(int aMaxNumberOfAsciiBytesToProcess, int aStartRawItemIndex, out bool aAllBytesWereAsciiCharacters) { int printableCharCount = 0; int bytesRemaining = aMaxNumberOfAsciiBytesToProcess; for (int i = aStartRawItemIndex; i < RawItems.Count && bytesRemaining > 0; i++) { RawItem item = RawItems[i]; byte[] data = item.DataArray; // for (int j = 0; j < data.Length && bytesRemaining > 0; j++) { byte b = data[j]; bool byteIsPrint = IsPrintableAsciiCharacter(b); if (byteIsPrint) { ++printableCharCount; } --bytesRemaining; } } // aAllBytesWereAsciiCharacters = (aMaxNumberOfAsciiBytesToProcess == printableCharCount); return(printableCharCount); }
private void StateSkippingToAddress() { if (iCurrentHeapCell != null) { throw new ArgumentException("Heap cell should be NULL"); } if (iState.NextCellAddress <= 0) { throw new ArgumentException("Start of next cell is <= 0"); } // Check to see if this item falls within our data range... RawItem item = iWorkingItemQueue.DequeueHeadItem(); bool preserveItem = (item.Address >= iState.NextCellAddress); // iState.CurrentAddress += RawItem.KSizeOfOneRawItemInBytes; System.Diagnostics.Debug.Assert(iState.CurrentAddress == item.Address); Debug(" {0x" + iState.CurrentAddress.ToString("x8") + "} - skiping: " + item.Data.ToString("x8")); // if (preserveItem) { // We were skipping, but we found the first new item SetNextState(TState.EGettingHeapCellLength); // Push the item back again ready for parings iWorkingItemQueue.ReEnqueueItem(item); } }
private void StateGettingNextFreeCellAddress() { if (iCurrentHeapCell == null) { throw new ArgumentException("Heap cell is NULL!"); } RawItem item = iWorkingItemQueue.DequeueHeadItem(); iState.NextFreeCellAddress = item.Data; if (iState.NextFreeCellAddress > Statistics.AddressRange.Max) { iDataSource.AddError(DataSource.TErrorTypes.EErrorTypeFreeCellAddressOutOfBounds); } iCurrentHeapCell.AddRawItemHeader(item); MarkForInspection(item); iState.CurrentAddress += RawItem.KSizeOfOneRawItemInBytes; System.Diagnostics.Debug.Assert(iState.CurrentAddress == item.Address); Debug(" {0x" + iState.CurrentAddress.ToString("x8") + "} - free: " + item.Data.ToString("x8")); // If we're decoding free cell contents, instead // we should try to identify the vTable info from // what remains of the free cell data TState nextState = TState.ECapturingRawData; if (Options.AttemptToDecodeFreeCellContents) { nextState = TState.EGettingVTable; } SetNextState(nextState); }
public static async Task Converts_raw_data_to_configuration() { var mockDatabaseProvider = new Mock <IDatabaseProvider>(MockBehavior.Strict); var rawData = new Dictionary <string, string> { { "nearbyDistance", "3.5" }, { "shortLeadTimeSpaces", "2" }, { "totalSpaces", "9" } }; mockDatabaseProvider .Setup(p => p.GetConfiguration()) .ReturnsAsync(RawItem.CreateConfiguration(rawData)); var configurationRepository = new ConfigurationRepository(mockDatabaseProvider.Object); var result = await configurationRepository.GetConfiguration(); Assert.NotNull(result); Assert.Equal(3.5m, result.NearbyDistance); Assert.Equal(2, result.ShortLeadTimeSpaces); Assert.Equal(9, result.TotalSpaces); }
public static RawItem Read(Stream input, Endian endian) { var instance = new RawItem(); instance.Name = input.ReadValueU32(endian); instance.BaseName = input.ReadValueU32(endian); instance.Type = input.ReadValueS32(endian); instance.Purchasable = input.ReadValueS32(endian); instance.Consumable = input.ReadValueS32(endian); instance.Rewardable = input.ReadValueS32(endian); instance.Collectable = input.ReadValueS32(endian); input.Seek(4, SeekOrigin.Current); instance.FeatOffset = input.ReadValueS64(endian); instance.FeatCount = input.ReadValueS64(endian); instance.Region = input.ReadValueU32(endian); instance.RebelDropTimer = input.ReadValueS32(endian); instance.MaxInventory = input.ReadValueS32(endian); instance.UIType = input.ReadValueS32(endian); instance.UIFlag = input.ReadValueS32(endian); instance.UIDisplayOrder = input.ReadValueS32(endian); instance.UIName = input.ReadValueU32(endian); instance.UIDescription = input.ReadValueU32(endian); instance.UITypeDescription = input.ReadValueU32(endian); instance.UIFlagDescription = input.ReadValueU32(endian); instance.UIImagePathOffset = input.ReadValueS64(endian); instance.UIVideoPathOffset = input.ReadValueS64(endian); instance.UIPar0 = input.ReadValueF32(endian); instance.UIPar1 = input.ReadValueF32(endian); instance.UIPar2 = input.ReadValueF32(endian); instance.UIPar3 = input.ReadValueF32(endian); instance.UIPar4 = input.ReadValueF32(endian); input.Seek(4, SeekOrigin.Current); return(instance); }
public void Add(byte[] aData, uint aAddress) { int length = aData.Length; if (length % 4 != 0) { throw new ArgumentException("Data is not a multiple of 4 bytes"); } for (int i = 0; i < length; i += 4) { // Make helper RawItemPrecursor prec = new RawItemPrecursor(); prec.Bytes[3] = aData[i + 0]; prec.Bytes[2] = aData[i + 1]; prec.Bytes[1] = aData[i + 2]; prec.Bytes[0] = aData[i + 3]; prec.ConvertBytesToCharacters(); // Make final item RawItem ret = new RawItem(); ret.Address = (uint)(aAddress + i); ret.OriginalData = prec.ByteValue; ret.Data = prec.ByteValueReversed; ret.CharacterisedData = prec.CharValue; // iItems.Add(ret); } }
public RawItem DequeueHeadItem() { RawItem head = iItems[0]; iItems.RemoveAt(0); return(head); }
public static IItem BuildSpecificItem(RawItem rawItem) { switch (rawItem.type.ToUpper()) { case "ARMOR": return(new ArmorItem(rawItem)); case "CONSUMEABLE": return(new ConsumableItem(rawItem)); case "CONTAINER": return(new ContainerItem(rawItem)); case "GEM": return(new GemItem(rawItem)); case "KEY": return(new KeyItem(rawItem)); case "MISCELLANEOUS": return(new MiscellaneousItem(rawItem)); case "MONEY": return(new MoneyItem(rawItem)); case "PROJECTILE": return(new ProjectileItem(rawItem)); case "QUEST": return(new QuestItem(rawItem)); case "QUIVER": return(new QuiverItem(rawItem)); case "REAGENT": return(new ReagentItem(rawItem)); case "RECIPE": return(new RecipeItem(rawItem)); case "TRADE GOODS": return(new TradeGoodItem(rawItem)); case "WEAPON": return(new WeaponItem(rawItem)); default: return(new BasicItem(rawItem)); } }
private static RawItem CreateRawItem( string monthKey, params KeyValuePair <string, List <string> >[] reservationData) => RawItem.CreateReservations( primaryKey: "GLOBAL", sortKey: $"RESERVATIONS#{monthKey}", reservations: new Dictionary <string, List <string> >(reservationData));
private string CreateCellContentsQuickView(HeapCell aCell) { const int KDWordsPerLine = 4; StringBuilder ret = new StringBuilder(); // ret.Append("<table>"); int rawItemsCount = Math.Min(KDWordsPerLine * 2, aCell.RawItems.Count); for (int i = 0; i < rawItemsCount; i += KDWordsPerLine) { ret.Append("<tr>"); // Work out how many items on this line int runIndex; int runExtent = i + KDWordsPerLine; RawItem rawItem = null; // First set of columns - original data for (runIndex = i; runIndex < runExtent; runIndex++) { // Get the item if (runIndex < rawItemsCount) { rawItem = aCell[runIndex]; ret.Append("<td align=center>" + rawItem.OriginalData.ToString("x8") + "</td>"); } else { ret.Append("<td></td>"); rawItem = null; } } ret.Append("<td> </td>"); // Second set of columns - characterised data for (runIndex = i; runIndex < runExtent; runIndex++) { // Get the item if (runIndex < rawItemsCount) { rawItem = aCell[runIndex]; ret.Append("<td align=center>" + HTMLEntityUtility.Entitize(rawItem.OriginalCharacterisedData) + "</td>"); } else { ret.Append("<td></td>"); rawItem = null; } } ret.Append("</tr>"); } ret.Append("</table>"); // return(ret.ToString()); }
public static void Write(Stream output, RawItem instance, Endian endian) { output.WriteValueU32(instance.Name, endian); output.WriteValueU32(instance.BaseName, endian); output.WriteValueS32(instance.Type, endian); output.WriteValueS32(instance.Purchasable, endian); output.WriteValueS32(instance.Consumable, endian); output.WriteValueS32(instance.Rewardable, endian); output.WriteValueS32(instance.Collectable, endian); output.Seek(4, SeekOrigin.Current); output.WriteValueS64(instance.FeatOffset, endian); output.WriteValueS64(instance.FeatCount, endian); output.WriteValueU32(instance.Region, endian); output.WriteValueS32(instance.RebelDropTimer, endian); output.WriteValueS32(instance.MaxInventory, endian); output.WriteValueS32(instance.UIType, endian); output.WriteValueS32(instance.UIFlag, endian); output.WriteValueS32(instance.UIDisplayOrder, endian); output.WriteValueU32(instance.UIName, endian); output.WriteValueU32(instance.UIDescription, endian); output.WriteValueU32(instance.UITypeDescription, endian); output.WriteValueU32(instance.UIFlagDescription, endian); output.WriteValueS64(instance.UIImagePathOffset, endian); output.WriteValueS64(instance.UIVideoPathOffset, endian); output.WriteValueF32(instance.UIPar0, endian); output.WriteValueF32(instance.UIPar1, endian); output.WriteValueF32(instance.UIPar2, endian); output.WriteValueF32(instance.UIPar3, endian); output.WriteValueF32(instance.UIPar4, endian); output.WriteValueU32(0, endian); // TODO(rick): proper pad }
public static async Task GetUser_converts_raw_item_to_user() { const string UserId = "User1"; var mockDatabaseProvider = new Mock <IDatabaseProvider>(MockBehavior.Strict); var rawItem = RawItem.CreateUser( primaryKey: "USER#User1", sortKey: "PROFILE", alternativeRegistrationNumber: "W789XYZ", commuteDistance: 1.23m, emailAddress: "*****@*****.**", firstName: "Sean", lastName: "Cantera", registrationNumber: "AB12CDE", requestReminderEnabled: true, reservationReminderEnabled: false); mockDatabaseProvider.Setup(p => p.GetUser(UserId)).ReturnsAsync(rawItem); var userRepository = new UserRepository(mockDatabaseProvider.Object, Mock.Of <IIdentityProvider>()); var result = await userRepository.GetUser(UserId); Assert.NotNull(result); CheckUser( result: new[] { result ! },
public void BuildSpecificItemTriketTest() { RawItem rawItem = new RawItem { cooldownEnd = "0", cooldownStart = "0", count = "1", curDurability = "100", equiplocation = "INVSLOT_TRINKET", id = "4712", level = "25", link = "...", maxDurability = "100", maxStack = "1", minLevel = "0", name = "Trashball", quality = "2", sellprice = "1250", subtype = "Miscellaneous", type = "armor" }; IItem resultItem = ItemFactory.BuildSpecificItem(rawItem); Assert.IsInstanceOfType(resultItem, typeof(ArmorItem)); //Assert.AreEqual(EquipmentSlot.INVSLOT_TRINKET1, resultItem.EquipLocation); //Assert.AreEqual(EquipmentSlot.INVSLOT_TRINKET2, resultItem.EquipLocation); }
private void UpdateEquipment() { CurrentEquipment.Clear(); foreach (EquipmentSlot equipmentSlot in Enum.GetValues(typeof(EquipmentSlot))) { if (equipmentSlot == EquipmentSlot.NOT_EQUIPABLE) { continue; } try { string resultJson = ReadEquitmentSlot(equipmentSlot); if (resultJson == "noItem") { continue; } RawItem rawItem = JsonConvert.DeserializeObject <RawItem>(resultJson); CurrentEquipment.Add(equipmentSlot, ItemFactory.BuildSpecificItem(rawItem)); AmeisenBotLogger.Instance.Log($"Parsed EquipmentItem: {equipmentSlot.ToString()} => {rawItem.name}", LogLevel.Error); } catch (Exception ex) { AmeisenBotLogger.Instance.Log($"Crash at updating the EquipmentSlot [{equipmentSlot.ToString()}]: \n{ex}", LogLevel.Error); } } }
public void BuildSpecificItemTest() { RawItem rawItem = new RawItem { cooldownEnd = "0", cooldownStart = "0", count = "1", curDurability = "100", equiplocation = "INVSLOT_HEAD", id = "4711", level = "25", link = "...", maxDurability = "100", maxStack = "1", minLevel = "0", name = "Armored Rubbish Bin", quality = "2", sellprice = "1250", subtype = "Mail", type = "armor" }; IItem resultItem = ItemFactory.BuildSpecificItem(rawItem); Assert.IsInstanceOfType(resultItem, typeof(ArmorItem)); Assert.AreEqual(EquipmentSlot.INVSLOT_HEAD, resultItem.EquipLocation); }
/// <summary> /// приведение ряда к условиям плоской местности /// </summary> /// <param name="ms_range">ряд</param> /// <param name="expectancy">повторяемости направлений ветра</param> /// <param name="ms_classes">классы открытости МС</param> /// <param name="water_type">расстояние до водной поверхности</param> /// <returns></returns> public static RawRange ToFlatTerrain(RawRange ms_range, StatisticalRange <WindDirections8> expectancy, Dictionary <WindDirections8, double> ms_classes, WaterDistanceType water_type) { //1. найти Кмс //2. пересчитать ряд RawRange result = new RawRange(); double K0 = (int)water_type; //средневзвешенный коэффициент открытости метеостанции double Kms = 0; foreach (WindDirections8 dir in WindDirections8.N.GetEnumItems()) { if (dir != WindDirections8.Calm && dir != WindDirections8.Undefined && dir != WindDirections8.Variable) { Kms += expectancy[dir] * ms_classes[dir]; } } double k0 = K0 / Kms; result.BeginChange(); foreach (RawItem item in ms_range) { RawItem ni = item.Clone(); ni.Speed = item.Speed * k0; result.Add(ni); } result.EndChange(); return(result); }
public ITemplate SelectTemplate(RawItem rawItem, List <ITemplateEngine> templateEngines) { var validTemplateFileNames = new [] { "_Layout", "_Template", }; // collect all template engines supported // walk up directory tree following conventions looking for templates matching those extensions in order of occurence if (rawItem is LocalFileSystemItem localItem) { var siblingFiles = Directory.GetFiles(localItem.ContentRoot, "*.*", SearchOption.TopDirectoryOnly); var validTemplates = siblingFiles.Where(file => validTemplateFileNames.Any(file.Contains)).ToList(); var supportedTemplates = validTemplates.Where(x => templateEngines.Any(engine => engine.Supports(x))); var firstSupportedTemplateFile = supportedTemplates.FirstOrDefault(); if (firstSupportedTemplateFile == null) { return(new NoTemplate()); } var engineForTemplate = templateEngines.First(x => x.Supports(firstSupportedTemplateFile)); return(engineForTemplate.CreateTemplateInstance(File.ReadAllBytes(firstSupportedTemplateFile))); } return(new NoTemplate()); }
protected int PrintableCharacterCount(int aMaxNumberOfUnicodeWordsToProcess, int aStartRawItemIndex, out bool aAllWordsWereAsciiCharacters) { int printableCharCount = 0; int wordsRemaining = aMaxNumberOfUnicodeWordsToProcess; for (int i = aStartRawItemIndex; i < RawItems.Count && wordsRemaining > 0; i++) { RawItem item = RawItems[i]; ushort[] data = item.DataArrayWords; // bool word1IsPrint = IsPrintableAsciiCharacter(data[0]); if (word1IsPrint) { ++printableCharCount; } --wordsRemaining; // if (wordsRemaining > 0) { bool word2IsPrint = IsPrintableAsciiCharacter(data[1]); if (word2IsPrint) { ++printableCharCount; } --wordsRemaining; } } // aAllWordsWereAsciiCharacters = (aMaxNumberOfUnicodeWordsToProcess == printableCharCount); return(printableCharCount); }
public void PopupShowAsync(Point aLocation, HeapCell aCell, RawItem aItem, HeapStatistics aStats, Size aOffset, System.Windows.Forms.KeyEventHandler aKeyHandler) { //System.Diagnostics.Debug.WriteLine( "PopupBase - Timer Started" ); iKeyHandler = aKeyHandler; HeapCellArrayWithStatistics array = new HeapCellArrayWithStatistics(); array.Add(aCell); PrepareContent(array, aStats, aItem); // iHoverPos = aLocation; // iShowPos = aLocation; iShowPos.Offset(aOffset.Width, aOffset.Height); // If we are using an async timer delay then we must start the timer and // when it expires, the popup will become visible. Otherwise, we show // the popup immediately. if (VisibilityDelay > 0) { iTimer.Stop(); iTimer.Enabled = true; iTimer.Start(); } else { PopupShow(); } }
private static RawItem CreateRawItem( string userId, string monthKey, params KeyValuePair <string, string>[] requestData) => RawItem.CreateRequests( primaryKey: $"USER#{userId}", sortKey: $"REQUESTS#{monthKey}", requests: new Dictionary <string, string>(requestData));
private void iRenderer_CellRightClicked(HeapCell aCell, RawItem aRawItem, Point aViewerPos) { if (CellRightClicked != null) { Point screenPos = iRenderer.PointToScreen(aViewerPos); CellRightClicked(aCell, aRawItem, screenPos); } }
public void RawItemQuestion() { var xElement = XElement.Parse( "<Compile Include=\"File.cs\" />" ); var optionValue = new RawItem( xElement ); var option = new UserQuestionLiteralWithDescriptionOption<RawItem>( "A", "Option A", optionValue, "WasNull" ); Assert.That( option.GetQuestionText(), Is.EqualTo( "(A) Option A:\r\n<Compile Include=\"File.cs\" />\r\n" ) ); Assert.That( option.GetValue(), Is.EqualTo( optionValue ) ); }
private RawItem restoreItem(RawItem item) { //если скорость ноль, то направление Штиль if (item.Speed == 0) { item.DirectionRhumb = WindDirections16.Calm; } return(item); }
public override void PopupShowAsyncImpl(HeapCell aCell, RawItem aItem, HeapStatistics aStats, Point aLocalControlCoordiantes, Point aScreenCoordinates, Size aOffsetBy, KeyEventHandler aKeyHandler) { PopupHide(); // System.Diagnostics.Debug.Assert(aItem.Tag != null && aItem.Tag is RelationshipInfo); // iActivePopup = new PopupCellRelationshipInfo(); iActivePopup.ColourFromHoverCoordinate = true; iActivePopup.PopupShowAsync(aScreenCoordinates, aCell, aItem, aStats, aOffsetBy, aKeyHandler); }
public void PopupShowAsync(HeapCell aCell, RawItem aItem, HeapStatistics aStats, Point aLocalControlCoordinates, Point aScreenCoordinates, Size aOffsetBy, System.Windows.Forms.KeyEventHandler aKeyHandler) { if (SupportsRawItemInfo) { lock (this) { PopupShowAsyncImpl(aCell, aItem, aStats, aLocalControlCoordinates, aScreenCoordinates, aOffsetBy, aKeyHandler); } } }
/// <summary> /// возвращает истину, если значение допустимо в этой точке /// </summary> /// <param name="item">данные для проверки</param> /// <returns></returns> public bool CheckItem(RawItem item) { if (limits.ContainsKey(nearestPoint)) { return(limits[nearestPoint].CheckItem(item)); } else { throw new Exception("Коллекция ключей пуста!"); } }
static unsafe object Map(RawItem arg) { var value = new string((char*)arg.Value, 0, arg.ValueLength / 2 - 1); var key = new string((char*)arg.Key); return new Item { Key = key, Value = value, SequenceNumber = arg.SequenceNumber }; }
/// <summary> /// /// </summary> /// <param name="item"></param> public ServerItem( RawItem item) : base(item.ItemId, (ItemKind)item.ItemKind, item.Transient, item.ItemName, new NamedValueSet(item.AppProps), item.DataType, item.AppScope, new NamedValueSet(item.SysProps), item.NetScope, item.Created, item.Expires, item.YData, item.YSign, item.StoreUSN) { _frozen = true; }