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;
            }
        }


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();
                }
            }
        }


[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
        }


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;
        }


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);
            }
        }


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

                };

            }

        }


public async Task<List<long>> GetChildIdListAsync(long id)
    {
        return await Select
        .Where(a => a.Id == id)
        .AsTreeCte()
        .ToListAsync(a => a.Id);
    }


public async Task<bool> HasUser(long id)
    {
        return await Select.Where(a => a.OrgId == id).AnyAsync();
    }


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;
    }


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;
    }
    */


public static bool Verify(string input)
    {
        if (input.IsNull())
        {
            return false;
        }

        return RegexPassword().IsMatch(input);
    }


protected void Write(char? value)
    {
        if (value.HasValue)
        {
            WriteUtf8SpanFormattable(value.Value);
        }
    }


public static bool IsServiceRunning(string serviceName)
        {
            return IsServiceRunning(Environment.MachineName, serviceName);
        }


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}\"");
        }


public static T AddItemAndRet<T>(this ResourceFolder folder, T item) where T : BaseResource {
        folder.AddItem(item);
        return item;
    }


public new TaskAwaiter<T> GetAwaiter() => this.Task.GetAwaiter();


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


public static bool instanceof(this Type left, Type right) {
        return right.IsAssignableFrom(left);
    }


public T? GetEffectiveValue(Type key) {
        return this.GetOrCreateEntryInternal(key).inheritedItem;
    }


public static ObservableItemProcessorSimple<T> MakeSimple<T>(IObservableList<T> list, Action<T>? onItemAdded, Action<T>? onItemRemoved) {
        return new ObservableItemProcessorSimple<T>(list, onItemAdded, onItemRemoved);
    }


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.


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;
    }


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;
    }


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;
    }


public static bool Compare(string text, string hash, bool uppercase = false, bool is16 = false)
    {
        return Compare(Encoding.UTF8.GetBytes(text), hash, uppercase, is16);
    }


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();
    }


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;
    }


public static IMvcBuilder AddSpecificationDocuments(this IMvcBuilder mvcBuilder, Action<SwaggerGenOptions> configure = default)
    {
        mvcBuilder.Services.AddSpecificationDocuments(configure);

        return mvcBuilder;
    }


public static IMvcBuilder AddUnifyResult(this IMvcBuilder mvcBuilder)
    {
        mvcBuilder.Services.AddUnifyResult<RESTfulResultProvider>();

        return mvcBuilder;
    }


internal static Assembly? GetAssembly(this object? obj) => obj?.GetType().Assembly;


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);
        }
    }


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;
    }


public override void Init(String value)
    {
        // 加上默认后缀
        if (!value.IsNullOrEmpty() && Path.GetExtension(value).IsNullOrEmpty()) value += ".ini";

        base.Init(value);
    }


public String Hash(String password) => password.MD5();

/// <summary>对密码进行散列处理，此处可以加盐，结果保存在数据库</summary>


public void Initialize(GeneratorInitializationContext context)
    {
        //Debugger.Launch();
        context.RegisterForPostInitialization(a =>
        {
            a.AddSource(nameof(m_generatorVariableAttribute), m_generatorVariableAttribute);
        });
        context.RegisterForSyntaxNotifications(() => new VariableSyntaxReceiver());
    }


[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;
    }


protected override void OnInitialized()
    {
        base.OnInitialized();
        HeaderText = ManagementLocalizer[nameof(HeaderText)];
    }


public static UpdateModel Deserialize(string json)
    {
        var obj = JsonSerializer.Deserialize(json, UpdateModelJsonContext.Default.UpdateModel);

        return obj;
    }


public static async Task<Result> RequestUserStatsAsync(SteamId steamid)
        {
            var r = await Internal.RequestUserStats(steamid);
            if (!r.HasValue) return Result.Fail;
            return r.Value.Result;
        }


public static bool DiskCacheContains(string url) => File.Exists(DiskCachePath(url));


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


public override void OnRoomServerSceneChanged(string sceneName)
        {
            // spawn the initial batch of Rewards
            if (sceneName == GameplayScene)
            {
                Spawner.InitialSpawn();
            }
        }


public static new async Task<BiquadFilterNode> CreateAsync(IJSRuntime jSRuntime, IJSObjectReference jSReference)
    {
        return await CreateAsync(jSRuntime, jSReference, new());
    }


public static new async Task<ChannelSplitterNode> CreateAsync(IJSRuntime jSRuntime, IJSObjectReference jSReference)
    {
        return await CreateAsync(jSRuntime, jSReference, new());
    }


public static async Task<AudioParamMap> CreateAsync(IJSRuntime jSRuntime, IJSObjectReference jSReference)
    {
        return await CreateAsync(jSRuntime, jSReference, new());
    }


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));
    }


public IEnumerator GetEnumerator() => new TestEnumerator(_list);

//IEnumerator<KeyValuePair<string, string>> IEnumerable<KeyValuePair<string, string>>.GetEnumerator()


public override void DrawProperties()
		{
			base.DrawProperties();
			m_perPixel = EditorGUILayoutToggleLeft( PerPixelLabelStr, m_perPixel );
		}


private static void CreateShaderTemplate(string templatePath, string defaultFileName)
    {
        ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0,
            ScriptableObject.CreateInstance<ShaderAsset>(),
            GetSelectedPathOrFallback() + "/" + defaultFileName,
            null,
            templatePath);
    }

// 通用方法，用于从给定的模板路径创建Shader


public override float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor)
		{
			return _height;
		}


public static FBO Create()
        {
            FBO fbo = new FBO();
            fbo.m_width  = 0;
            fbo.m_height = 0;
            return fbo;
        }


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);
				}
			}
		}


public bool IsProcessRunning()
        {
            return this.loadingOp.Count > 0;
        }


[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void WriteCommonVal<T>(T val) =>
            Serializer.Serialize(typeof(T), val, this, option, false);


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;
            }
        }


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}");
		}


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}";
				}
			}
		}


private void OnHandleEventMessage(IEventMessage message)
	{
		if(message is SceneEventDefine.ChangeToHomeScene)
		{
			_machine.ChangeState<FsmSceneHome>();
		}
		else if(message is SceneEventDefine.ChangeToBattleScene)
		{
			_machine.ChangeState<FsmSceneBattle>();
		}
	}


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);
				}
			}
		}
	}


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));
        }


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;
        }


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;
        }


public abstract bool Execute(ActionContext context);


public abstract bool Execute(IEnumerable<TrackAsset> tracks);


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;
        }


protected virtual void OnBeforeTrackSerialize() { }


public static IAsyncDisposable Wrap(object? resource) => TryWrap(resource) ?? NoopDisposable.Instance;


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;
        }
    }


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;
        }


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;
            }
        }


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();
    }


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


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();
        }


private void SwitchState(State newState, bool callExit = true)
    {
        if (callExit)
        {
            _curState.Exit();
        }

        _curState = newState;
        _curState.Enter();
    }


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;
        }
    }


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!);
    }


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()}";
    }


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]));
    }


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;
    }


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.


public static void ViReplaceLine(ConsoleKeyInfo? key = null, object arg = null)
        {
            _singleton._groupUndoHelper.StartGroup(ViReplaceLine, arg);
            DeleteLine(key, arg);
            ViInsertMode(key, arg);
        }


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);
    }


public static void CreateComponent<T>(this RenderTreeBuilder builder) where T : IComponent
    {
        var sequence = 0;
        CreateComponent<T>(builder, ref sequence);
    }


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>()
            ;
    }


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>());
    }


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;
    }


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);
    }


public static bool IsAspNetStaticRequest(this HttpRequest request) =>
			(request is not null) &&
			request.Headers.TryGetValue(HeaderNames.UserAgent, out var ua) &&
			ua.Contains(Consts.AspNetStatic);


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);
					}
				});
		}


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;
    }


[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)
     */


public override bool IsMDim() { return false; }


void RegisterDragDropEvents()
    {
        var manager = CoreDragDropManager.GetForCurrentView();
        manager.TargetRequested += TargetRequested;
    }


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);
        }


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.


func logStacks() {
	time.Sleep(time.Second) // Hack to wait for goroutines to end
	buf := make([]byte, 1<<20)
	n := runtime.Stack(buf, true)
	fmt.Fprintln(os.Stderr, string(buf[:n]))
}

// logStacks prints the stacks of live goroutines. This functionality
// is disabled by default but can be enabled to find background work that
// is not obeying cancellation.


func NewColorableStderr() io.Writer {
	return os.Stderr
}

// NewColorableStderr returns new instance of Writer which handles escape sequence for stderr.


func Pause() (err error) {
	_, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}

// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT


func pwrite(fd int, p []byte, offset int64) (n int, err error) {
	var _p0 *byte
	if len(p) > 0 {
		_p0 = &p[0]
	}
	var _p1 int
	_p1 = len(p)
	r0, er := C.pwrite64(C.int(fd), C.uintptr_t(uintptr(unsafe.Pointer(_p0))), C.size_t(_p1), C.longlong(offset))
	n = int(r0)
	if r0 == -1 && er != nil {
		err = er
	}
	return
}


func callfstatat(dirfd int, _p0 uintptr, stat uintptr, flags int) (r1 uintptr, e1 Errno) {
	r1, _, e1 = syscall6(uintptr(unsafe.Pointer(&libc_fstatat)), 4, uintptr(dirfd), _p0, stat, uintptr(flags), 0, 0)
	return
}


func calltruncate(_p0 uintptr, length int64) (r1 uintptr, e1 Errno) {
	r1, _, e1 = syscall6(uintptr(unsafe.Pointer(&libc_truncate)), 2, _p0, uintptr(length), 0, 0, 0, 0)
	return
}


func callsetsid() (r1 uintptr, e1 Errno) {
	r1 = uintptr(C.setsid())
	e1 = syscall.GetErrno()
	return
}


func Ftruncate(fd int, length int64) (err error) {
	_, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func Flock(fd int, how int) (err error) {
	_, _, e1 := syscall_syscall(libc_flock_trampoline_addr, uintptr(fd), uintptr(how), 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}

//go:cgo_import_dynamic libc_fchownat fchownat "libc.so"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT


func Mlock(b []byte) (err error) {
	var _p0 unsafe.Pointer
	if len(b) > 0 {
		_p0 = unsafe.Pointer(&b[0])
	} else {
		_p0 = unsafe.Pointer(&_zero)
	}
	_, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func (d *dbBaseOracle) ShowTablesQuery() string {
	return "SELECT TABLE_NAME FROM USER_TABLES"
}

// ShowTablesQuery show All the tables in database


func (t *idnaTrie) lookupUnsafe(s []byte) uint16 {
	c0 := s[0]
	if c0 < 0x80 { // is ASCII
		return idnaValues[c0]
	}
	i := idnaIndex[c0]
	if c0 < 0xE0 { // 2-byte UTF-8
		return t.lookupValue(uint32(i), s[1])
	}
	i = idnaIndex[uint32(i)<<6+uint32(s[1])]
	if c0 < 0xF0 { // 3-byte UTF-8
		return t.lookupValue(uint32(i), s[2])
	}
	i = idnaIndex[uint32(i)<<6+uint32(s[2])]
	if c0 < 0xF8 { // 4-byte UTF-8
		return t.lookupValue(uint32(i), s[3])
	}
	return 0
}

// lookupUnsafe returns the trie value for the first UTF-8 encoding in s.
// s must start with a full and valid UTF-8 encoded rune.


func callnrecvmsg(s int, msg uintptr, flags int) (r1 uintptr, e1 Errno) {
	r1 = uintptr(C.nrecvmsg(C.int(s), C.uintptr_t(msg), C.int(flags)))
	e1 = syscall.GetErrno()
	return
}


func Getegid() (egid int) {
	r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0)
	egid = int(r0)
	return
}


func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) {
	var _p0 *byte
	_p0, err = BytePtrFromString(path)
	if err != nil {
		return
	}
	_, _, e1 := Syscall6(SYS_FSTATAT64, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) {
	var _p0 unsafe.Pointer
	if len(buf) > 0 {
		_p0 = unsafe.Pointer(&buf[0])
	} else {
		_p0 = unsafe.Pointer(&_zero)
	}
	_, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen))
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func SetLogger(l Logger) {
	internal.LoggerV2Impl = &internal.LoggerWrapper{Logger: l}
}

// SetLogger sets the logger that is used in grpc. Call only from
// init() functions.
//
// Deprecated: use SetLoggerV2.


func sizeStringPtr(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) {
	v := **p.StringPtr()
	return f.tagsize + protowire.SizeBytes(len(v))
}

// sizeStringPtr returns the size of wire encoding a *string pointer as a String.
// It panics if the pointer is nil.


func newPluginManager(conf *katalystconfig.Configuration) (pluginmanager.PluginManager, error) {
	// make sure plugin registration directory already exist
	err := os.MkdirAll(conf.PluginRegistrationDir, os.FileMode(0o755))
	if err != nil {
		return nil, fmt.Errorf("initializes plugin registration dir failed: %s", err)
	}

	return &customizedPluginManager{
		enabled: *atomic.NewBool(false),
		PluginManager: pluginmanager.NewPluginManager(
			conf.PluginRegistrationDir, /* sockDir */
			&record.FakeRecorder{},
		),
	}, nil
}

// newPluginManager initializes the registration logic for extendable plugins.
// all plugin manager added to generic context must use the same socket and
// default checkpoint path, and if some plugin needs to use a different socket path,
// it should create the plugin manager itself.


func (p *StaticPolicy) ResourceName() string {
	return string(apiconsts.ResourceNetBandwidth)
}

// ResourceName returns resource names managed by this plugin


func (cl *CNRLifecycle) processNextWorkItem() bool {
	key, quit := cl.syncQueue.Get()
	if quit {
		return false
	}
	defer cl.syncQueue.Done(key)

	err := cl.sync(key.(string))
	if err == nil {
		cl.syncQueue.Forget(key)
		return true
	}

	utilruntime.HandleError(fmt.Errorf("sync %q failed with %v", key, err))
	cl.syncQueue.AddRateLimited(key)

	return true
}

// processNextWorkItem dequeues items, processes them, and marks them done.
// It enforces that the sync is never invoked concurrently with the same key.


func filterExpiredPodMetrics(metrics []apimetrics.PodMetrics) []apimetrics.PodMetrics {
	now := time.Now()
	return lo.Filter(metrics, func(item apimetrics.PodMetrics, _ int) bool {
		return now.Before(item.Timestamp.Time)
	})
}

// filterExpiredPodMetrics is used to filter out metrics before the current time from the metric slice.


func (i *Input) WithKeyMap(k *KeyMap) Field {
	i.keymap = k.Input
	i.textinput.KeyMap.AcceptSuggestion = i.keymap.AcceptSuggestion
	return i
}

// WithKeyMap sets the keymap on an input field.


func literal(s string) string {
	return regexp.QuoteMeta(s)
}

// literal compiles s into a literal regular expression, escaping any regexp
// reserved characters.


func (w *Watcher) AddWith(name string, opts ...addOpt) error {
	_ = getOptions(opts...)

	w.mu.Lock()
	w.userWatches[name] = struct{}{}
	w.mu.Unlock()
	_, err := w.addWatch(name, noteAllEvents)
	return err
}

// AddWith is like [Watcher.Add], but allows adding options. When using Add()
// the defaults described below are used.
//
// Possible options are:
//
//   - [WithBufferSize] sets the buffer size for the Windows backend; no-op on
//     other platforms. The default is 64K (65536 bytes).


func (zero *evalZeroArity) OverloadID() string {
	return zero.overload
}

// OverloadID implements the InterpretableCall interface method.


func (m *MilestoneStats) GetTotalMilestones() int {
	if m == nil || m.TotalMilestones == nil {
		return 0
	}
	return *m.TotalMilestones
}

// GetTotalMilestones returns the TotalMilestones field if it's non-nil, zero value otherwise.


// decompress4x_main_loop_x86 is an x86 with BMI2 assembler implementation
// of Decompress1X when tablelog > 8.
//
//go:noescape


func (o *Output) Hyperlink(link, name string) string {
	return OSC + "8;;" + link + ST + name + OSC + "8;;" + ST
}

// Hyperlink creates a hyperlink using OSC8.


func BeTrueBecause(format string, args ...any) types.GomegaMatcher {
	return &matchers.BeTrueMatcher{Reason: fmt.Sprintf(format, args...)}
}

// BeTrueBecause succeeds if actual is true and displays the provided reason if it is false
// fmt.Sprintf is used to render the reason


func UseConcurrentReads(value bool) ClientOption {
	return func(c *Client) error {
		c.disableConcurrentReads = !value
		return nil
	}
}

// UseConcurrentReads allows the Client to perform concurrent Reads.
//
// Concurrent reads are generally safe to use and not using them will degrade
// performance, so this option is enabled by default.
//
// When enabled, WriteTo will use Stat/Fstat to get the file size and determines
// how many concurrent workers to use.
// Some "read once" servers will delete the file if they receive a stat call on an
// open file and then the download will fail.
// Disabling concurrent reads you will be able to download files from these servers.
// If concurrent reads are disabled, the UseFstat option is ignored.


func newValueFunc(desc *Desc, valueType ValueType, function func() float64) *valueFunc {
	result := &valueFunc{
		desc:       desc,
		valType:    valueType,
		function:   function,
		labelPairs: MakeLabelPairs(desc, nil),
	}
	result.init(result)
	return result
}

// newValueFunc returns a newly allocated valueFunc with the given Desc and
// ValueType. The value reported is determined by calling the given function
// from within the Write method. Take into account that metric collection may
// happen concurrently. If that results in concurrent calls to Write, like in
// the case where a valueFunc is directly registered with Prometheus, the
// provided function must be concurrency-safe.


func (linux *systemDRecord) servicePath() string {
	return "/etc/systemd/system/" + linux.name + ".service"
}

// Standard service path for systemD daemons


func WithInt64Callback(callback Int64Callback) Int64ObservableOption {
	return int64CallbackOpt{callback}
}

// WithInt64Callback adds callback to be called for an instrument.


func FaaSName(val string) attribute.KeyValue {
	return FaaSNameKey.String(val)
}

// FaaSName returns an attribute KeyValue conforming to the "faas.name"
// semantic conventions. It represents the name of the single function that
// this runtime instance executes.


func EnduserRole(val string) attribute.KeyValue {
	return EnduserRoleKey.String(val)
}

// EnduserRole returns an attribute KeyValue conforming to the
// "enduser.role" semantic conventions. It represents the actual/assumed role
// the client is making the request under extracted from token or application
// security context.


func Verify(mac *[16]byte, m []byte, key *[32]byte) bool {
	var tmp [16]byte
	Sum(&tmp, m, key)
	return subtle.ConstantTimeCompare(tmp[:], mac[:]) == 1
}

// Verify returns true if mac is a valid authenticator for m with the given key.


func Setdomainname(p []byte) (err error) {
	var _p0 *byte
	if len(p) > 0 {
		_p0 = &p[0]
	}
	_, e1 := callsetdomainname(uintptr(unsafe.Pointer(_p0)), len(p))
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}

// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT


func Dup2(from int, to int) (err error) {
	_, _, e1 := syscall_syscall(libc_dup2_trampoline_addr, uintptr(from), uintptr(to), 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}

//go:cgo_import_dynamic libc_dup dup "libc.so"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT


func Creat(path string, mode uint32) (fd int, err error) {
	var _p0 *byte
	_p0, err = BytePtrFromString(path)
	if err != nil {
		return
	}
	runtime.EnterSyscall()
	r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CREAT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode))
	runtime.ExitSyscall()
	fd = int(r0)
	if int64(r0) == -1 {
		err = errnoErr2(e1, e2)
	}
	return
}


func callsetregid(rgid int, egid int) (r1 uintptr, e1 Errno) {
	r1, _, e1 = rawSyscall6(uintptr(unsafe.Pointer(&libc_setregid)), 2, uintptr(rgid), uintptr(egid), 0, 0, 0, 0)
	return
}


func yaml_emitter_emit_scalar(emitter *yaml_emitter_t, event *yaml_event_t) bool {
	if !yaml_emitter_select_scalar_style(emitter, event) {
		return false
	}
	if !yaml_emitter_process_anchor(emitter) {
		return false
	}
	if !yaml_emitter_process_tag(emitter) {
		return false
	}
	if !yaml_emitter_increase_indent(emitter, true, false) {
		return false
	}
	if !yaml_emitter_process_scalar(emitter) {
		return false
	}
	emitter.indent = emitter.indents[len(emitter.indents)-1]
	emitter.indents = emitter.indents[:len(emitter.indents)-1]
	emitter.state = emitter.states[len(emitter.states)-1]
	emitter.states = emitter.states[:len(emitter.states)-1]
	return true
}


func Convert_apiextensions_CustomResourceDefinitionCondition_To_v1_CustomResourceDefinitionCondition(in *apiextensions.CustomResourceDefinitionCondition, out *CustomResourceDefinitionCondition, s conversion.Scope) error {
	return autoConvert_apiextensions_CustomResourceDefinitionCondition_To_v1_CustomResourceDefinitionCondition(in, out, s)
}

// Convert_apiextensions_CustomResourceDefinitionCondition_To_v1_CustomResourceDefinitionCondition is an autogenerated conversion function.


func NewOptComputeSkipReason(v ComputeSkipReason) OptComputeSkipReason {
	return OptComputeSkipReason{
		Value: v,
		Set:   true,
	}
}

// NewOptComputeSkipReason returns new OptComputeSkipReason with value set to v.


func RecordID(ctx context.Context, id int64) (DomainFeedback, error) {
	e := DomainFeedback{ID: id}
	err := ReportsDB.Get(ctx, &e)
	return e, err
}

// RecordID returns the report for the ID.


func (r *elemRef) count() int {
	if r.node != nil {
		return len(r.node.inodes)
	}
	return int(r.page.count)
}

// count returns the number of inodes or page elements.


func ValidHostHeader(h string) bool {
	// The latest spec is actually this:
	//
	// http://tools.ietf.org/html/rfc7230#section-5.4
	//     Host = uri-host [ ":" port ]
	//
	// Where uri-host is:
	//     http://tools.ietf.org/html/rfc3986#section-3.2.2
	//
	// But we're going to be much more lenient for now and just
	// search for any byte that's not a valid byte in any of those
	// expressions.
	for i := 0; i < len(h); i++ {
		if !validHostByte[h[i]] {
			return false
		}
	}
	return true
}

// ValidHostHeader reports whether h is a valid host header.


func KeyctlGetKeyringID(id int, create bool) (ringid int, err error) {
	createInt := 0
	if create {
		createInt = 1
	}
	return KeyctlInt(KEYCTL_GET_KEYRING_ID, id, createInt, 0, 0)
}

// Keyctl commands with special signatures.
// KeyctlGetKeyringID implements the KEYCTL_GET_KEYRING_ID command.
// See the full documentation at:
// http://man7.org/linux/man-pages/man3/keyctl_get_keyring_ID.3.html


func Kill(pid int, sig Signal) (err error) {
	r0, er := C.kill(C.int(pid), C.int(sig))
	if r0 == -1 && er != nil {
		err = er
	}
	return
}


func read(fd int, p []byte) (n int, err error) {
	var _p0 *byte
	if len(p) > 0 {
		_p0 = &p[0]
	}
	r0, e1 := callread(fd, uintptr(unsafe.Pointer(_p0)), len(p))
	n = int(r0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) {
	_, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) {
	var _p0 *byte
	_p0, err = BytePtrFromString(fsType)
	if err != nil {
		return
	}
	var _p1 *byte
	_p1, err = BytePtrFromString(dir)
	if err != nil {
		return
	}
	_, _, e1 := syscall_syscall6(libc_mount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags), uintptr(data), 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}

//go:cgo_import_dynamic libc_mknodat mknodat "libc.so"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT


func Getrtable() (rtable int, err error) {
	r0, _, e1 := syscall_rawSyscall(libc_getrtable_trampoline_addr, 0, 0, 0)
	rtable = int(r0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}

//go:cgo_import_dynamic libc_getrlimit getrlimit "libc.so"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT


func isTitle(c *context) bool {
	ct := c.caseType()
	if c.info&hasMappingMask == 0 || ct == cTitle {
		return true
	}
	if c.info&exceptionBit == 0 {
		if ct == cLower {
			c.err = transform.ErrEndOfSpan
			return false
		}
		return true
	}
	// Get the exception data.
	e := exceptions[c.info>>exceptionShift:]
	if nTitle := e[1] & lengthMask; nTitle != noChange {
		c.err = transform.ErrEndOfSpan
		return false
	}
	nFirst := (e[1] >> lengthBits) & lengthMask
	if ct == cLower && nFirst != noChange {
		c.err = transform.ErrEndOfSpan
		return false
	}
	return true
}

// isTitle reports whether the current rune is in title case.


func (t *nfcTrie) lookupValue(n uint32, b byte) uint16 {
	switch {
	case n < 46:
		return uint16(nfcValues[n<<6+uint32(b)])
	default:
		n -= 46
		return uint16(nfcSparse.lookup(n, b))
	}
}

// lookupValue determines the type of block n and looks up the value for b.


func brokerMessageToV2Issue49ChatSubscribeMessage(bMsg extensions.BrokerMessage) (V2Issue49ChatSubscribeMessage, error) {
	var msg V2Issue49ChatSubscribeMessage

	// Convert to string
	payload := string(bMsg.Payload)
	msg.Payload = payload // No need for type conversion to reference

	// TODO: run checks on msg type

	return msg, nil
}

// brokerMessageToV2Issue49ChatSubscribeMessage will fill a new V2Issue49ChatSubscribeMessage with data from generic broker message


func (s *State) CodePath() string {
	name := MainGo
	if s.CellIsTest {
		name = MainTestGo
	}
	return path.Join(s.TempDir, name)
}

// CodePath is the path to where the code is going to be saved. Either `main.go` or `main_test.go` file.


func DeclareVariable(decls *Declarations, name, value string) {
	decls.Variables[name] = &Variable{
		Cursor:          NoCursor,
		CellLines:       CellLines{},
		Key:             name,
		Name:            name,
		ValueDefinition: value,
	}
}

// DeclareVariable creates a variable definition in `decls`.
// `value` is copied verbatim, so any type of variable goes.


func (wscb *WorkflowStepCreateBulk) ExecE(ctx context.Context, cbs ...func(ctx context.Context, mc ClientSet, created *WorkflowStep) error) error {
	_, err := wscb.SaveE(ctx, cbs...)
	return err
}

// ExecE calls the given function after executed the query,
// which is always good for cascading create operations.


func (wss *WorkflowStageSelect) Scan(ctx context.Context, v any) error {
	ctx = setContextOp(ctx, wss.ctx, "Select")
	if err := wss.prepareQuery(ctx); err != nil {
		return err
	}
	return scanWithInterceptors[*WorkflowStageQuery, *WorkflowStageSelect](ctx, wss.WorkflowStageQuery, wss, wss.inters, v)
}

// Scan applies the selector query and scans the result into the given value.


func NameLT(v string) predicate.ResourceDefinitionMatchingRule {
	return predicate.ResourceDefinitionMatchingRule(sql.FieldLT(FieldName, v))
}

// NameLT applies the LT predicate on the "name" field.


func ProjectIDIn(vs ...object.ID) predicate.ResourceRun {
	return predicate.ResourceRun(sql.FieldIn(FieldProjectID, vs...))
}

// ProjectIDIn applies the In predicate on the "project_id" field.


func TemplateIDNotIn(vs ...object.ID) predicate.ResourceRun {
	return predicate.ResourceRun(sql.FieldNotIn(FieldTemplateID, vs...))
}

// TemplateIDNotIn applies the NotIn predicate on the "template_id" field.


func CreatedByNEQ(v string) predicate.ResourceRun {
	return predicate.ResourceRun(sql.FieldNEQ(FieldCreatedBy, v))
}

// CreatedByNEQ applies the NEQ predicate on the "created_by" field.


func TypeContainsFold(v string) predicate.WorkflowStep {
	return predicate.WorkflowStep(sql.FieldContainsFold(FieldType, v))
}

// TypeContainsFold applies the ContainsFold predicate on the "type" field.


func (i Values) ValidateWith(schema *openapi3.Schema) error {
	if schema == nil {
		return nil
	}

	// Check required and undefined.
	l := sets.StringKeySet(i)
	r := sets.NewString(schema.Required...)
	a := sets.StringKeySet(schema.Properties)

	if diff := r.Difference(l).UnsortedList(); len(diff) != 0 {
		return fmt.Errorf("not found required values %v", diff)
	}

	if diff := l.Difference(a).UnsortedList(); len(diff) != 0 {
		return fmt.Errorf("found undefiend values %v", diff)
	}

	// Validate.
	for n, v := range i {
		if schema.Properties[n] == nil || schema.Properties[n].Value == nil {
			continue
		}

		var (
			s           = schema.Properties[n].Value
			errTypeFunc = func(name string, ok bool, err error, expectedType string, actualValue any) error {
				if !ok {
					return fmt.Errorf("%s is not type %s, actual value: %v", name, expectedType, actualValue)
				}

				if err != nil {
					return fmt.Errorf("failed to convert %s to %s: %w", name, expectedType, err)
				}
				return nil
			}
			validateSchemaFunc = func(name string, val any) error {
				err := s.VisitJSON(val)
				if err != nil {
					var e *openapi3.SchemaError
					if errors.As(err, &e) {
						return errorx.Errorf("invalid %s: %v", name, e.Reason)
					}
					return err
				}
				return nil
			}
		)

		var (
			val any
			ok  bool
			err error
		)

		switch {
		default:
			_, ok, err := GetAny[any](v)
			if !ok || err != nil {
				return errTypeFunc(n, ok, err, s.Type, v)
			}

			continue
		case s.Type == openapi3.TypeString:
			val, ok, err = GetString(v)
			if !ok || err != nil {
				return errTypeFunc(n, ok, err, s.Type, v)
			}
		case s.Type == openapi3.TypeBoolean:
			val, ok, err = GetBool(v)
			if !ok || err != nil {
				return errTypeFunc(n, ok, err, s.Type, v)
			}
		case s.Type == openapi3.TypeInteger:
			val, ok, err = GetInt(v)
			if !ok || err != nil {
				return errTypeFunc(n, ok, err, s.Type, v)
			}
		case s.Type == openapi3.TypeNumber:
			val, ok, err = GetNumber(v)
			if !ok || err != nil {
				return errTypeFunc(n, ok, err, s.Type, v)
			}
		case HasAnyTypes(s):
			// Skip validate for any type.
			continue
		case s.Type == openapi3.TypeArray:
			val, ok, err = GetSlice[any](v)
			if !ok || err != nil {
				return errTypeFunc(n, ok, err, s.Type, v)
			}
		case s.Type == openapi3.TypeObject:
			val, ok, err = GetMap[any](v)
			if !ok || err != nil {
				return errTypeFunc(n, ok, err, s.Type, v)
			}
		}

		err = validateSchemaFunc(n, val)
		if err != nil {
			return err
		}
	}

	return nil
}

// ValidateWith validates the property value with the given schemas.


func NewBinaryLiteralFromUint(value uint64, byteSize int) BinaryLiteral {
	if byteSize != -1 && (byteSize < 1 || byteSize > 8) {
		panic("Invalid byteSize")
	}
	buf := make([]byte, 8)
	binary.BigEndian.PutUint64(buf, value)
	if byteSize == -1 {
		buf = trimLeadingZeroBytes(buf)
	} else {
		buf = buf[8-byteSize:]
	}
	return buf
}

// NewBinaryLiteralFromUint creates a new BinaryLiteral instance by the given uint value in BitEndian.
// byteSize will be used as the length of the new BinaryLiteral, with leading bytes filled to zero.
// If byteSize is -1, the leading zeros in new BinaryLiteral will be trimmed.


func ParseDatetimeFromNum(sc *stmtctx.StatementContext, num int64) (Time, error) {
	return ParseTimeFromNum(sc, num, mysql.TypeDatetime, DefaultFsp)
}

// ParseDatetimeFromNum is a helper function wrapping ParseTimeFromNum with datetime type and default fsp.


func MatchesPodSpec(rules []types.ResourceRule) bool {
	for _, r := range rules {
		gr := r.ToGVR().GroupResource()
		if defaultPodSpecResources[gr] {
			return true
		}
	}
	return false
}

// MatchesPodSpec returns true if any rule matches a Pod spec


func WithVectorDimensions(size int) Option {
	return func(p *Store) {
		p.vectorDimensions = size
	}
}

// WithVectorDimensions is an option for specifying the vector size.


func MappedBits[T comparable](values []T, maps map[T]Bits, opts ...BuilderOpt[T]) Bits {
	bo := builderOpts[T]{}
	for _, opt := range opts {
		opt(&bo)
	}

	b := Bits(0)
	for _, value := range values {
		for _, t := range bo.transform {
			value = t(value)
		}
		if val, ok := maps[value]; ok {
			b |= val
		}
	}
	return b
}

// MappedBits builds a Bits map from a set of values (e.g. strings) that are mapped in the form
// value --> corresponding Bits value
// in the "maps" constructor argument


func MarshalText(w io.Writer, m Message) error { return defaultTextMarshaler.Marshal(w, m) }

// MarshalText writes the proto text format of m to w.


func xorInGeneric(d *state, buf []byte) {
	n := len(buf) / 8

	for i := 0; i < n; i++ {
		a := binary.LittleEndian.Uint64(buf)
		d.a[i] ^= a
		buf = buf[8:]
	}
}

// xorInGeneric xors the bytes in buf into the state; it
// makes no non-portable assumptions about memory layout
// or alignment.


func Symlink(path string, link string) (err error) {
	var _p0 *byte
	_p0, err = BytePtrFromString(path)
	if err != nil {
		return
	}
	var _p1 *byte
	_p1, err = BytePtrFromString(link)
	if err != nil {
		return
	}
	_, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}

// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT


func Time(t *Time_t) (tt Time_t, err error) {
	r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0)
	tt = Time_t(r0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func socket(domain int, typ int, proto int) (fd int, err error) {
	r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto))
	fd = int(r0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func munmap(addr uintptr, length uintptr) (err error) {
	_, _, e1 := syscall_syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) {
	var _p0 *byte
	_p0, err = BytePtrFromString(oldpath)
	if err != nil {
		return
	}
	var _p1 *byte
	_p1, err = BytePtrFromString(newpath)
	if err != nil {
		return
	}
	_, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) TransportCredentials {
	return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp})
}

// NewClientTLSFromCert constructs TLS credentials from the provided root
// certificate authority certificate(s) to validate server connections. If
// certificates to establish the identity of the client need to be included in
// the credentials (eg: for mTLS), use NewTLS instead, where a complete
// tls.Config can be specified.
// serverNameOverride is for testing only. If set to a non empty string,
// it will override the virtual host name of authority (e.g. :authority header
// field) in requests.


func Close(fd int) (err error) {
	_, _, e1 := syscall_syscall(libc_close_trampoline_addr, uintptr(fd), 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}

//go:cgo_import_dynamic libc_clock_gettime clock_gettime "libc.so"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT


func (l *HandlerList) Swap(name string, replace NamedHandler) bool {
	var swapped bool

	for i := 0; i < len(l.list); i++ {
		if l.list[i].Name == name {
			l.list[i] = replace
			swapped = true
		}
	}

	return swapped
}

// Swap will swap out all handlers matching the name passed in. The matched
// handlers will be swapped in. True is returned if the handlers were swapped.


func mapassign_faststr(t *rt.GoType, h unsafe.Pointer, s string) unsafe.Pointer

//go:linkname mapassign_faststr runtime.mapassign_faststr
//goland:noinspection GoUnusedParameter


func (r Response) AddHeader(header string, value string) Response {
	r.Header().Add(header, value)
	return r
}

// AddHeader is a shortcut for .Header().Add(header,value)


func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes {
	for _, method := range anyMethods {
		group.handle(method, relativePath, handlers)
	}

	return group.returnObj()
}

// Any registers a route that matches all the HTTP methods.
// GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.


func Float64Value(v *float64) float64 {
	if v != nil {
		return *v
	}
	return 0
}

// Float64Value returns the value of the float64 pointer passed in or
// 0 if the pointer is nil.


func isTIGER128(fl FieldLevel) bool {
	return tiger128Regex.MatchString(fl.Field().String())
}

// isTIGER128 is the validation function for validating if the field's value is a valid TIGER128.


func appendMerge(target, sub []int) []int {
	lt, ls := len(target), len(sub)
	out := make([]int, 0, lt+ls)

	for x, y := 0, 0; x < lt || y < ls; {
		if x >= lt {
			out = append(out, sub[y:]...)
			break
		}

		if y >= ls {
			out = append(out, target[x:]...)
			break
		}

		xValue := target[x]
		yValue := sub[y]

		switch {

		case xValue == yValue:
			out = append(out, xValue)
			x++
			y++

		case xValue < yValue:
			out = append(out, xValue)
			x++

		case yValue < xValue:
			out = append(out, yValue)
			y++

		}
	}

	target = append(target[:0], out...)

	return target
}

// appendMerge merges and sorts given already SORTED and UNIQUE segments.


func cleanupSurroundingIdentical(groups []diffStats, eq func(i, j int) bool) []diffStats {
	var ix, iy int // indexes into sequence x and y
	for i, ds := range groups {
		// Handle equal group.
		if ds.NumDiff() == 0 {
			ix += ds.NumIdentical
			iy += ds.NumIdentical
			continue
		}

		// Handle unequal group.
		nx := ds.NumIdentical + ds.NumRemoved + ds.NumModified
		ny := ds.NumIdentical + ds.NumInserted + ds.NumModified
		var numLeadingIdentical, numTrailingIdentical int
		for j := 0; j < nx && j < ny && eq(ix+j, iy+j); j++ {
			numLeadingIdentical++
		}
		for j := 0; j < nx && j < ny && eq(ix+nx-1-j, iy+ny-1-j); j++ {
			numTrailingIdentical++
		}
		if numIdentical := numLeadingIdentical + numTrailingIdentical; numIdentical > 0 {
			if numLeadingIdentical > 0 {
				// Remove leading identical span from this group and
				// insert it into the preceding group.
				if i-1 >= 0 {
					groups[i-1].NumIdentical += numLeadingIdentical
				} else {
					// No preceding group exists, so prepend a new group,
					// but do so after we finish iterating over all groups.
					defer func() {
						groups = append([]diffStats{{Name: groups[0].Name, NumIdentical: numLeadingIdentical}}, groups...)
					}()
				}
				// Increment indexes since the preceding group would have handled this.
				ix += numLeadingIdentical
				iy += numLeadingIdentical
			}
			if numTrailingIdentical > 0 {
				// Remove trailing identical span from this group and
				// insert it into the succeeding group.
				if i+1 < len(groups) {
					groups[i+1].NumIdentical += numTrailingIdentical
				} else {
					// No succeeding group exists, so append a new group,
					// but do so after we finish iterating over all groups.
					defer func() {
						groups = append(groups, diffStats{Name: groups[len(groups)-1].Name, NumIdentical: numTrailingIdentical})
					}()
				}
				// Do not increment indexes since the succeeding group will handle this.
			}

			// Update this group since some identical elements were removed.
			nx -= numIdentical
			ny -= numIdentical
			groups[i] = diffStats{Name: ds.Name, NumRemoved: nx, NumInserted: ny}
		}
		ix += nx
		iy += ny
	}
	return groups
}

// cleanupSurroundingIdentical scans through all unequal groups, and
// moves any leading sequence of equal elements to the preceding equal group and
// moves and trailing sequence of equal elements to the succeeding equal group.
//
// This is necessary since coalesceInterveningIdentical may coalesce edit groups
// together such that leading/trailing spans of equal elements becomes possible.
// Note that this can occur even with an optimal diffing algorithm.
//
// Example:
//
//	Input: [
//		{NumIdentical: 61},
//		{NumIdentical: 1 , NumRemoved: 11, NumInserted: 2}, // assume 3 leading identical elements
//		{NumIdentical: 67},
//		{NumIdentical: 7, NumRemoved: 12, NumInserted: 3},  // assume 10 trailing identical elements
//		{NumIdentical: 54},
//	]
//	Output: [
//		{NumIdentical: 64}, // incremented by 3
//		{NumRemoved: 9},
//		{NumIdentical: 67},
//		{NumRemoved: 9},
//		{NumIdentical: 64}, // incremented by 10
//	]


func Setns(ns NsHandle, nstype int) (err error) {
	return ErrNotImplemented
}

// Setns sets namespace using golang.org/x/sys/unix.Setns on Linux. It
// is not implemented on other platforms.
//
// Deprecated: Use golang.org/x/sys/unix.Setns instead.


func MessagingServicebusMessageEnqueuedTime(val int) attribute.KeyValue {
	return MessagingServicebusMessageEnqueuedTimeKey.Int(val)
}

// MessagingServicebusMessageEnqueuedTime returns an attribute KeyValue
// conforming to the "messaging.servicebus.message.enqueued_time" semantic
// conventions. It represents the UTC epoch seconds at which the message has
// been accepted and stored in the entity.


func (t TraceID) IsValid() bool {
	return !bytes.Equal(t[:], nilTraceID[:])
}

// IsValid checks whether the trace TraceID is valid. A valid trace ID does
// not consist of zeros only.


func LowercaseLevelEncoder(l Level, enc PrimitiveArrayEncoder) {
	enc.AppendString(l.String())
}

// LowercaseLevelEncoder serializes a Level to a lowercase string. For example,
// InfoLevel is serialized to "info".


func ToUnicode(s string) (string, error) {
	return Punycode.process(s, false)
}

// ToUnicode is a wrapper for Punycode.ToUnicode.


func Setegid(egid int) (err error) {
	_, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
	r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence))
	newoffset = int64(r0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) {
	var _p0 unsafe.Pointer
	if len(buf) > 0 {
		_p0 = unsafe.Pointer(&buf[0])
	} else {
		_p0 = unsafe.Pointer(&_zero)
	}
	_, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen))
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func ForceCodec(codec encoding.Codec) CallOption {
	return ForceCodecCallOption{Codec: codec}
}

// ForceCodec returns a CallOption that will set codec to be used for all
// request and response messages for a call. The result of calling Name() will
// be used as the content-subtype after converting to lowercase, unless
// CallContentSubtype is also used.
//
// See Content-Type on
// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
// more details. Also see the documentation on RegisterCodec and
// CallContentSubtype for more details on the interaction between Codec and
// content-subtype.
//
// This function is provided for advanced users; prefer to use only
// CallContentSubtype to select a registered codec instead.
//
// # Experimental
//
// Notice: This API is EXPERIMENTAL and may be changed or removed in a
// later release.


func (v Value) IsValid() bool {
	return v.typ != nilType
}

// IsValid reports whether v is populated with a value.