Here are the examples of the csharp api System.Collections.Generic.HashSet.Add(char) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
37 Examples
19
Source : 3. Longest Substring Without Repeating Characters.cs
with MIT License
from AlexChesser
with MIT License
from AlexChesser
public int LengthOfLongestSubstring(string s)
{
int max = 0;
HashSet<char> substring = new HashSet<char>();
int left = 0, right = 0;
while (right < s.Length)
{
if (!substring.Contains(s[right]))
{
substring.Add(s[right++]);
max = Math.Max(max, substring.Count);
}
else
{
substring.Remove(s[left++]);
}
}
return max;
}
19
Source : OcrEngineAsian.cs
with MIT License
from Bphots
with MIT License
from Bphots
public override OcrResult ProcessOcr(double count, string path, HashSet<string> candidates)
{
var ocrResult = new OcrResult();
var checkDva = false;
var textCount = (int) count;
var heroesSet = new HashSet<char>();
foreach (
var character in candidates.Where(c => c.Count() == textCount).SelectMany(c => c).Where(c => c > 255))
heroesSet.Add(character);
if (textCount == 2 && Math.Abs(count - 2.5) < 0.35)
{
checkDva = true;
heroesSet.Add('D');
heroesSet.Add('V');
heroesSet.Add('A');
}
if (!heroesSet.Any())
return ocrResult;
var whiteList = heroesSet.Aggregate(string.Empty, (current, character) => current + character);
Engine.SetVariable("tessedit_char_whitelist", whiteList);
FilePath filePath = path;
if (count >= 7)
{
using (var bitMap = new Bitmap(filePath))
{
using (var extendedBitmap = ExtendImage(bitMap))
{
extendedBitmap.Save(filePath.GetDirPath() + @"tempExtended.bmp");
filePath = filePath.GetDirPath() + @"tempExtended.bmp";
}
}
}
using (var pix = Pix.LoadFromFile(filePath))
using (var page = Engine.Process(pix))
{
var text = page.GetText();
if (checkDva && IsMathcingDva(text))
{
ocrResult.Results["D.Va"] = new MatchResult
{
Key = text,
Value = "D.Va",
InDoubt = false,
Score = 6,
Trustable = true,
FullyTrustable = true
};
return ocrResult;
}
var textTrim = text.Trim();
if (textCount == 2 && textTrim.Length >= 2 && textTrim[0] != '丽' && textTrim[0] == textTrim[1])
{
text = @"丽X";
}
foreach (var hero in candidates.Where(s => s.Length == textCount))
{
var score = CalculateScore(text, hero);
if (score > 0)
{
var trustable = !checkDva &&
((score / (double)(textCount * FullyMatchScore) > 0.66 && count >= 2) ||
(score / (double)(textCount * FullyMatchScore) >= 0.5 && count >= 4));
if (!trustable && hero == "加尔")
continue;
ocrResult.Results[hero] = new MatchResult
{
Key = text,
Value = hero,
InDoubt = score / (double)(textCount * FullyMatchScore) <= 0.5 || textCount <= 1,
Score = score,
Trustable = trustable,
FullyTrustable = textCount >= 2 && score == textCount * FullyMatchScore
};
}
}
return ocrResult;
}
}
19
Source : OcrEngineAsian.cs
with MIT License
from Bphots
with MIT License
from Bphots
public override OcrResult ProcessOcr(string path, HashSet<string> candidates)
{
var ocrResult = new OcrResult();
var heroesSet = new HashSet<char>();
foreach (var character in candidates.SelectMany(c => c))
heroesSet.Add(character);
if (!heroesSet.Any())
return ocrResult;
var whiteList = heroesSet.Aggregate(string.Empty, (current, character) => current + character);
Engine.SetVariable("tessedit_char_whitelist", whiteList);
var inDoubt = false;
using (var pix = Pix.LoadFromFile(path))
using (var page = Engine.Process(pix))
{
var text = page.GetText();
var match = string.Empty;
var maxScore = 0;
foreach (var candidate in candidates)
{
var score = CalculateScore(text, candidate);
if (maxScore == score)
inDoubt = true;
if (maxScore < score)
{
maxScore = score;
match = candidate;
}
}
ocrResult.Results[match] = new MatchResult
{
Key = text,
Value = match,
InDoubt = inDoubt,
Score = maxScore,
Trustable = maxScore/(double) (match.Length*FullyMatchScore) >= 0.3,
FullyTrustable = maxScore / (double)(match.Length * FullyMatchScore) >= 0.66
};
return ocrResult;
}
}
19
Source : CharRange.cs
with MIT License
from codewitch-honey-crisis
with MIT License
from codewitch-honey-crisis
public static IEnumerable<char> ExpandRanges(IEnumerable<CharRange> ranges)
{
var seen = new HashSet<char>();
foreach (var range in ranges)
foreach (char ch in range)
if(seen.Add(ch))
yield return ch;
}
19
Source : LeapTextRenderer.cs
with MIT License
from crookookoo
with MIT License
from crookookoo
private void generateTextMesh(int index, LeapTextGraphic graphic, Mesh mesh) {
using (new ProfilerSample("Generate Text Mesh")) {
Color globalTintConverted;
Color graphicColorConverted;
if (QualitySettings.activeColorSpace == ColorSpace.Linear) {
globalTintConverted = _globalTint.linear;
graphicColorConverted = graphic.color.linear;
} else {
globalTintConverted = _globalTint;
graphicColorConverted = graphic.color;
}
mesh.Clear(keepVertexLayout: false);
graphic.isRepresentationDirty = false;
int scaledFontSize = Mathf.RoundToInt(graphic.fontSize * _dynamicPixelsPerUnit);
//Check for characters not found in the font
{
HashSet<char> unfoundCharacters = null;
CharacterInfo info;
foreach (var character in graphic.text) {
if (character == '\n') {
continue;
}
if (unfoundCharacters != null && unfoundCharacters.Contains(character)) {
continue;
}
if (!_font.GetCharacterInfo(character, out info, scaledFontSize, graphic.fontStyle)) {
if (unfoundCharacters == null) unfoundCharacters = new HashSet<char>();
unfoundCharacters.Add(character);
Debug.LogError("Could not find character [" + character + "] in font " + _font + "!");
}
}
}
var text = graphic.text;
float _charScale = this._scale * SCALE_CONSTANT / _dynamicPixelsPerUnit;
float _scale = _charScale * graphic.fontSize / _font.fontSize;
float lineHeight = _scale * graphic.lineSpacing * _font.lineHeight * _dynamicPixelsPerUnit;
RectTransform rectTransform = graphic.transform as RectTransform;
float maxWidth;
if (rectTransform != null) {
maxWidth = rectTransform.rect.width;
} else {
maxWidth = float.MaxValue;
}
_widthCalculator.font = _font;
_widthCalculator.charScale = _charScale;
_widthCalculator.fontStyle = graphic.fontStyle;
_widthCalculator.scaledFontSize = scaledFontSize;
TextWrapper.Wrap(text, graphic.tokens, _tempLines, _widthCalculator.func, maxWidth);
float textHeight = _tempLines.Count * lineHeight;
Vector3 origin = Vector3.zero;
origin.y -= _font.ascent * _scale * _dynamicPixelsPerUnit;
if (rectTransform != null) {
origin.y -= rectTransform.rect.y;
switch (graphic.verticalAlignment) {
case LeapTextGraphic.VerticalAlignment.Center:
origin.y -= (rectTransform.rect.height - textHeight) / 2;
break;
case LeapTextGraphic.VerticalAlignment.Bottom:
origin.y -= (rectTransform.rect.height - textHeight);
break;
}
}
foreach (var line in _tempLines) {
if (rectTransform != null) {
origin.x = rectTransform.rect.x;
switch (graphic.horizontalAlignment) {
case LeapTextGraphic.HorizontalAlignment.Center:
origin.x += (rectTransform.rect.width - line.width) / 2;
break;
case LeapTextGraphic.HorizontalAlignment.Right:
origin.x += (rectTransform.rect.width - line.width);
break;
}
} else {
switch (graphic.horizontalAlignment) {
case LeapTextGraphic.HorizontalAlignment.Left:
origin.x = 0;
break;
case LeapTextGraphic.HorizontalAlignment.Center:
origin.x = -line.width / 2;
break;
case LeapTextGraphic.HorizontalAlignment.Right:
origin.x = -line.width;
break;
}
}
for (int i = line.start; i < line.end; i++) {
char c = text[i];
CharacterInfo info;
if (!_font.GetCharacterInfo(c, out info, scaledFontSize, graphic.fontStyle)) {
continue;
}
int offset = _verts.Count;
_tris.Add(offset + 0);
_tris.Add(offset + 1);
_tris.Add(offset + 2);
_tris.Add(offset + 0);
_tris.Add(offset + 2);
_tris.Add(offset + 3);
_verts.Add(_charScale * new Vector3(info.minX, info.maxY, 0) + origin);
_verts.Add(_charScale * new Vector3(info.maxX, info.maxY, 0) + origin);
_verts.Add(_charScale * new Vector3(info.maxX, info.minY, 0) + origin);
_verts.Add(_charScale * new Vector3(info.minX, info.minY, 0) + origin);
_uvs.Add(info.uvTopLeft);
_uvs.Add(info.uvTopRight);
_uvs.Add(info.uvBottomRight);
_uvs.Add(info.uvBottomLeft);
if (_useColor) {
_colors.Append(4, globalTintConverted * graphicColorConverted);
}
origin.x += info.advance * _charScale;
}
origin.y -= lineHeight;
}
for (int i = 0; i < _uvs.Count; i++) {
Vector4 uv = _uvs[i];
uv.w = index;
_uvs[i] = uv;
}
mesh.SetVertices(_verts);
mesh.SetTriangles(_tris, 0);
mesh.SetUVs(0, _uvs);
if (_useColor) {
mesh.SetColors(_colors);
}
_verts.Clear();
_uvs.Clear();
_tris.Clear();
_colors.Clear();
_tempLines.Clear();
}
}
19
Source : ServerCookieEncoderTest.cs
with MIT License
from cuteant
with MIT License
from cuteant
[Fact]
public void IllegalCharInCookieNameMakesStrictEncoderThrowsException()
{
var illegalChars = new HashSet<char>();
// CTLs
for (int i = 0x00; i <= 0x1F; i++)
{
illegalChars.Add((char)i);
}
illegalChars.Add((char)0x7F);
var separaters = new []
{
'(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/', '[', ']',
'?', '=', '{', '}', ' ', '\t'
};
// separators
foreach(char c in separaters)
{
illegalChars.Add(c);
}
foreach (char c in illegalChars)
{
replacedert.Throws<ArgumentException>(() => ServerCookieEncoder.StrictEncoder.Encode(
new DefaultCookie("foo" + c + "bar", "value")));
}
}
19
Source : ServerCookieEncoderTest.cs
with MIT License
from cuteant
with MIT License
from cuteant
[Fact]
public void IllegalCharInCookieValueMakesStrictEncoderThrowsException()
{
var illegalChars = new HashSet<char>();
// CTLs
for (int i = 0x00; i <= 0x1F; i++)
{
illegalChars.Add((char)i);
}
illegalChars.Add((char)0x7F);
// whitespace, DQUOTE, comma, semicolon, and backslash
var separaters = new[]
{
' ', '"', ',', ';', '\\'
};
foreach(char c in separaters)
{
illegalChars.Add(c);
}
foreach (char c in illegalChars)
{
replacedert.Throws<ArgumentException>(() => ServerCookieEncoder.StrictEncoder.Encode(
new DefaultCookie("name", "value" + c)));
}
}
19
Source : RecognitionOption.cs
with MIT License
from CXuesong
with MIT License
from CXuesong
public static void Validate(IEnumerable<RecognitionOption> choices)
{
Utils.replacedertArgument(choices != null, "choices list cannot be null");
Utils.replacedertArgument(choices.Any(), "choices list cannot be empty");
HashSet<string> speechChoice = new HashSet<string>();
HashSet<char> dtmfChoice = new HashSet<char>();
foreach (var choice in choices)
{
Utils.replacedertArgument(choice != null, "choice cannot be null");
choice.Validate();
if (choice.DtmfVariation.HasValue)
{
char c = choice.DtmfVariation.Value;
Utils.replacedertArgument(!dtmfChoice.Contains(c), "Dtmf choices must be uniquely specified across all recognition options");
dtmfChoice.Add(c);
}
if (choice.SpeechVariation != null)
{
foreach (string sc in choice.SpeechVariation)
{
Utils.replacedertArgument(!speechChoice.Contains(sc), "Speech choices must be uniquely specified across all recognition options");
speechChoice.Add(sc);
}
}
}
}
19
Source : StringUtils.cs
with MIT License
from daxnet
with MIT License
from daxnet
public new void Add(char ch) {
if (_caseSensitive)
base.Add(ch);
else {
base.Add(char.ToLowerInvariant(ch));
base.Add(char.ToUpperInvariant(ch));
}
}
19
Source : StepImplementation.cs
with Apache License 2.0
from getgauge
with Apache License 2.0
from getgauge
[Step("Dll Reference: Vowels in English language are <vowelString>.")]
public void SetLanguageVowels(string vowelString)
{
_vowels = new HashSet<char>();
foreach (var c in vowelString)
{
_vowels.Add(c);
}
}
19
Source : StepImplementation.cs
with Apache License 2.0
from getgauge
with Apache License 2.0
from getgauge
[Step("Project Reference: Vowels in English language are <vowelString>.")]
public void SetLanguageVowels(string vowelString)
{
_vowels = new HashSet<char>();
foreach (var c in vowelString)
{
_vowels.Add(c);
}
}
19
Source : FF8TextEncodingCodepage.cs
with MIT License
from MaKiPL
with MIT License
from MaKiPL
public void GetParameters(out char[] chars, out HashSet<char>[] bytes)
{
chars = (char[])_chars.Clone();
bytes = new HashSet<char>[256];
for (var i = 0; i < 256; i++)
bytes[i] = new HashSet<char>();
foreach (var pair in _bytes)
bytes[pair.Value].Add(pair.Key);
}
19
Source : WindowsReFsVhdSession.cs
with MIT License
from microsoft
with MIT License
from microsoft
public static WindowsReFsVhdSession Create()
{
var driveLetterHashSet = new HashSet<char>();
foreach (DriveInfo driveInfo in DriveInfo.GetDrives())
{
driveLetterHashSet.Add(char.ToUpper(driveInfo.Name[0]));
}
bool openDriveLetterFound = false;
char openDriveLetter = 'B';
for (; openDriveLetter <= 'Z'; openDriveLetter++)
{
if (driveLetterHashSet.Contains(openDriveLetter))
{
continue;
}
openDriveLetterFound = true;
break;
}
if (!openDriveLetterFound)
{
throw new InvalidOperationException("No open drive letters found to use for mounting a ReFS VHD");
}
string replacedemblyDirectory = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location) ?? string.Empty;
string createVhdScriptPath = Path.Combine(replacedemblyDirectory, "CreateReFSVhd.ps1");
string removeVhdScriptPath = Path.Combine(replacedemblyDirectory, "RemoveVhd.ps1");
if (!File.Exists(createVhdScriptPath) || !File.Exists(removeVhdScriptPath))
{
throw new InvalidOperationException("Missing create/remove scripts in same directory as this replacedembly");
}
RunPowershellScript(createVhdScriptPath, $"{openDriveLetter}");
return new WindowsReFsVhdSession(openDriveLetter, removeVhdScriptPath);
}
19
Source : BraceCompletionAggregator.cs
with MIT License
from microsoft
with MIT License
from microsoft
private void Init()
{
HashSet<char> closing = new HashSet<char>();
_providerCache = new Dictionary<char,Dictionary<IContentType, List<ProviderHelper>>>();
_contentTypeCache = new Dictionary<char, List<IContentType>>();
List<ProviderHelper> providerHelpers = new List<ProviderHelper>();
providerHelpers.AddRange(_factory.SessionProviders.Select(p => new ProviderHelper(p)));
providerHelpers.AddRange(_factory.ContextProviders.Select(p => new ProviderHelper(p)));
providerHelpers.AddRange(_factory.DefaultProviders.Select(p => new ProviderHelper(p)));
// build the cache
// opening brace -> content type -> provider
foreach (ProviderHelper providerHelper in providerHelpers)
{
foreach (char closeChar in providerHelper.Metadata.ClosingBraces)
{
closing.Add(closeChar);
}
foreach (char openingBrace in providerHelper.Metadata.OpeningBraces)
{
// opening brace level
Dictionary<IContentType, List<ProviderHelper>> providersForBrace;
if (!_providerCache.TryGetValue(openingBrace, out providersForBrace))
{
providersForBrace = new Dictionary<IContentType, List<ProviderHelper>>();
_providerCache.Add(openingBrace, providersForBrace);
}
// convert the type names into IContentTypes for the cache
foreach (IContentType contentType in providerHelper.Metadata.ContentTypes.Select((typeName)
=> _factory.ContentTypeRegistryService.GetContentType(typeName))
.Where((t) => t != null))
{
// content type level
List<ProviderHelper> curProviders;
if (!providersForBrace.TryGetValue(contentType, out curProviders))
{
curProviders = new List<ProviderHelper>();
providersForBrace.Add(contentType, curProviders);
}
curProviders.Add(providerHelper);
}
Debug.replacedert(providersForBrace != null && providersForBrace.Count > 0, "providersForBrace should not be empty");
}
}
_openingBraces = String.Join(String.Empty, _providerCache.Keys);
_closingBraces = String.Join(String.Empty, closing);
// sort caches
foreach (KeyValuePair<char, Dictionary<IContentType, List<ProviderHelper>>> cache in _providerCache)
{
// sort the list of content types so the most specific ones are first
_contentTypeCache.Add(cache.Key, SortContentTypes(cache.Value.Keys.ToList()));
Debug.replacedert(!_contentTypeCache[cache.Key].Any(t =>
_contentTypeCache[cache.Key].Where(tt =>
tt.TypeName.Equals(t.TypeName, StringComparison.OrdinalIgnoreCase)).Count() != 1),
"duplicate content types");
// sort the providers by type
foreach (IContentType t in cache.Value.Keys)
{
cache.Value[t].Sort();
}
}
}
19
Source : FontGenerator.cs
with GNU General Public License v3.0
from mrojkov
with GNU General Public License v3.0
from mrojkov
private static void ExtractCharacters(LocalizationDictionary dictionary, HashSet<char> chars,
Dictionary<char, int> frequency)
{
foreach (var (_, value) in dictionary) {
if (value.Text == null) {
continue;
}
foreach (var c in value.Text) {
if (c != '\n' && !char.IsSurrogate(c)) {
chars.Add(c);
frequency[c] = frequency.TryGetValue(c, out var v) ? v + 1 : 1;
}
}
}
}
19
Source : Sut.cs
with MIT License
from nemesissoft
with MIT License
from nemesissoft
private static ITransformerStore BuildRandomStore()
{
static bool IsChar(Type t) => t == typeof(char) || t == typeof(char?);
var settingTypes = new[]
{
typeof(ArraySettings), typeof(CollectionSettings), typeof(DictionarySettings),
typeof(DeconstructableSettings), typeof(KeyValuePairSettings), typeof(ValueTupleSettings),
};
int seed = Environment.TickCount / 10;
var special = new[] { '\\', '|', ';', '=', '∅', ',', '{', '}', '[', ']', '(', ')', '⮿', '␀', '!', '@', '#', '$', '%', '&' };
Stack<char> GetRandomChars(int length, string reason)
{
seed += 10;
Console.WriteLine($"Seed for {reason} = {seed}");
var rand = new Random(seed);
var result = new HashSet<char>(
#if !NET461 && !NET47
length
#endif
);
do
{
result.Add(
special[rand.Next(special.Length)]
);
} while (result.Count < length);
return new Stack<char>(result);
}
var settings = new List<ISettings>();
foreach (var settingType in settingTypes)
{
var ctor = settingType.GetConstructors().Select(c => (Ctor: c, Params: c.GetParameters()))
.Where(pair => (pair.Params?.Length ?? 0) > 0)
.OrderByDescending(p => p.Params.Length)
.FirstOrDefault().Ctor ?? throw new NotSupportedException($"No suitable constructor found for {settingType}");
var @params = ctor.GetParameters();
var charNum = @params.Count(p => IsChar(p.ParameterType));
var chars = GetRandomChars(charNum, settingType.Name);
var args = @params
.Select(p => p.ParameterType)
.Select(t => IsChar(t) ? chars.Pop() : TypeMeta.GetDefault(t))
.ToArray();
settings.Add((ISettings)ctor.Invoke(args));
}
var settingsStoreBuilder = SettingsStoreBuilder.GetDefault();
foreach (var s in settings)
settingsStoreBuilder.AddOrUpdate(s);
return TextTransformer.GetDefaultStoreWith(settingsStoreBuilder.Build());
}
19
Source : BlockCompletionTest.cs
with GNU Lesser General Public License v2.1
from planetarium
with GNU Lesser General Public License v2.1
from planetarium
[Fact(Timeout = Timeout)]
public async Task Complete()
{
// 0, 1: Already existed blocks
// 2, 3, 4, 5, 6: first chunk
// 7, 8, 9, 10, 11: second chunk
// 12, 13, 14: last chunk
ImmutableArray<Block<DumbAction>> fixture =
GenerateBlocks<DumbAction>(15).ToImmutableArray();
// Blocks each block has:
// A: 0, 4, 8, 12
// B: 1, 5, 9, 13
// C: 2, 6, 10, 14
// D: 3, 7, 11
char[] peers = { 'A', 'B', 'C', 'D' };
ImmutableDictionary<char, ImmutableDictionary<BlockHash, Block<DumbAction>>>
peerBlocks = peers.ToImmutableDictionary(
p => p,
p => fixture.Skip(p - 'A').Where((_, i) => i % 4 < 1).ToImmutableDictionary(
b => b.Hash,
b => b
)
);
const int initialHeight = 2;
const int window = 5;
var bc = new BlockCompletion<char, DumbAction>(
fixture.Take(initialHeight).Select(b => b.Hash).ToImmutableHashSet().Contains,
window
);
ImmutableArray<BlockHash> initialDemands = fixture
.Skip(initialHeight + 10)
.Select(b => b.Hash)
.ToImmutableArray();
bc.Demand(initialDemands);
_logger.Verbose("Initial demands: {0}", initialDemands);
IAsyncEnumerable<Tuple<Block<DumbAction>, char>> rv = bc.Complete(
new[] { 'A', 'B', 'C', 'D' },
(peer, hashes, token) => new AsyncEnumerable<Block<DumbAction>>(async yield =>
{
var blocksPeerHas = peerBlocks[peer];
var sent = new HashSet<BlockHash>();
foreach (BlockHash hash in hashes)
{
if (blocksPeerHas.ContainsKey(hash))
{
Block<DumbAction> block = blocksPeerHas[hash];
await yield.ReturnAsync(block);
sent.Add(block.Hash);
}
}
_logger.Verbose("Peer {Peer} sent blocks: {SentBlockHashes}.", peer, sent);
})
);
var downloadedBlocks = new HashSet<Block<DumbAction>>();
var sourcePeers = new HashSet<char>();
await AsyncEnumerable.ForEachAsync(rv, pair =>
{
downloadedBlocks.Add(pair.Item1);
sourcePeers.Add(pair.Item2);
});
replacedert.Equal(fixture.Skip(2).ToHashSet(), downloadedBlocks);
replacedert.Subset(peers.ToHashSet(), sourcePeers);
}
19
Source : ModificationTableForm.cs
with Apache License 2.0
from ProteoWizard
with Apache License 2.0
from ProteoWizard
private void SetUnimodDefaults(IList<object[]> queryRows)
{
var roundedDeltaMreplacedes = deltaMreplacedTable.Rows.Cast<DataRow>().Select(o => DistinctModificationFormat.Round((double) o[0]));
var mreplacedSet = new HashSet<double>(roundedDeltaMreplacedes);
var siteSet = new HashSet<char>();
foreach (var item in queryRows)
siteSet.Add((char) item[0]);
if (InvokeRequired)
Invoke(new MethodInvoker(() => _unimodControl.SetUnimodDefaults(siteSet, mreplacedSet, DistinctModificationFormat)));
else
_unimodControl.SetUnimodDefaults(siteSet, mreplacedSet, DistinctModificationFormat);
}
19
Source : SequenceUtil.cs
with Apache License 2.0
from ProteoWizard
with Apache License 2.0
from ProteoWizard
public static void ValidateAAList(IEnumerable<char> seq)
{
HashSet<char> seen = new HashSet<char>();
foreach (char c in seq)
{
if (!IsAA(c))
throw new InvalidDataException(string.Format(Resources.AminoAcid_ValidateAAList_Invalid_amino_acid__0__found_in_the_value__1__, c, seq));
if (seen.Contains(c))
throw new InvalidDataException(string.Format(Resources.AminoAcid_ValidateAAList_The_amino_acid__0__is_repeated_in_the_value__1__, c, seq));
seen.Add(c);
}
}
19
Source : EditEnzymeDlg.cs
with Apache License 2.0
from ProteoWizard
with Apache License 2.0
from ProteoWizard
public static bool ValidateAATextBox(this MessageBoxHelper helper, TextBox control, bool allowEmpty, out string aaText)
{
aaText = control.Text.Trim().ToUpperInvariant();
if (aaText.Length == 0)
{
if (!allowEmpty)
{
helper.ShowTextBoxError(control, Resources.EditEnzymeDlg_ValidateAATextBox__0__must_contain_at_least_one_amino_acid);
return false;
}
}
else
{
StringBuilder aaBuilder = new StringBuilder();
HashSet<char> setAA = new HashSet<char>();
foreach (char c in aaText)
{
if (!AminoAcid.IsAA(c))
{
helper.ShowTextBoxError(control, Resources.EditEnzymeDlg_ValidateAATextBox_The_character__0__is_not_a_valid_amino_acid, c);
return false;
}
// Silently strip duplicates.
if (!setAA.Contains(c))
{
aaBuilder.Append(c);
setAA.Add(c);
}
}
aaText = aaBuilder.ToString();
}
return true;
}
19
Source : EditMeasuredIonDlg.cs
with Apache License 2.0
from ProteoWizard
with Apache License 2.0
from ProteoWizard
private static bool ValidateAATextBox(MessageBoxHelper helper, TextBox control, bool allowEmpty, out string aaText)
{
aaText = control.Text.Trim().ToUpperInvariant();
if (aaText.Length == 0)
{
if (!allowEmpty)
{
helper.ShowTextBoxError(control, Resources.EditMeasuredIonDlg_ValidateAATextBox__0__must_contain_at_least_one_amino_acid);
return false;
}
}
else
{
StringBuilder aaBuilder = new StringBuilder();
HashSet<char> setAA = new HashSet<char>();
foreach (char c in aaText)
{
if (!AminoAcid.IsAA(c))
{
helper.ShowTextBoxError(control, Resources.EditMeasuredIonDlg_ValidateAATextBox_The_character__0__is_not_a_valid_amino_acid, c);
return false;
}
// Silently strip duplicates.
if (!setAA.Contains(c))
{
aaBuilder.Append(c);
setAA.Add(c);
}
}
aaText = aaBuilder.ToString();
}
return true;
}
19
Source : FieldFontImporter.cs
with Mozilla Public License 2.0
from RHY3756547
with Mozilla Public License 2.0
from RHY3756547
private static char[] ParseRanges(string ranges)
{
var tuples = ParseTuples(ranges);
var characters = new HashSet<char>();
foreach (var tuple in tuples)
{
// Every tuple should consist of two characters seperated by a comma
var parts = tuple.Split(',');
if (parts.Length != 2)
{
throw new Exception($"Unexpected number of tuple elements in tuple: {tuple}");
}
if (parts[0].Length != 1 || parts[1].Length != 1)
{
throw new Exception($"A tuple can only contain two characters seperated by a comma: {tuple}");
}
// Compute the entire character range from the two extremes (inclusive)
var start = parts[0][0];
var end = parts[1][0];
for (int i = start; i <= end; i++)
{
characters.Add((char) i);
}
}
return characters.ToArray();
}
19
Source : Misc.cs
with GNU Lesser General Public License v2.1
from RPCS3
with GNU Lesser General Public License v2.1
from RPCS3
[Command("rate"), Cooldown(20, 60, CooldownBucketType.Channel)]
[Description("Gives a ~~random~~ expert judgment on the matter at hand")]
public async Task Rate(CommandContext ctx, [RemainingText, Description("Something to rate")] string whatever = "")
{
try
{
var funMult = DateTime.UtcNow.Month == 4 && DateTime.UtcNow.Day == 1 ? 100 : Config.FunMultiplier;
var choices = RateAnswers;
var choiceFlags = new HashSet<char>();
whatever = whatever.ToLowerInvariant().StripInvisibleAndDiacritics().ToCanonicalForm();
var originalWhatever = whatever;
var matches = Instead.Matches(whatever);
if (matches.Any())
{
var insteadWhatever = matches.Last().Groups["instead"].Value.TrimEager();
if (!string.IsNullOrEmpty(insteadWhatever))
whatever = insteadWhatever;
}
foreach (var attachment in ctx.Message.Attachments)
whatever += $" {attachment.FileSize}";
var nekoUser = await ctx.Client.GetUserAsync(272032356922032139ul).ConfigureAwait(false);
var nekoMember = ctx.Client.GetMember(nekoUser);
var nekoMatch = new HashSet<string>(new[] {nekoUser.Id.ToString(), nekoUser.Username, nekoMember?.DisplayName ?? "neko", "neko", "nekotekina",});
var kdUser = await ctx.Client.GetUserAsync(272631898877198337ul).ConfigureAwait(false);
var kdMember = ctx.Client.GetMember(kdUser);
var kdMatch = new HashSet<string>(new[] {kdUser.Id.ToString(), kdUser.Username, kdMember?.DisplayName ?? "kd-11", "kd", "kd-11", "kd11", });
var botUser = ctx.Client.CurrentUser;
var botMember = ctx.Client.GetMember(botUser);
var botMatch = new HashSet<string>(new[] {botUser.Id.ToString(), botUser.Username, botMember?.DisplayName ?? "RPCS3 bot", "yourself", "urself", "yoself",});
var prefix = DateTime.UtcNow.ToString("yyyyMMddHH");
var words = whatever.Split(Separators);
var result = new StringBuilder();
for (var i = 0; i < words.Length; i++)
{
var word = words[i].TrimEager();
var suffix = "";
var tmp = word.TrimEnd(Suffixes);
if (tmp.Length != word.Length)
{
suffix = word[..tmp.Length];
word = tmp;
}
tmp = word.TrimStart(Prefixes);
if (tmp.Length != word.Length)
{
result.Append(word[..^tmp.Length]);
word = tmp;
}
if (word.EndsWith("'s"))
{
suffix = "'s" + suffix;
word = word[..^2];
}
void MakeCustomRoleRating(DiscordMember? mem)
{
if (mem is null || choiceFlags.Contains('f'))
return;
var roleList = mem.Roles.ToList();
if (roleList.Count == 0)
return;
var role = roleList[new Random((prefix + mem.Id).GetHashCode()).Next(roleList.Count)].Name?.ToLowerInvariant();
if (string.IsNullOrEmpty(role))
return;
if (role.EndsWith('s'))
role = role[..^1];
var article = Vowels.Contains(role[0]) ? "n" : "";
choices = RateAnswers.Concat(Enumerable.Repeat($"Pretty fly for a{article} {role} guy", RateAnswers.Count * funMult / 20)).ToList();
choiceFlags.Add('f');
}
var appended = false;
DiscordMember? member = null;
if (Me.Contains(word))
{
member = ctx.Member;
word = ctx.Message.Author.Id.ToString();
result.Append(word);
appended = true;
}
else if (word == "my")
{
result.Append(ctx.Message.Author.Id).Append("'s");
appended = true;
}
else if (botMatch.Contains(word))
{
word = ctx.Client.CurrentUser.Id.ToString();
result.Append(word);
appended = true;
}
else if (Your.Contains(word))
{
result.Append(ctx.Client.CurrentUser.Id).Append("'s");
appended = true;
}
else if (word.StartsWith("actually") || word.StartsWith("nevermind") || word.StartsWith("nvm"))
{
result.Clear();
appended = true;
}
if (member is null && i == 0 && await ctx.ResolveMemberAsync(word).ConfigureAwait(false) is DiscordMember m)
member = m;
if (member != null)
{
if (suffix.Length == 0)
MakeCustomRoleRating(member);
if (!appended)
{
result.Append(member.Id);
appended = true;
}
}
if (nekoMatch.Contains(word))
{
if (i == 0 && suffix.Length == 0)
{
choices = RateAnswers.Concat(Enumerable.Repeat("Ugh", RateAnswers.Count * 3 * funMult)).ToList();
MakeCustomRoleRating(nekoMember);
}
result.Append(nekoUser.Id);
appended = true;
}
if (kdMatch.Contains(word))
{
if (i == 0 && suffix.Length == 0)
{
choices = RateAnswers.Concat(Enumerable.Repeat("RSX genius", RateAnswers.Count * 3 * funMult)).ToList();
MakeCustomRoleRating(kdMember);
}
result.Append(kdUser.Id);
appended = true;
}
if (!appended)
result.Append(word);
result.Append(suffix).Append(' ');
}
whatever = result.ToString();
var cutIdx = whatever.LastIndexOf("never mind", StringComparison.Ordinal);
if (cutIdx > -1)
whatever = whatever[cutIdx..];
whatever = whatever.Replace("'s's", "'s").TrimStart(EveryTimable).Trim();
if (whatever.StartsWith("rate "))
whatever = whatever[("rate ".Length)..];
if (originalWhatever == "sonic" || originalWhatever.Contains("sonic the"))
choices = RateAnswers
.Concat(Enumerable.Repeat("💩 out of 🦔", RateAnswers.Count * funMult))
.Concat(Enumerable.Repeat("Sonic out of 🦔", funMult))
.Concat(Enumerable.Repeat("Sonic out of 10", funMult))
.ToList();
if (string.IsNullOrEmpty(whatever))
await ctx.Channel.SendMessageAsync("Rating nothing makes _**so much**_ sense, right?").ConfigureAwait(false);
else
{
var seed = (prefix + whatever).GetHashCode(StringComparison.CurrentCultureIgnoreCase);
var seededRng = new Random(seed);
var answer = choices[seededRng.Next(choices.Count)];
var msgBuilder = new DiscordMessageBuilder()
.WithContent(answer)
.WithReply(ctx.Message.Id);
await ctx.RespondAsync(msgBuilder).ConfigureAwait(false);
}
}
catch (Exception e)
{
Config.Log.Warn(e, $"Failed to rate {whatever}");
}
}
19
Source : OptionFunctions.cs
with MIT License
from rushfive
with MIT License
from rushfive
private void InitializeMaps(List<OptionBase<TRunInfo>> options)
{
foreach (OptionBase<TRunInfo> option in options)
{
addProcessInfo(option);
if (option.Type == typeof(bool))
{
addToBoolMaps(option);
}
}
// local functions
void addProcessInfo(OptionBase<TRunInfo> option)
{
var (fullKey, shortKey) = OptionTokenizer.TokenizeKeyConfiguration(option.Key);
OptionProcessInfo<TRunInfo> processInfo = option.GetProcessInfo();
_fullOptionInfo.Add(fullKey, processInfo);
if (shortKey != null)
{
_shortOptionInfo.Add(shortKey.Value, processInfo);
}
}
void addToBoolMaps(OptionBase<TRunInfo> option)
{
var (fullKey, shortKey) = OptionTokenizer.TokenizeKeyConfiguration(option.Key);
_fullBoolTypeKeys.Add(fullKey);
if (shortKey != null)
{
_shortBoolTypeKeys.Add(shortKey.Value);
}
}
}
19
Source : CharSetGenerator.cs
with MIT License
from SardineFish
with MIT License
from SardineFish
void LoadFromFile(string path)
{
var text = File.ReadAllText(path);
text.ForEach(chr => charset.Add(chr));
}
19
Source : FontAtlasGeneratorEditorWindow.cs
with MIT License
from sarkahn
with MIT License
from sarkahn
string HandleUnsupportedGlyphs(ref string input, ref string fallbackString, Font font, Font fallbackFont)
{
HashSet<char> toRemove = new HashSet<char>();
foreach (char ch in input)
{
if (!font.HasCharacter(ch))
{
toRemove.Add(ch);
}
}
switch (unsupportedGlyphHandling_)
{
case UnsupportedGlyphHandling.Empty:
{
foreach (char ch in toRemove)
{
input = input.Replace(ch, ' ');
}
}
break;
case UnsupportedGlyphHandling.Remove:
{
input = CleanString(input, toRemove);
}
break;
case UnsupportedGlyphHandling.Fallback:
{
if( fallbackFont_ == null )
{
foreach (char ch in toRemove)
{
input = input.Replace(ch, ' ');
}
}
else
{
// Copy our input to fallback.
fallbackString = input;
// Run through each char in our input
for (int i = 0; i < input.Length; ++i)
{
char ch = input[i];
// Remove characters that our primary font has or
// that our fallback font doesn't
if (font.HasCharacter(ch) || !fallbackFont.HasCharacter(ch))
{
// If this isn't a fallback character or if our fallback
// character isn't in our fallback font then we'll blank
// it out on our fallback string
// This will leave us with a string of the identical length
// to the input but all non-fallback-able chars blanked out
fallbackString = fallbackString.Replace(ch, ' ');
}
if (!font.HasCharacter(ch))
{
input = input.Replace(ch, ' ');
}
}
}
//Debug.Log("Input: " + input);
//Debug.Log("Fallback: " + fallbackString);
}
break;
}
return input;
}
19
Source : StringEscaper.cs
with GNU Lesser General Public License v2.1
from sharpsuite
with GNU Lesser General Public License v2.1
from sharpsuite
public static void BuildAllowedCharacterCache()
{
AllowedCharacters.Clear();
AllowedCharacters.Add('-');
AllowedCharacters.Add(':');
AllowedCharacters.Add('_');
AllowedCharacters.Add('.');
for (char c = 'a'; c <= 'z'; c++)
{
AllowedCharacters.Add(c);
AllowedCharacters.Add(char.ToUpperInvariant(c));
}
for (char c = '0'; c <= '9'; c++)
AllowedCharacters.Add(c);
}
19
Source : PathFormat.Windows.cs
with MIT License
from Singulink
with MIT License
from Singulink
private static HashSet<char> GetInvalidNameChars(bool includeWildcardChars)
{
var invalidChars = new HashSet<char>() { '<', '>', ':', '"', '|', '/', '\\' };
for (int i = 0; i <= 31; i++)
invalidChars.Add((char)i);
if (includeWildcardChars) {
invalidChars.Add('?');
invalidChars.Add('*');
}
return invalidChars;
}
19
Source : CharRange.cs
with MIT License
from SpecFlowOSS
with MIT License
from SpecFlowOSS
public static IEnumerable<char> ExpandRanges(IEnumerable<CharRange> ranges)
{
var seen = new HashSet<char>();
foreach (var range in ranges)
foreach (char ch in range)
if (seen.Add(ch))
yield return ch;
}
19
Source : bip39_tests.cs
with MIT License
from stratisproject
with MIT License
from stratisproject
[Fact]
public void GenerateHardcodedNormalization()
{
var builder = new StringBuilder();
builder.Append("\"");
var chars = new HashSet<char>();
var ranges = new List<CharRangeT>();
ranges.Add(CharRange(0, 1000)); //Some latin language accent
ranges.Add(CharRange(0x3040, 0x309F)); //Hiragana
ranges.Add(CharRange(0x30A0, 0x30FF)); //Katakana
//CJK Unified Ideographs 4E00-9FFF Common
//CJK Unified Ideographs Extension A 3400-4DFF Rare
//CJK Unified Ideographs Extension B 20000-2A6DF Rare, historic
//CJK Compatibility Ideographs F900-FAFF Duplicates, unifiable variants, corporate characters
//CJK Compatibility Ideographs Supplement 2F800-2FA1F Unifiable variants
ranges.Add(CharRange(0x4e00, 0x9FFF));
ranges.Add(CharRange(0x3400, 0x4DFF));
ranges.Add(CharRange(0x20000, 0x2A6DF));
ranges.Add(CharRange(0xF900, 0xFAFF));
ranges.Add(CharRange(0x2F800, 0x2FA1F));
ranges.Add(CharRange(0x3300, 0x33FF));
ranges.Add(CharRange(0x3000, 0x303F));
ranges.Add(CharRange(0xFF00, 0xFFFF));
ranges.Add(CharRange(0x2000, 0x206F));
ranges.Add(CharRange(0x20A0, 0x20CF));
foreach(char letter in ranges.SelectMany(c => c).OrderBy(c => c))
{
string nonNormal = new String(new[] { letter });
try
{
string normal = nonNormal.Normalize(NormalizationForm.FormKD);
if(nonNormal != normal && chars.Add(letter))
{
builder.Append(nonNormal + normal + "\\n");
}
}
catch(ArgumentException)
{
}
}
builder.Append("\"");
string subsreplacedutionTable = builder.ToString();
builder = new StringBuilder();
builder.AppendLine("{");
foreach(CharRangeT range in ranges)
{
builder.AppendLine("new[]{" + range.From + "," + range.To + "},");
}
builder.AppendLine("}");
string rangeTable = builder.ToString();
}
19
Source : BasePinyinMatch.cs
with MIT License
from toolgood
with MIT License
from toolgood
protected void MergeKeywords(string[] keys, int id, string keyword, List<Tuple<string, string[]>> list)
{
if (id >= keys.Length) {
list.Add(Tuple.Create(keyword, keys));
return;
}
var key = keys[id];
if (key[0] >= 0x3400 && key[0] <= 0x9fd5) {
var all = PinyinDict.GetAllPinyin(key[0]);
var fpy = new HashSet<char>();
foreach (var item in all) {
fpy.Add(item[0]);
}
foreach (var item in fpy) {
MergeKeywords(keys, id + 1, keyword + item, list);
}
} else {
MergeKeywords(keys, id + 1, keyword + key[0], list);
}
}
19
Source : BasePinyinMatch.cs
with MIT License
from toolgood
with MIT License
from toolgood
protected void MergeKeywords(string[] keys, int id, string keyword, List<Tuple<string, string[]>> list, int index, List<int> indexs)
{
if (id >= keys.Length) {
list.Add(Tuple.Create(keyword, keys));
indexs.Add(index);
return;
}
var key = keys[id];
if (key[0] >= 0x3400 && key[0] <= 0x9fd5) {
var all = PinyinDict.GetAllPinyin(key[0]);
var fpy = new HashSet<char>();
foreach (var item in all) {
fpy.Add(item[0]);
}
foreach (var item in fpy) {
MergeKeywords(keys, id + 1, keyword + item, list, index, indexs);
}
} else {
MergeKeywords(keys, id + 1, keyword + key[0], list, index, indexs);
}
}
19
Source : PropertyHashFactory.cs
with MIT License
from trampster
with MIT License
from trampster
ColumnCollisions[] FindColumnCollisions(Property[] properties)
{
int longestProperty = properties.Max(property => property.Length);
var collisions = new ColumnCollisions[longestProperty];
for(int index = 0; index < longestProperty; index++)
{
collisions[index] = new ColumnCollisions(index);
}
for(int columnIndex = 0; columnIndex < longestProperty; columnIndex++)
{
var charactersFound = new HashSet<char>();
foreach(var property in properties)
{
var character = property[columnIndex % property.Length];
if(!charactersFound.Add(character))
{
collisions[columnIndex].AddCollision();
}
}
}
return collisions;
}
19
Source : Program.cs
with MIT License
from Tuscann
with MIT License
from Tuscann
static void Main() // 90/100
{
string input = Console.ReadLine().ToUpper();
string wordToRepeat = "";
string num = "";
var charList = new HashSet<char>();
var endList = new List<string>();
char[] inputChars = input.ToCharArray();
for (int i = 0; i < inputChars.Length; i++)
{
if (char.IsDigit(inputChars[i]))
{
num += inputChars[i];
if (i < inputChars.Length - 1)
{
if (char.IsDigit(inputChars[i + 1]))
{
int doubleNum = int.Parse(inputChars[i] + "" + inputChars[i + 1]);
for (int v = 0; v < doubleNum; v++)
{
endList.Add(wordToRepeat);
}
wordToRepeat = "";
doubleNum = 0;
}
else
{
for (int v = 0; v < int.Parse(num); v++)
{
endList.Add(wordToRepeat);
}
wordToRepeat = "";
num = "";
}
}
else
{
for (int v = 0; v < int.Parse(num); v++)
{
endList.Add(wordToRepeat);
}
wordToRepeat = "";
num = "";
}
}
else
{
wordToRepeat += char.ToUpper(inputChars[i]);
}
if (!char.IsDigit(inputChars[i]))
{
charList.Add(inputChars[i]);
}
}
Console.WriteLine($"Unique symbols used: {charList.Count}");
Console.WriteLine(string.Join("", endList));
}
19
Source : HtmlEscape.cs
with MIT License
from Wyamio
with MIT License
from Wyamio
public HtmlEscape WithDefaultStandard()
{
for (char c = '0'; c <= '9'; c++)
{
_standardCharacters.Add(c);
}
for (char c = 'a'; c <= 'z'; c++)
{
_standardCharacters.Add(c);
}
for (char c = 'A'; c <= 'Z'; c++)
{
_standardCharacters.Add(c);
}
_standardCharacters.Add('\r');
_standardCharacters.Add('\n');
_standardCharacters.Add(' ');
return this;
}
19
Source : HtmlEscape.cs
with MIT License
from Wyamio
with MIT License
from Wyamio
public HtmlEscape WithStandard(params char[] standard)
{
foreach (char c in standard)
{
_standardCharacters.Add(c);
}
return this;
}
19
Source : LeapTextRenderer.cs
with MIT License
from xjorma
with MIT License
from xjorma
private void generateTextMesh(int index, LeapTextGraphic graphic, Mesh mesh) {
using (new ProfilerSample("Generate Text Mesh")) {
mesh.Clear(keepVertexLayout: false);
graphic.isRepresentationDirty = false;
int scaledFontSize = Mathf.RoundToInt(graphic.fontSize * _dynamicPixelsPerUnit);
//Check for characters not found in the font
{
HashSet<char> unfoundCharacters = null;
CharacterInfo info;
foreach (var character in graphic.text) {
if (character == '\n') {
continue;
}
if (unfoundCharacters != null && unfoundCharacters.Contains(character)) {
continue;
}
if (!_font.GetCharacterInfo(character, out info, scaledFontSize, graphic.fontStyle)) {
if (unfoundCharacters == null) unfoundCharacters = new HashSet<char>();
unfoundCharacters.Add(character);
Debug.LogError("Could not find character [" + character + "] in font " + _font + "!");
}
}
}
var text = graphic.text;
float _charScale = this._scale * SCALE_CONSTANT / _dynamicPixelsPerUnit;
float _scale = _charScale * graphic.fontSize / _font.fontSize;
float lineHeight = _scale * graphic.lineSpacing * _font.lineHeight * _dynamicPixelsPerUnit;
RectTransform rectTransform = graphic.transform as RectTransform;
float maxWidth;
if (rectTransform != null) {
maxWidth = rectTransform.rect.width;
} else {
maxWidth = float.MaxValue;
}
_widthCalculator.font = _font;
_widthCalculator.charScale = _charScale;
_widthCalculator.fontStyle = graphic.fontStyle;
_widthCalculator.scaledFontSize = scaledFontSize;
TextWrapper.Wrap(text, graphic.tokens, _tempLines, _widthCalculator.func, maxWidth);
float textHeight = _tempLines.Count * lineHeight;
Vector3 origin = Vector3.zero;
origin.y -= _font.ascent * _scale * _dynamicPixelsPerUnit;
if (rectTransform != null) {
origin.y -= rectTransform.rect.y;
switch (graphic.verticalAlignment) {
case LeapTextGraphic.VerticalAlignment.Center:
origin.y -= (rectTransform.rect.height - textHeight) / 2;
break;
case LeapTextGraphic.VerticalAlignment.Bottom:
origin.y -= (rectTransform.rect.height - textHeight);
break;
}
}
foreach (var line in _tempLines) {
if (rectTransform != null) {
origin.x = rectTransform.rect.x;
switch (graphic.horizontalAlignment) {
case LeapTextGraphic.HorizontalAlignment.Center:
origin.x += (rectTransform.rect.width - line.width) / 2;
break;
case LeapTextGraphic.HorizontalAlignment.Right:
origin.x += (rectTransform.rect.width - line.width);
break;
}
} else {
switch (graphic.horizontalAlignment) {
case LeapTextGraphic.HorizontalAlignment.Left:
origin.x = 0;
break;
case LeapTextGraphic.HorizontalAlignment.Center:
origin.x = -line.width / 2;
break;
case LeapTextGraphic.HorizontalAlignment.Right:
origin.x = -line.width;
break;
}
}
for (int i = line.start; i < line.end; i++) {
char c = text[i];
CharacterInfo info;
if (!_font.GetCharacterInfo(c, out info, scaledFontSize, graphic.fontStyle)) {
continue;
}
int offset = _verts.Count;
_tris.Add(offset + 0);
_tris.Add(offset + 1);
_tris.Add(offset + 2);
_tris.Add(offset + 0);
_tris.Add(offset + 2);
_tris.Add(offset + 3);
_verts.Add(_charScale * new Vector3(info.minX, info.maxY, 0) + origin);
_verts.Add(_charScale * new Vector3(info.maxX, info.maxY, 0) + origin);
_verts.Add(_charScale * new Vector3(info.maxX, info.minY, 0) + origin);
_verts.Add(_charScale * new Vector3(info.minX, info.minY, 0) + origin);
_uvs.Add(info.uvTopLeft);
_uvs.Add(info.uvTopRight);
_uvs.Add(info.uvBottomRight);
_uvs.Add(info.uvBottomLeft);
if (_useColor) {
_colors.Append(4, _globalTint * graphic.color);
}
origin.x += info.advance * _charScale;
}
origin.y -= lineHeight;
}
for (int i = 0; i < _uvs.Count; i++) {
Vector4 uv = _uvs[i];
uv.w = index;
_uvs[i] = uv;
}
mesh.SetVertices(_verts);
mesh.SetTriangles(_tris, 0);
mesh.SetUVs(0, _uvs);
if (_useColor) {
mesh.SetColors(_colors);
}
_verts.Clear();
_uvs.Clear();
_tris.Clear();
_colors.Clear();
_tempLines.Clear();
}
}