/// <summary>Trim leaf elements, and sanitize.</summary> /// <param name="leafElements">the leaf elements</param> /// <returns>the trimmed and sanitized list</returns> internal static IList <IElement> TrimLeafElementsAndSanitize(IList <IElement> leafElements) { List <IElement> waitingLeaves = new List <IElement>(leafElements); TrimSubList(waitingLeaves, 0, waitingLeaves.Count, false); TrimSubList(waitingLeaves, 0, waitingLeaves.Count, true); int pos = 0; while (pos < waitingLeaves.Count - 1) { if (waitingLeaves[pos] is Text) { Text first = (Text)waitingLeaves[pos]; if (IsElementFloating(first)) { TrimTextElement(first, false); TrimTextElement(first, true); } else { int firstEnd = GetIndexAfterLastNonSpace(first); if (firstEnd < first.GetText().Length) { TrimSubList(waitingLeaves, pos + 1, waitingLeaves.Count, false); first.SetText(first.GetText().JSubstring(0, firstEnd + 1)); } } } pos++; } return(waitingLeaves); }
/// <summary>Trims a text element.</summary> /// <param name="text">the text element</param> /// <param name="last">indicates where to start, if true, we start at the end</param> private static void TrimTextElement(Text text, bool last) { int begin = last ? 0 : GetIndexOfFirstNonSpace(text); int end = last ? GetIndexAfterLastNonSpace(text) : text.GetText().Length; text.SetText(text.GetText().JSubstring(begin, end)); }
/// <summary>Gets the index of first character that isn't white space in some text.</summary> /// <remarks> /// Gets the index of first character that isn't white space in some text. /// Note: newline characters aren't counted as white space characters. /// </remarks> /// <param name="text">the text</param> /// <returns>the index of first character that isn't white space</returns> private static int GetIndexOfFirstNonSpace(Text text) { int pos = 0; while (pos < text.GetText().Length&& IsNonLineBreakSpace(text.GetText()[pos])) { pos++; } return(pos); }
/// <summary>Gets the index of last character following a character that isn't white space in some text.</summary> /// <remarks> /// Gets the index of last character following a character that isn't white space in some text. /// Note: newline characters aren't counted as white space characters. /// </remarks> /// <param name="text">the text</param> /// <returns>the index following the last character that isn't white space</returns> private static int GetIndexAfterLastNonSpace(Text text) { int pos = text.GetText().Length; while (pos > 0 && IsNonLineBreakSpace(text.GetText()[pos - 1])) { pos--; } return(pos); }
private void UpdateDocType() { if (DocType != DocType.Undefined) { return; } // Simple handling since <!doctype> tag must be well formed // to be properly recognized as such. int startPosition = _cs.Position; while (!_cs.IsEndOfStream() && _cs.CurrentChar != '>' && _cs.CurrentChar != '<') { _cs.MoveToNextChar(); } if (_cs.CurrentChar != '>') { return; } string docTypeText = Text.GetText(new TextRange(startPosition - 1, _cs.Position - startPosition + 2)); DocType = DocTypeSignatures.GetDocType(docTypeText); UpdateParseMode(DocType); }
/// <summary>Trims a sub list of leaf elements.</summary> /// <param name="list">the list of leaf elements</param> /// <param name="begin">the index where to begin</param> /// <param name="end">the index where to end</param> /// <param name="last">indicates where to start, if true, we start at the end</param> private static void TrimSubList(List <IElement> list, int begin, int end, bool last) { while (end > begin) { int pos = last ? end - 1 : begin; IElement leaf = list[pos]; if (IsElementFloating(leaf) || leaf is RunningElement) { if (last) { --end; } else { ++begin; } continue; } if (leaf is Text) { Text text = (Text)leaf; TrimTextElement(text, last); if (text.GetText().Length == 0) { if (HasZeroWidth(text)) { list.JRemoveAt(pos); } end--; continue; } } break; } }
public ValueEventHandler(Element element) { this.element = element; currentValue = Text.GetText(); element.accessible.ObjectEvents.TextChanged += OnTextChanged; }
public VendorScreen(Game game, Vector2i size, PlayerPawn pawn) : base(game, size) { this.pawn = pawn; buyButtons = new VendorButton[0]; sellButtons = new VendorButton[0]; UpdateSell(pawn.GetKnownSpellIds()); vendorText.SetText(vendorText.GetText() + "\n\nYou can currently know @FFFFFF" + pawn.SpellSlotCount.GetValue() + "@- spells."); }
public void AddText() { string testString = "Ali"; builder.AddText(testString); Paragraph paragraph = builder.GetParagraph(); Text textContent = (Text)paragraph.GetChildren()[0]; Assert.Equal(testString, textContent.GetText()); }
private void HandleText(XmlReader reader) { Text text = new Text(reader.Value); if (isUnderlined) { text.SetUnderline(); } if (0 != text.GetText().Length) { paragraph.Add(text); } }
private static void displayMenu() { MenuItem[] menu = Menu.loadXMLMenu(); var output = string.Empty; output += string.Format("{0}{1}", "=============", Environment.NewLine); output += string.Format("{0}{1}", "Key | Menu", Environment.NewLine); output += string.Format("{0}{1}", "=====|=======", Environment.NewLine); foreach (MenuItem menuItem in menu) { output += string.Format("{0} | {1}{2}", menuItem.ActivationKey, Text.GetText(menuItem.TextKey, Menu.textItems), Environment.NewLine); } output += string.Format("{0}{1}", "=============", Environment.NewLine); System.Console.WriteLine(output); }
public static string GetXmlIdentifierBeforeIndex(Text editor, int index) { if (editor == null) { throw new ArgumentNullException("document"); } if (index < 0 || index > editor.ContentLength) { throw new ArgumentOutOfRangeException("index", index, "Value must be between 0 and " + editor.ContentLength); } int i = index - 1; while (i >= 0 && IsXmlNameChar(editor.GetCharAt(i)) && editor.GetCharAt(i) != '/') { i--; } return(editor.GetText(i + 1, index - i - 1)); }
protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); // TODO: Add your drawing code here _spriteBatch.Begin(); _spriteBatch.Draw(background, Vector2.Zero, null, Color.White, 0f, Vector2.Zero, _scale, SpriteEffects.None, 0f); _spriteBatch.Draw(enemy.GetAsset(), new Vector2(enemy.GetxPosition(), enemy.GetyPosition()), null, Color.White, 0f, new Vector2(enemy.GetAsset().Width / 2, enemy.GetAsset().Height / 2), _scale, SpriteEffects.None, 0f); _spriteBatch.Draw(enemy.GetAsset(), new Vector2(enemy2.GetxPosition(), enemy2.GetyPosition()), null, Color.White, 0f, new Vector2(enemy2.GetAsset().Width / 2, enemy2.GetAsset().Height / 2), _scale, SpriteEffects.None, 0f); _spriteBatch.Draw(enemy.GetAsset(), new Vector2(enemy3.GetxPosition(), enemy3.GetyPosition()), null, Color.White, 0f, new Vector2(enemy3.GetAsset().Width / 2, enemy3.GetAsset().Height / 2), _scale, SpriteEffects.None, 0f); _spriteBatch.Draw(enemy.GetAsset(), new Vector2(enemy4.GetxPosition(), enemy4.GetyPosition()), null, Color.White, 0f, new Vector2(enemy4.GetAsset().Width / 2, enemy4.GetAsset().Height / 2), _scale, SpriteEffects.None, 0f); _spriteBatch.Draw(enemy.GetAsset(), new Vector2(enemy5.GetxPosition(), enemy5.GetyPosition()), null, Color.White, 0f, new Vector2(enemy5.GetAsset().Width / 2, enemy5.GetAsset().Height / 2), _scale, SpriteEffects.None, 0f); _spriteBatch.Draw(treasure.GetAsset(), new Vector2(treasure.GetxPosition(), treasure.GetyPosition()), null, Color.White, 0f, new Vector2(treasure.GetAsset().Width / 2, treasure.GetAsset().Height / 2), _scale, SpriteEffects.None, 0f); _spriteBatch.Draw(player.GetAsset(), new Vector2(player.GetxPosition(), player.GetyPosition()), null, Color.White, 0f, new Vector2(player.GetAsset().Width / 2, player.GetAsset().Height / 2), _scale, SpriteEffects.None, 0f); _spriteBatch.DrawString(levelText.GetText(), $"Level {game.GetPlayerLevel()}", new Vector2(levelText.GetxPosition(), levelText.GetyPosition()), Color.White); _spriteBatch.End(); base.Draw(gameTime); }
protected virtual string GetReplacementValue(EventInfo eventInfo) { string text = string.Empty; if (UseMessageValue) { text = GetValue(eventInfo); } else { if (SourceMessageValueType != MessageValueType.Text && SourceIdentifier != null) { switch (SourceMessageValueType) { case MessageValueType.Json: text = (Text?.GetText(eventInfo.Variables) ?? text).GetJsonValue(SourceIdentifier.GetText(eventInfo.Variables)) ?? string.Empty; break; case MessageValueType.Xml: text = (Text?.GetText(eventInfo.Variables) ?? text).GetXmlValue(SourceIdentifier.GetText(eventInfo.Variables)) ?? string.Empty; break; } } else { text = Text?.GetText(eventInfo.Variables) ?? text; } } if (PromptValue) { text = GetPromptValue(eventInfo, PromptDescription.GetText(eventInfo.Variables), text); } if (UseReplace && ReplacementText != null) { Regex regex = new Regex(RegexPattern.GetText(eventInfo.Variables)); text = regex.Replace(text, ReplacementText.GetText(eventInfo.Variables)); } return(text); }
private SyntaxToken LexDirectiveToken() { _kind = SyntaxKind.BadToken; _contextualKind = SyntaxKind.BadToken; _diagnostics.Clear(); _start = _charReader.Position; var trailingTrivia = new List <SyntaxNode>(); var isEndOfLine = false; switch (_charReader.Current) { case '#': NextChar(); if (_charReader.Current == '#') { NextChar(); _kind = SyntaxKind.HashHashToken; } else { _kind = SyntaxKind.HashToken; _currentDirectiveKind = null; } break; case '\r': case '\n': _kind = SyntaxKind.EndOfDirectiveToken; _currentDirectiveKind = null; isEndOfLine = true; break; case '\0': _kind = SyntaxKind.EndOfDirectiveToken; _currentDirectiveKind = null; break; case '<': if (_currentDirectiveKind != SyntaxKind.IncludeKeyword) { goto default; } ReadBracketedString(); break; default: ReadToken(); if (_contextualKind.IsPreprocessorDirective()) { _currentDirectiveKind = _contextualKind; } break; } var end = _charReader.Position; var kind = _kind; var span = TextSpan.FromBounds(Text.Filename, _start, end); var text = Text.GetText(span); var diagnostics = _diagnostics.ToImmutableArray(); LexDirectiveTrailingTrivia(trailingTrivia, kind, isEndOfLine); var token = new SyntaxToken(kind, _contextualKind, false, MakeAbsolute(span), span, text, _value, ImmutableArray <SyntaxNode> .Empty, trailingTrivia.ToImmutableArray(), diagnostics, null, false); return(token); }
/// <summary> /// /// </summary> /// <param name="text"></param> /// <param name="elementStartIndex"></param> /// <param name="editor"></param> /// <returns></returns> public static bool ElementStartsWith(string text, int elementStartIndex, Text editor) { int textLength = Math.Min(text.Length, editor.ContentLength - elementStartIndex); return(editor.GetText(elementStartIndex, textLength).Equals(text, StringComparison.OrdinalIgnoreCase)); }
public override string GetText() => "<p>" + Text.GetText() + "</p>";
/// <summary> /// Входная точка для приёма сообщений /// </summary> /// <param name="message">Сообщение</param> /// <returns></returns> public async Task InPoint(Message message) { //Присвеваем время последней активности LastTimeActive = message.Date; //Присваеваем цикл временной активности LastCycleActive = GetCycle(); #region Command Exit //Проверка на команды выходы из сессии var testExit = message.Text.ToLower(); if (testExit == "exit") { await Sender(ContentToMessage(_text.GetText(NameText.ExitSession, Language))); //Перевод состояния в ожидание idTeam State = UserState.SpamGetIdTeam; return; } #endregion #region Время и Speed Messaging if (State == UserState.RouteMessage) { //Вычисление времени последней активности var time = message.Date.Subtract(LastTimeActive); //Проверка высокой скорости отправки сообщений //Чаще 1 сообщения в 15 секунд if (time.TotalSeconds < 15) { //Увеличение счётчика нарушений CountSpeedMessage++; //Нарушение 3 раза if (CountSpeedMessage > 3) { await Sender(ContentToMessage(_text.GetText(NameText.SpeedMessaging, Language))); } //Нарушение 5 раз if (CountSpeedMessage > 5) { await Sender(ContentToMessage(_text.GetText(NameText.SpamSpeedMessaging, Language))); State = UserState.SpamSpeedMessaging; //Выход из метода return; } } else { //Обнуляем счётчик CountSpeedMessage = 0; } } #endregion //Реализация хранения состояния пользователя switch (State) { case UserState.Started: //Старт { //Отправляем приветствие await Sender(ContentToMessage(_text.GetText(NameText.Hello, Language.Russian))); //Отправляем просьбу выбрать язык await Sender(ContentToMessage(_text.GetText(NameText.Language, Language.Russian))); //Изменяем состояние в позицию ожидания цыфры языка State = UserState.Selectlanguage; } break; case UserState.Selectlanguage: //Выбор языка { var text = message.Text.ToLower(); switch (text) { case "1": { //Присваеваем значение языка Language = Language.Russian; await Sender(ContentToMessage(_text.GetText(NameText.SucessSelectLanguage, Language))); //Изменяем состояние в ожидание идентификатора Team State = UserState.SelectGetIdTeam; //Просьба прислать id Team await Sender(ContentToMessage(_text.GetText(NameText.GetIdTeam, Language))); } break; case "2": { //Присваеваем значение языка Language = Language.English; await Sender(ContentToMessage(_text.GetText(NameText.SucessSelectLanguage, Language))); //Изменяем состояние в ожидание идентификатора Team State = UserState.SelectGetIdTeam; //Просьба прислать id Team await Sender(ContentToMessage(_text.GetText(NameText.GetIdTeam, Language))); } break; default: { //На случай ошибки в выборе языка await Sender(ContentToMessage(_text.GetText(NameText.ErrorIdTeam, Language.Russian))); //Увеличиваем счётчик ошибок ввода языка CountErrorSelectLenguage++; } break; } //Проверка на спам во время выбора языка if (CountErrorSelectLenguage > 5) { //Перевод в состояние бана по SpamSelectlanguage State = UserState.SpamSelectlanguage; //На случай ошибки в выборе языка await Sender(ContentToMessage(_text.GetText(NameText.SpamSelectLanguage, Language.Russian))); //Присваеваем занчние внцтреплатформенного цикла СycleEvent = GetCycle(); } } break; case UserState.SpamSelectlanguage: //Спам по выбору языка { await Sender(ContentToMessage(_text.GetText(NameText.SpamSelectLanguage, Language.Russian))); } break; case UserState.SelectGetIdTeam: //Ввод id { var text = message.Text.ToLower(); //Проверка присланного идентификтаора Team if (await ExistIdTeam(text)) { //Присваеваем idTeam TeamId = text; //Отправляем Сообщение что всё ок await Sender(ContentToMessage(_text.GetText(NameText.SucessIdTeam, Language))); //Переводим в режим роутинга сообщений на API State = UserState.RouteMessage; } else { //Отправляем ошибку await Sender(ContentToMessage(_text.GetText(NameText.ErrorIdTeam, Language))); //Увеличиваем счётчик ошибок ввода id CountErrorSelectTeamId++; } //Проверка на Spam if (CountErrorSelectTeamId > 5) { //Отправляем сообщение с баном по вводу id await Sender(ContentToMessage(_text.GetText(NameText.SpamIdTeam, Language))); State = UserState.SpamGetIdTeam; //Присваеваем занчние внцтреплатформенного цикла СycleEvent = GetCycle(); } } break; case UserState.SpamGetIdTeam: //Спам по вводу id { await Sender(ContentToMessage(_text.GetText(NameText.SpamIdTeam, Language))); } break; case UserState.RouteMessage: //Роутинг сообщений в API { await Sender(ContentToMessage(new Content() { Text = message.Text })); // TODO Добавить код } break; case UserState.SpamSpeedMessaging: //Спам с высокой скоросью { await Sender(ContentToMessage(_text.GetText(NameText.SpamSpeedMessaging, Language))); } break; } }
public override string GetText() => "<strong>" + Text.GetText() + "</strong>";
public string GetSubstringAt(int start, int length) { return(Text.GetText(new TextRange(start, length))); }
public override string GetText() => "<em>" + Text.GetText() + "</em>";
public static void Init(IokeObject rl) { Runtime runtime = rl.runtime; rl.Kind = "Readline"; rl.MimicsWithoutCheck(runtime.Origin); runtime.Ground.SetCell("Readline", rl); rl.SetCell("VERSION", runtime.NewText("Mono.Terminal.LineEditor wrapper")); ConsoleHolder holder = new ConsoleHolder(); holder.history = new History("ioke", 10); IokeObject history = runtime.NewFromOrigin(); rl.SetCell("HISTORY", history); rl.RegisterMethod(runtime.NewNativeMethod("will print a prompt to standard out and then try to read a line with working readline functionality. takes two arguments, the first is the string to prompt, the second is a boolean that says whether we should add the read string to history or not", new NativeMethod("readline", DefaultArgumentsDefinition.builder() .WithRequiredPositional("prompt") .WithRequiredPositional("addToHistory?") .Arguments, (method, context, message, on, outer) => { var args = new SaneArrayList(); outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary <string, object>()); object line = method.runtime.nil; try { if (holder.readline == null) { InitReadline(method.runtime, holder); } string v = holder.readline.Edit(Text.GetText(args[0]), ""); if (null != v) { if (IokeObject.IsObjectTrue(args[1])) { holder.history.Append(v); } line = method.runtime.NewText(v); } } catch (IOException e) { IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition, message, context, "Error", "IO"), context).Mimic(message, context); condition.SetCell("message", message); condition.SetCell("context", context); condition.SetCell("receiver", on); condition.SetCell("exceptionMessage", runtime.NewText(e.Message)); var st = new System.Diagnostics.StackTrace(e); var ob = new SaneArrayList(); foreach (var frame in st.GetFrames()) { ob.Add(runtime.NewText(frame.ToString())); } condition.SetCell("exceptionStackTrace", runtime.NewList(ob)); runtime.WithReturningRestart("ignore", context, () => { runtime.ErrorCondition(condition); }); } return(line); }))); history.RegisterMethod(runtime.NewNativeMethod("will add a new line to the history", new NativeMethod("<<", DefaultArgumentsDefinition.builder() .WithRequiredPositional("line") .Arguments, (method, context, message, on, outer) => { var args = new SaneArrayList(); outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary <string, object>()); foreach (object o in args) { holder.history.Append(Text.GetText(o)); } return(context.runtime.nil); }))); }
static void Main(string[] args) { string strochka1 = "садок вишневий коло хати,"; string strochka2 = "хрущi над вишнями гудуть,"; string strochka3 = "плугатарi з плугами йдуть,"; string strochka4 = "спiвають iдучи дiвчата,"; Line line1 = new Line(strochka1.ToCharArray(), strochka1.Length); Line line2 = new Line(strochka2.ToCharArray(), strochka2.Length); Line line3 = new Line(strochka3.ToCharArray(), strochka3.Length); Line line4 = new Line(strochka4.ToCharArray(), strochka4.Length); Text text = new Text(line1); text.AddToText(line2); text.AddToText(line3); text.AddToText(line4); char[][] chars = text.GetText(); Console.WriteLine("Current text"); text.OutputText(chars, text.GetNumberOfStr()); Console.WriteLine("'1' - to add a string, \n'2' - to delete a string, " + "\n'3' - to delete strings that contains a word, " + "\n'4' - to clear a text, \n'5' - to get a length of the longest string, " + "\n'6' - to make first letters to uppercase, \n'7' - to see this message"); for (int n = 0; n < 7; n++) { Console.Write("input a num: "); string inputed = Console.ReadLine(); if (CorrectConvert(inputed)) { int choice = int.Parse(inputed); switch (choice) { case 1: string strochka5 = "а матерi вечерять ждуть."; Line line5 = new Line(strochka5.ToCharArray(), strochka5.Length); text.AddToText(line5); chars = text.GetText(); Console.WriteLine("Current text"); text.OutputText(chars, text.GetNumberOfStr()); break; case 2: Console.WriteLine("please, enter an index: "); int index = int.Parse(Console.ReadLine()); text.DeleteLine(index); chars = text.GetText(); Console.WriteLine("Current text"); text.OutputText(chars, text.GetNumberOfStr()); break; case 3: Console.WriteLine("please, enter a substring"); string str = Console.ReadLine(); text.DeleteStringWhichContainsWord(str.ToCharArray(), str.Length); chars = text.GetText(); Console.WriteLine("Current text"); text.OutputText(chars, text.GetNumberOfStr()); break; case 4: text.Erase(); chars = text.GetText(); Console.WriteLine("Current text"); text.OutputText(chars, text.GetNumberOfStr()); break; case 5: int length = text.TheBigestLength(); Console.WriteLine($"the biggest length is: {length}"); break; case 6: text.UpperCase(); chars = text.GetText(); Console.WriteLine("Current text"); text.OutputText(chars, text.GetNumberOfStr()); break; case 7: Console.WriteLine("'1' - to add a string, \n'2' - to delete a string, " + "\n'3' - to delete strings that contains a word, " + "\n'4' - to clear a text, \n'5' - to get a length of the longest string, " + "\n'6' - to make first letters to uppercase, \n'7' - to see this message"); break; default: Console.WriteLine("error"); break; } } } }
public string GetText() { return(Text.GetText(_start, _length)); }
public override string GetText() => "<mark>" + Text.GetText() + "</mark>";