public void TagNode_renames_itself() { // ARRANGE var tag = DefaultTag(); this.ProviderContextMock .Setup(c => c.Persistence) .Returns(this.PersistenceMock.Object); this.PersistenceMock .Setup(m => m.Tags) .Returns(this.TagRepositoryMock.Object); Tag?renamedTag = null; this.TagRepositoryMock .Setup(r => r.Upsert(It.IsAny <Tag>())) .Callback <Tag>(t => renamedTag = t) .Returns(tag); // ACT new TagNode(tag).RenameItem(this.ProviderContextMock.Object, "t", "tt"); // ASSERT Assert.Equal("tt", renamedTag !.Name); }
public override bool Equals(Tag?other) { if (other is SingleTag singleTag) { return(Types.Contains(singleTag.Type)); } else if (other is CombinedTag combinedTag) { var iterateThis = Types.Count <= combinedTag.Types.Count; var set = iterateThis ? combinedTag.Types : Types; foreach (var type in iterateThis ? Types : combinedTag.Types) { if (set.Contains(type)) { return(true); } } return(false); } else if (other is null) { return(false); } throw new InvalidOperationException("Unreachable"); }
public void FacetPropertyNode_renames_itself() { // ARRANGE var tag = DefaultTag(WithDefaultProperty); this.ProviderContextMock .Setup(c => c.Persistence) .Returns(this.PersistenceMock.Object); this.PersistenceMock .Setup(m => m.Tags) .Returns(this.TagRepositoryMock.Object); Tag?renamedTag = null; this.TagRepositoryMock .Setup(r => r.Upsert(It.IsAny <Tag>())) .Callback <Tag>(t => renamedTag = t) .Returns(tag); // ACT new FacetPropertyNode(tag, tag.Facet.Properties.Single()).RenameItem(this.ProviderContextMock.Object, "p", "pp"); // ASSERT Assert.Equal("pp", renamedTag !.Facet.Properties.Single().Name); }
private bool GetTagTree(SqliteDataReader reader, ref List <Tag> result, Tag?parent, int level) { // We must be on the right level on entry into this method Debug.Assert(reader.GetInt32(3) == level); // we iterate on the siblings on the same level while (reader.GetInt32(3) == level) { var tag = new Tag(this, reader.GetString(2), parent); result.Add(tag); if (reader.Read()) { var nextLevel = reader.GetInt32(3); // A child has level + 1 if (nextLevel == level + 1) { if (GetTagTree(reader, ref result, tag, level + 1) == false) { return(false); } } else if (nextLevel < level) { return(true); } } else { // We are at the end of the list ... return(false); } } return(true); }
public void TagNode_copies_itself_as_new_tag() { // ARRANGE var tag = DefaultTag(WithDefaultProperty); this.ProviderContextMock .Setup(c => c.Persistence) .Returns(this.PersistenceMock.Object); this.PersistenceMock .Setup(m => m.Tags) .Returns(this.TagRepositoryMock.Object); Tag?createdTag = null; this.TagRepositoryMock .Setup(r => r.Upsert(It.IsAny <Tag>())) .Callback <Tag>(t => createdTag = t) .Returns(tag); var tagsContainer = new TagsNode(); // ACT new TagNode(tag) .CopyItem(this.ProviderContextMock.Object, "t", "tt", tagsContainer); // ASSERT Assert.Equal("tt", createdTag !.Name); Assert.Equal("p", createdTag !.Facet.Properties.Single().Name); Assert.Equal(tag.Facet.Properties.Single().Type, createdTag !.Facet.Properties.Single().Type); }
public Tag(ITag tag, string name, Tag?parent = null) { _tag = tag; Name = name; Parent = parent; parent?.Children?.Add(this); }
private Tag? ToTag(IEnumerable<string> tagParts) { Tag? result = null; foreach (var part in tagParts) { result = _newTag(part, result); } return result; }
public static long[] UndoTagFromAllUserChanges(long userId, Tag badTag, Tag?replaceWith = null) { var changesetids = OneOffs.GetUsersChangesetIds(userId); var changes = OneOffs.GetElementsFromChanges(changesetids); var badChanges = changes.Where(e => e.Tags != null && e.Tags.Contains(badTag)).Select(e => new OsmGeoKey(e)).Distinct().ToArray(); var currentVersions = OsmApiClient.GetElements(badChanges).Result; var fix = OneOffs.UndoTagFromElements(badTag, currentVersions, replaceWith); var changesetTags = GetCommitTags($"Undo all instances of {badTag} from user {userId}."); var fixIds = Subjects.UploadChange(fix, changesetTags, @"FIX Offices\Uploaded\").Result; return(fixIds); }
// Converts the value of the element to a string representation. public static string ValueAsString(this VectorElement element) { // The physical types Char1 and Char2 indicate the value is a string if (element.TypeOfValue == PhysicalType.Char1) { return(Encoding.ASCII.GetString(element.GetValues()).Trim((char)0)); } if (element.TypeOfValue == PhysicalType.Char2) { return(Encoding.Unicode.GetString(element.GetValues()).Trim((char)0)); } // Get the tag definition of the element being displayed Tag?tag = Tag.GetTag(element.TagOfElement); // Determine the format in which to display the values // based on the tag definition and the type of the value Func <int, string> formatter = element.TypeOfValue switch { PhysicalType.Complex8 => index => ((Complex)element.Get(index)).ToComplexNotation(), PhysicalType.Complex16 => index => ((Complex)element.Get(index)).ToComplexNotation(), PhysicalType.Timestamp => index => { string format = tag?.FormatString ?? "{0:yyyy-MM-dd HH:mm:ss.fffffff}"; object value = element.Get(index); return(string.Format(format, value)); }, _ => index => { string format = tag?.FormatString ?? "{0}"; object value = element.Get(index); return(string.Format(format, value)); } }; // Convert the values to their string representations IEnumerable <string> values = Enumerable .Range(0, element.Size) .Select(formatter); // Join the values in the collection // to a single, comma-separated string string join = string.Join(", ", values); // Wrap the string in curly braces and return return($"{{ {join} }}"); }
public async Task <IActionResult> OnGetAsync(int?id) { if (id == null) { return(NotFound()); } Tag = await _context.Tags.FirstOrDefaultAsync(m => m.Id == id); if (Tag == null) { return(NotFound()); } return(Page()); }
public void Change(EquipmentField field, Tag?tag) { if (!_equipments.ContainsKey(field) || _equipments[field] == null) { return; } var before = _equipments[field] !; var after = _equipments[field] !with { Tag = tag }; _equipments[field] = after; ProcessAffect(before, after); }
public Tag Update(Tag tag) { Tag?existing = context.Tags.Find(tag.Id); if (existing == null) { throw new Exception(); } EntityEntry <Tag> entry = context.Entry(existing); entry.CurrentValues.SetValues(tag); entry.CurrentValues["CreatedDate"] = existing.CreatedDate; context.SaveChanges(); return(entry.Entity); }
public override bool Equals(Tag?other) { if (other is SingleTag singleTag) { return(singleTag.Type.Equals(Type)); } else if (other is CombinedTag combinedTag) { return(combinedTag.Types.Contains(Type)); } else if (other is null) { return(false); } throw new InvalidOperationException("Unreachable"); }
public async Task <IActionResult> OnPostAsync(int?id) { if (id == null) { return(NotFound()); } Tag = await _context.Tags.FindAsync(id); if (Tag != null) { _context.Tags.Remove(Tag); await _context.SaveChangesAsync(); } return(RedirectToPage("./Index")); }
public bool TryFindTagLayer(Tag layer, string title, out Tag?tag) { if (layer.title == title) { tag = layer; return(true); } foreach (var child in layer.Childes) { if (child.title == title) { tag = child; return(true); } } tag = null; return(false); }
public IActionResult Update([FromBody] Tag?tag) { var validationError = ValidateTag(tag); if (validationError != null) { return(BadRequest(validationError)); } var updatedTag = tagsRepository.TryUpdate(tag !); if (updatedTag == null) { return(BadRequest("Tag has not updated")); } return(Ok(updatedTag)); }
public bool Equals(Tag?x, Tag?y) { if (x is null) { if (y is null) { return(true); } return(false); } if (y is null) { return(false); } return(string.Equals(x.Key, y.Key, StringComparison.Ordinal) && string.Equals(x.Value, y.Value, StringComparison.Ordinal)); }
private string?ValidateTag(Tag?tag) { if (tag == null) { return("Body is required"); } if (string.IsNullOrEmpty(tag.Name)) { return("Name is required"); } if (tag.BooksIsbnNumbers == null || !tag.BooksIsbnNumbers.Any()) { return("BooksIsbnNumbers is required"); } return(null); }
public async Task <int> Handle(CreatePromptCommand request, CancellationToken cancellationToken = default) { if (request.ParentId.HasValue) { if (!_currentUserService.TryGetCurrentUser(out GetUserViewModel? user)) { throw new CreatePromptUnauthorizedParentException(); } Prompt?parent = await _dbContext.Prompts.FindAsync(request.ParentId); if (parent.OwnerId != user !.Id) { throw new CreatePromptUnauthorizedParentException(); } } var isDraft = !request.ParentId.HasValue && request.SaveDraft; var prompt = new Prompt { AuthorsNote = request.AuthorsNote?.Replace("\r\n", "\n"), DateCreated = DateTime.UtcNow, DateEdited = null, Memory = request.Memory?.Replace("\r\n", "\n"), Nsfw = request.Nsfw, PromptContent = request.PromptContent.Replace("\r\n", "\n"), Quests = request.Quests?.Replace("\r\n", "\n"), Title = request.Title.Replace("\r\n", "\n"), Description = request.Description?.Replace("\r\n", "\n"), OwnerId = request.OwnerId, Upvote = 0, Views = 0, IsDraft = isDraft, PublishDate = isDraft ? null : (DateTime?)DateTime.UtcNow, ParentId = request.ParentId, ScriptZip = request.ScriptZip, NovelAiScenario = string.IsNullOrWhiteSpace(request.NovelAiScenario) ? null : request.NovelAiScenario, HoloAiScenario = string.IsNullOrWhiteSpace(request.HoloAiScenario) ? null : request.HoloAiScenario }; foreach (var worldInfo in request.WorldInfos) { if (string.IsNullOrWhiteSpace(worldInfo.Entry) || string.IsNullOrWhiteSpace(worldInfo.Keys)) { continue; } prompt.WorldInfos.Add(new WorldInfo { DateCreated = DateTime.UtcNow, Entry = worldInfo.Entry.Replace("\r\n", "\n"), Keys = worldInfo.Keys.Replace("\r\n", "\n"), Prompt = prompt }); } var promptTags = request.PromptTags.Split(',').Select(p => p.Trim().ToLower()).Distinct(); foreach (var promptTag in promptTags) { if (string.IsNullOrWhiteSpace(promptTag)) { continue; } if (string.Equals(promptTag, "nsfw", StringComparison.OrdinalIgnoreCase)) { prompt.Nsfw = true; continue; } Tag?tag = await _dbContext.Tags.FirstOrDefaultAsync(e => EF.Functions.ILike(e.Name, NpgsqlHelper.SafeIlike(promptTag), NpgsqlHelper.EscapeChar), cancellationToken : cancellationToken); if (tag == null) { prompt.PromptTags.Add(new PromptTag { Prompt = prompt, Tag = new Tag { Name = promptTag } }); } else { prompt.PromptTags.Add(new PromptTag { Prompt = prompt, Tag = tag }); } } _dbContext.Prompts.Add(prompt); await _dbContext.SaveChangesAsync(cancellationToken); return(prompt.Id); }
=> $"{(string.IsNullOrEmpty(Tag?.Language) ? string.Empty : $"[{Tag.Language}]")}";
public static OsmChange UndoTagFromElements(Tag tagToRemove, OsmGeo[] osmGeos, Tag?replaceWith = null) { var stillBad = osmGeos.Where(e => e.Tags != null && e.Tags.Contains(tagToRemove) && e.Visible == true).ToArray(); foreach (var e in stillBad) { e.Tags.RemoveKeyValue(tagToRemove); if (replaceWith != null) { e.Tags.Add(replaceWith.Value); } } var theFix = Changes.FromGeos(null, stillBad, null); return(theFix); }
public abstract bool Equals(Tag?other);
public bool Equals(Tag?other) { return(Value == other?.Value && Color == other?.Color); }
public async Task <Unit> Handle(UpdatePromptCommand request, CancellationToken cancellationToken = default) { if (!_currentUserService.TryGetCurrentUser(out GetUserViewModel? user)) { return(Unit.Value); } Prompt?prompt = await _dbContext.Prompts .Include(e => e.PromptTags) .Include(e => e.WorldInfos) .FirstOrDefaultAsync(e => e.Id == request.Id, cancellationToken); var isOwner = user !.Id == prompt.OwnerId; var canEditField = isOwner ? isOwner : (user.Role & RoleEnum.FieldEdit) != 0; var canEditTags = isOwner ? isOwner : (user.Role & RoleEnum.TagEdit) != 0; if (canEditField) { var isDraft = !prompt.ParentId.HasValue && (isOwner ? request.SaveDraft : prompt.IsDraft); prompt.AuthorsNote = request.AuthorsNote?.Replace("\r\n", "\n"); prompt.DateEdited = DateTime.UtcNow; prompt.Memory = request.Memory?.Replace("\r\n", "\n"); prompt.Nsfw = request.Nsfw; prompt.PromptContent = request.PromptContent.Replace("\r\n", "\n"); prompt.Quests = request.Quests?.Replace("\r\n", "\n"); prompt.Title = request.Title.Replace("\r\n", "\n"); prompt.Description = request.Description?.Replace("\r\n", "\n"); prompt.WorldInfos = new List <WorldInfo>(); prompt.IsDraft = isDraft; prompt.PublishDate ??= isDraft ? null : (DateTime?)DateTime.UtcNow; prompt.ScriptZip = isOwner ? request.ScriptZip ?? prompt.ScriptZip : prompt.ScriptZip; prompt.NovelAiScenario = string.IsNullOrWhiteSpace(request.NovelAiScenario) ? null : request.NovelAiScenario; prompt.HoloAiScenario = string.IsNullOrWhiteSpace(request.HoloAiScenario) ? null : request.HoloAiScenario; foreach (var worldInfo in request.WorldInfos) { if (string.IsNullOrWhiteSpace(worldInfo.Entry) || string.IsNullOrWhiteSpace(worldInfo.Keys)) { continue; } prompt.WorldInfos.Add(new WorldInfo { DateCreated = DateTime.UtcNow, Entry = worldInfo.Entry.Replace("\r\n", "\n"), Keys = worldInfo.Keys.Replace("\r\n", "\n"), Prompt = prompt }); } } if (canEditTags) { prompt.PromptTags = new List <PromptTag>(); var promptTags = request.PromptTags.Split(',').Select(p => p.Trim().ToLower()).Distinct(); foreach (var promptTag in promptTags) { if (string.IsNullOrWhiteSpace(promptTag)) { continue; } if (string.Equals(promptTag, "nsfw", StringComparison.OrdinalIgnoreCase)) { prompt.Nsfw = true; continue; } Tag?tag = await _dbContext.Tags.FirstOrDefaultAsync(e => EF.Functions.ILike(e.Name, NpgsqlHelper.SafeIlike(promptTag), NpgsqlHelper.EscapeChar)); if (tag == null) { prompt.PromptTags.Add(new PromptTag { Prompt = prompt, Tag = new Tag { Name = promptTag } }); } else { prompt.PromptTags.Add(new PromptTag { Prompt = prompt, Tag = tag }); } } } _dbContext.Prompts.Update(prompt); await _dbContext.SaveChangesAsync(cancellationToken); return(Unit.Value); }
public async Task <ClickResponseModel> Click(ClickModel clickModel, Guid userId) { var errors = new List <string>(); var response = new ClickResponseModel(errors); using var transaction = context.Database.BeginTransaction(IsolationLevel.RepeatableRead); var now = DateTime.UtcNow; Tag?tag = null; if (Guid.TryParse(clickModel.TagId, out Guid tagGuid)) { tag = await context.Tags.Include(x => x.User).SingleOrDefaultAsync(x => x.Id == tagGuid); if (tag == null) { errors.Add(InvalidTagIdError); } } else { tag = await context.Tags.Include(x => x.User).SingleOrDefaultAsync(x => x.User.Username == clickModel.TagId); if (tag == null) { errors.Add(InvlaidUsernameError); } } if (tag == null) { errors.Add(NoUsernameOrTagId); } var user = await context.Users.SingleAsync(x => x.Id == userId); if (user.Balance <= 0 && user.Repurchase && !string.IsNullOrWhiteSpace(user.BillingId) && !string.IsNullOrWhiteSpace(user.CardId) && !string.IsNullOrWhiteSpace(user.RepurchaseAmount)) { await purchaseManager.Purchase(new PurchaseModel { Amount = user.RepurchaseAmount, Refill = true, UseSaved = true, }, user); } if (!errors.Any() && user.Balance <= 0) { errors.Add(InsufficientFundsError); } if (errors.Any()) { await transaction.RollbackAsync(); return(response); } user.Balance -= 1; tag !.User.Balance += 1; context.Clicks.Add(new Click { Id = Guid.NewGuid(), TagId = tag !.Id, UserId = userId, Timestamp = now, ViewId = clickModel.viewId, PageId = clickModel.PageId, Page = clickModel.Page, Referrer = clickModel.Referrer });
/// <summary> /// Parse the productions: /// block_node_or_indentless_sequence ::= /// ALIAS /// ***** /// | properties (block_content | indentless_block_sequence)? /// ********** * /// | block_content | indentless_block_sequence /// * /// block_node ::= ALIAS /// ***** /// | properties block_content? /// ********** * /// | block_content /// * /// flow_node ::= ALIAS /// ***** /// | properties flow_content? /// ********** * /// | flow_content /// * /// properties ::= TAG ANCHOR? | ANCHOR TAG? /// ************************* /// block_content ::= block_collection | flow_collection | SCALAR /// ****** /// flow_content ::= flow_collection | SCALAR /// ****** /// </summary> private ParsingEvent ParseNode(bool isBlock, bool isIndentlessSequence) { if (GetCurrentToken() is Error errorToken) { throw new SemanticErrorException(errorToken.Start, errorToken.End, errorToken.Value); } var current = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a node"); if (current is AnchorAlias alias) { state = states.Pop(); ParsingEvent evt = new Events.AnchorAlias(alias.Value, alias.Start, alias.End); Skip(); return(evt); } var start = current.Start; string?anchorName = null; string?tagName = null; Anchor?lastAnchor = null; Tag? lastTag = null; // The anchor and the tag can be in any order. This loop repeats at most twice. while (true) { if (anchorName == null && current is Anchor anchor) { lastAnchor = anchor; anchorName = string.IsNullOrEmpty(anchor.Value) ? null : anchor.Value; Skip(); } else if (tagName == null && current is Tag tag) { lastTag = tag; if (string.IsNullOrEmpty(tag.Handle)) { tagName = tag.Suffix; } else if (tagDirectives.Contains(tag.Handle)) { tagName = string.Concat(tagDirectives[tag.Handle].Prefix, tag.Suffix); } else { throw new SemanticErrorException(tag.Start, tag.End, "While parsing a node, found undefined tag handle."); } if (string.IsNullOrEmpty(tagName)) { tagName = null; } Skip(); } else if (current is Anchor secondAnchor) { throw new SemanticErrorException(secondAnchor.Start, secondAnchor.End, "While parsing a node, found more than one anchor."); } else if (current is AnchorAlias anchorAlias) { throw new SemanticErrorException(anchorAlias.Start, anchorAlias.End, "While parsing a node, did not find expected token."); } else if (current is Error error) { if (lastTag != null && lastAnchor != null && !string.IsNullOrEmpty(anchorName)) { return(new Events.Scalar(anchorName, default, string.Empty, default, false, false, lastAnchor.Start, lastAnchor.End));
public bool Equals(Tag?input) { return(OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual); }
public bool TryFindTagLayer(Tag layer, string title, out Tag?tag) { return(manager.TryFindTagLayer(layer, title, out tag)); }
/// <summary> /// Creates a new selecter of the given type /// </summary> /// <param name="SelectWay">the type of selector</param> /// <param name="HasTag">a tag the selected entity must have. Note that this can be overwritten by <see cref="Tags"/></param> public Selector(ID.Selector SelectWay, Tag? HasTag = null) { SelectorType = SelectWay; if (HasTag != null) { Tags = new EntityTag[] { new EntityTag(HasTag) }; } }
/// <summary> /// Initializes a new instance of the <see cref="TagPayloadBase"/> class. /// </summary> /// <param name="tag">The tag.</param> protected TagPayloadBase(Tag tag) { Tag = tag; }