repo_name
stringlengths
2
55
dataset
stringclasses
1 value
owner
stringlengths
3
31
lang
stringclasses
10 values
func_name
stringlengths
1
104
code
stringlengths
20
96.7k
docstring
stringlengths
1
4.92k
url
stringlengths
94
241
sha
stringlengths
40
40
Polyfill
github_2023
SimonCropp
csharp
Polyfill.SaveAsync
public static Task SaveAsync( this XDocument target, XmlWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); target.Save(writer); return Task.CompletedTask; }
/// <summary>
https://github.com/SimonCropp/Polyfill/blob/b3fc2b19ec553e6971f8bb688d0116c8b61f6788/src/Polyfill/Polyfill_XDocument.cs#L26-L34
b3fc2b19ec553e6971f8bb688d0116c8b61f6788
Polyfill
github_2023
SimonCropp
csharp
OperatingSystemPolyfill.IsOSPlatform
public static bool IsOSPlatform(string platform) => #if NET5_0_OR_GREATER OperatingSystem.IsOSPlatform(platform); #else RuntimeInformation.IsOSPlatform(OSPlatform.Create(platform)); #endif /// <summary> /// Checks if the operating system version is greater than or equal to the specified platform version. This method can be used to guard APIs that were added in the specified OS version. /// </summary> /// <param name="platform">The case-insensitive platform name. Examples: Browser, Linux, FreeBSD, Android, iOS, macOS, tvOS, watchOS, Windows.</param> /// <param name="major">The major release number.</param> /// <param name="minor">The minor release number (optional).</param> /// <param name="build">The build release number (optional).</param> /// <param name="revision">The revision release number (optional).</param> /// <returns>true if the current application is running on the specified platform and is at least in the version specified in the parameters; false otherwise.</returns> ///Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isosplatformversionatleast
/// <summary>
https://github.com/SimonCropp/Polyfill/blob/b3fc2b19ec553e6971f8bb688d0116c8b61f6788/src/Polyfill/OperatingSystemPolyfill.cs#L52-L68
b3fc2b19ec553e6971f8bb688d0116c8b61f6788
Polyfill
github_2023
SimonCropp
csharp
UIntPolyfill.TryParse
public static bool TryParse(string? target, IFormatProvider? provider, out uint result) => #if NET7_0_OR_GREATER uint.TryParse(target, provider, out result); #else uint.TryParse(target, NumberStyles.Integer, provider, out result); #endif
/// <summary>
https://github.com/SimonCropp/Polyfill/blob/b3fc2b19ec553e6971f8bb688d0116c8b61f6788/src/Polyfill/Numbers/UIntPolyfill.cs#L23-L28
b3fc2b19ec553e6971f8bb688d0116c8b61f6788
grzyClothTool
github_2023
grzybeek
csharp
CutFloatValueEventArgs.ReadXml
public override void ReadXml(XmlNode node) { base.ReadXml(node); fValue = Xml.GetChildFloatAttribute(node, "fValue", "value"); }
// PsoDataType.Float, 32, 0, 0)
https://github.com/grzybeek/grzyClothTool/blob/4f0ddcfffadcf3fbf8a4529b084c90bf464a81b5/CodeWalker/CodeWalker.Core/GameFiles/FileTypes/CutFile.cs#L984-L988
4f0ddcfffadcf3fbf8a4529b084c90bf464a81b5
grzyClothTool
github_2023
grzybeek
csharp
CutVehicleExtraEventArgs.ReadXml
public override void ReadXml(XmlNode node) { base.ReadXml(node); pExtraBoneIds = Xml.GetChildRawIntArray(node, "pExtraBoneIds"); }
// PsoDataType.Array, 40, 0, (MetaName)3)//ARRAYINFO, PsoDataType.SInt, 0, 0, 0),
https://github.com/grzybeek/grzyClothTool/blob/4f0ddcfffadcf3fbf8a4529b084c90bf464a81b5/CodeWalker/CodeWalker.Core/GameFiles/FileTypes/CutFile.cs#L1181-L1185
4f0ddcfffadcf3fbf8a4529b084c90bf464a81b5
grzyClothTool
github_2023
grzybeek
csharp
AnimSequence.EvaluateQuaternionType7
public Quaternion EvaluateQuaternionType7(int frame) { if (!IsType7Quat) { return new Quaternion( Channels[0].EvaluateFloat(frame), Channels[1].EvaluateFloat(frame), Channels[2].EvaluateFloat(frame), Channels[3].EvaluateFloat(frame) ); } var t7 = Channels[3] as AnimChannelCachedQuaternion;//type 1 if (t7 == null) t7 = Channels[4] as AnimChannelCachedQuaternion;//type 2 var x = Channels[0].EvaluateFloat(frame); var y = Channels[1].EvaluateFloat(frame); var z = Channels[2].EvaluateFloat(frame); var normalized = t7.EvaluateFloat(frame); switch (t7.QuatIndex) { case 0: return new Quaternion(normalized, x, y, z); case 1: return new Quaternion(x, normalized, y, z); case 2: return new Quaternion(x, y, normalized, z); case 3: return new Quaternion(x, y, z, normalized); default: return Quaternion.Identity; } }
//for convenience
https://github.com/grzybeek/grzyClothTool/blob/4f0ddcfffadcf3fbf8a4529b084c90bf464a81b5/CodeWalker/CodeWalker.Core/GameFiles/Resources/Clip.cs#L2171-L2204
4f0ddcfffadcf3fbf8a4529b084c90bf464a81b5
grzyClothTool
github_2023
grzybeek
csharp
FbxIO.Read
public static FbxDocument Read(byte[] data) { using (var stream = new MemoryStream(data)) { var isbinary = FbxBinary.IsBinary(stream); if (isbinary) { var reader = new FbxBinaryReader(stream); return reader.Read(); } else //try ASCII { var reader = new FbxAsciiReader(stream); return reader.Read(); } } }
/// <summary>
https://github.com/grzybeek/grzyClothTool/blob/4f0ddcfffadcf3fbf8a4529b084c90bf464a81b5/CodeWalker/CodeWalker.Core/Utils/Fbx.cs#L35-L51
4f0ddcfffadcf3fbf8a4529b084c90bf464a81b5
grzyClothTool
github_2023
grzybeek
csharp
Program.Main
[STAThread] static void Main(string[] args) { //Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Always check the GTA folder first thing if (!GTAFolder.UpdateGTAFolder(Properties.Settings.Default.RememberGTAFolder)) { MessageBox.Show("Could not load CodeWalker because no valid GTA 5 folder was selected. CodeWalker will now exit.", "GTA 5 Folder Not Found", MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } #if !DEBUG try { #endif #if !DEBUG } catch (Exception ex) { MessageBox.Show("An unexpected error was encountered!\n" + ex.ToString()); //this can happen if folder wasn't chosen, or in some other catastrophic error. meh. } #endif }
/// <summary>
https://github.com/grzybeek/grzyClothTool/blob/4f0ddcfffadcf3fbf8a4529b084c90bf464a81b5/CodeWalker/CodeWalker/Program.cs#L18-L43
4f0ddcfffadcf3fbf8a4529b084c90bf464a81b5
DatasetHelpers
github_2023
Particle1904
csharp
PromptGeneratorService.GeneratePromptFromDataset
public string GeneratePromptFromDataset(string[] tags, string prependTags, string appendTags, int amountOfTags) { _stringBuilder.Clear(); if (!string.IsNullOrEmpty(prependTags)) { _stringBuilder.Append(prependTags); _stringBuilder.Append(", "); } for (int i = 0; i < amountOfTags; i++) { string tag = tags[_random.Next(tags.Length)]; _stringBuilder.Append(tag); if (i != amountOfTags - 1) { _stringBuilder.Append(", "); } } if (!string.IsNullOrEmpty(appendTags)) { _stringBuilder.Append(", "); _stringBuilder.Append(appendTags); } string prompt = _stringBuilder.ToString().Replace(", , ", ", ").Replace(", ,", ", ").Replace(" ", " "); return prompt; }
/// <summary>
https://github.com/Particle1904/DatasetHelpers/blob/f55d0567c227a6eec658f597384439056e47762f/SmartData.Lib/Services/PromptGeneratorService.cs#L39-L67
f55d0567c227a6eec658f597384439056e47762f
DatasetHelpers
github_2023
Particle1904
csharp
TagProcessorService.ProcessAllTagFiles
public async Task ProcessAllTagFiles(string inputFolderPath, string tagsToAdd, string tagsToEmphasize, string tagsToRemove) { string[] files = Utilities.GetFilesByMultipleExtensions(inputFolderPath, _txtSearchPattern); CancellationToken cancellationToken = _cancellationTokenSource.Token; TotalFilesChanged?.Invoke(this, files.Length); foreach (string file in files) { cancellationToken.ThrowIfCancellationRequested(); string readTags = await File.ReadAllTextAsync(file); string processedTags = ProcessListOfTags(readTags, tagsToAdd, tagsToEmphasize, tagsToRemove); await File.WriteAllTextAsync(file, processedTags); ProgressUpdated?.Invoke(this, EventArgs.Empty); } }
/// <summary>
https://github.com/Particle1904/DatasetHelpers/blob/f55d0567c227a6eec658f597384439056e47762f/SmartData.Lib/Services/TagProcessorService.cs#L152-L168
f55d0567c227a6eec658f597384439056e47762f
aibpm.plus
github_2023
leooneone
csharp
StartActivityService.Submit
public override async Task<ActivityOutput> Submit(InstanceDataInput input) { InstanceEntity instance = null; WorkflowTemplateEntity tpl = null; ActivityModel currentActivity = null; var workItemId = 0l; var workItem = default(WorkItemEntity); if (input.Type == QueryType.WorkItem) { workItem = await _workItemRepository.GetAsync(input.WorkItemId); if (workItem == null) throw ResultOutput.Exception("该工作项不存在。"); else { if (workItem.ParticipantId != User.Id) {//后续考虑委托办理和管理员权限可以代为操作 //throw ResultOutput.Exception("您不是该节点审批人,无权进行此操作!"); } if (workItem.State > ActivityState.UnRead) { throw ResultOutput.Exception("该工作项当前不可操作。"); } tpl = await _workflowTemplateRepository.GetAsync(workItem.WorkflowTemplateId); instance = await _instanceRepository.GetAsync(workItem.InstanceId); currentActivity = _activityService.GetActivity(tpl, workItem.ActivityId); if (!input.IsSaveOnly) ValidInput(input, tpl); workItemId=input.WorkItemId; } } else if (input.Type == QueryType.Template) { tpl = await _workflowTemplateRepository.GetAsync(input.TemplateId); if (input.InstanceId <= 0) {//如果还没有创建实例,先创建实例 instance = new InstanceEntity(); instance.FormModel = JsonConvert.SerializeObject(input.Form); instance.TemplateId = input.TemplateId; instance.GroupId = tpl.GroupId; instance.Name = $"{User.Name}发起的『{tpl.Name}』流程"; instance.OUId = input.OUId; instance.InitiatorId = User.Id; if (!input.IsSaveOnly) ///仅保存的话不存储流程实例 { instance.State = InstanceState.Running; var setting = await base.GetSetting(); instance.ReferenceNo = AiliCould.Core.BPM.Helper.ReferenceNoHelper.GetNo(setting.ReferenceNoSetting, ""); } else instance.State = InstanceState.UnInitiated; var res = await _instanceRepository.InsertAsync(instance); } currentActivity = _activityService.GetActivity(tpl, input.ActivityCode); {//沒有創建 workItem 則創建 workItem workItem = await AddCurrentWorkItem(instance, tpl, currentActivity,input.IsSaveOnly); //完成当前节点工作项目 } workItemId = workItem.Id; } if (string.IsNullOrEmpty(instance.ReferenceNo) && !input.IsSaveOnly) { var setting = await base.GetSetting(); instance.ReferenceNo = AiliCould.Core.BPM.Helper.ReferenceNoHelper.GetNo(setting.ReferenceNoSetting, ""); instance.State = InstanceState.Running; } ///根据表单设置的权限更新表单 var formModel = _activityService.UpdateForm(instance.FormModel, currentActivity.Permission, input.Form); instance.FormModel = JsonConvert.SerializeObject(formModel); ///更新表单信息 await _instanceRepository.UpdateAsync(instance); if (input.IsSaveOnly) return null; else { await FinishWorkItem(workItemId, input.Comment, input.ApprovalResult); return new ActivityOutput { Instance = instance, Template = tpl, OptionalParticipants = input.OptionalParticipants, FormModel = formModel, CurrentActivity = currentActivity }; } }
/// <summary>
https://github.com/leooneone/aibpm.plus/blob/00b7e0f9274fbdeefd1686d65bd9ac414a1ebaf5/Modules/AI/AI.BPM/Services/BPM/Activity/Activities/StartActivityService.cs#L40-L145
00b7e0f9274fbdeefd1686d65bd9ac414a1ebaf5
aibpm.plus
github_2023
leooneone
csharp
RoleRepository.GetChildIdListAsync
public async Task<List<long>> GetChildIdListAsync(long id) { return await Select .Where(a => a.Id == id) .AsTreeCte() .ToListAsync(a => a.Id); }
/// <summary>
https://github.com/leooneone/aibpm.plus/blob/00b7e0f9274fbdeefd1686d65bd9ac414a1ebaf5/src/platform/ZhonTai.Admin/Repositories/Role/RoleRepository.cs#L20-L26
00b7e0f9274fbdeefd1686d65bd9ac414a1ebaf5
aibpm.plus
github_2023
leooneone
csharp
UserOrgRepository.HasUser
public async Task<bool> HasUser(long id) { return await Select.Where(a => a.OrgId == id).AnyAsync(); }
/// <summary>
https://github.com/leooneone/aibpm.plus/blob/00b7e0f9274fbdeefd1686d65bd9ac414a1ebaf5/src/platform/ZhonTai.Admin/Repositories/UserOrg/UserOrgRepository.cs#L20-L23
00b7e0f9274fbdeefd1686d65bd9ac414a1ebaf5
aibpm.plus
github_2023
leooneone
csharp
CacheService.GetList
public List<dynamic> GetList() { var list = new List<dynamic>(); var appConfig = LazyGetRequiredService<AppConfig>(); Assembly[] assemblies = AssemblyHelper.GetAssemblyList(appConfig.AssemblyNames); foreach (Assembly assembly in assemblies) { var types = assembly.GetExportedTypes().Where(a => a.GetCustomAttribute<ScanCacheKeysAttribute>(false) != null); foreach (Type type in types) { var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); foreach (FieldInfo field in fields) { var descriptionAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute; list.Add(new { field.Name, Value = field.GetRawConstantValue().ToString(), descriptionAttribute?.Description }); } } } return list; }
/// <summary>
https://github.com/leooneone/aibpm.plus/blob/00b7e0f9274fbdeefd1686d65bd9ac414a1ebaf5/src/platform/ZhonTai.Admin/Services/Cache/CacheService.cs#L32-L60
00b7e0f9274fbdeefd1686d65bd9ac414a1ebaf5
aibpm.plus
github_2023
leooneone
csharp
ConfigHelper.Load
public static IConfiguration Load(string fileName, string environmentName = "", bool optional = true, bool reloadOnChange = false) { var filePath = Path.Combine(AppContext.BaseDirectory, "Configs"); if (!Directory.Exists(filePath)) return null; var builder = new ConfigurationBuilder() .SetBasePath(filePath) .AddJsonFile(fileName.ToLower() + ".json", optional, reloadOnChange); if (environmentName.NotNull()) { builder.AddJsonFile(fileName.ToLower() + "." + environmentName + ".json", optional: optional, reloadOnChange: reloadOnChange); } return builder.Build(); }
/* 使用热更新 var uploadConfig = new ConfigHelper().Load("uploadconfig", _env.EnvironmentName, true); services.Configure<UploadConfig>(uploadConfig); private readonly UploadConfig _uploadConfig; public ImgController(IOptionsMonitor<UploadConfig> uploadConfig) { _uploadConfig = uploadConfig.CurrentValue; } */
https://github.com/leooneone/aibpm.plus/blob/00b7e0f9274fbdeefd1686d65bd9ac414a1ebaf5/src/platform/ZhonTai.Common/Helpers/ConfigHelper.cs#L31-L47
00b7e0f9274fbdeefd1686d65bd9ac414a1ebaf5
aibpm.plus
github_2023
leooneone
csharp
PasswordHelper.Verify
public static bool Verify(string input) { if (input.IsNull()) { return false; } return RegexPassword().IsMatch(input); }
/// <summary>
https://github.com/leooneone/aibpm.plus/blob/00b7e0f9274fbdeefd1686d65bd9ac414a1ebaf5/src/platform/ZhonTai.Common/Helpers/PasswordHelper.cs#L19-L27
00b7e0f9274fbdeefd1686d65bd9ac414a1ebaf5
RazorSlices
github_2023
DamianEdwards
csharp
RazorSlice.Write
protected void Write(char? value) { if (value.HasValue) { WriteUtf8SpanFormattable(value.Value); } }
/// <summary>
https://github.com/DamianEdwards/RazorSlices/blob/cf2e413551e49c3a3b40623ce020d678697f123a/src/RazorSlices/RazorSlice.Formattables.cs#L28-L34
cf2e413551e49c3a3b40623ce020d678697f123a
p4vfs
github_2023
microsoft
csharp
ServiceInfo.IsServiceRunning
public static bool IsServiceRunning(string serviceName) { return IsServiceRunning(Environment.MachineName, serviceName); }
/// <summary>
https://github.com/microsoft/p4vfs/blob/10d93293a4846b4fee3267f9a6da38f8fd5c5a66/source/P4VFS.Extensions/Source/Utilities/ServiceInfo.cs#L58-L61
10d93293a4846b4fee3267f9a6da38f8fd5c5a66
VisualChatGPTStudio
github_2023
jeffdapaz
csharp
DiffView.ShowDiffViewAsync
public static async System.Threading.Tasks.Task ShowDiffViewAsync(string filePath, string originalCode, string optimizedCode) { string extension = System.IO.Path.GetExtension(filePath).TrimStart('.'); string tempFolder = System.IO.Path.GetTempPath(); string tempFilePath1 = System.IO.Path.Combine(tempFolder, $"Original.{extension}"); string tempFilePath2 = System.IO.Path.Combine(tempFolder, $"Optimized.{extension}"); System.IO.File.WriteAllText(tempFilePath1, originalCode); System.IO.File.WriteAllText(tempFilePath2, optimizedCode); DTE dte = await VS.GetServiceAsync<DTE, DTE>(); await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); dte.ExecuteCommand("Tools.DiffFiles", $"\"{tempFilePath1}\" \"{tempFilePath2}\""); }
/// <summary>
https://github.com/jeffdapaz/VisualChatGPTStudio/blob/b393c71d8c8ddeb12d13c5a77e63caf39cd734ab/VisualChatGPTStudioShared/Utils/DiffView.cs#L17-L33
b393c71d8c8ddeb12d13c5a77e63caf39cd734ab
FramePFX
github_2023
AngryCarrot789
csharp
ResourceObjectUtils.AddItemAndRet
public static T AddItemAndRet<T>(this ResourceFolder folder, T item) where T : BaseResource { folder.AddItem(item); return item; }
/// <summary>
https://github.com/AngryCarrot789/FramePFX/blob/73f9ddb9ddfa9a50755f78bbfcbc19ef45ce61b8/FramePFX/Editing/ResourceManaging/ResourceObjectUtils.cs#L29-L32
73f9ddb9ddfa9a50755f78bbfcbc19ef45ce61b8
FramePFX
github_2023
AngryCarrot789
csharp
ActivityTask.GetAwaiter
public new TaskAwaiter<T> GetAwaiter() => this.Task.GetAwaiter();
/// <inheritdoc cref="ActivityTask.GetAwaiter"/>
https://github.com/AngryCarrot789/FramePFX/blob/73f9ddb9ddfa9a50755f78bbfcbc19ef45ce61b8/FramePFX/Tasks/ActivityTask.cs#L168-L168
73f9ddb9ddfa9a50755f78bbfcbc19ef45ce61b8
FramePFX
github_2023
AngryCarrot789
csharp
ArrayUtils.Hash
public static int Hash<T>(T[] array) { if (array == null) return 0; IEqualityComparer<T> comparer = EqualityComparer<T>.Default; int result = 1; foreach (T t in array) { result = 31 * result + comparer.GetHashCode(t); } return result; }
// Using IEqualityComparer + generic functions is easier than having
https://github.com/AngryCarrot789/FramePFX/blob/73f9ddb9ddfa9a50755f78bbfcbc19ef45ce61b8/FramePFX/Utils/ArrayUtils.cs#L29-L40
73f9ddb9ddfa9a50755f78bbfcbc19ef45ce61b8
FramePFX
github_2023
AngryCarrot789
csharp
TypeUtils.instanceof
public static bool instanceof(this Type left, Type right) { return right.IsAssignableFrom(left); }
/// <summary>
https://github.com/AngryCarrot789/FramePFX/blob/73f9ddb9ddfa9a50755f78bbfcbc19ef45ce61b8/FramePFX/Utils/TypeUtils.cs#L33-L35
73f9ddb9ddfa9a50755f78bbfcbc19ef45ce61b8
FramePFX
github_2023
AngryCarrot789
csharp
InheritanceDictionary.GetEffectiveValue
public T? GetEffectiveValue(Type key) { return this.GetOrCreateEntryInternal(key).inheritedItem; }
/// <summary>
https://github.com/AngryCarrot789/FramePFX/blob/73f9ddb9ddfa9a50755f78bbfcbc19ef45ce61b8/FramePFX/Utils/Collections/InheritanceDictionary.cs#L96-L98
73f9ddb9ddfa9a50755f78bbfcbc19ef45ce61b8
FramePFX
github_2023
AngryCarrot789
csharp
ObservableItemProcessor.MakeSimple
public static ObservableItemProcessorSimple<T> MakeSimple<T>(IObservableList<T> list, Action<T>? onItemAdded, Action<T>? onItemRemoved) { return new ObservableItemProcessorSimple<T>(list, onItemAdded, onItemRemoved); }
/// <summary>
https://github.com/AngryCarrot789/FramePFX/blob/73f9ddb9ddfa9a50755f78bbfcbc19ef45ce61b8/FramePFX/Utils/Collections/Observable/ObservableItemProcessor.cs#L40-L42
73f9ddb9ddfa9a50755f78bbfcbc19ef45ce61b8
FramePFX
github_2023
AngryCarrot789
csharp
RateLimitedDispatchAction.InvokeAsync
public void InvokeAsync(T param) { _ = Interlocked.Exchange(ref this.currentValue, new ObjectWrapper(param)); base.InvokeAsyncCore(); }
// An object wrapper is required in order to permit InvokeAsync being called with a null value.
https://github.com/AngryCarrot789/FramePFX/blob/73f9ddb9ddfa9a50755f78bbfcbc19ef45ce61b8/FramePFX/Utils/RDA/RateLimitedDispatchAction.cs#L321-L324
73f9ddb9ddfa9a50755f78bbfcbc19ef45ce61b8
ThingsGateway
github_2023
ThingsGateway
csharp
ImportExportService.ExportAsync
public async Task<FileStreamResult> ExportAsync<T>(object input, string fileName, bool isDynamicExcelColumn = true) where T : class { var path = ImportExportUtil.GetFileDir(ref fileName); fileName = CommonUtils.GetSingleId() + fileName; var filePath = Path.Combine(path, fileName); using (FileStream fs = new(filePath, FileMode.Create)) { await fs.ExportExcel<T>(input, isDynamicExcelColumn).ConfigureAwait(false); } var result = _fileService.GetFileStreamResult(filePath, fileName); return result; }
/// <summary>
https://github.com/ThingsGateway/ThingsGateway/blob/c355968addb85577c008fc6ea9ba5b58e08ce784/src/Admin/ThingsGateway.Admin.Application/Services/ImportExport/ImportExportService.cs#L38-L51
c355968addb85577c008fc6ea9ba5b58e08ce784
ThingsGateway
github_2023
ThingsGateway
csharp
SessionService.PageAsync
public async Task<QueryData<SessionOutput>> PageAsync(QueryPageOptions option) { var ret = new QueryData<SessionOutput>() { IsSorted = option.SortOrder != SortOrder.Unset, IsFiltered = option.Filters.Count > 0, IsAdvanceSearch = option.AdvanceSearches.Count > 0 || option.CustomerSearches.Count > 0, IsSearch = option.Searches.Count > 0 }; var dataScope = await SysUserService.GetCurrentUserDataScopeAsync().ConfigureAwait(false); using var db = GetDB(); var query = db.GetQuery<SysUser>(option) .WhereIF(dataScope != null && dataScope?.Count > 0, u => dataScope.Contains(u.OrgId))//在指定机构列表查询 .WhereIF(dataScope?.Count == 0, u => u.CreateUserId == UserManager.UserId) .WhereIF(!option.SearchText.IsNullOrWhiteSpace(), a => a.Account.Contains(option.SearchText!)); if (option.IsPage) { RefAsync<int> totalCount = 0; var items = await query.ToPageListAsync(option.PageIndex, option.PageItems, totalCount).ConfigureAwait(false); var verificatInfoDicts = _verificatInfoService.GetListByUserIds(items.Select(a => a.Id).ToList()).GroupBy(a => a.UserId).ToDictionary(a => a.Key, a => a.ToList()); var r = items.Select((it) => { var reuslt = it.Adapt<SessionOutput>(); if (verificatInfoDicts.TryGetValue(it.Id, out var verificatInfos)) { SessionService.GetTokenInfos(verificatInfos);//获取剩余时间 reuslt.VerificatCount = verificatInfos.Count;//令牌数量 reuslt.VerificatSignList = verificatInfos;//令牌列表 //如果有mqtt客户端ID就是在线 reuslt.Online = verificatInfos.Any(it => it.ClientIds.Count > 0); } return reuslt; }).ToList(); ret.TotalCount = totalCount; ret.Items = r; } else if (option.IsVirtualScroll) { RefAsync<int> totalCount = 0; var items = await query.ToPageListAsync(option.StartIndex, option.PageItems, totalCount).ConfigureAwait(false); var verificatInfoDicts = _verificatInfoService.GetListByUserIds(items.Select(a => a.Id).ToList()).GroupBy(a => a.UserId).ToDictionary(a => a.Key, a => a.ToList()); var r = items.Select((it) => { var reuslt = it.Adapt<SessionOutput>(); if (verificatInfoDicts.TryGetValue(it.Id, out var verificatInfos)) { SessionService.GetTokenInfos(verificatInfos);//获取剩余时间 reuslt.VerificatCount = verificatInfos.Count;//令牌数量 reuslt.VerificatSignList = verificatInfos;//令牌列表 //如果有mqtt客户端ID就是在线 reuslt.Online = verificatInfos.Any(it => it.ClientIds.Count > 0); } return reuslt; }).ToList(); ret.TotalCount = totalCount; ret.Items = r; } else { var items = await query.ToListAsync().ConfigureAwait(false); var verificatInfoDicts = _verificatInfoService.GetListByUserIds(items.Select(a => a.Id).ToList()).GroupBy(a => a.UserId).ToDictionary(a => a.Key, a => a.ToList()); var r = items.Select((it) => { var reuslt = it.Adapt<SessionOutput>(); if (verificatInfoDicts.TryGetValue(it.Id, out var verificatInfos)) { SessionService.GetTokenInfos(verificatInfos);//获取剩余时间 reuslt.VerificatCount = verificatInfos.Count;//令牌数量 reuslt.VerificatSignList = verificatInfos;//令牌列表 //如果有mqtt客户端ID就是在线 reuslt.Online = verificatInfos.Any(it => it.ClientIds.Count > 0); } return reuslt; }).ToList(); ret.TotalCount = items.Count; ret.Items = r; } return ret; }
/// <summary>
https://github.com/ThingsGateway/ThingsGateway/blob/c355968addb85577c008fc6ea9ba5b58e08ce784/src/Admin/ThingsGateway.Admin.Application/Services/Session/SessionService.cs#L47-L141
c355968addb85577c008fc6ea9ba5b58e08ce784
ThingsGateway
github_2023
ThingsGateway
csharp
ConfigurableOptionsServiceCollectionExtensions.AddConfigurableOptions
public static IServiceCollection AddConfigurableOptions<TOptions>(this IServiceCollection services) where TOptions : class, IConfigurableOptions { var optionsType = typeof(TOptions); // 获取选项配置 var (optionsSettings, path) = Penetrates.GetOptionsConfiguration(optionsType); // 配置选项(含验证信息) var configurationRoot = App.Configuration; var optionsConfiguration = configurationRoot.GetSection(path); // 配置选项监听 if (typeof(IConfigurableOptionsListener<TOptions>).IsAssignableFrom(optionsType)) { var onListenerMethod = optionsType.GetMethod(nameof(IConfigurableOptionsListener<TOptions>.OnListener)); if (onListenerMethod != null) { // 监听全局配置改变,目前该方式存在触发两次的 bug:https://github.com/dotnet/aspnetcore/issues/2542 ChangeToken.OnChange(() => configurationRoot.GetReloadToken(), ((Action)(() => { var options = optionsConfiguration.Get<TOptions>(); if (options != null) onListenerMethod.Invoke(options, new object[] { options, optionsConfiguration }); })).Debounce()); } } var optionsConfigure = services.AddOptions<TOptions>() .Bind(optionsConfiguration, options => { options.BindNonPublicProperties = true; // 绑定私有变量 }) .ValidateDataAnnotations() .ValidateOnStart(); // 实现 Key 映射 services.PostConfigureAll<TOptions>(options => { // 查找所有贴了 MapSettings 的键值对 var remapKeys = optionsType.GetProperties(BindingFlags.Instance | BindingFlags.Public) .Where(u => u.IsDefined(typeof(MapSettingsAttribute), true)); if (!remapKeys.Any()) return; foreach (var prop in remapKeys) { var propType = prop.PropertyType; var realKey = prop.GetCustomAttribute<MapSettingsAttribute>(true).Path; var realValue = configurationRoot.GetValue(propType, $"{path}:{realKey}"); prop.SetValue(options, realValue); } }); // 配置复杂验证后后期配置 var validateInterface = optionsType.GetInterfaces() .FirstOrDefault(u => u.IsGenericType && typeof(IConfigurableOptions).IsAssignableFrom(u.GetGenericTypeDefinition())); if (validateInterface != null) { var genericArguments = validateInterface.GenericTypeArguments; // 配置复杂验证 if (genericArguments.Length > 1) { services.TryAddEnumerable(ServiceDescriptor.Singleton(typeof(IValidateOptions<TOptions>), genericArguments.Last())); } // 配置后期配置 var postConfigureMethod = optionsType.GetMethod(nameof(IConfigurableOptions<TOptions>.PostConfigure)); if (postConfigureMethod != null) { if (optionsSettings?.PostConfigureAll != true) optionsConfigure.PostConfigure(options => postConfigureMethod.Invoke(options, new object[] { options, optionsConfiguration })); else services.PostConfigureAll<TOptions>(options => postConfigureMethod.Invoke(options, new object[] { options, optionsConfiguration })); } } return services; }
/// <summary>
https://github.com/ThingsGateway/ThingsGateway/blob/c355968addb85577c008fc6ea9ba5b58e08ce784/src/Admin/ThingsGateway.Furion/ConfigurableOptions/Extensions/ConfigurableOptionsServiceCollectionExtensions.cs#L37-L114
c355968addb85577c008fc6ea9ba5b58e08ce784
ThingsGateway
github_2023
ThingsGateway
csharp
MD5Encryption.Compare
public static bool Compare(string text, string hash, bool uppercase = false, bool is16 = false) { return Compare(Encoding.UTF8.GetBytes(text), hash, uppercase, is16); }
/// <summary>
https://github.com/ThingsGateway/ThingsGateway/blob/c355968addb85577c008fc6ea9ba5b58e08ce784/src/Admin/ThingsGateway.Furion/DataEncryption/Encryptions/MD5Encryption.cs#L31-L34
c355968addb85577c008fc6ea9ba5b58e08ce784
ThingsGateway
github_2023
ThingsGateway
csharp
Scoped.Create
public static void Create(Action<IServiceScopeFactory, IServiceScope> handler, IServiceScopeFactory scopeFactory = default) { CreateAsync(async (fac, scope) => { handler(fac, scope); await Task.CompletedTask.ConfigureAwait(false); }, scopeFactory).GetAwaiter().GetResult(); }
/// <summary>
https://github.com/ThingsGateway/ThingsGateway/blob/c355968addb85577c008fc6ea9ba5b58e08ce784/src/Admin/ThingsGateway.Furion/DependencyInjection/Scoped.cs#L27-L34
c355968addb85577c008fc6ea9ba5b58e08ce784
ThingsGateway
github_2023
ThingsGateway
csharp
NewtonsoftJsonExtensions.AddDateTimeTypeConverters
public static IList<JsonConverter> AddDateTimeTypeConverters(this IList<JsonConverter> converters, string outputFormat = "yyyy-MM-dd HH:mm:ss", bool localized = false) { converters.Add(new NewtonsoftJsonDateTimeJsonConverter(outputFormat, localized)); converters.Add(new NewtonsoftNullableJsonDateTimeJsonConverter(outputFormat, localized)); converters.Add(new NewtonsoftJsonDateTimeOffsetJsonConverter(outputFormat, localized)); converters.Add(new NewtonsoftJsonNullableDateTimeOffsetJsonConverter(outputFormat, localized)); return converters; }
/// <summary>
https://github.com/ThingsGateway/ThingsGateway/blob/c355968addb85577c008fc6ea9ba5b58e08ce784/src/Admin/ThingsGateway.Furion/JsonSerialization/Extensions/NewtonsoftJsonExtensions.cs#L29-L38
c355968addb85577c008fc6ea9ba5b58e08ce784
ThingsGateway
github_2023
ThingsGateway
csharp
SpecificationDocumentServiceCollectionExtensions.AddSpecificationDocuments
public static IMvcBuilder AddSpecificationDocuments(this IMvcBuilder mvcBuilder, Action<SwaggerGenOptions> configure = default) { mvcBuilder.Services.AddSpecificationDocuments(configure); return mvcBuilder; }
/// <summary>
https://github.com/ThingsGateway/ThingsGateway/blob/c355968addb85577c008fc6ea9ba5b58e08ce784/src/Admin/ThingsGateway.Furion/SpecificationDocument/Extensions/SpecificationDocumentServiceCollectionExtensions.cs#L33-L38
c355968addb85577c008fc6ea9ba5b58e08ce784
ThingsGateway
github_2023
ThingsGateway
csharp
UnifyResultServiceCollectionExtensions.AddUnifyResult
public static IMvcBuilder AddUnifyResult(this IMvcBuilder mvcBuilder) { mvcBuilder.Services.AddUnifyResult<RESTfulResultProvider>(); return mvcBuilder; }
/// <summary>
https://github.com/ThingsGateway/ThingsGateway/blob/c355968addb85577c008fc6ea9ba5b58e08ce784/src/Admin/ThingsGateway.Furion/UnifyResult/Extensions/UnifyResultServiceCollectionExtensions.cs#L32-L37
c355968addb85577c008fc6ea9ba5b58e08ce784
ThingsGateway
github_2023
ThingsGateway
csharp
NewObjectExtensions.GetAssembly
internal static Assembly? GetAssembly(this object? obj) => obj?.GetType().Assembly;
/// <summary>
https://github.com/ThingsGateway/ThingsGateway/blob/c355968addb85577c008fc6ea9ba5b58e08ce784/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/ObjectExtensions.cs#L35-L35
c355968addb85577c008fc6ea9ba5b58e08ce784
ThingsGateway
github_2023
ThingsGateway
csharp
HttpMultipartFormDataBuilderDeclarativeExtractor.Extract
public void Extract(HttpRequestBuilder httpRequestBuilder, HttpDeclarativeExtractorContext context) { // 尝试解析单个 Action<HttpMultipartFormDataBuilder> 类型参数 if (context.Args.SingleOrDefault(u => u is Action<HttpMultipartFormDataBuilder>) is not Action<HttpMultipartFormDataBuilder> multipartFormDataBuilderAction) { return; } // 处理和 [Multipart] 特性冲突问题 if (httpRequestBuilder.MultipartFormDataBuilder is not null) { multipartFormDataBuilderAction.Invoke(httpRequestBuilder.MultipartFormDataBuilder); } else { // 设置多部分表单内容 httpRequestBuilder.SetMultipartContent(multipartFormDataBuilderAction); } }
/// <inheritdoc />
https://github.com/ThingsGateway/ThingsGateway/blob/c355968addb85577c008fc6ea9ba5b58e08ce784/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/HttpMultipartFormDataBuilderDeclarativeExtractor.cs#L20-L39
c355968addb85577c008fc6ea9ba5b58e08ce784
ThingsGateway
github_2023
ThingsGateway
csharp
FileUtil.ReadFile
public static string ReadFile(string Path, Encoding? encoding = default) { encoding ??= Encoding.UTF8; if (!File.Exists(Path)) { return null; } StreamReader streamReader = new StreamReader(Path, encoding); string result = streamReader.ReadToEnd(); streamReader.Close(); streamReader.Dispose(); return result; }
/// <summary>
https://github.com/ThingsGateway/ThingsGateway/blob/c355968addb85577c008fc6ea9ba5b58e08ce784/src/Admin/ThingsGateway.NewLife.X/Common/FileUtil.cs#L23-L36
c355968addb85577c008fc6ea9ba5b58e08ce784
ThingsGateway
github_2023
ThingsGateway
csharp
InIConfigProvider.Init
public override void Init(String value) { // 加上默认后缀 if (!value.IsNullOrEmpty() && Path.GetExtension(value).IsNullOrEmpty()) value += ".ini"; base.Init(value); }
/// <summary>初始化</summary>
https://github.com/ThingsGateway/ThingsGateway/blob/c355968addb85577c008fc6ea9ba5b58e08ce784/src/Admin/ThingsGateway.NewLife.X/Configuration/IniConfigProvider.cs#L13-L19
c355968addb85577c008fc6ea9ba5b58e08ce784
ThingsGateway
github_2023
ThingsGateway
csharp
MD5PasswordProvider.Hash
public String Hash(String password) => password.MD5();
/// <summary>对密码进行散列处理,此处可以加盐,结果保存在数据库</summary>
https://github.com/ThingsGateway/ThingsGateway/blob/c355968addb85577c008fc6ea9ba5b58e08ce784/src/Admin/ThingsGateway.NewLife.X/Security/IPasswordProvider.cs#L41-L41
c355968addb85577c008fc6ea9ba5b58e08ce784
ThingsGateway
github_2023
ThingsGateway
csharp
VariableObjectSourceGenerator.Initialize
public void Initialize(GeneratorInitializationContext context) { //Debugger.Launch(); context.RegisterForPostInitialization(a => { a.AddSource(nameof(m_generatorVariableAttribute), m_generatorVariableAttribute); }); context.RegisterForSyntaxNotifications(() => new VariableSyntaxReceiver()); }
/// <inheritdoc/>
https://github.com/ThingsGateway/ThingsGateway/blob/c355968addb85577c008fc6ea9ba5b58e08ce784/src/Foundation/ThingsGateway.Foundation.SourceGenerator/SourceGenerator/VariableObjectSourceGenerator.cs#L53-L61
c355968addb85577c008fc6ea9ba5b58e08ce784
ThingsGateway
github_2023
ThingsGateway
csharp
RuntimeInfoController.GetChannelListAsync
[HttpGet("channelList")] [DisplayName("获取通道信息")] public async Task<SqlSugarPagedList<ChannelRuntime>> GetChannelListAsync(ChannelPageInput input) { var channelRuntimes = await GlobalData.GetCurrentUserChannels().ConfigureAwait(false); var data = channelRuntimes .Select(a => a.Value) .WhereIF(!string.IsNullOrEmpty(input.Name), u => u.Name.Contains(input.Name)) .WhereIF(!string.IsNullOrEmpty(input.PluginName), u => u.PluginName == input.PluginName) .WhereIF(input.PluginType != null, u => u.PluginType == input.PluginType) .ToPagedList(input); return data; }
/// <summary>
https://github.com/ThingsGateway/ThingsGateway/blob/c355968addb85577c008fc6ea9ba5b58e08ce784/src/Gateway/ThingsGateway.Gateway.Application/Controller/RuntimeInfoController.cs#L37-L51
c355968addb85577c008fc6ea9ba5b58e08ce784
ThingsGateway
github_2023
ThingsGateway
csharp
UpdateZipFileInfo.OnInitialized
protected override void OnInitialized() { base.OnInitialized(); HeaderText = ManagementLocalizer[nameof(HeaderText)]; }
/// <inheritdoc/>
https://github.com/ThingsGateway/ThingsGateway/blob/c355968addb85577c008fc6ea9ba5b58e08ce784/src/Gateway/ThingsGateway.Management/Update/Update/UpdateZipFileInfo.razor.cs#L42-L46
c355968addb85577c008fc6ea9ba5b58e08ce784
ExifGlass
github_2023
d2phap
csharp
UpdateModel.Deserialize
public static UpdateModel Deserialize(string json) { var obj = JsonSerializer.Deserialize(json, UpdateModelJsonContext.Default.UpdateModel); return obj; }
/// <summary>
https://github.com/d2phap/ExifGlass/blob/ca73fd2105de29b7f6bec9f82f715b51cdbebc82/Source/ExifGlass.Core/Settings/UpdateModel.cs#L48-L53
ca73fd2105de29b7f6bec9f82f715b51cdbebc82
BONELAB-Fusion
github_2023
Lakatrazz
csharp
SteamServerStats.RequestUserStatsAsync
public static async Task<Result> RequestUserStatsAsync(SteamId steamid) { var r = await Internal.RequestUserStats(steamid); if (!r.HasValue) return Result.Fail; return r.Value.Result; }
/// <summary>
https://github.com/Lakatrazz/BONELAB-Fusion/blob/8889d7008e90c36cdcb8ba6bdf15a499d8f17ebb/LabFusion/dependencies/Facepunch.Steamworks/SteamServerStats.cs#L18-L23
8889d7008e90c36cdcb8ba6bdf15a499d8f17ebb
Unity-ImageLoader
github_2023
IvanMurzak
csharp
ImageLoader.DiskCacheContains
public static bool DiskCacheContains(string url) => File.Exists(DiskCachePath(url));
/// <summary>
https://github.com/IvanMurzak/Unity-ImageLoader/blob/8f9ebd0e03a8d465adfc659b9124a504fba3c177/Assets/_PackageRoot/Runtime/ImageLoader.DiskCache.cs#L52-L52
8f9ebd0e03a8d465adfc659b9124a504fba3c177
XCSkillEditor_Unity
github_2023
smartgrass
csharp
ServerClientAttributeProcessor.InjectGuardParameters
static void InjectGuardParameters(MethodDefinition md, ILProcessor worker, Instruction top) { int offset = md.Resolve().IsStatic ? 0 : 1; for (int index = 0; index < md.Parameters.Count; index++) { ParameterDefinition param = md.Parameters[index]; if (param.IsOut) { TypeReference elementType = param.ParameterType.GetElementType(); md.Body.Variables.Add(new VariableDefinition(elementType)); md.Body.InitLocals = true; worker.InsertBefore(top, worker.Create(OpCodes.Ldarg, index + offset)); worker.InsertBefore(top, worker.Create(OpCodes.Ldloca_S, (byte)(md.Body.Variables.Count - 1))); worker.InsertBefore(top, worker.Create(OpCodes.Initobj, elementType)); worker.InsertBefore(top, worker.Create(OpCodes.Ldloc, md.Body.Variables.Count - 1)); worker.InsertBefore(top, worker.Create(OpCodes.Stobj, elementType)); } } }
// this is required to early-out from a function with "ref" or "out" parameters
https://github.com/smartgrass/XCSkillEditor_Unity/blob/a1ea899b4504eff4ab64de33abf98681f4409f82/Assets/Mirror/Editor/Weaver/Processors/ServerClientAttributeProcessor.cs#L117-L137
a1ea899b4504eff4ab64de33abf98681f4409f82
XCSkillEditor_Unity
github_2023
smartgrass
csharp
NetworkRoomManagerExt.OnRoomServerSceneChanged
public override void OnRoomServerSceneChanged(string sceneName) { // spawn the initial batch of Rewards if (sceneName == GameplayScene) { Spawner.InitialSpawn(); } }
/// <summary>
https://github.com/smartgrass/XCSkillEditor_Unity/blob/a1ea899b4504eff4ab64de33abf98681f4409f82/Assets/Mirror/Examples/Room/Scripts/NetworkRoomManagerExt.cs#L16-L23
a1ea899b4504eff4ab64de33abf98681f4409f82
Blazor.WebAudio
github_2023
KristofferStrube
csharp
BiquadFilterNode.CreateAsync
public static new async Task<BiquadFilterNode> CreateAsync(IJSRuntime jSRuntime, IJSObjectReference jSReference) { return await CreateAsync(jSRuntime, jSReference, new()); }
/// <inheritdoc/>
https://github.com/KristofferStrube/Blazor.WebAudio/blob/ea1acdd530ee4dc07e3efda4bc0712447b0af18a/src/KristofferStrube.Blazor.WebAudio/AudioNodes/BiquadFilterNode.cs#L21-L24
ea1acdd530ee4dc07e3efda4bc0712447b0af18a
Blazor.WebAudio
github_2023
KristofferStrube
csharp
ChannelSplitterNode.CreateAsync
public static new async Task<ChannelSplitterNode> CreateAsync(IJSRuntime jSRuntime, IJSObjectReference jSReference) { return await CreateAsync(jSRuntime, jSReference, new()); }
/// <inheritdoc/>
https://github.com/KristofferStrube/Blazor.WebAudio/blob/ea1acdd530ee4dc07e3efda4bc0712447b0af18a/src/KristofferStrube.Blazor.WebAudio/AudioNodes/ChannelSplitterNode.cs#L22-L25
ea1acdd530ee4dc07e3efda4bc0712447b0af18a
Blazor.WebAudio
github_2023
KristofferStrube
csharp
AudioParamMap.CreateAsync
public static async Task<AudioParamMap> CreateAsync(IJSRuntime jSRuntime, IJSObjectReference jSReference) { return await CreateAsync(jSRuntime, jSReference, new()); }
/// <inheritdoc/>
https://github.com/KristofferStrube/Blazor.WebAudio/blob/ea1acdd530ee4dc07e3efda4bc0712447b0af18a/src/KristofferStrube.Blazor.WebAudio/AudioWorklet/AudioParamMap.cs#L14-L17
ea1acdd530ee4dc07e3efda4bc0712447b0af18a
nArchitecture.Core
github_2023
kodlamaio-projects
csharp
HashingHelper.CreatePasswordHash
public static void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt) { using HMACSHA512 hmac = new(); passwordSalt = hmac.Key; passwordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password)); }
/// <summary>
https://github.com/kodlamaio-projects/nArchitecture.Core/blob/9561d89f545169c3c2078c229c3a62dddf2886ad/src/Core.Security/Hashing/HashingHelper.cs#L11-L17
9561d89f545169c3c2078c229c3a62dddf2886ad
Dumpify
github_2023
MoaidHathot
csharp
TestExplicit.GetEnumerator
public IEnumerator GetEnumerator() => new TestEnumerator(_list);
//IEnumerator<KeyValuePair<string, string>> IEnumerable<KeyValuePair<string, string>>.GetEnumerator()
https://github.com/MoaidHathot/Dumpify/blob/78ef11df642fac68e6676c08c322a79ce30e25f9/src/Dumpify.Playground/Program.cs#L717-L717
78ef11df642fac68e6676c08c322a79ce30e25f9
ShaderLibrary
github_2023
falseeeeeeeeee
csharp
WorldNormalInputsNode.DrawProperties
public override void DrawProperties() { base.DrawProperties(); m_perPixel = EditorGUILayoutToggleLeft( PerPixelLabelStr, m_perPixel ); }
//public override void Destroy()
https://github.com/falseeeeeeeeee/ShaderLibrary/blob/5d3931c2fd7c8478c984bb2f0be2d0875d6352d2/ShaderLib_2021/Assets/Plugins/AmplifyShaderEditor/Plugins/Editor/Nodes/SurfaceShaderInputs/WorldNormalInputsNode.cs#L45-L49
5d3931c2fd7c8478c984bb2f0be2d0875d6352d2
ShaderLibrary
github_2023
falseeeeeeeeee
csharp
CreateCustomShader.CreateShaderTemplate
private static void CreateShaderTemplate(string templatePath, string defaultFileName) { ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<ShaderAsset>(), GetSelectedPathOrFallback() + "/" + defaultFileName, null, templatePath); }
// 通用方法,用于从给定的模板路径创建Shader
https://github.com/falseeeeeeeeee/ShaderLibrary/blob/5d3931c2fd7c8478c984bb2f0be2d0875d6352d2/ShaderLib_2022/Assets/Plugins/CreateCustomShader/Editor/CreateCustomShader.cs#L11-L18
5d3931c2fd7c8478c984bb2f0be2d0875d6352d2
ShaderLibrary
github_2023
falseeeeeeeeee
csharp
MainDrawer.GetPropertyHeight
public override float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor) { return _height; }
// Call in custom shader gui
https://github.com/falseeeeeeeeee/ShaderLibrary/blob/5d3931c2fd7c8478c984bb2f0be2d0875d6352d2/ShaderLib_2022/Assets/Plugins/LightWeightShaderGUI/Editor/ShaderDrawer.cs#L91-L94
5d3931c2fd7c8478c984bb2f0be2d0875d6352d2
GDC23_PracticalMobileRendering
github_2023
WeakKnight
csharp
FBO.Create
public static FBO Create() { FBO fbo = new FBO(); fbo.m_width = 0; fbo.m_height = 0; return fbo; }
// Create a dummy FBO
https://github.com/WeakKnight/GDC23_PracticalMobileRendering/blob/cb8f6f4e6933abe6a3d1b72c821864f239b14338/PracticalMobileRendering/Assets/Scripts/RenderPipeline/Runtime/LowLevelGraphicsAPI/FBO.cs#L149-L155
cb8f6f4e6933abe6a3d1b72c821864f239b14338
GenshinGamePlay
github_2023
526077247
csharp
AIDecisionTree.Think
public static void Think(AIKnowledge knowledge, AIDecision decision) { var conf = ConfigAIDecisionTreeCategory.Instance.Get(knowledge.DecisionArchetype); if (conf != null) { if (knowledge.CombatComponent != null && knowledge.CombatComponent.IsInCombat) { if (conf.CombatNode != null) Handler(knowledge, decision, conf.CombatNode); } else { if (conf.Node != null) Handler(knowledge, decision, conf.Node); } } }
/// <summary>
https://github.com/526077247/GenshinGamePlay/blob/5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7/Assets/Scripts/Code/Game/Component/AI/Decision/AIDecisionTree.cs#L13-L29
5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7
GenshinGamePlay
github_2023
526077247
csharp
ResourcesManager.IsProcessRunning
public bool IsProcessRunning() { return this.loadingOp.Count > 0; }
/// <summary>
https://github.com/526077247/GenshinGamePlay/blob/5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7/Assets/Scripts/Code/Module/Resource/ResourcesManager.cs#L53-L56
5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7
GenshinGamePlay
github_2023
526077247
csharp
Writer.WriteCommonVal
[MethodImpl(MethodImplOptions.AggressiveInlining)] public void WriteCommonVal<T>(T val) => Serializer.Serialize(typeof(T), val, this, option, false);
/// <summary>
https://github.com/526077247/GenshinGamePlay/blob/5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7/Assets/Scripts/ThirdParty/Nino/Serialization/Writer.Generic.cs#L16-L18
5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7
GenshinGamePlay
github_2023
526077247
csharp
StringMgr.Split
public static unsafe string[] Split(this ReadOnlySpan<char> str, char separator) { if (str.IsEmpty) { return Array.Empty<string>(); } var indexes = ObjectPool<ExtensibleBuffer<int>>.Request(); var index = 0; int i = 0; int max = str.Length; fixed (char* ptr = &str.GetPinnableReference()) { var cPtr = ptr; while (i < max) { if (*cPtr++ == separator) { indexes[index++] = i; } i++; } string[] ret = new string[index + 1]; var retSpan = ret.AsSpan(); int start = 0; for (i = 0; i < index; i++) { ref int end = ref indexes.Data[i]; if(start >= max || start == end) { retSpan[i] = string.Empty; } else { retSpan[i] = new string(ptr, start, end - start); } start = end + 1; } if (start < max) { retSpan[index] = new string(ptr, start, max - start); } else { retSpan[index] = string.Empty; } ObjectPool<ExtensibleBuffer<int>>.Return(indexes); return ret; } }
/// <summary>
https://github.com/526077247/GenshinGamePlay/blob/5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7/Assets/Scripts/ThirdParty/Nino/Shared/Mgr/StringMgr.cs#L15-L70
5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7
GenshinGamePlay
github_2023
526077247
csharp
TaskCopyBuildinFiles.CopyBuildinFilesToStreaming
private void CopyBuildinFilesToStreaming(BuildParametersContext buildParametersContext, ManifestContext manifestContext) { ECopyBuildinFileOption option = buildParametersContext.Parameters.CopyBuildinFileOption; string packageOutputDirectory = buildParametersContext.GetPackageOutputDirectory(); string streamingAssetsDirectory = buildParametersContext.GetStreamingAssetsDirectory(); string buildPackageName = buildParametersContext.Parameters.PackageName; string buildPackageVersion = buildParametersContext.Parameters.PackageVersion; // 加载补丁清单 PackageManifest manifest = manifestContext.Manifest; // 清空流目录 if (option == ECopyBuildinFileOption.ClearAndCopyAll || option == ECopyBuildinFileOption.ClearAndCopyByTags) { EditorTools.ClearFolder(streamingAssetsDirectory); } bool copy = false; // 拷贝文件列表(所有文件) if (option == ECopyBuildinFileOption.ClearAndCopyAll || option == ECopyBuildinFileOption.OnlyCopyAll) { copy = true; foreach (var packageBundle in manifest.BundleList) { string sourcePath = $"{packageOutputDirectory}/{packageBundle.FileName}"; string destPath = $"{streamingAssetsDirectory}/{packageBundle.FileName}"; EditorTools.CopyFile(sourcePath, destPath, true); } } // 拷贝文件列表(带标签的文件) if (option == ECopyBuildinFileOption.ClearAndCopyByTags || option == ECopyBuildinFileOption.OnlyCopyByTags) { string[] tags = buildParametersContext.Parameters.CopyBuildinFileTags.Split(';'); foreach (var packageBundle in manifest.BundleList) { if (packageBundle.HasTag(tags) == false) continue; copy = true; string sourcePath = $"{packageOutputDirectory}/{packageBundle.FileName}"; string destPath = $"{streamingAssetsDirectory}/{packageBundle.FileName}"; EditorTools.CopyFile(sourcePath, destPath, true); } } if (copy) { // 拷贝补丁清单文件 { string fileName = YooAssetSettingsData.GetManifestBinaryFileName(buildPackageName, buildPackageVersion); string sourcePath = $"{packageOutputDirectory}/{fileName}"; string destPath = $"{streamingAssetsDirectory}/{fileName}"; EditorTools.CopyFile(sourcePath, destPath, true); } // 拷贝补丁清单哈希文件 { string fileName = YooAssetSettingsData.GetPackageHashFileName(buildPackageName, buildPackageVersion); string sourcePath = $"{packageOutputDirectory}/{fileName}"; string destPath = $"{streamingAssetsDirectory}/{fileName}"; EditorTools.CopyFile(sourcePath, destPath, true); } // 拷贝补丁清单版本文件 { string fileName = YooAssetSettingsData.GetPackageVersionFileName(buildPackageName); string sourcePath = $"{packageOutputDirectory}/{fileName}"; string destPath = $"{streamingAssetsDirectory}/{fileName}"; EditorTools.CopyFile(sourcePath, destPath, true); } } // 刷新目录 AssetDatabase.Refresh(); BuildLogger.Log($"内置文件拷贝完成:{streamingAssetsDirectory}"); }
/// <summary>
https://github.com/526077247/GenshinGamePlay/blob/5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7/Modules/com.tuyoogame.yooasset/Editor/AssetBundleBuilder/BuildTasks/TaskCopyBuildinFiles.cs#L29-L104
5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7
GenshinGamePlay
github_2023
526077247
csharp
RawBundleWebLoader.Update
public override void Update() { if (_steps == ESteps.Done) return; if (_steps == ESteps.None) { if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote) { _steps = ESteps.Download; FileLoadPath = MainBundleInfo.Bundle.CachedDataFilePath; } else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming) { _steps = ESteps.Website; FileLoadPath = MainBundleInfo.Bundle.CachedDataFilePath; } else { throw new System.NotImplementedException(MainBundleInfo.LoadMode.ToString()); } } // 1. 下载远端文件 if (_steps == ESteps.Download) { int failedTryAgain = Impl.DownloadFailedTryAgain; _downloader = DownloadSystem.CreateDownload(MainBundleInfo, failedTryAgain); _downloader.SendRequest(); _steps = ESteps.CheckDownload; } // 2. 检测下载结果 if (_steps == ESteps.CheckDownload) { DownloadProgress = _downloader.DownloadProgress; DownloadedBytes = _downloader.DownloadedBytes; if (_downloader.IsDone() == false) return; if (_downloader.HasError()) { _steps = ESteps.Done; Status = EStatus.Failed; LastError = _downloader.GetLastError(); } else { _steps = ESteps.CheckFile; } } // 3. 从站点下载 if (_steps == ESteps.Website) { int failedTryAgain = Impl.DownloadFailedTryAgain; var bundleInfo = ManifestTools.ConvertToUnpackInfo(MainBundleInfo.Bundle); _website = DownloadSystem.CreateDownload(bundleInfo, failedTryAgain); _website.SendRequest(); _steps = ESteps.CheckWebsite; } // 4. 检测站点下载 if (_steps == ESteps.CheckWebsite) { DownloadProgress = _website.DownloadProgress; DownloadedBytes = _website.DownloadedBytes; if (_website.IsDone() == false) return; if (_website.HasError()) { _steps = ESteps.Done; Status = EStatus.Failed; LastError = _website.GetLastError(); } else { _steps = ESteps.CheckFile; } } // 5. 检测结果 if (_steps == ESteps.CheckFile) { // 设置下载进度 DownloadProgress = 1f; DownloadedBytes = (ulong)MainBundleInfo.Bundle.FileSize; _steps = ESteps.Done; if (File.Exists(FileLoadPath)) { Status = EStatus.Succeed; } else { Status = EStatus.Failed; LastError = $"Raw file not found : {FileLoadPath}"; } } }
/// <summary>
https://github.com/526077247/GenshinGamePlay/blob/5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7/Modules/com.tuyoogame.yooasset/Runtime/AssetSystem/Loader/RawBundleWebLoader.cs#L33-L133
5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7
GenshinGamePlay
github_2023
526077247
csharp
GameManager.OnHandleEventMessage
private void OnHandleEventMessage(IEventMessage message) { if(message is SceneEventDefine.ChangeToHomeScene) { _machine.ChangeState<FsmSceneHome>(); } else if(message is SceneEventDefine.ChangeToBattleScene) { _machine.ChangeState<FsmSceneBattle>(); } }
/// <summary>
https://github.com/526077247/GenshinGamePlay/blob/5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7/Modules/com.tuyoogame.yooasset/Samples~/Space Shooter/GameScript/Runtime/GameLogic/GameManager.cs#L53-L63
5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7
GenshinGamePlay
github_2023
526077247
csharp
StreamingAssetsHelper.Init
public static void Init() { if (_isInit == false) { _isInit = true; var manifest = Resources.Load<BuildinFileManifest>("BuildinFileManifest"); if (manifest != null) { foreach (string fileName in manifest.BuildinFiles) { _cacheData.Add(fileName); } } } }
/// <summary>
https://github.com/526077247/GenshinGamePlay/blob/5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7/Modules/com.tuyoogame.yooasset/Samples~/Space Shooter/ThirdParty/StreamingAssetsHelper/StreamingAssetsHelper.cs#L43-L57
5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7
GenshinGamePlay
github_2023
526077247
csharp
Double3Drawer.PopulateGenericMenu
public void PopulateGenericMenu(InspectorProperty property, GenericMenu genericMenu) { double3 value = (double3)property.ValueEntry.WeakSmartValue; var vec = new Vector3((float)value.x, (float)value.y, (float)value.z); if (genericMenu.GetItemCount() > 0) { genericMenu.AddSeparator(""); } genericMenu.AddItem(new GUIContent("Normalize"), Mathf.Approximately(vec.magnitude, 1f), () => NormalizeEntries(property)); genericMenu.AddItem(new GUIContent("Zero", "Set the vector to (0, 0, 0)"), vec == Vector3.zero, () => SetVector(property, Vector3.zero)); genericMenu.AddItem(new GUIContent("One", "Set the vector to (1, 1, 1)"), vec == Vector3.one, () => SetVector(property, Vector3.one)); genericMenu.AddSeparator(""); genericMenu.AddItem(new GUIContent("Right", "Set the vector to (1, 0, 0)"), vec == Vector3.right, () => SetVector(property, Vector3.right)); genericMenu.AddItem(new GUIContent("Left", "Set the vector to (-1, 0, 0)"), vec == Vector3.left, () => SetVector(property, Vector3.left)); genericMenu.AddItem(new GUIContent("Up", "Set the vector to (0, 1, 0)"), vec == Vector3.up, () => SetVector(property, Vector3.up)); genericMenu.AddItem(new GUIContent("Down", "Set the vector to (0, -1, 0)"), vec == Vector3.down, () => SetVector(property, Vector3.down)); genericMenu.AddItem(new GUIContent("Forward", "Set the vector property to (0, 0, 1)"), vec == Vector3.forward, () => SetVector(property, Vector3.forward)); genericMenu.AddItem(new GUIContent("Back", "Set the vector property to (0, 0, -1)"), vec == Vector3.back, () => SetVector(property, Vector3.back)); }
/// <summary>
https://github.com/526077247/GenshinGamePlay/blob/5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7/Packages/com.thridparty.odin/Sirenix/Odin Inspector/Modules/Unity.Mathematics/MathematicsDrawers.cs#L598-L617
5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7
GenshinGamePlay
github_2023
526077247
csharp
TMP_SpriteAssetEditor.DisplayPageNavigation
void DisplayPageNavigation(ref int currentPage, int arraySize, int itemsPerPage) { Rect pagePos = EditorGUILayout.GetControlRect(false, 20); pagePos.width /= 3; int shiftMultiplier = Event.current.shift ? 10 : 1; // Page + Shift goes 10 page forward // Previous Page GUI.enabled = currentPage > 0; if (GUI.Button(pagePos, "Previous Page")) { currentPage -= 1 * shiftMultiplier; //m_isNewPage = true; } // Page Counter GUI.enabled = true; pagePos.x += pagePos.width; int totalPages = (int)(arraySize / (float)itemsPerPage + 0.999f); GUI.Label(pagePos, "Page " + (currentPage + 1) + " / " + totalPages, TMP_UIStyleManager.centeredLabel); // Next Page pagePos.x += pagePos.width; GUI.enabled = itemsPerPage * (currentPage + 1) < arraySize; if (GUI.Button(pagePos, "Next Page")) { currentPage += 1 * shiftMultiplier; //m_isNewPage = true; } // Clamp page range currentPage = Mathf.Clamp(currentPage, 0, arraySize / itemsPerPage); GUI.enabled = true; }
/// <summary>
https://github.com/526077247/GenshinGamePlay/blob/5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7/Packages/com.unity.textmeshpro/Scripts/Editor/TMP_SpriteAssetEditor.cs#L672-L708
5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7
GenshinGamePlay
github_2023
526077247
csharp
TMP_MaterialManager.GetStencilMaterial
public static Material GetStencilMaterial(Material baseMaterial, int stencilID) { // Check if Material supports masking if (!baseMaterial.HasProperty(ShaderUtilities.ID_StencilID)) { Debug.LogWarning("Selected Shader does not support Stencil Masking. Please select the Distance Field or Mobile Distance Field Shader."); return baseMaterial; } int baseMaterialID = baseMaterial.GetInstanceID(); // If baseMaterial already has a corresponding masking material, return it. for (int i = 0; i < m_materialList.Count; i++) { if (m_materialList[i].baseMaterial.GetInstanceID() == baseMaterialID && m_materialList[i].stencilID == stencilID) { m_materialList[i].count += 1; #if TMP_DEBUG_MODE ListMaterials(); #endif return m_materialList[i].stencilMaterial; } } // No matching masking material found. Create and return a new one. Material stencilMaterial; //Create new Masking Material Instance for this Base Material stencilMaterial = new Material(baseMaterial); stencilMaterial.hideFlags = HideFlags.HideAndDontSave; #if UNITY_EDITOR stencilMaterial.name += " Masking ID:" + stencilID; #endif stencilMaterial.shaderKeywords = baseMaterial.shaderKeywords; // Set Stencil Properties ShaderUtilities.GetShaderPropertyIDs(); stencilMaterial.SetFloat(ShaderUtilities.ID_StencilID, stencilID); //stencilMaterial.SetFloat(ShaderUtilities.ID_StencilOp, 0); stencilMaterial.SetFloat(ShaderUtilities.ID_StencilComp, 4); //stencilMaterial.SetFloat(ShaderUtilities.ID_StencilReadMask, stencilID); //stencilMaterial.SetFloat(ShaderUtilities.ID_StencilWriteMask, 0); MaskingMaterial temp = new MaskingMaterial(); temp.baseMaterial = baseMaterial; temp.stencilMaterial = stencilMaterial; temp.stencilID = stencilID; temp.count = 1; m_materialList.Add(temp); #if TMP_DEBUG_MODE ListMaterials(); #endif return stencilMaterial; }
/// <summary>
https://github.com/526077247/GenshinGamePlay/blob/5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7/Packages/com.unity.textmeshpro/Scripts/Runtime/TMP_MaterialManager.cs#L43-L104
5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7
GenshinGamePlay
github_2023
526077247
csharp
TimelineAction.Execute
public abstract bool Execute(ActionContext context);
/// <summary>
https://github.com/526077247/GenshinGamePlay/blob/5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7/Packages/com.unity.timeline/Editor/Actions/TimelineAction.cs#L25-L25
5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7
GenshinGamePlay
github_2023
526077247
csharp
TrackAction.Execute
public abstract bool Execute(IEnumerable<TrackAsset> tracks);
/// <summary>
https://github.com/526077247/GenshinGamePlay/blob/5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7/Packages/com.unity.timeline/Editor/Actions/TrackAction.cs#L27-L27
5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7
GenshinGamePlay
github_2023
526077247
csharp
AnimationPlayableAssetEditor.GetClipOptions
public override ClipDrawOptions GetClipOptions(TimelineClip clip) { var clipOptions = base.GetClipOptions(clip); var asset = clip.asset as AnimationPlayableAsset; if (asset != null) clipOptions.errorText = GetErrorText(asset, clip.GetParentTrack() as AnimationTrack, clipOptions.errorText); if (clip.recordable) clipOptions.highlightColor = DirectorStyles.Instance.customSkin.colorAnimationRecorded; return clipOptions; }
/// <inheritdoc/>
https://github.com/526077247/GenshinGamePlay/blob/5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7/Packages/com.unity.timeline/Editor/Animation/AnimationPlayableAssetEditor.cs#L17-L29
5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7
GenshinGamePlay
github_2023
526077247
csharp
TrackAsset.OnBeforeTrackSerialize
protected virtual void OnBeforeTrackSerialize() { }
/// <summary>
https://github.com/526077247/GenshinGamePlay/blob/5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7/Packages/com.unity.timeline/Runtime/AssetUpgrade/TrackUpgrade.cs#L27-L27
5b1e4e62ebdc0b189e158ec55b3d3b4b5e3857d7
StructuredConcurrency
github_2023
StephenCleary
csharp
DisposeUtility.Wrap
public static IAsyncDisposable Wrap(object? resource) => TryWrap(resource) ?? NoopDisposable.Instance;
/// <summary>
https://github.com/StephenCleary/StructuredConcurrency/blob/309813256331af44f15ba8add05350428f60c846/src/Nito.StructuredConcurrency/Internals/DisposeUtility.cs#L15-L15
309813256331af44f15ba8add05350428f60c846
StructuredConcurrency
github_2023
StephenCleary
csharp
InterlockedEx.Apply
public static T Apply<T>(ref T value, Func<T, T> transformation) where T : class { _ = transformation ?? throw new ArgumentNullException(nameof(transformation)); while (true) { var localValue = Interlocked.CompareExchange(ref value, null!, null!); var modified = transformation(localValue); if (Interlocked.CompareExchange(ref value, modified, localValue) == localValue) return modified; } }
/// <summary>
https://github.com/StephenCleary/StructuredConcurrency/blob/309813256331af44f15ba8add05350428f60c846/src/Nito.StructuredConcurrency/Internals/InterlockedEx.cs#L17-L29
309813256331af44f15ba8add05350428f60c846
GameFramework-Next
github_2023
Alex-Rachel
csharp
LogRedirection.GetStackTrace
private static string GetStackTrace() { // 通过反射获取ConsoleWindow类 var consoleWindowType = typeof(EditorWindow).Assembly.GetType("UnityEditor.ConsoleWindow"); // 获取窗口实例 var fieldInfo = consoleWindowType.GetField("ms_ConsoleWindow", BindingFlags.Static | BindingFlags.NonPublic); if (fieldInfo != null) { var consoleInstance = fieldInfo.GetValue(null); if (consoleInstance != null) if (EditorWindow.focusedWindow == (EditorWindow)consoleInstance) { // 获取m_ActiveText成员 fieldInfo = consoleWindowType.GetField("m_ActiveText", BindingFlags.Instance | BindingFlags.NonPublic); // 获取m_ActiveText的值 if (fieldInfo != null) { var activeText = fieldInfo.GetValue(consoleInstance).ToString(); return activeText; } } } return null; }
/// <summary>
https://github.com/Alex-Rachel/GameFramework-Next/blob/4f2fbfa6fc0eb0bfa55c92fd51df295eae3de4b3/UnityProject/Assets/GameScripts/Editor/Extension/Utility/LogRedirection.cs#L95-L123
4f2fbfa6fc0eb0bfa55c92fd51df295eae3de4b3
GameFramework-Next
github_2023
Alex-Rachel
csharp
ReleaseTools.CreateEncryptionInstance
private static IEncryptionServices CreateEncryptionInstance(string packageName, EBuildPipeline buildPipeline) { var encryptionClassName = AssetBundleBuilderSetting.GetPackageEncyptionClassName(packageName, buildPipeline); var encryptionClassTypes = EditorTools.GetAssignableTypes(typeof(IEncryptionServices)); var classType = encryptionClassTypes.Find(x => x.FullName != null && x.FullName.Equals(encryptionClassName)); if (classType != null) { Debug.Log($"Use Encryption {classType}"); return (IEncryptionServices)Activator.CreateInstance(classType); } else { return null; } }
/// <summary>
https://github.com/Alex-Rachel/GameFramework-Next/blob/4f2fbfa6fc0eb0bfa55c92fd51df295eae3de4b3/UnityProject/Assets/GameScripts/Editor/ReleaseTools/ReleaseTools.cs#L165-L179
4f2fbfa6fc0eb0bfa55c92fd51df295eae3de4b3
GameFramework-Next
github_2023
Alex-Rachel
csharp
GameApp.Entrance
public static void Entrance(object[] objects) { s_HotfixAssembly = (List<Assembly>)objects[0]; Log.Warning("======= 看到此条日志代表你成功运行了热更新代码 ======="); Log.Warning("======= Entrance GameApp ======="); Instance.InitSystem(); Instance.Start(); Utility.Unity.AddUpdateListener(Instance.Update); Utility.Unity.AddFixedUpdateListener(Instance.FixedUpdate); Utility.Unity.AddLateUpdateListener(Instance.LateUpdate); Utility.Unity.AddDestroyListener(Instance.OnDestroy); Utility.Unity.AddOnDrawGizmosListener(Instance.OnDrawGizmos); Utility.Unity.AddOnApplicationPauseListener(Instance.OnApplicationPause); Instance.StartGameLogic(); }
/// <summary>
https://github.com/Alex-Rachel/GameFramework-Next/blob/4f2fbfa6fc0eb0bfa55c92fd51df295eae3de4b3/UnityProject/Assets/GameScripts/HotFix/GameLogic/GameApp.cs#L15-L29
4f2fbfa6fc0eb0bfa55c92fd51df295eae3de4b3
vertical-slice-api-template
github_2023
mehdihadeli
csharp
AggregateIdValueConverter.Create
private static TAggregateId Create(TId id) => ( Activator.CreateInstance( typeof(TAggregateId), BindingFlags.Instance | BindingFlags.NonPublic, null, new object?[] { id }, null, null ) as TAggregateId )!;
// instantiate AggregateId and pass id to its protected or private constructor
https://github.com/mehdihadeli/vertical-slice-api-template/blob/3837aefd7d6ed6bf8e32faca932a145f25f0dfb4/src/Shared/EF/Converters/AggregateIdValueConverter.cs#L15-L25
3837aefd7d6ed6bf8e32faca932a145f25f0dfb4
AcrylicView.MAUI
github_2023
sswi
csharp
CornerFrameLayout.SetRadius
public void SetRadius(float topLeft, float topRight, float bottomRight, float bottomLeft) { mRadii[0] = topLeft; mRadii[1] = topLeft; mRadii[2] = topRight; mRadii[3] = topRight; mRadii[4] = bottomRight; mRadii[5] = bottomRight; mRadii[6] = bottomLeft; mRadii[7] = bottomLeft; Invalidate(); }
/// <summary>
https://github.com/sswi/AcrylicView.MAUI/blob/a70ec049b39ba9f5300f27c16d4bf1539e00c373/AcrylicView/Platforms/Android/Drawable/CornerFrameLayout.cs#L47-L61
a70ec049b39ba9f5300f27c16d4bf1539e00c373
Template
github_2023
CSharpRedotTools
csharp
StateMachineComponent.SwitchState
private void SwitchState(State newState, bool callExit = true) { if (callExit) { _curState.Exit(); } _curState = newState; _curState.Enter(); }
/// <summary>
https://github.com/CSharpRedotTools/Template/blob/d1b39583643c63beeda68c629ecc6c76cf98df4c/Genres/2D Top Down/Scripts/Components/StateMachineComponent.cs#L39-L48
d1b39583643c63beeda68c629ecc6c76cf98df4c
PotatoVN
github_2023
GoldenPotato137
csharp
GalStatusSyncResultHelper.ToInfoBarSeverity
public static InfoBarSeverity ToInfoBarSeverity(this GalStatusSyncResult result) { switch (result) { case GalStatusSyncResult.Ok: return InfoBarSeverity.Success; case GalStatusSyncResult.UnAuthorized: case GalStatusSyncResult.NoId: case GalStatusSyncResult.Other: return InfoBarSeverity.Error; case GalStatusSyncResult.NotSupported: return InfoBarSeverity.Warning; default: return InfoBarSeverity.Error; } }
/// <summary>
https://github.com/GoldenPotato137/PotatoVN/blob/e8db00158d27c07f868cae89d9aaa5a5bd9c3349/GalgameManager/Enums/GalStatusSyncResult.cs#L24-L39
e8db00158d27c07f868cae89d9aaa5a5bd9c3349
PotatoVN
github_2023
GoldenPotato137
csharp
NavigationHelper.NavigateToHomePage
public static void NavigateToHomePage(INavigationService navigationService, IFilterService? filterService = null, IEnumerable<FilterBase>? filters = null) { Debug.Assert(!(filterService is null ^ filters is null)); // 同时为null或同时不为null if (filterService is not null && filters is not null) { filterService.ClearFilters(); foreach (FilterBase filter in filters) { filterService.AddFilter(filter); if (filter is CategoryFilter c) c.Category.LastClicked = DateTime.Now; if (filter is SourceFilter s) s.Source.LastClicked = DateTime.Now; } } navigationService.NavigateTo(typeof(HomeViewModel).FullName!); }
/// <summary>
https://github.com/GoldenPotato137/PotatoVN/blob/e8db00158d27c07f868cae89d9aaa5a5bd9c3349/GalgameManager/Helpers/NavigationHelper.cs#L34-L52
e8db00158d27c07f868cae89d9aaa5a5bd9c3349
PotatoVN
github_2023
GoldenPotato137
csharp
TimeToDisplayTimeConverter.Convert
public static string Convert(int value) { var timeAsHour = App.GetService<ILocalSettingsService>().ReadSettingAsync<bool>(KeyValues.TimeAsHour).Result; if (timeAsHour) return value > 60 ? $"{value / 60}h{value % 60}m" : $"{value}m"; return $"{value} {"Minute".GetLocalized()}"; }
//不需要
https://github.com/GoldenPotato137/PotatoVN/blob/e8db00158d27c07f868cae89d9aaa5a5bd9c3349/GalgameManager/Helpers/Converter/TimeToDisplayTimeConverter.cs#L24-L30
e8db00158d27c07f868cae89d9aaa5a5bd9c3349
PotatoVN
github_2023
GoldenPotato137
csharp
ObservableCollectionExtensions.SyncCollection
public static void SyncCollection<T>(this ObservableCollection<T> collection, IList<T> other, bool sort = false) where T : notnull { // var delta = other.Count - collection.Count; // for (var i = 0; i < delta; i++) // collection.Add(other[0]); //内容不总要,只是要填充到对应的总数 // for (var i = delta; i < 0; i++) // collection.RemoveAt(collection.Count - 1); // // for (var i = 0; i < other.Count; i++) // collection[i] = other[i]; HashSet<T> toRemove = new(collection.Where(obj => !other.Contains(obj))); HashSet<T> toAdd = new(other.Where(obj => !collection.Contains(obj))); foreach (T obj in toRemove) collection.Remove(obj); foreach (T obj in toAdd) collection.Add(obj); if (!sort) return; Dictionary<T, int> index = new(); for (var i = 0; i < other.Count; i++) index[other[i]] = i; collection.Sort((a, b) => index[a].CompareTo(index[b])); }
/// <summary>
https://github.com/GoldenPotato137/PotatoVN/blob/e8db00158d27c07f868cae89d9aaa5a5bd9c3349/GalgameManager/Helpers/Extensions/ObservableCollectionExtensions.cs#L14-L38
e8db00158d27c07f868cae89d9aaa5a5bd9c3349
PotatoVN
github_2023
GoldenPotato137
csharp
GalgameUid.Similarity
public int Similarity(GalgameUid? rhs) { if (rhs is null) return 0; var result = 0; result += !PvnId.IsNullOrEmpty() && PvnId == rhs.PvnId ? 1 : 0; result += !BangumiId.IsNullOrEmpty() && BangumiId == rhs.BangumiId ? 1 : 0; result += !VndbId.IsNullOrEmpty() && VndbId == rhs.VndbId ? 1 : 0; result += !CnName.IsNullOrEmpty() && CnName == rhs.CnName ? 1 : 0; result += Name == rhs.Name ? 1 : 0; return result; }
/// <summary>
https://github.com/GoldenPotato137/PotatoVN/blob/e8db00158d27c07f868cae89d9aaa5a5bd9c3349/GalgameManager/Models/GalgameUid.cs#L24-L34
e8db00158d27c07f868cae89d9aaa5a5bd9c3349
BarcodeScanning.Native.Maui
github_2023
afriscic
csharp
Program.Main
static void Main(string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, null, typeof(AppDelegate)); }
// This is the main entry point of the application.
https://github.com/afriscic/BarcodeScanning.Native.Maui/blob/dd51248cb791fe8b7099b5d06b6f71c9d766ea81/BarcodeScanning.Test/Platforms/iOS/Program.cs#L9-L14
dd51248cb791fe8b7099b5d06b6f71c9d766ea81
AIShell
github_2023
PowerShell
csharp
PSConsoleReadLine.ViReplaceLine
public static void ViReplaceLine(ConsoleKeyInfo? key = null, object arg = null) { _singleton._groupUndoHelper.StartGroup(ViReplaceLine, arg); DeleteLine(key, arg); ViInsertMode(key, arg); }
/// <summary>
https://github.com/PowerShell/AIShell/blob/8fc4c0dc16cdcf5aaefefec24e3b10ecc85c3ad0/shell/ReadLine/Replace.vi.cs#L138-L143
8fc4c0dc16cdcf5aaefefec24e3b10ecc85c3ad0
AIShell
github_2023
PowerShell
csharp
ReplaceCommand.RegenerateAsync
private async Task<string> RegenerateAsync() { ArgumentPlaceholder ap = _agent.ArgPlaceholder; // We are doing the replacement locally, but want to fake the regeneration. await Task.Delay(2000, Shell.CancellationToken); ResponseData data = ap.ResponseData; _agent.ReplaceKnownPlaceholders(data); if (data.PlaceholderSet is null) { _agent.ResetArgumentPlaceholder(); } return _agent.GenerateAnswer(data, Shell); }
/// <summary>
https://github.com/PowerShell/AIShell/blob/8fc4c0dc16cdcf5aaefefec24e3b10ecc85c3ad0/shell/agents/Microsoft.Azure.Agent/Command.cs#L260-L276
8fc4c0dc16cdcf5aaefefec24e3b10ecc85c3ad0
elsa-studio
github_2023
elsa-workflows
csharp
RenderTreeBuilderExtensions.CreateComponent
public static void CreateComponent<T>(this RenderTreeBuilder builder) where T : IComponent { var sequence = 0; CreateComponent<T>(builder, ref sequence); }
/// <summary>
https://github.com/elsa-workflows/elsa-studio/blob/95c37625ffcdfde09f1a3244a386b0ab005cdd82/src/framework/Elsa.Studio.Core/Extensions/RenderTreeBuilderExtensions.cs#L14-L18
95c37625ffcdfde09f1a3244a386b0ab005cdd82
elsa-studio
github_2023
elsa-workflows
csharp
ServiceCollectionExtensions.AddLoginModuleCore
public static IServiceCollection AddLoginModuleCore(this IServiceCollection services) { return services .AddScoped<IFeature, Feature>() .AddOptions() .AddAuthorizationCore() .AddScoped<AuthenticatingApiHttpMessageHandler>() .AddScoped<AuthenticationStateProvider, AccessTokenAuthenticationStateProvider>() .AddScoped<IUnauthorizedComponentProvider, RedirectToLoginUnauthorizedComponentProvider>() .AddScoped<ICredentialsValidator, DefaultCredentialsValidator>() ; }
/// <summary>
https://github.com/elsa-workflows/elsa-studio/blob/95c37625ffcdfde09f1a3244a386b0ab005cdd82/src/modules/Elsa.Studio.Login/Extensions/ServiceCollectionExtensions.cs#L20-L31
95c37625ffcdfde09f1a3244a386b0ab005cdd82
elsa-studio
github_2023
elsa-workflows
csharp
InputDescriptorCheckListExtensions.GetCheckList
public static CheckList GetCheckList(this InputDescriptor descriptor) { var specifications = descriptor.UISpecifications; var props = specifications != null ? specifications.TryGetValue("checklist", out var propsValue) ? propsValue is JsonElement value ? value : default : default : default; if (props.ValueKind == JsonValueKind.Undefined) return new CheckList(Array.Empty<CheckListItem>()); var serializerOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, }; var checkListProps = props.Deserialize<CheckListProps>(serializerOptions); return checkListProps?.CheckList ?? new CheckList(Array.Empty<CheckListItem>()); }
/// <summary>
https://github.com/elsa-workflows/elsa-studio/blob/95c37625ffcdfde09f1a3244a386b0ab005cdd82/src/modules/Elsa.Studio.UIHints/Extensions/InputDescriptorCheckListExtensions.cs#L15-L30
95c37625ffcdfde09f1a3244a386b0ab005cdd82
elsa-studio
github_2023
elsa-workflows
csharp
RemoteLogPersistenceStrategyService.GetLogPersistenceStrategiesAsync
public async Task<IEnumerable<LogPersistenceStrategyDescriptor>> GetLogPersistenceStrategiesAsync(CancellationToken cancellationToken = default) { if (_descriptors == null) { var api = await backendApiClientProvider.GetApiAsync<ILogPersistenceStrategiesApi>(cancellationToken); var response = await api.ListAsync(cancellationToken); _descriptors = response.Items; } return _descriptors; }
/// <inheritdoc />
https://github.com/elsa-workflows/elsa-studio/blob/95c37625ffcdfde09f1a3244a386b0ab005cdd82/src/modules/Elsa.Studio.Workflows.Core/Domain/Services/RemoteLogPersistenceStrategyService.cs#L13-L23
95c37625ffcdfde09f1a3244a386b0ab005cdd82
elsa-studio
github_2023
elsa-workflows
csharp
RemoteWorkflowDefinitionService.ListAsync
public async Task<PagedListResponse<WorkflowDefinitionSummary>> ListAsync(ListWorkflowDefinitionsRequest request, VersionOptions? versionOptions = null, CancellationToken cancellationToken = default) { var api = await GetApiAsync(cancellationToken); return await api.ListAsync(request, versionOptions, cancellationToken); }
/// <inheritdoc />
https://github.com/elsa-workflows/elsa-studio/blob/95c37625ffcdfde09f1a3244a386b0ab005cdd82/src/modules/Elsa.Studio.Workflows.Core/Domain/Services/WorkflowDefinitionService.cs#L25-L29
95c37625ffcdfde09f1a3244a386b0ab005cdd82
AspNetStatic
github_2023
ZarehD
csharp
HttpContextExtensions.IsAspNetStaticRequest
public static bool IsAspNetStaticRequest(this HttpRequest request) => (request is not null) && request.Headers.TryGetValue(HeaderNames.UserAgent, out var ua) && ua.Contains(Consts.AspNetStatic);
/// <summary>
https://github.com/ZarehD/AspNetStatic/blob/25aced55cddc84eaf910363ec377ffef99853e7b/src/AspNetStatic/HttpContextExtensions.cs#L33-L36
25aced55cddc84eaf910363ec377ffef99853e7b
AspNetStatic
github_2023
ZarehD
csharp
StaticGeneratorHostExtension.GenerateStaticContent
public static void GenerateStaticContent( this IHost host, string destinationRoot, bool exitWhenDone = default, bool alwaysDefaultFile = default, bool dontUpdateLinks = default, bool dontOptimizeContent = default, TimeSpan? regenerationInterval = default, ulong httpTimeoutSeconds = c_DefaultHttpTimeoutSeconds) { Throw.IfNull(host); Throw.IfNullOrWhitespace(destinationRoot); var fileSystem = host.Services.GetService<IFileSystem>() ?? new FileSystem(); Throw.DirectoryNotFoundWhen( () => !fileSystem.Directory.Exists(destinationRoot), SR.Err_InvalidDestinationRoot); var loggerFactory = host.Services.GetRequiredService<ILoggerFactory>(); var logger = loggerFactory.CreateLogger(nameof(StaticGeneratorHostExtension)); var pageUrlProvider = host.Services.GetRequiredService<IStaticResourcesInfoProvider>(); if (!pageUrlProvider.PageResources.Any()) { logger.NoPagesToProcess(); return; } var optimizerSelector = GetOptimizerSelector(host.Services, dontOptimizeContent); var lifetime = host.Services.GetRequiredService<IHostApplicationLifetime>(); lifetime.ApplicationStopping.Register(_appShutdown.Cancel); lifetime.ApplicationStarted.Register( async () => { try { _httpClient.BaseAddress = new Uri(GetBaseUri(host)); _httpClient.Timeout = TimeSpan.FromSeconds(httpTimeoutSeconds); _httpClient.DefaultRequestHeaders.Add(HeaderNames.UserAgent, Consts.AspNetStatic); var generatorConfig = new StaticGeneratorConfig( pageUrlProvider.Resources, destinationRoot, alwaysDefaultFile, !dontUpdateLinks, pageUrlProvider.DefaultFileName, pageUrlProvider.PageFileExtension.EnsureStartsWith('.'), pageUrlProvider.DefaultFileExclusions, !dontOptimizeContent, optimizerSelector, pageUrlProvider.SkipPageResources, pageUrlProvider.SkipCssResources, pageUrlProvider.SkipJsResources, pageUrlProvider.SkipBinResources); logger.RegenerationConfig(regenerationInterval); var doPeriodicRefresh = regenerationInterval is not null; #if USE_PERIODIC_TIMER if (!_appShutdown.IsCancellationRequested) { if (doPeriodicRefresh) _timer = new(regenerationInterval!.Value); do { await StaticGenerator.Execute( generatorConfig, _httpClient, fileSystem, loggerFactory, _appShutdown.Token) .ConfigureAwait(false); } while (doPeriodicRefresh && await _timer.WaitForNextTickAsync(_appShutdown.Token).ConfigureAwait(false)); } if (exitWhenDone && !doPeriodicRefresh && !_appShutdown.IsCancellationRequested) { logger.Exiting(); await Task.Delay(500).ConfigureAwait(false); await host.StopAsync().ConfigureAwait(false); } #else await StaticPageGenerator.Execute( generatorConfig, _httpClient, fileSystem, loggerFactory, _appShutdown.Token) .ConfigureAwait(false); if (doPeriodicRefresh && !_appShutdown.IsCancellationRequested) { _timer.Interval = regenerationInterval!.Value.TotalMilliseconds; _timer.Elapsed += async (s, e) => { await StaticPageGenerator.Execute( generatorConfig, _httpClient, fileSystem, loggerFactory, _appShutdown.Token) .ConfigureAwait(false); if (_appShutdown.IsCancellationRequested) { _timer.Stop(); } }; _timer.Start(); } if (_appShutdown.IsCancellationRequested) { _timer.Stop(); } else if (exitWhenDone && !doPeriodicRefresh) { logger.Exiting(); await Task.Delay(500).ConfigureAwait(false); await host.StopAsync().ConfigureAwait(false); } #endif } catch (OperationCanceledException) { } catch (Exception ex) { logger.Exception(ex); } }); }
/// <summary>
https://github.com/ZarehD/AspNetStatic/blob/25aced55cddc84eaf910363ec377ffef99853e7b/src/AspNetStatic/StaticGeneratorHostExtension.cs#L86-L215
25aced55cddc84eaf910363ec377ffef99853e7b
azure-search-openai-demo-csharp
github_2023
Azure-Samples
csharp
StringExtensions.ToCitationUrl
internal static string ToCitationUrl(this string fileName, string baseUrl) { var builder = new UriBuilder(baseUrl); builder.Path += $"/{fileName}"; builder.Fragment = "view-fitV"; return builder.Uri.AbsoluteUri; }
/// <summary>
https://github.com/Azure-Samples/azure-search-openai-demo-csharp/blob/fd451e3cef53fe0c65ae8c283d95a389e4f203bd/app/frontend/Extensions/StringExtensions.cs#L11-L18
fd451e3cef53fe0c65ae8c283d95a389e4f203bd
devhomegithubextension
github_2023
microsoft
csharp
DeveloperIdTests.LoginUI_ControllerPATLoginTest_Success
[TestMethod] [TestCategory("LiveData")] public async Task LoginUI_ControllerPATLoginTest_Success() { // Create DataRows during Runtime since these need Env vars RuntimeDataRow[] dataRows = { new() { InitialState = "EnterpriseServerPATPage", Actions = LoginUITestData.ConnectButtonAction, Inputs = LoginUITestData.GoodPATEnterpriseServerPATInput, FinalState = "LoginSucceededPage", HostAddress = Environment.GetEnvironmentVariable("DEV_HOME_TEST_GITHUB_ENTERPRISE_SERVER"), }, new() { InitialState = "EnterpriseServerPATPage", Actions = LoginUITestData.ConnectButtonAction, Inputs = LoginUITestData.GoodPATGithubComPATInput, FinalState = "LoginSucceededPage", HostAddress = "https://api.github.com", }, } ; foreach (RuntimeDataRow dataRow in dataRows) { var testExtensionAdaptiveCard = new MockExtensionAdaptiveCard(string.Empty, string.Empty, string.Empty); Assert.AreEqual(0, testExtensionAdaptiveCard.UpdateCount); // Create a LoginUIController and initialize it with the testExtensionAdaptiveCard. var controller = new LoginUIController(MockDeveloperIdProvider.GetInstance()); Assert.AreEqual(ProviderOperationStatus.Success, controller.Initialize(testExtensionAdaptiveCard).Status); Assert.AreEqual(1, testExtensionAdaptiveCard.UpdateCount); // Set the initial state. testExtensionAdaptiveCard.State = dataRow.InitialState ?? string.Empty; Assert.AreEqual(dataRow.InitialState, testExtensionAdaptiveCard.State); // Set HostAddress for EnterpriseServerPATPage to make this a valid state if (dataRow.InitialState == "EnterpriseServerPATPage") { controller.HostAddress = new Uri(dataRow.HostAddress ?? string.Empty); Assert.AreEqual(dataRow.HostAddress, controller.HostAddress.OriginalString); } // Call OnAction() with the actions and inputs. Assert.AreEqual(ProviderOperationStatus.Success, (await controller.OnAction(dataRow.Actions ?? string.Empty, dataRow.Inputs ?? string.Empty)).Status); // Verify the final state Assert.AreEqual(dataRow.FinalState, testExtensionAdaptiveCard.State); Assert.AreEqual(2, testExtensionAdaptiveCard.UpdateCount); controller.Dispose(); } }
/* This test requires the following environment variables to be set: * DEV_HOME_TEST_GITHUB_ENTERPRISE_SERVER : The host address of the GitHub Enterprise Server to test against * DEV_HOME_TEST_GITHUB_COM_PAT : A valid Personal Access Token for GitHub.com (with at least repo_public permissions) * DEV_HOME_TEST_GITHUB_ENTERPRISE_SERVER_PAT : A valid Personal Access Token for the GitHub Enterprise Server set in DEV_HOME_TEST_GITHUB_ENTERPRISE_SERVER (with at least repo_public permissions) */
https://github.com/microsoft/devhomegithubextension/blob/054645220c7e9e71dd7c75a9781d36964af346c0/test/GitHubExtension/DeveloperId/LoginUITests.cs#L149-L205
054645220c7e9e71dd7c75a9781d36964af346c0
S7CommPlusDriver
github_2023
thomas-v2
csharp
POffsetInfoType_FbArray.IsMDim
public override bool IsMDim() { return false; }
//!!! TODO
https://github.com/thomas-v2/S7CommPlusDriver/blob/76ca5e78cba06628146591277adf3dfafd62ca63/src/S7CommPlusDriver/Core/POffsetInfoType.cs#L120-L120
76ca5e78cba06628146591277adf3dfafd62ca63
JitHubV2
github_2023
JitHubApp
csharp
WebView2Ex.RegisterDragDropEvents
void RegisterDragDropEvents() { var manager = CoreDragDropManager.GetForCurrentView(); manager.TargetRequested += TargetRequested; }
//LinkedListNode<ICoreDropOperationTarget>? thisNode;
https://github.com/JitHubApp/JitHubV2/blob/01d7d884407b4b92a51cf0a95c08e95ed2acde5d/JitHub.WebView/UI/WebView2Ex.DragDrop.cs#L26-L30
01d7d884407b4b92a51cf0a95c08e95ed2acde5d
FSR3Unity
github_2023
ndepoel
csharp
IntParameter.Interp
public override void Interp(int from, int to, float t) { // Int snapping interpolation. Don't use this for enums as they don't necessarily have // contiguous values. Use the default interpolator instead (same as bool). value = (int)(from + (to - from) * t); }
/// <summary>
https://github.com/ndepoel/FSR3Unity/blob/71879e71aa72465a79bdf009d7d71f9f7ab83066/Packages/com.unity.postprocessing/PostProcessing/Runtime/ParameterOverride.cs#L233-L238
71879e71aa72465a79bdf009d7d71f9f7ab83066
SqlParser-cs
github_2023
TylerBrinks
csharp
ParserTestBase.ParseSqlStatements
public Sequence<Statement?> ParseSqlStatements(string sql, IEnumerable<Dialect> dialects, bool unescape = false, ParserOptions? options = null) { options ??= new ParserOptions { Unescape = unescape }; return OneOfIdenticalResults(dialect => { options.TrailingCommas |= dialect.SupportsTrailingCommas; return new Parser().ParseSql(sql, dialect, options); }, dialects)!; }
// Ensures that `sql` parses as a single statement and returns it.
https://github.com/TylerBrinks/SqlParser-cs/blob/66aea72a1cb0ed72e3f50cc4bf83326de41b93c2/src/SqlParser.Tests/ParserTestBase.cs#L172-L180
66aea72a1cb0ed72e3f50cc4bf83326de41b93c2