text):
    """Property: is_re_compilable should not crash on any string"""
    result = types.is_re_compilable(text)
    assert isinstance(result, bool)

    if result:
        import re
        try:
            re.compile(text)
        except:
            assert False, f"is_re_compilable returned True but pattern '{text}' cannot be compiled"
```

**Failing input**: `'['`

## Reproducing the Bug

```python
import pandas.api.types as types

invalid_patterns = ['[', '(', '*', '(?P<', '\\']

for pattern in invalid_patterns:
    try:
        result = types.is_re_compilable(pattern)
        print(f"is_re_compilable('{pattern}') = {result}")
    except Exception as e:
        print(f"is_re_compilable('{pattern}') raised {type(e).__name__}: {e}")
```

## Why This Is A Bug

The function is documented to return a boolean indicating whether the object can be compiled as a regex pattern. When given an invalid regex pattern, it should return `False` rather than raising an exception. The current implementation only catches `TypeError` but not `re.error` (which includes `re.PatternError`).

## Fix

```diff
--- a/pandas/core/dtypes/inference.py
+++ b/pandas/core/dtypes/inference.py
@@ -186,7 +186,7 @@ def is_re_compilable(obj) -> bool:
     """
     try:
         re.compile(obj)
-    except TypeError:
+    except (TypeError, re.error):
         return False
     else:
         return True
```# Bug Report: optax.linear_onecycle_schedule Division by Zero with Small Steps

**Target**: `optax.linear_onecycle_schedule`
**Severity**: High
**Bug Type**: Crash
**Date**: 2025-08-18

## Summary

`linear_onecycle_schedule` returns NaN for all step counts when `transition_steps=1` due to division by zero in the underlying `piecewise_interpolate_schedule` function.

## Property-Based Test

```python
@given(
    transition_steps=st.integers(min_value=1, max_value=100),
    peak_value=st.floats(min_value=0.01, max_value=10.0, allow_nan=False, allow_infinity=False),
    pct_start=st.floats(min_value=0.01, max_value=0.49, allow_nan=False, allow_infinity=False),
    pct_final=st.floats(min_value=0.51, max_value=0.99, allow_nan=False, allow_infinity=False)
)
def test_linear_onecycle_phase_ordering(transition_steps, peak_value, pct_start, pct_final):
    assume(pct_start < pct_final)

    schedule = optax.linear_onecycle_schedule(
        transition_steps=transition_steps,
        peak_value=peak_value,
        pct_start=pct_start,
        pct_final=pct_final
    )

    peak_step = int(pct_start * transition_steps)
    result_at_peak = float(schedule(peak_step))
    assert abs(result_at_peak - peak_value) <= peak_value * 0.1
```

**Failing input**: `transition_steps=1, peak_value=1.0, pct_start=0.25, pct_final=0.75`

## Reproducing the Bug

```python
import optax
import numpy as np

schedule = optax.linear_onecycle_schedule(
    transition_steps=1,
    peak_value=1.0,
    pct_start=0.25,
    pct_final=0.75
)

result = schedule(0)
print(f"Result: {result}")
assert not np.isnan(result), "Result is NaN!"
```

## Why This Is A Bug

The function should han


e,
        dataset_info={{_base_.dataset_info}}),
    val=dict(
        type='TopDownOCHumanDataset',
        ann_file=f'{data_root}/annotations/'
        'ochuman_coco_format_val_range_0.00_1.00.json',
        img_prefix=f'{data_root}/images/',
        data_cfg=data_cfg,
        pipeline=val_pipeline,
        dataset_info={{_base_.dataset_info}}),
    test=dict(
        type='TopDownOCHumanDataset',
        ann_file=f'{data_root}/annotations/'
        'ochuman_coco_format_test_range_0.00_1.00.json',
        img_prefix=f'{data_root}/images/',
        data_cfg=data_cfg,
        pipeline=val_pipeline,
        dataset_info={{_base_.dataset_info}}),
)


href="home.php?mod=spacecp&ac=eccredit&op=list&uid=$uid&from=buyer&filter=before#" onclick="ajaxget(this.href, 'ajaxrate', 'specialposts');doane(event);">$caches[sellercredit][before][total]
					$caches[sellercredit][all][total]

{lang eccredit_sellerinfo} $member[buyercredit]

					{lang eccredit_1week}
					{lang eccredit_1month}
					{lang eccredit_6month}
					{lang eccredit_6monthbefore}
					{lang eccredit_total}

					 {lang eccredit_good}	$caches[buyercredit][thisweek][good]
					$caches[buyercredit][thismonth][good]
					$caches[buyercredit][halfyear][good]
					$caches[buyercredit][before][good]
					$caches[buyercredit][all][good]

					 {lang eccredit_soso}
					$caches[buyercredit][thisweek][soso]
					$caches[buyercredit][thismonth][soso]


			["text"] = "60",
			},
			{
				["type"] = "Label",
				["text"] = "下行输入血量低于百分多少回城，填0不回城",
				["size"] = 12,
				["align"] = "left",
				["color"] = "0,0,255",
			},
			{
				["type"] = "Edit",
				["prompt"] = "回城血量",
				["text"] = "40",
			},
			isArray = true
		}
	}
	local MyJsonString = json.encode(MyTable);
	return showUI(MyJsonString);
end
function isColor(x,y,c,s)
	local fl,abs = math.floor,math.abs
	s = fl(0xff*(100-s)*0.01)
	local r,g,b = fl(c/0x10000),fl(c%0x10000/0x100),fl(c%0x100)
	local rr,gg,bb = getColorRGB(x,y)
	if abs(r-rr)<s and abs(g-gg)<s and abs(b-bb)<s then
		return true
	end
end
function touch(x,y)
	touchDown(1,x,y);mSleep(50);touchUp(1,x,y);mSleep(50)
end
function touchm(x,y,x1,y1)
	touchDown(1,x,y);mSleep(50);touchMove(1, x1, y1);mSleep(500);touchUp(1,x1, y1);mSleep(50)
end
function baojing()
	vibrator();

end
function pdshebei()
	width, height = getScreenSize();
	if width == 320 and height == 480 then
		shebei=1
	elseif width == 640 and height == 960 then
		shebei=2
		ir=0
		im=0
		iq=0
		yq=0
	elseif width == 640 and height == 1136 then
		shebei=3
		ir=176
		im=88
		iq=104
		yq=-1
	elseif width == 750  and height == 1334 then
		shebei=4
		ir=176
		im=88
		iq=104
		yq=-1
	elseif width == 1242 and height == 2208 then
		shebei=5
	elseif width == 768 and height == 1024 then
		shebei=6
	elseif width == 1536 and height == 2048 then
		shebei=7
	end
	if shebei~=2 and shebei~=3 then
		dialog("该脚本可能无法在您的设备上使用，目前脚本只支持iPhone5/5C/5S/4/4S，其他设备脚本制作中。。。敬请期待", 300)
	end
end
function pdfanzhuan()
	mSleep(1000)
	if isColor(470+im,23,0x5282ff,85) and isColor(485+im,22,0xb50808,85) and isColor(487+im,24,0xd63018,85) and isColor(469+im,24,0x4a79ff,85) then
		dialog("请翻转屏幕180度\n保持home键在右边\n准备好后按确认", 999)
	end
end
function xunhuan(c,t,s)
	if os.time()-t>c*2 then
		baojing()
		dialog("程序出错，错误代码:"..s,99999)


/css/i/arr-up.png) no-repeat}body#consignee_body{height:360px;*height:380px}#consignee-form{position:relative;height:360px}#consignee-form .jdint-tips{position:absolute;width:155px;height:350px;top:0;left:255px}#consignee-form .jdint-tips .tips-bg{position:absolute;z-index:1;top:15px;left:55px;width:290px;height:140px;background:#be4746;-webkit-border-radius:10px;-moz-border-radius:10px;border-radius:10px;opacity:.8;filter:alpha(opacity=80)}#consignee-form .jdint-tips .tips-cont{position:relative;z-index:2;width:240px;margin:40px 0 0 95px;color:#fff;line-height:18px}#consignee-form .jdint-tips .btn{display:inline-block;*display:inline;*zoom:1;height:25px;line-height:25px;padding:0 16px;background:#ffefe0;color:#333;vertical-align:middle}#consignee-form .jdint-tips .joy-icon{display:block;position:absolute;z-index:2;left:0;top:0;width:110px;height:100px;background:url(//misc.360buyimg.com/user/purchase/2.0.0/css/i/joy-icon-jdint.png) no-repeat;overflow:hidden}#consignee-form .error-msg{display:none}#consignee-form .message{display:inline-block}#consignee-form #consignee_province{width:80px}#consignee-form #consignee_city{width:110px}#consignee-form #consignee_county,#consignee-form #consignee_town{width:120px}#consignee-form .consignee-tag-info{color:#999;margin-left:10px}#consignee-form .consignee-tag span{border:1px solid #ccc;border-radius:1px;padding:2px 10px;margin:0 2px;cursor:pointer}#consignee-form .consignee-tag span:hover{color:#e4393c;border:1px solid #e4393c}#consignee-form .ui-area-tab em{color:#005aa0}#consignee-form .has-scrollbar .ui-area-content-wrap .ui-area-tab{float:none!important}#consignee-form .has-scrollbar .ui-switchable-panel{height:225px;overflow:auto}#consignee-form .has-scrollbar .ui-area-content-list{overflow:hidden}#consignee-form #jd_area .ui-area-content-list li{padding:0 0 0 15px}#consignee-form #jd_area .ui-area-content-list li a{padding:0 4px}#consignee-form #jd_area .ui-area-content-wrap{width:420px;left:-45px}#consignee-form #jd_area .ui-area-content-wrap .ui-area-content-list .long-area{width:175px}#consignee-form #jd_area .ui-area-wrap .ui-area-hover{z-index:11}.tab-nav{margin-bottom:15px}.tab-nav ul{display:inline-block;display:block}.tab-nav ul:after{content:".";display:block;height:0;clear:both;visibility:hidden}* html .tab-nav ul{height:1%}*+html .tab-nav ul{min-height:1%}.tab-nav .tab-nav-item{float:left;position:relative;margin-right:10px;border:1px solid #ebebeb;padding:6px 24px;cursor:pointer}.tab-nav .tab-nav-item.disabled{background:#ebebeb;border-color:#ebebeb;color:#ccc;cursor


=atomic",
	}
}

func (VirtualMachineExportLinks) SwaggerDoc() map[string]string {
	return map[string]string{
		"":         "VirtualMachineExportLinks contains the links that point the exported VM resources",
		"internal": "+optional",
		"external": "+optional",
	}
}

func (VirtualMachineExportLink) SwaggerDoc() map[string]string {
	return map[string]string{
		"":          "VirtualMachineExportLink contains a list of volumes available for export, as well as the URLs to obtain these volumes",
		"cert":      "Cert is the public CA certificate base64 encoded",
		"volumes":   "Volumes is a list of available volumes to export\n+listType=map\n+listMapKey=name\n+optional",
		"manifests": "Manifests is a list of available manifests for the export\n+listType=map\n+listMapKey=type\n+optional",
	}
}

func (VirtualMachineExportManifest) SwaggerDoc() map[string]string {
	return map[string]string{
		"":     "VirtualMachineExportManifest contains the type and URL of the exported manifest",
		"type": "Type is the type of manifest returned",
		"url":  "Url is the url of the endpoint that returns the manifest",
	}
}

func (VirtualMachineExportVolume) SwaggerDoc() map[string]string {
	return map[string]string{
		"":        "VirtualMachineExportVolume contains the name and available formats for the exported volume",
		"name":    "Name is the name of the exported volume",
		"formats": "+listType=map\n+listMapKey=format\n+optional",
	}
}

func (VirtualMachineExportVolumeFormat) SwaggerDoc() map[string]string {
	return map[string]string{
		"":       "VirtualMachineExportVolumeFormat contains the format type and URL to get the volume in that format",
		"format": "Format is the format of the image at the specified URL",
		"url":    "Url is the url that contains the volume in the format specified",
	}
}

func (Condition) SwaggerDoc() map[string]string {
	return map[string]string{
		"":                   "Condition defines conditions",
		"lastProbeTime":      "+optional\n+nullable",
		"lastTransitionTime": "+optional\n+nullable",
		"reason":             "+optional",
		"message":            "+optional",
	}
}
/*
 * This file is part of the KubeVirt project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Copyright 2020 Red Hat, Inc.
 *
 */

package v1beta1

import (
	"time"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"

	v1 "kubevirt.io/api/core/v1"
)

const DefaultFailureDeadline = 5 * time.Minute
const DefaultGracePeriod = 5 * time.Minute

// VirtualMachineSnapshot defines the operation of snapshotting a VM
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
type VirtualMachineSnapshot struct {
	metav1.TypeMeta   `json:",inline"`
	metav1.ObjectMeta `json:"metadata,omitempty"`

	Spec VirtualMachineSnapshotSpec `json:"spec"`

	// +optional
	Status *VirtualMachineSnapshotStatus `json:"status,omitempty"`
}

// DeletionPolicy defines that to do with VirtualMachineSnapshot
// when VirtualMachineSnapshot is deleted


 the intercept.
  ///
  /// [initialCoefficients] Coefficients to be used during the first iteration of
  /// optimization algorithm. [initialCoefficients] should have length that is
  /// equal to the number of features in the [trainData].
  ///
  /// [collectLearningData] Whether or not to collect learning data, for
  /// instance cost function value per each iteration. Affects performance much.
  /// If [collectLearningData] is true, one may access [costPerIteration]
  /// getter in order to evaluate learning process more thoroughly.
  ///
  /// [dtype] A data type for all the numeric values, used by the algorithm. Can
  /// affect performance or accuracy of the computations. Default value is
  /// [DType.float32].
  factory LinearRegressor.newton(
    DataFrame trainData,
    String targetName, {
    double lambda = lambdaDefaultValue,
    bool fitIntercept = fitInterceptDefaultValue,
    double interceptScale = interceptScaleDefaultValue,
    bool collectLearningData = collectLearningDataDefaultValue,
    DType dtype = dTypeDefaultValue,
    Matrix? initialCoefficients,
  }) =>
      initLinearRegressorModule().get<LinearRegressorFactory>().create(
            fittingData: trainData,
            targetName: targetName,
            optimizerType: LinearOptimizerType.newton,
            iterationsLimit: 1,
            learningRateType: learningRateTypeDefaultValue,
            initialCoefficientsType: InitialCoefficientsType.zeroes,
            initialLearningRate: initialLearningRateDefaultValue,
            decay: decayDefaultValue,
            dropRate: dropRateDefaultValue,
            minCoefficientsUpdate: minCoefficientsUpdateDefaultValue,
            lambda: lambda,
            regularizationType: RegularizationType.L2,
            fitIntercept: fitIntercept,
            interceptScale: interceptScale,
            randomSeed: 1,
            batchSize: 1,
            initialCoefficients: initialCoefficients,
            isFittingDataNormalized: false,
            collectLearningData: collectLearningData,
            dtype: dtype,
          );

  /// Restores previously fitted [LinearRegressor] instance from the [json]
  ///
  ///
  /// ````dart
  /// import 'dart:io';
  /// import 'package:ml_dataframe/ml_dataframe.dart';
  ///
  /// final data = <Iterable>[
  ///   ['feature 1', 'feature 2', 'feature 3', 'outcome']
  ///   [        5.0,         7.0,         6.0,      98.0],
  ///   [        1.0,         2.0,         3.0,      10.0],
  ///   [       10.0,        12.0,        31.0,    -977.0],
  ///   [        9.0,         8.0,         5.0,       0.0],
  ///   [        4.0,         0.0,         1.0,       6.0],
  /// ];
  /// final targetName = 'outcome';
  /// final samples = DataFrame(data, headerExists: true);
  /// final regressor = LinearRegressor(
  ///   samples,
  ///   targetName,
  ///   iterationsLimit: 2,
  ///   learningRateType: LearningRateType.constant,
  ///   initialLearningRate: 1.0,
  ///   batchSize: 5,
  ///   fitIntercept: true,
  ///   interceptScale: 3.0,
  /// );
  ///
  /// final pathToFile = './classifier.json';
  ///
  /// await regressor.saveAsJson(pathToFile);
  ///
  /// final file = File(pathToFile);
  /// final json = await file.readAsString();
  /// final restoredRegressor = LinearRegressor.fromJson(json);
  ///
  /// // here you can use previously fitted restored regressor to make
  /// // some prediction, e.g. via `restoredRegressor.predict(...)`;
  /// ````
  factory LinearRegressor.fromJson(String json) =>
      initLinearRegressorModule().get<LinearRegressorFactory>().fromJson(json);

  /// Optimization algorithm that was used to learn the model's coefficients
  LinearOptimizerType get optimizerType;

  /// A maximum number o


tructions to remain empty")
		}
		if response.NextSteps != nil {
			t.Errorf("Expected nil next steps to remain nil")
		}
	})

	t.Run("Special characters in error messages", func(t *testing.T) {
		specialErr := errors.New("Error with 'quotes' and \"double quotes\" and \n newlines")
		response := NewResponseBuilder().
			WithError(specialErr, "special_error").
			Build()

		if response.Error != specialErr.Error() {
			t.Errorf("Expected error to preserve special characters")
		}
	})

	t.Run("Very long output strings", func(t *testing.T) {
		longOutput := ""
		for i := 0; i < 1000; i++ {
			longOutput += fmt.Sprintf("Line %d: This is a very long output string that tests the builder's handling of large data. ", i)
		}

		response := types.CommandResponse{
			Success: true,
			Output:  longOutput,
		}

		if response.Output != longOutput {
			t.Errorf("Expected long output to be preserved completely")
		}
	})
}

// Helper function
func containsSubstring(s, substr string) bool {
	return len(substr) > 0 && len(s) >= len(substr) && (s == substr ||
		(len(s) > len(substr) && (s[:len(substr)] == substr ||
			s[len(s)-len(substr):] == substr ||
			findSubstring(s, substr) != -1)))
}

func findSubstring(s, substr string) int {
	for i := 0; i <= len(s)-len(substr); i++ {
		if s[i:i+len(substr)] == substr {
			return i
		}
	}
	return -1
}
// Package fastly provides binary security validation to ensure the Fastly CLI
// executable hasn't been compromised or replaced with a malicious version.
package fastly

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
)

// BinarySecurityError represents a security validation failure for the Fastly CLI binary.
// It provides detailed information about what security check failed and why.
type BinarySecurityError struct {
	Path    string
	Issue   string
	Details string
}

func (e *BinarySecurityError) Error() string {
	return fmt.Sprintf("SYSTEM ERROR: Binary security check failed for %s: %s - %s. This is a critical security issue that prevents execution of the fastly command.", e.Path, e.Issue, e.Details)
}

// ValidateBinarySecurity performs comprehensive security checks on the fastly binary
// to ensure it hasn't been compromised. This includes:
//   - Verifying the binary exists and is executable
//   - Checking for world-writable permissions (Unix)
//   - Ensuring the binary's directory is not world-writable
//   - Validating the binary is not a symlink to an untrusted location
func ValidateBinarySecurity() error {
	var binaryPath string
	var err error

	// Check if FASTLY_CLI_PATH is set
	if customPath := os.Getenv("FASTLY_CLI_PATH"); customPath != "" {
		binaryPath = customPath
		// Verify the custom path exists
		if _, err := os.Stat(binaryPath); err != nil {
			return fmt.Errorf("SYSTEM ERROR: FASTLY_CLI_PATH binary not found at %s: %w", binaryPath, err)
		}
	} else {
		// Find the fastly binary in PATH
		binaryPath, err = exec.LookPath("fastly")
		if err != nil {
			currentPath := os.Getenv("PATH")
			return fmt.Errorf("SYSTEM ERROR: Fastly CLI binary not found in PATH (%s): %w", currentPath, err)
		}
	}

	// Resolve any symlinks to get the real path
	realPath, err := filepath.EvalSymlinks(binaryPath)
	if err != nil {
		return fmt.Errorf("failed to resolve binary path: %w", err)
	}


}
package protobufs

import (
	"bytes"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestHypergraphConfiguration_Serialization(t *testing.T) {
	tests := []struct {
		name   string
		config *HypergraphConfiguration
	}{
		{
			name: "complete configuration",
			config: &HypergraphConfiguration{
				ReadPublicKey:  make([]byte, 57), // Ed448 key
				WritePublicKey: make([]byte, 57), // Ed448 key
			},
		},
		{
			name: "empty keys",
			config: &HypergraphConfiguration{
				ReadPublicKey:  []byte{},
				WritePublicKey: []byte{},
			},
		},
		{
			name: "different keys",
			config: &HypergraphConfiguration{
				ReadPublicKey:  append([]byte{0x01}, make([]byte, 56)...),
				WritePublicKey: append([]byte{0x02}, make([]byte, 56)...),
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// Test serialization
			data, err := tt.config.ToCanonicalBytes()
			require.NoError(t, err)
			require.NotNil(t, data)

			// Test deserialization
			config2 := &HypergraphConfiguration{}
			err = config2.FromCanonicalBytes(data)
			require.NoError(t, err)

			// Compare
			assert.Equal(t, tt.config.ReadPublicKey, config2.ReadPublicKey)
			assert.Equal(t, tt.config.WritePublicKey, config2.WritePublicKey)
		})
	}
}

func TestHypergraphDeploy_Serialization(t *testing.T) {
	tests := []struct {
		name   string
		deploy *HypergraphDeploy
	}{
		{
			name: "complete deploy",
			deploy: &HypergraphDeploy{
				Config: &HypergraphConfiguration{
					ReadPublicKey:  make([]byte, 57),
					WritePublicKey: make([]byte, 57),
				},
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// Test serialization
			data, err := tt.deploy.ToCanonicalBytes()
			require.NoError(t, err)
			require.NotNil(t, data)

			// Test deserialization
			deploy2 := &HypergraphDeploy{}
			err = deploy2.FromCanonicalBytes(data)
			require.NoError(t, err)

			// Compare
			require.NotNil(t, deploy2.Config)
			assert.Equal(t, tt.deploy.Config.ReadPublicKey, deploy2.Config.ReadPublicKey)
			assert.Equal(t, tt.deploy.Config.WritePublicKey, deploy2.Config.WritePublicKey)
		})
	}
}

func TestVertexAdd_Serialization(t *testing.T) {
	tests := []struct {
		name   string
		vertex *VertexAdd
	}{
		{
			name: "complete vertex",
			vertex: &VertexAdd{
				Domain:      make([]byte, 32),
				DataAddress: make([]byte, 32),
				Data:        []byte("test vector commitment tree data"),
				Signature:   make([]byte, 114), // Ed448 signature
			},
		},
		{
			name: "minimal vertex",
			vertex: &VertexAdd{
				Domain:      make([]byte, 32),
				DataAddress: make([]byte, 32),
				Data:        []byte{0x01},
				Signature:   []byte{},
			},
		},
		{
			name: "large data",
			vertex: &VertexAdd{
				Domain:      make([]byte, 32),
				DataAddress: make([]byte, 32),
				D


ights and bias

    Return value
    ------------
    Return the predicted labels
    """
    if not isinstance(X, np.ndarray):
        X = np.asarray(X)
    if not isinstance(theta, np.ndarray):
        theta = np.asarray(theta)
    if X.shape[1] == theta.shape[0]:
        X_hat = X
    else:
        X_hat = np.append(X, np.ones((X.shape[0], 1)), axis=1)

    results = softmax(X_hat @ theta.T)
    prediction = results == np.max(results, axis = 1).reshape(-1, 1)
    return np.where(prediction)[1]

def predict_compute_metrics(X_test, Y_test, theta):
    """
    Function to compute metrics for a set of data and weights and bias given

    Parameters
    ----------
    X_test: np.ndarray
        Set of datas to predict labels
    Y_test: np.ndarray
        Real prediction of the labels
    theta: np.ndarray
        Weights and bias

    Return value
    ------------
    Return the metrics computed
    """
    if not isinstance(X_test, np.ndarray):
        X_test = np.asarray(X_test)
    predicted_val_logreg = predict_log_reg_2(X_test, theta)
    return metrics.compute_metrics(Y_test, predicted_val_logreg)

def test_log_reg_with_dataset_values():
    """
    Function to test logistic multinomial regression with dataset values
    """
    from main import FEAT, LABELS

    X = np.asarray(FEAT)
    _, n = X.shape
    # I see that the performances are better for a theta initialised to 0 whereas a random theta...
    #theta = np.random.randint(1,10, size=(np.unique(LABELS).shape[0], X.shape[1] + 1)).astype(float)
    theta = np.zeros((np.unique(LABELS).shape[0], X.shape[1] + 1))
    n_it, lr = 1000, 1e-4

    theta = train_log_reg_2(X, LABELS, theta, n_it, lr)
    print("\n\nFound theta (bias are last column and weights are the rest):")
    print(theta)
    print()

def test_log_reg_f1score():
    """Test the efficiency of logistic regression with optimally chosen (before) parameters"""
    from main import FEAT, LABELS, FEAT_test, LABELS_test

    X = np.asarray(FEAT)
    _, n = X.shape
    theta = np.zeros((np.unique(LABELS).shape[0], X.shape[1] + 1))
    n_it, lr = 1000, 1e-4
    theta = train_log_reg_2(X, LABELS, theta, n_it, lr)
    print("\n\nFound theta (bias are last column and weights are the rest):")
    print(theta)
    print("\n\nMetrics obtained:")
    print(predict_compute_metrics(FEAT_test, LABELS_test, theta))

def main():
    # test_log_reg_with_dataset_values()
    test_log_reg_f1score()
    return


local role = require(GetScriptDirectory() .. "/RoleUtility");
local utils = require(GetScriptDirectory() ..  "/util")
local campUtils = require(GetScriptDirectory() ..  "/CampUtility")
local bot = GetBot()
local minute = 0;
local sec = 0;
local preferedCamp = nil;
local AvailableCamp = {};
local LaneCreeps = {};
local numCamp = 18;
local farmState = 0;
local teamPlayers = nil;
local lanes = {LANE_TOP, LANE_MID, LANE_BOT};
local cause = "";
local cogsTarget = nil;
local t3Destroyed = false;
local shrineTarget = nil;
local cLoc = nil;
local farmLane = false;

local tPing = 0;
local tChat = 0;

local testTime = 0;

function GetDesire()

	--campUtils.PrintCamps()

	--[[if DotaTime() > testTime + 20.0 then
		campUtils.PingCamp(1, 3, TEAM_RADIANT, bot);
		testTime = DotaTime();
	end]]--

	if bot:GetUnitName() == "npc_dota_hero_faceless_voids" and bot:IsAlive() then
		cLoc = GetSaveLocToFarmLane();
		if cLoc ~= nil  then
			--bot:ActionImmediate_Ping(cLoc.x, cLoc.y, true);
			--tPing = DotaTime();
			farmLane = true;
			return BOT_MODE_DESIRE_HIGH;
		else
			farmLane = false;
		end
	end

	local num_cogs = 0;

	if IsUnitAroundLocation(GetAncient(GetTeam()):GetLocation(), 3000) then
		return BOT_MODE_DESIRE_NONE;
	end

	if teamPlayers == nil then teamPlayers = GetTeamPlayers(GetTeam()) end

	local EnemyHeroes = bot:GetNearbyHeroes(1600, true, BOT_MODE_NONE);

	minute = math.floor(DotaTime() / 60)
	sec = DotaTime() % 60

	if #AvailableCamp < numCamp and ( ( DotaTime() > 30 and DotaTime() < 60 and sec > 30 and sec < 31 )
	   or ( DotaTime() > 30 and  sec > 0 and sec < 1 ) )
	then
		AvailableCamp, numCamp = campUtils.RefreshCamp(bot);
		--print(tostring(GetTeam())..tostring(#AvailableCamp))
	end

	if bot:GetUnitName() == "npc_dota_hero_rattletrap" then
		if ( bot:GetActiveMode() == BOT_MODE_RETREAT and bot:WasRecentlyDamagedByAnyHero(3.0) ) or #EnemyHeroes == 0 or cause == "cogs" then
			local units = GetUnitList(UNIT_LIST_ALLIED_OTHER);
			local minDist = 10000;
			for _,u in pairs(units)
			do
				if u:GetUnitName() == "npc_dota_rattletrap_cog" then
					num_cogs = num_cogs + 1;
					local cogDist = GetUnitToUnitDistance(u, GetAncient(GetTeam()));
					if cogDist < minDist then
						cogsTarget = u;
						minDist = cogDist;
					end
				end
			end
			if num_cogs == 8 then
				--print("attack cogs while retreat. Num cogs = "..tostring(num_cogs));
				cause = "cogs";
				return BOT_MODE_DESIRE_ABSOLUTE;
			end
		elseif bot:GetActiveMode() == BOT_MODE_ATTACK or cause == "cogs" then
			local npcTarget = bot:GetTarget();
			if npcTarget ~= nil and npcTarget:IsHero() and GetUnitToUnitDistance(bot, npcTarget) > 300 then
				local units = GetUnitList(UNIT_LIST_ALLIED_OTHER);
				local minDist = 10000


element)

Unordered lists start each item with a *

- works too

Indent a level to make a nested list

Ordered lists are supported.

Start each item (number-period-space) like 1.

It doesn't matter what number you use, I will render them sequentially

So you might want to start each line with 1. and let me sort it out

Here is the code:

* Lists must be preceded by a blank line (or block element)
* Unordered lists start each item with a `*`
- `-` works too
	* Indent a level to make a nested list
		1. Ordered lists are supported.
		2. Start each item (number-period-space) like `1. `
		42. It doesn't matter what number you use, I will render them sequentially
		1. So you might want to start each line with `1.` and let me sort it out

Block Quote

Angle brackets > are used for block quotes.

Technically not every line needs to start with a > as long as
there are no empty lines between paragraphs.

Looks kinda ugly though.

Block quotes can be nested.

Multiple Levels

Most markdown syntaxes work inside block quotes.

Lists

Links

Etc.

Here is the code:

> Angle brackets `>` are used for block quotes.
Technically not every line needs to start with a `>` as long as
there are no empty lines between paragraphs.
> Looks kinda ugly though.
> > Block quotes can be nested.
> > > Multiple Levels
>
> Most markdown syntaxes work inside block quotes.
>
> * Lists
> * [Links][arbitrary_id]
> * Etc.

Inline Code

Inline code is indicated by surrounding it with backticks:

`Inline code`

If your code has `backticks`  that need to be displayed, you can use double backticks:

``Code with `backticks` `` (mind the spaces preceding the final set of backticks)

Block Code

If you indent at least four spaces or one tab, I'll display a code block.

print('This is a code block')
print('The block must be preceded by a blank line')
print('Then indent at least 4 spaces or 1 tab')
	print('Nesting does nothing. Your code is displayed Literally')

I also know how to do something called Fenced Code Blocks which I will tell you about later.

Horizontal Rules

If you type three asterisks *** or three dashes --- on a line, I'll display a horizontal ru


let graph = LineGraph {
            parent_id: "graph".to_string(),
            width: 500f64,
            height: 450f64,
            data_x: xdata.clone(),
            data_y: ydata.clone(),
            series_labels: series_names.clone(),
            x_axis_label: "Component".to_string(),
            y_axis_label: "Explained Variance (%)".to_string(),
            draw_points: true,
            draw_gridlines: true,
            draw_legend: false,
            draw_grey_background: false,
        };

        writer.write_all(
            &format!("
{}
", graph.get_svg()).as_bytes(),
        )?;

        // The following will print a full-precision version of the eigenvectors as a comment (hidden from the user).
        // It is intended to be parsed by the InversePCA tool to perform the inverse operation.

        writer.write_all("\n\n".as_bytes())?;

        writer.write_all("\n".as_bytes())?;

        let _ = writer.flush();

        if verbose {
            if cfg!(target_os = "macos") || cfg!(target_os = "ios") {
                let output = Command::new("open")
                    .arg(output_html_file.clone())
                    .output()
                    .expect("failed to execute process");

                let _ = output.stdout;
            } else if cfg!(target_os = "windows") {
                // let output = Command::new("cmd /c start")
                let output = Command::new("explorer.exe")
                    .arg(output_html_file.clone())
                    .output()
                    .expect("failed to execute process");

                let _ = output.stdout;
            } else if cfg!(target_os = "linux") {
                let output = Command::new("xdg-open")
                    .arg(output_html_file.clone())
                    .output()
                    .expect("failed to execute process");

                let _ = output.stdout;
            }

            println!("Please see {} for output report.", output_html_file);
        }

        // Output the component images
        if num_comp == 0 && !num_comp_set {
            // if it's not set, then output all the components.
            num_comp = num_files;
        }
        for a in 0..num_comp {
            pc = component_order[a];
            let out_file = format!("{}PCA_component{}.tif", wd, (a + 1));
            let mut output = Raster::initialize_using_file(&out_file, &input_raster[0]);
            output.configs.data_type = DataType::F32;
            for row in 0..rows {
                for col in 0..columns {
                    z1 = input_raster[0].get_value(row, col);


a: "\e1fc";
  --fa--fa: "\e1fc\e1fc"; }

.fa-chess-pawn {
  --fa: "\f443";
  --fa--fa: "\f443\f443"; }

.fa-kit-medical {
  --fa: "\f479";
  --fa--fa: "\f479\f479"; }

.fa-first-aid {
  --fa: "\f479";
  --fa--fa: "\f479\f479"; }

.fa-grid-2-plus {
  --fa: "\e197";
  --fa--fa: "\e197\e197"; }

.fa-bells {
  --fa: "\f77f";
  --fa--fa: "\f77f\f77f"; }

.fa-person-through-window {
  --fa: "\e5a9";
  --fa--fa: "\e5a9\e5a9"; }

.fa-toolbox {
  --fa: "\f552";
  --fa--fa: "\f552\f552"; }

.fa-globe-wifi {
  --fa: "\e685";
  --fa--fa: "\e685\e685"; }

.fa-envelope-dot {
  --fa: "\e16f";
  --fa--fa: "\e16f\e16f"; }

.fa-envelope-badge {
  --fa: "\e16f";
  --fa--fa: "\e16f\e16f"; }

.fa-magnifying-glass-waveform {
  --fa: "\e661";
  --fa--fa: "\e661\e661"; }

.fa-hands-holding-circle {
  --fa: "\e4fb";
  --fa--fa: "\e4fb\e4fb"; }

.fa-bug {
  --fa: "\f188";
  --fa--fa: "\f188\f188"; }

.fa-bowl-chopsticks {
  --fa: "\e2e9";
  --fa--fa: "\e2e9\e2e9"; }

.fa-credit-card {
  --fa: "\f09d";
  --fa--fa: "\f09d\f09d"; }

.fa-credit-card-alt {
  --fa: "\f09d";
  --fa--fa: "\f09d\f09d"; }

.fa-circle-s {
  --fa: "\e121";
  --fa--fa: "\e121\e121"; }

.fa-box-ballot {
  --fa: "\f735";
  --fa--fa: "\f735\f735"; }

.fa-car {
  --fa: "\f1b9";
  --fa--fa: "\f1b9\f1b9"; }

.fa-automobile {
  --fa: "\f1b9";
  --fa--fa: "\f1b9\f1b9"; }

.fa-hand-holding-hand {
  --fa: "\e4f7";
  --fa--fa: "\e4f7\e4f7"; }

.fa-user-tie-hair {
  --fa: "\e45f";
  --fa--fa: "\e45f\e45f"; }

.fa-podium-star {
  --fa: "\f758";
  --fa--fa: "\f758\f758"; }

.fa-user-hair-mullet {
  --fa: "\e45c";
  --fa--fa: "\e45c\e45c"; }

.fa-business-front {
  --fa: "\e45c";
  --fa--fa: "\e45c\e45c"; }

.fa-party-back {
  --fa: "\e45c";
  --fa--fa: "\e45c\e45c"; }

.fa-trian-balbot {
  --fa: "\e45c";
  --fa--fa: "\e45c\e45c"; }

.fa-microphone-


USED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/python.hpp"

#include "GafferOSL/ClosurePlug.h"
#include "GafferOSL/OSLCode.h"
#include "GafferOSL/OSLImage.h"
#include "GafferOSL/OSLLight.h"
#include "GafferOSL/OSLObject.h"
#include "GafferOSL/OSLShader.h"
#include "GafferOSL/ShadingEngine.h"
#include "GafferOSL/ShadingEngineAlgo.h"

#include "GafferBindings/DataBinding.h"
#include "GafferBindings/DependencyNodeBinding.h"
#include "GafferBindings/PlugBinding.h"
#include "GafferBindings/SignalBinding.h"

#include "Gaffer/Plug.h"

#include "IECorePython/IECoreBinding.h"
#include "IECorePython/ScopedGILRelease.h"

#include "OSL/oslversion.h"

#include "fmt/format.h"

using namespace boost::python;
using namespace GafferBindings;
using namespace GafferOSL;

namespace
{

object shaderMetadata( const OSLShader &s, const char *key, bool copy = true )
{
	return dataToPython( s.shaderMetadata( key ), copy );
}

object parameterMetadata( const OSLShader &s, const Gaffer::Plug *plug, const char *key, bool copy = true )
{
	return dataToPython( s.parameterMetadata( plug, key ), copy );
}

ShadingEnginePtr oslShaderShadingEngine( const OSLShader &s, const IECore::CompoundObject *substitutions )
{
	IECorePython::ScopedGILRelease gilRelease;
	return const_cast<ShadingEngine*>( s.shadingEngine( substitutions ).get() );
}

int oslLibraryVersionMajor()
{
	return OSL_LIBRARY_VERSION_MAJOR;
}

int oslLibraryVersionMinor()
{
	return OSL_LIBRARY_VERSION_MINOR;
}

int oslLibraryVersionPatch()
{
	return OSL_LIBRARY_VERSION_PATCH;
}

int oslLibraryVersionCode()
{
	return OSL_LIBRARY_VERSION_CODE;
}

std::string oslCodeSource( const OSLCode &oslCode, const std::string &shaderName )
{
	IECorePython::ScopedGILRelease gilRelease;
	return oslCode.source( shaderName );
}

std::string repr( ShadingEngine::Transform &s )
{
	return fmt::format(
		"GafferOSL.ShadingEngine.Transform( fromObjectSpace = {}, toObjectSpace = {} )",
		IECorePython::repr<Imath::M44f>( s.fromObjectSpace ),
		IECorePython::repr<Imath::M44f>( s.toObjectSpace )
	);
}

IECore::CompoundDataPtr shadeWrapper( ShadingEngine &shadingEngine, const IECore::CompoundData *points, boost::python::dict pythonTransforms, boost::python::dict pythonPointClouds )
{
	ShadingEngine::Transforms transforms;

	list values = pythonTransforms.values();
	list keys = pythonTransforms.keys();

	for (int i = 0; i < boost::python::len( keys ); i++)
	{
		object key( keys[i] );
		object value( values[i] );

		extract<const char *> keyElem( key );
		if( !keyElem.check() )
		{
			PyErr_SetString( PyExc_TypeError, "Incompatible key type. Only strings accepted." );
			throw_error_already_set();
		}

		extract


e;
  transition: box-shadow 0.3s ease;
}

.amis-scope .dark-CBGroupOrItem.is-hover {
  box-shadow: #e8ebee 0 2px 10px 0;
}

.amis-scope .dark-CBGroupOrItem + .dark-CBGroupOrItem {
  margin-top: 0.625rem;
}

.amis-scope .dark-CBGroupOrItem-dragbar {
  cursor: move;
  width: 20px;
  margin-left: -5px;
  opacity: 0.6;
  text-align: center;
  transition: opacity 0s ease-out;
  color: #84888c;
}

.amis-scope .dark-CBGroupOrItem-dragbar:hover {
  color: #0983ff;
}

.amis-scope .dark-CBGroupOrItem-body {
  display: flex;
  flex-direction: row;
  align-items: center;
  position: relative;
  transition: all 0s ease-out;
}

.amis-scope .dark-CBGroupOrItem-body-group {
  width: 100%;
  flex-direction: row;
  display: flex;
  align-items: center;
  transition: all 0.2s ease;
  padding-left: 10px;
}

.amis-scope .dark-CBGroupOrItem-body-group.is-hover {
  cursor: grab;
  box-shadow: 0px 2px 14px 0px rgba(0, 0, 0, 0.16);
  border-radius: 8px;
  padding: 10px;
  margin: -10px 0px;
  background: #fff;
  z-index: 1;
}

.amis-scope .dark-CBGroupOrItem-body-group > .dark-CBGroupOrItem-dragbar {
  left: -0.3125rem;
  position: absolute;
}

.amis-scope .dark-CBGroupOrItem-body-group > .dark-CBGroup {
  margin: 0px;
}

.amis-scope .dark-CBGroupOrItem-body-item {
  background-color: #f7f9fa;
  width: 100%;
  padding: 0.75rem 0.75rem 0.75rem 1.75rem;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.amis-scope .dark-CBGroupOrItem-body-item > .dark-CBGroupOrItem-dragbar {
  left: 0.625rem;
  position: absolute;
}

.amis-scope .dark-CBGroupOrItem.is-dragging {
  display: none;
}

.amis-scope .dark-CBGroupOrItem.is-ghost > .dark-CBGroupOrItem-body:before {
  position: absolute;
  z-index: 2;
  content: "";
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 123, 255, 0.2);
}

.amis-scope .dark-CBGroupOrItem .dark-CBGroup {
  flex-grow: 1;
}

.amis-scope .dark-CBGroupOrItem > .dark-CBGroupOrItem-body > .dark-CBGroupOrItem-body-group > .dark-CBGroupOrItem-dragbar,
.amis-scope .dark-CBGroupOrItem > .dark-CBGroupOrItem-body > .dark-CBGroupOrItem-body-item > .dark-CBGroupOrItem-dragbar,
.amis-scope .dark-CBGroupOrItem > .dark-CBGroupOrItem-body > .dark-CBGroupOrItem-body-item > .dark-CBDelete {
  opacity: 0;
}

.amis-scope .dark-CBGroupOrItem:hover > .dark-CBGroupOrItem-body > .dark-CBGroupOrItem-body-item > .dark-CBGroupOrItem-dragbar,
.amis-scope .dark-CBGroupOrItem:hover > .dark-CBGroupOrItem-body > .dark-CBGroupOrItem-body-item > .dark-CBDelete {


!= nil {
				tc.init(client, tc.mockData, tc.mockUpdateData)
			}
			useClient(client, func() {
				resource.UnitTest(t, resource.TestCase{
					ProtoV6ProviderFactories: testutils.NewProtoV6ProviderFactory(NewSubprovider()),
					Steps:                    tc.steps,
				})
			})
			client.AssertExpectations(t)
		})
	}

}

func TestClientCertificateAkamaiResource_ImportState(t *testing.T) {
	t.Parallel()
	baseChecker := tst.NewImportChecker().
		CheckEqual("certificate_id", "123456789").
		CheckEqual("certificate_name", "test-certificate").
		CheckEqual("contract_id", "123456789").
		CheckEqual("geography", "CORE").
		CheckEqual("group_id", "987654321").
		CheckEqual("key_algorithm", "RSA").
		CheckEqual("notification_emails.#", "2").
		CheckEqual("notification_emails.0", "testemail1@example.com").
		CheckEqual("notification_emails.1", "testemail2@example.com").
		CheckEqual("secure_network", "STANDARD_TLS").
		CheckEqual("subject", "/C=US/O=Akamai Technologies, Inc./OU=Example 123456789 987654321/CN=test-certificate/").
		CheckEqual("created_by", "joeDoe").
		CheckEqual("created_date", "2023-01-01T12:00:00Z").
		CheckEqual("versions.#", "1").
		CheckEqual("versions.0.version", "1").
		CheckEqual("versions.0.status", "DEPLOYED").
		CheckEqual("versions.0.expiry_date", "2024-12-31T23:59:59Z").
		CheckEqual("versions.0.issuer", "Example Issuer").
		CheckEqual("versions.0.key_algorithm", "RSA").
		CheckEqual("versions.0.created_by", "joeDoe").
		CheckEqual("versions.0.created_date", "2023-01-01T12:00:00Z").
		CheckEqual("versions.0.issued_date", "2023-01-01T12:00:00Z").
		CheckEqual("versions.0.key_size_in_bytes", "2048").
		CheckEqual("versions.0.subject", "/C=US/O=Akamai Technologies, Inc./OU=Example 123456789 987654321/CN=test-certificate/").
		CheckEqual("versions.0.version_guid", "test_identifier_1-1").
		CheckEqual("versions.0.signature_algorithm", "SHA256_WITH_RSA")

	secnondVersionChecker := baseChecker.
		CheckEqual("versions.#", "2").
		CheckEqual("versions.0.version", "2").
		CheckEqual("versions.0.status", "DEPLOYED").
		CheckEqual("versions.0.expiry_date", "2025-12-31T23:59:59Z").
		CheckEqual("versions.0.issuer", "Example Issuer").
		CheckEqual("versions.0.key_algorithm", "RSA").
		CheckEqual("versions.0.created_by", "joeDoe").
		CheckEqual("versions.0.created_date", "2025-01-01T12:00:00Z").
		CheckEqual("versions.0.issued_date", "2025-01-01T12:00:00Z").
		CheckEqual("versions.0.key_size_in_bytes", "2048").
		CheckEqual("versions.0.subject", "/C=US/O=Akamai Technologies, Inc./OU=Example 123456789 987654321/CN=test-certificate/").
		CheckEqual("versions.0.version_guid", "test_identifier_1-2").
		CheckEqual("versions.0.signature_algorithm", "SHA256_WITH_RSA").
		CheckEqual("versions.1.version", "1").
		CheckEqual("versions.1.status", "DEPLOYED").
		CheckEqual("versions.1.expiry_date", "2024-12-31T23:59:59Z").
		CheckEqual("versions.1.issuer", "Example Issuer").
		CheckEqual("versions.1.key_algorithm", "RSA").


visit_detail_id	|No	|Integer|	A foreign key to the VISIT_DETAIL table of the visit immediately preceding this visit|
|visit_detail_parent_id		|	No	|Integer|A foreign key to the VISIT_DETAIL table record to represent the immediate parent visit-detail record.|
|visit_occurrence_id		|	Yes	|Integer|A foreign key that refers to the record in the VISIT_OCCURRENCE table. This is a required field, because for every visit_detail is a child of visit_occurrence and cannot exist without a corresponding parent record in visit_occurrence.|

### Conventions

  * All conventions used in VISIT_OCCURRENCE apply to VISIT_DETAIL, some notable exceptions:
  * A Visit Detail is an optional detail record for each Visit Occurrence to a healthcare facility. For every record in VISIT_DETAIL there has to be a parent VISIT_OCCURRENCE record.
  * One record in VISIT_DETAIL can only have one VISIT_OCCURRENCE parent.
  * A single VISIT_OCCURRENCE record may have many child VISIT_DETAIL records.
  * Valid Visit Concepts belong to the "Visit" domain. Standard Visit Concepts are yet to be defined, but will represent a detail of the Standard Visit Concept in VISIT_OCCURRENCE.
  * Handling of death: In the case when a patient died during admission (VISIT_OCCURRENCE.DISCHARGE_DISPOSITION_CONCEPT_ID = 4216643 'Patient died'), a record in the Death table should be created with DEATH_TYPE_CONCEPT_ID = 44818516 (EHR discharge status "Expired").
  * Source Concepts from place of service vocabularies are mapped into these Standard Visit Concepts in the Standardized Vocabularies.
  * At any one day, there could be more than one visit. VISIT_OCCURRENCE allows for more than one visit within a single day. VISIT_DETAIL is to be used to only capture details within the visit.
  * One visit may involve multiple providers, in which case, in VISIT_OCCURRENCE, the ETL must specify how a single provider id is selected or leave the provider_id field null. VISIT_DETAIL allows for ETL to speicify multiple child records per visit occurrence - and each of these child records may represent different provider_ids.
  * One visit may involve multiple Care Sites, in which case, in VISIT_OCCURRENCE, the ETL must specify how a single care_site id is selected or leave the care_site_id field null. VISIT_DETAIL allows for ETL to speicify multiple child records per visit occurrence - and each of these child records may represent different care_sites.
  * Just like in VISIT_OCCURRENCE, records in VISIT_DETAIL may be sequentially related to each. These sequential relations are represented using preceding_visit_detail_id
  * Unlike VISIT_OCCURRENCE, VISIT_DETAIL may have nested visits with hierarchial relationships to each other.
  * Representation of US claim data: US claims data generally has two-levels. Header/summary data that summarizes the entire claim; Line/detail that details a claim. Detail is thus a child of the summary, and for every record in summary there is one or more records in detail. i.e. there will be atleast one FK link from VISIT_DETAIL to VISIT_OCCURRENCE.

 Example: an entire inpatient stay maybe one record in the VISIT_OCCURRENCE table. This may have one or more detail records such as ER, ICU, medical floor, rehabilitation floor etc. Each of these visit details may have different start/end date-times, different concept_ids and fact_ids. These would become separate records in VISIT_DETAIL with a FK link to VISIT_OCCURRENCE.

 Each record within VISIT_DETAIL may be related to each other, sequentially –> ER leading to ICU leading to medical floor, lead


ARM], NULL },
		},
	}
};

static struct dvb_usb_device_properties dposh_properties = {
	.caps = DVB_USB_IS_AN_I2C_ADAPTER,

	.usb_ctrl = DEVICE_SPECIFIC,
	.firmware = "dvb-usb-dposh-01.fw",
	.download_firmware = m920x_firmware_download,

	.size_of_priv     = sizeof(struct m920x_state),

	.identify_state   = m920x_identify_state,
	.num_adapters = 1,
	.adapter = {{
		.num_frontends = 1,
		.fe = {{
		/* Hardware pid filters don't work with this device/firmware */

		.frontend_attach  = m920x_mt352_frontend_attach,
		.tuner_attach     = m920x_qt1010_tuner_attach,

		.stream = {
			.type = USB_BULK,
			.count = 8,
			.endpoint = 0x81,
			.u = {
				 .bulk = {
					 .buffersize = 512,
				 }
			}
		},
		}},
	}},
	.i2c_algo         = &m920x_i2c_algo,

	.num_device_descs = 1,
	.devices = {
		 {   .name = "Dposh DVB-T USB2.0",
		     .cold_ids = { &m920x_table[DPOSH_M9206_COLD], NULL },
		     .warm_ids = { &m920x_table[DPOSH_M9206_WARM], NULL },
		 },
	 }
};

static struct dvb_usb_device_properties pinnacle_pctv310e_properties = {
	.caps = DVB_USB_IS_AN_I2C_ADAPTER,

	.usb_ctrl = DEVICE_SPECIFIC,
	.download_firmware = NULL,

	.rc.legacy = {
		.rc_interval      = 100,
		.rc_map_table     = rc_map_pinnacle310e_table,
		.rc_map_size      = ARRAY_SIZE(rc_map_pinnacle310e_table),
		.rc_query         = m920x_rc_query,
	},

	.size_of_priv     = sizeof(struct m920x_state),

	.identify_state   = m920x_identify_state,
	.num_adapters = 1,
	.adapter = {{
		.num_frontends = 1,
		.fe = {{

		.caps = DVB_USB_ADAP_HAS_PID_FILTER |
			DVB_USB_ADAP_PID_FILTER_CAN_BE_TURNED_OFF,

		.pid_filter_count = 8,
		.pid_filter       = m920x_pid_filter,
		.pid_filter_ctrl  = m920x_pid_filter_ctrl,

		.frontend_attach  = m920x_mt352_frontend_attach,
		.tuner_attach     = m920x_fmd1216me_tuner_attach,

		.stream = {
			.type = USB_ISOC,
			.count = 5,
			.endpoint = 0x84,
			.u = {
				.isoc = {
					.framesperurb = 128,
					.framesize = 564,
					.interval = 1,
				}
			}
		},
		}},
	} },
	.i2c_algo         = &m920x_i2c_algo,

	.num_device_descs = 1,
	.devices = {
		{   "Pinnacle PCTV 310e",
			{ &m920x_table[VISIONPLUS_PINNACLE_PCTV310E], NULL },
			{ NULL },
		}
	}
};

static struct dvb_usb_device_properties vp7049_properties = {
	.caps = DVB_USB_IS_AN_I2C_ADAPTER,

	.usb_ctrl = DEVICE_SPECIFIC,
	.firmware = "dvb-usb-vp7049-0.95.fw",
	.download_firmware = m920x_firmware_download,

	.rc.core = {
		.rc_interval    = 150,
		.rc_codes       = RC_MAP_TWINHAN_VP1027_DVBS,
		.rc_query       = m920x_rc_core_query,
		.allowed_protos = RC_PROTO_BIT_UNKNOWN,
	},

	.size_of_priv     = sizeof(struct m920x_state),

	.identify_state   = m920x_identify_state,
	.num_adapters = 1,
	.adapter = {{
		.num_frontends = 1,
		.fe = {{

		.caps = DVB_USB_ADAP_HAS_PID_FILTER |
			DVB_USB_ADAP_PID_FILTER_CAN_BE_TURNED_OFF,

		.pid_filter_count = 8,
		.pid_filter       = m920x_pid_filter,
		.pid_filter_ctrl  = m920x_pid_filter_ctrl,

		.frontend_attach  = m920x_mt352_frontend_attach_vp7049,
		.tuner_attach     = m920x_mt2060_tuner_attach,

		.stream = {
			.type = USB_BULK,
			.count = 8,
			.endpoint = 0x81,
			.u = {
				 .bulk = {
					 .buffersize = 512,
				 }
			}
		},
		} },
	} },
	.i2c_algo         = &m920x_i2c_algo,

	.num_device_descs = 1,
	.devices = {
		{   "DTV-DVB UDTT7049",
			{ &m920x_table[AZUREWAVE_TWINHAN_VP7049], NULL },
			{ NULL },
		}
	 }
};

static struct usb_driver m920x_driver = {
	.name		= "dvb_usb_m920x",
	.probe		= m920x_probe,
	.disconnect	= dvb_usb_device_exit,
	.id_table	= m920x_table,
};

module_usb_driver(m920x_driver);

MODULE_AUTHOR("Aapo Tahkola <aet@rasterburn.org>");
MODULE_DESCRIPTION("DVB Driver for ULI M920x");
MODULE_VERSION("0.1");
MODULE_LICENSE("GPL");


异常拦截
         */
        internal val isNotIgnoredNoSuchMemberFailure get() = instance?.isNotIgnoredNoSuchMemberFailure ?: true

        /**
         * 绑定当前 [Member] 到当前 Hooker
         * @param member 当前 [Member]
         */
        internal fun bindMember(member: Member?) {
            instance?.members?.clear()
            member?.also { instance?.members?.add(it) }
        }

        /**
         * 绑定 [Member] 数组到当前 Hooker
         * @param members 当前 [Member] 数组
         */
        internal fun bindMembers(members: MutableList<Member>) {
            instance?.members?.clear()
            members.forEach { instance?.members?.add(it) }
        }
    }
}/*
 * YukiHookAPI - An efficient Hook API and Xposed Module solution built in Kotlin.
 * Copyright (C) 2019 HighCapable
 * https://github.com/HighCapable/YukiHookAPI
 *
 * Apache License Version 2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * This file is created by fankes on 2022/9/4.
 */
@file:Suppress("TYPEALIAS_EXPANSION_DEPRECATION", "DEPRECATION")

package com.highcapable.yukihookapi.hook.core.finder.members.data

import com.highcapable.yukihookapi.hook.core.finder.type.factory.CountConditions
import com.highcapable.yukihookapi.hook.core.finder.type.factory.ObjectsConditions
import com.highcapable.yukihookapi.hook.core.finder.ReflectionMigration
import java.lang.reflect.Constructor

/**
 * [Constructor] 规则查找数据类
 * @param paramTypes 参数类型数组
 * @param paramTypesConditions 参数类型条件
 * @param paramCount 参数个数
 * @param paramCountRange 参数个数范围
 * @param paramCountConditions 参数个数条件
 */
@Deprecated(ReflectionMigration.KAVAREF_INFO)
internal class ConstructorRulesData internal constructor(
    var paramTypes: Array<out Class<*>>? = null,
    var paramTypesConditions: ObjectsConditions? = null,
    var paramCount: Int = -1,
    var paramCountRange: IntRange = IntRange.EMPTY,
    var paramCountConditions: CountConditions? = null
) : MemberRulesData() {

    override val templates
        get() = arrayOf(
            paramCount.takeIf { it >= 0 }?.let { "paramCount:[$it]" } ?: "",
            paramCountRange.takeIf { it.isEmpty().not() }?.let { "paramCountRange:[$it]" } ?: "",
            paramCountConditions?.let { "paramCountConditions:[existed]" } ?: "",
            paramTypes?.typeOfString()?.let { "paramTypes:[$it]" } ?: "",
            paramTypesConditions


// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.

using Microsoft.UI.Xaml.Controls;
using Snap.Hutao.Core;
using Snap.Hutao.Core.ExceptionService;

namespace Snap.Hutao.Service.Notification;

internal sealed class InfoBarMessage
{
    public InfoBarSeverity Severity { get; init; }

    public string? Title { get; init; }

    public string? Message { get; init; }

    public object? Content { get; init; }

    public string? ActionButtonContent { get; init; }

    public ICommand? ActionButtonCommand { get; init; }

    public int MilliSecondsDelay { get; init; }

    public static InfoBarMessage Any(InfoBarSeverity severity, string message)
    {
        return new()
        {
            Severity = severity,
            Message = message,
            MilliSecondsDelay = 5000 + TextReadingTime.Estimate(message),
        };
    }

    public static InfoBarMessage Error(string message)
    {
        return new()
        {
            Severity = InfoBarSeverity.Error,
            Message = message,
            MilliSecondsDelay = 0,
        };
    }

    public static InfoBarMessage Error(string title, string message)
    {
        return new()
        {
            Severity = InfoBarSeverity.Error,
            Title = title,
            Message = message,
            MilliSecondsDelay = 0,
        };
    }

    public static InfoBarMessage Error(string title, Exception exception)
    {
        return new()
        {
            Severity = InfoBarSeverity.Error,
            Title = title,
            Message = ExceptionFormat.Format(exception),
            MilliSecondsDelay = 0,
        };
    }

    public static InfoBarMessage Error(Exception exception)
    {
        return new()
        {
            Severity = InfoBarSeverity.Error,
            Title = TypeNameHelper.GetTypeDisplayName(exception),
            Message = ExceptionFormat.Format(exception),
            MilliSecondsDelay = 0,
        };
    }

    publ


ls("0110")) {
// mti = "0100";
// } else if (inIsoMsg.getString(0).equals("0210")) {
// mti = "0200";
// } else if (inIsoMsg.getString(0).equals("0410")) {
// mti = "0400";
// } else {
// mti = outIsoMsg.getString(0);
// }
// return mti + outIsoMsg.getString(11) + outIsoMsg.getString(7) +
// outIsoMsg.getString(37) + "0000000000";
// }
//
// protected static void packIsoMsg(String fileName, ISOMsg msg) throws
// Exception {
// final File f = new File(fileName);
// if (!f.exists() || !f.isFile()) {
// throw new Exception("Invalid path of ISO message xml file. Could not
// continue.");
// }
// final FileInputStream fis = new FileInputStream(f);
// msg.setPackager(new XMLPackager());
// msg.unpack(fis);
// msg.setPackager(new org.jpos.iso.packager.GenericPackager(msgConfigFile));
// msg.setDirection(ISOMsg.OUTGOING);
// }
//
// private static FDR8583MsgPojo bufToPojo(ISOMsg inIsoMsg) throws
// FileNotFoundException, ISOException, UnsupportedEncodingException {
// // init logger
// final Logger logger = new Logger();
// /*
// * logger.addListener(new SimpleLogListener(System.out)); // init packager
// GenericPackager genericPackager = new GenericPackager( new
// FileInputStream(msgConfigFile)); genericPackager.setLogger(logger,
// "Paypal8583Client"); // get inbound msg header FDR8583LenHeader inHeader =
// new FDR8583LenHeader(buf); // get inbound message body ISOMsg inIsoMsg = new
// ISOMsg(); inIsoMsg.setPackager(genericPackager);
// inIsoMsg.unpack(getMsgBodyFromBuf(buf));
// */
//
// // dump message content to pojo and return
// final FDR8583MsgPojo inMsgPojo = new FDR8583MsgPojo();
// inMsgPojo.rawMsg = ISOUtil.hexString(inIsoMsg.pack());
// msgToPojo(inIsoMsg, inMsgPojo);
// return inMsgPojo;
// }
//
// private static ISOMsg getISOMsg(String requestFileName) throws Exception {
// final File f = new File(requestFileName);
// if (!f.exists() || !f.isFile()) {
// throw new Exception("Invalid path of ISO message xml file. Could not
// continue.");
// }
// final FileInputStream fis = new FileInputStream(f);
// final ISOMsg requestISOMsg = new ISOMsg();
// requestISOMsg.setPackager(new XMLPackager());
// requestISOMsg.unpack(fis);
// requestISOMsg.setPackager(new org.jpos.iso.packager.GenericPackager());
// return requestISOMsg;
// }
//
// private static void pojoToMsg(FDR8583MsgPojo msgPojo, ISOMsg isoMsg) throws
// ISOException {
// // populate msg body
// if (msgPojo == null || isoMsg == null) {
// return;
// }
// for (int i = 0; i <= FDR8583MsgPojo.maxMsgField; i++) {
// isoMsg.set(i, msgPojo.msgFields.get(i));
// }
// }
//
// private static void msgToPojo(ISOMsg isoMsg, FDR8583MsgPojo msgPojo) throws
// ISOException {
// // populate header value
// if (isoMsg == null || msgPojo == null) {


r) {
        var sink = new ComputingResultSink();
        var curve = new ModCurve(BigInteger.parse(points.a), BigInteger.parse(points.b), BigInteger.parse(points.n), BigInteger.parse(points.order));
        var config = {
            curve: curve,
            generator: ModPoint.fromBigInts(BigInteger.parse(points.gx), BigInteger.parse(points.gy), curve),
            target: ModPoint.fromBigInts(BigInteger.parse(points.tx), BigInteger.parse(points.ty), curve),
            additionTableSeed: tableSeed,
            additionTableLength: tableLength,
            parrallelWalksCount: walksCount,
            distinguishedPointMask: BigInteger.parse("0"),
            computeStats: false,
            checkCyclePeriod: tableLength,
            checkCycleLength: tableLength
        };

        test(configName + ": " + points.expected + " * " + config.generator + " = " + config.target + " on " + config.curve, () => {
            PollardRho.runLimited(config, sink);
            equal(0, sink.result.compare(ModNumber.create(BigInteger.parse(points.expected), curve.order)));
        });
    }

    export function run(): void {
        QUnit.module("PollardRho");

        var correctResults = [
            new NonAlgorithmicConfig(
                "0", "3", "31", "43", // Curve (A, B, N)
                "11", "1", // Generator (X, Y)
                "23", "24", // Target (X, Y)
                "10") // Expected result
        ];

        correctResults.forEach(r => result("1 walk", r, 0, 64, 1));
        correctResults.forEach(r => result("2 walks", r, 0, 64, 2));
    }
}

export = PollardRhoTests;import { namedTypes } from "ast-types";
import { memberExpression } from "../../util/ast";
import { EntityField, EnumDataType, EntityLookupField } from "../../types";
import { jsxElement, jsxFragment } from "../util";
import { EntityComponent } from "../types";
/**
 * Creates a node for displaying given entity field value
 * @param field the entity field to create value view for
 * @returns the node AST representation
 */
export function createFieldValue(
  field: EntityField,
  dataId: namedTypes.Identifier,
  entityIdToName: Record<string, string>,
  entityToTitleComponent: Record<string, EntityComponent>
): namedTypes.JSXElement | namedTypes.JSXFragment {
  const value = memberExpression`${dataId}.${field.name}`;
  switch (field.dataType) {
    case EnumDataType.CreatedAt:
    case EnumDataType.UpdatedAt:
      return jsxElement`<TimeSince time={${value}} />`;
    case EnumDataType.Lookup:
      const lookupField = field as EntityLookupField;
      const relatedEntityName =
        entityIdToName[lookupField.properties.relatedEntityId];
      const relatedEntityTitleComponent =
        entityToTitleComponent[relatedEntityName];

      return jsxElement`<${relatedEntityTitleComponent.name} id={${value}?.id}  />`;

    case EnumDataType.Boolean:
      return jsxFragment`<>{${value} && <CircleIcon icon="check" style={EnumCircleIconStyle.positive} />}</>`;
    case EnumDataType.DateTime:
    case EnumDataType.DecimalNumber:
    case EnumDataType.Email:
    case EnumDataType.GeographicLocation:
    case EnumDataType.Id:
    case EnumDataType.MultiLineText:
    case EnumDataType.MultiSelectOptionSet:
    case EnumDataType.OptionSet:
    case EnumDataType.Password:
    case EnumDataType.Roles:
    case EnumDataType.SingleLineText:
    case Enum


ri tim proyek.

Kode etik ini berlaku baik di dalam ruang proyek maupun di ruang publik
ketika seseorang mewakili proyek atau komunitasnya.

Kejadian perilaku yang kasar, mengganggu, atau tidak dapat diterima lainnya
dapat dilaporkan dengan menghubungi pemelihara proyek di victorfelder(at)gmail.com.
Semua keluhan akan ditinjau dan diselidiki, dan akan menghasilkan tanggapan yang
dianggap perlu dan sesuai dengan keadaan. Pemelihara proyek berkewajiban untuk
menjaga kerahasiaan pelapor insiden.

Kode Etik ini diadaptasi dari [Contributor Covenant][homepage],
versi 1.3.0, avaible at https://contributor-covenant.org/version/1/3/0/

[homepage]: https://contributor-covenant.org

[Terjemahan](README.md#nslations)
ഈ പദ്ധതിയുടെ സംഭാവകരും പരിപാലകരും എന്ന നിലയിലും ഒരു തുറന്നതും സ്വാഗതം ചെയ്യുന്നതുമായ കമ്മ്യൂണിറ്റി വളർത്തിയെടുക്കുന്നതിനായി, ഞങ്ങൾ ഇഷ്യുകൾ റിപ്പോർട്ട് ചെയ്യുന്നതിലൂടെ, ഫീച്ചർ അഭ്യർത്ഥനകൾ പോസ്റ്റ് ചെയ്യുന്നതിലൂടെ, ഡോക്യുമെന്റേഷൻ അപ്ഡേറ്റ് ചെയ്യുന്നതിലൂടെ, പുള്ളി അഭ്യർത്ഥനകൾ അല്ലെങ്കിൽ പാച്ചുകൾ സമർപ്പിക്കുന്നതിലൂടെ, മറ്റ് പ്രവർത്തനങ്ങൾ എന്നിവയിലൂടെ സംഭാവന നൽകുന്ന എല്ലാ ആളുകളെയും ബഹുമാനിക്കാൻ പ്രതിജ്ഞയെടുക്കുന്നു.

പരിചയത്തിന്റെ അളവ്, ലിംഗം, ലിംഗ സ്വത്വവും പ്രകടിപ്പിക്കലും, ലൈംഗിക റോൾ, വൈകല്യം, വ്യക്തിഗത രൂപം, ശരീര വലുപ്പം, വംശം, വംശീയത, പ്രായം, മതം, അല്ലെങ്കിൽ ദേശീയത എന്നിവയ്‌ക്കെല്ലാം പരിഗണിക്കാതെ ഈ പദ്ധതിയിലെ പങ്കാളിത്തം എല്ലാവർക്കും ആക്രമണരഹിതമാക്കാൻ ഞങ്ങൾ പ്രതിജ്ഞാബദ്ധരാണ്.

പങ്കാളികളുടെ അസ്വീകാര്യ


isters */
		u32 sdlr;		/* 0x3c output enable bit delay registers */
		u32 gtr;		/* 0x40 general timing register */
		u32 gcr;		/* 0x44 general configuration register */
		u32 gsr[3];		/* 0x48 general status registers */
		u8 res0[0x2c];		/* 0x54 */
	} dx[4];
	u8 res11[0x388];	/* 0x500 */
	u32 upd2;		/* 0x888 */
};

#define PTR3_TDINIT1(x)		((x) << 20)
#define PTR3_TDINIT0(x)		((x) <<  0)

#define PTR4_TDINIT3(x)		((x) << 20)
#define PTR4_TDINIT2(x)		((x) <<  0)

#define DRAMTMG0_TWTP(x)	((x) << 24)
#define DRAMTMG0_TFAW(x)	((x) << 16)
#define DRAMTMG0_TRAS_MAX(x)	((x) <<  8)
#define DRAMTMG0_TRAS(x)	((x) <<  0)

#define DRAMTMG1_TXP(x)		((x) << 16)
#define DRAMTMG1_TRTP(x)	((x) <<  8)
#define DRAMTMG1_TRC(x)		((x) <<  0)

#define DRAMTMG2_TCWL(x)	((x) << 24)
#define DRAMTMG2_TCL(x)		((x) << 16)
#define DRAMTMG2_TRD2WR(x)	((x) <<  8)
#define DRAMTMG2_TWR2RD(x)	((x) <<  0)

#define DRAMTMG3_TMRW(x)	((x) << 16)
#define DRAMTMG3_TMRD(x)	((x) << 12)
#define DRAMTMG3_TMOD(x)	((x) <<  0)

#define DRAMTMG4_TRCD(x)	((x) << 24)
#define DRAMTMG4_TCCD(x)	((x) << 16)
#define DRAMTMG4_TRRD(x)	((x) <<  8)
#define DRAMTMG4_TRP(x)		((x) <<  0)

#define DRAMTMG5_TCKSRX(x)	((x) << 24)
#define DRAMTMG5_TCKSRE(x)	((x) << 16)
#define DRAMTMG5_TCKESR(x)	((x) <<  8)
#define DRAMTMG5_TCKE(x)	((x) <<  0)

#define RFSHTMG_TREFI(x)	((x) << 16)
#define RFSHTMG_TRFC(x)		((x) <<  0)

#define PIR_CLRSR	(0x1 << 27)	/* clear status registers */
#define PIR_QSGATE	(0x1 << 10)	/* Read DQS gate training */
#define PIR_DRAMINIT	(0x1 << 8)	/* DRAM initialization */
#define PIR_DRAMRST	(0x1 << 7)	/* DRAM reset */
#define PIR_PHYRST	(0x1 << 6)	/* PHY reset */
#define PIR_DCAL	(0x1 << 5)	/* DDL calibration */
#define PIR_PLLINIT	(0x1 << 4)	/* PLL initialization */
#define PIR_ZCAL	(0x1 << 1)	/* ZQ calibration */
#define PIR_INIT	(0x1 << 0)	/* PHY initialization trigger */

#define PGSR_INIT_DONE	(0x1 << 0)	/* PHY init done */

#define ZQCR_PWRDOWN	(1U << 31)	/* ZQ power down */

#define ACBDLR_WRITE_DELAY(x)	((x) << 8)

#define DXBDLR_DQ(x)	(x)		/* DQ0-7 BDLR index */
#define DXBDLR_DM	8		/* DM BDLR index */
#define DXBDLR_DQS	9		/* DQS BDLR index */
#define DXBDLR_DQSN	10		/* DQSN BDLR index */

#define DXBDLR_WRITE_DELAY(x)	((x) << 8)
#define DXBDLR_READ_DELAY(x)	((x) << 0)

/*
 * The delay parameters below allow to allegedly specify delay times of some
 * unknown unit for each individual bit trace in each of the four data bytes
 * the 32-bit wide access consists of. Also three control signals can be
 * adjusted individually.
 */
#define NR_OF_BYTE_LANES	(32 / BITS_PER_BYTE)
/* The eight data lines (DQn) plus DM, DQS and DQSN */
#define LINES_PER_BYTE_LANE	(BITS_PER_BYTE + 3)
struct dram_para {
	u16 page_size;
	u8 bus_full_width;
	u8 dual_rank;
	u8 row_bits;
	u8 bank_bits;
	const u8 dx_read_delays[NR_OF_BYTE_LANES][LINES_PER_BYTE_LANE];
	const u8 dx_write_delays[NR_OF_BYTE_LANES][LINES_PER_BYTE_LANE];
	const u8 ac_delays[31];
};

static inline int ns_to_t(int nanoseconds)
{
	const unsigned int ctrl_freq = CONFIG_DRAM_CLK / 2;

	return DIV_ROUND_UP(ctrl_freq * nanoseconds, 1000);
}

void mctl_set_timing_params(uint16_t socid, struct dram_para *para);

#endif /* _SUNXI_DRAM_SUN8I_H3_H */


/set.
     * @param {!mixed} value - The value you want to set it to.
     * @param {boolean} setrecursively - If true, will set value of non-existing path as well.
     */
    _setDeep(obj: object, path: any, value: number | string | boolean, setrecursively = false): boolean {
        /*       path.reduce((a, b, level) => {
                   if (setrecursively && typeof a[b] === "undefined" && level !== path.length) {
                       a[b] = {};
                       return a[b];
                   }

                   if (level === path.length) {
                       a[b] = value;
                       return value;
                   }
                   return a[b];
               }, obj);

       */
        // this is a super simple parsing, you will want to make this more complex to handle correctly any path
        // it will split by the dots at first and then simply pass along the array (on next iterations)
        let properties = Array.isArray(path) ? path : path.split(".")

        // Not yet at the last property so keep digging
        if (properties.length > 1) {
            // The property doesn't exists OR is not an object (and so we overwritte it) so we create it
            if (!obj.hasOwnProperty(properties[0]) || typeof obj[properties[0]] !== "object") obj[properties[0]] = {}
            // We iterate.
            return this._setDeep(obj[properties[0]], properties.slice(1), value)
            // This is the last property - the one where to set the value
        } else {
            // We set the value to the last property
            obj[properties[0]] = value
            return true // this is the end
        }
    }
}
import { ThreatConnect } from "~/searcher";

describe("ThreatConnect", function () {
  const subject = new ThreatConnect();

  it("should support ip, domain and email", function () {
    expect(subject.supportedTypes).toEqual(["ip", "domain", "email"]);
  });

  describe("#searchByIP", function () {
    const ip = "1.1.1.1";
    it("should return a URL", function () {
      expect(subject.searchByIP(ip)).toBe(
        `https://app.threatconnect.com/auth/indicators/details/address.xhtml?address=${ip}`,
      );
    });
  });

  describe("#searchByDomain", function () {
    const domain = "github.com";
    it("should return a URL", function () {
      expect(subject.searchByDomain(domain)).toBe(
        `https://app.threatconnect.com/auth/indicators/details/host.xhtml?host=${domain}`,
      );
    });
  });

  describe("#searchByEmail", function () {
    const email = "test@test.com";
    it("should return a URL", function () {
      expect(subject.searchByEmail(email)).toBe(
        "https://app.threatconnect.com/auth/indicators/details/emailaddress.xhtml?emailaddress=test%40test.com",
      );
    });
  });
});
import * as N3 from 'n3';
import * as QuadStore from 'quadstore';
import * as RdfString from 'rdf-string';

const { DataFactory } = N3;
const { namedNode, quad } = DataFactory;

export type Quad = N3.Quad;
export type StringQuad = QuadStore.StringQuad;

export interface GraphTrie {
  [key: string]: StringQuad | GraphTrie;
}

export function isObjectQuad(s: Quad | StringQuad): s is Quad {
  return !isStringQuad(s);
}

export function isStringQuad(
  s: GraphTrie | Quad | StringQuad
): s is StringQuad {
  return (
    typeof s.subject === 'string' &&
    typeof s.predicate === 'string' &&
    typeof s.object === 'string' &&
    typeof s.graph === 'string'
  );


bbp_set_rxpath(pAd, pAd->Antenna.field.RxPath);

		/*Number of transmitter chains*/
		bbp_set_txdac(pAd, pAd->Antenna.field.TxPath - 1);
	}
#endif /* RT3593 */

#ifdef DOT11_N_SUPPORT
	if (get_ht_cent_ch(pAd, &rf_bw, &ext_ch) == FALSE)
#endif /* DOT11_N_SUPPORT */
	{
		rf_bw = BW_20;
		ext_ch = EXTCHA_NONE;
		pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel;
	}

	/* request by Gary 20070208 for middle and long range A Band*/
	if (IS_RT3572(pAd)) {
#ifdef DOT11_N_SUPPORT
		if (rf_bw == BW_40)
			bbp_val = (pAd->CommonCfg.Channel > 14) ? 0x48 : 0x38;
		else
#endif /* DOT11_N_SUPPORT */
			bbp_val = (pAd->CommonCfg.Channel > 14) ? 0x40 : 0x38;
		bbp_set_agc(pAd, bbp_val, RX_CHAIN_ALL);
	}

	bbp_set_bw(pAd, rf_bw);
	/*  TX/RX : control channel setting */
	rtmp_mac_set_ctrlch(pAd, ext_ch);
	bbp_set_ctrlch(pAd, ext_ch);

#ifdef RT3593
	if (IS_RT3593(pAd))
	{
#ifdef CONFIG_AP_SUPPORT
		IF_DEV_CONFIG_OPMODE_ON_AP(pAd)
		{
			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x0D);
			if (pAd->CommonCfg.Channel > 14)
			{
				RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x00);
			}
			else
			{
				RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x06);
			}
		}
#endif	/* CONFIG_AP_SUPPORT */
#ifdef CONFIG_STA_SUPPORT
		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
		{
	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x12);
			if (pAd->CommonCfg.Channel > 14)
			{
				RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x00);
			}
			else
			{
	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x0A);
			}
		}
#endif	/* CONFIG_STA_SUPPORT */
	}
	else
#endif
	{
		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x12);
		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x0A);
	}
	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, 0x10);

#ifdef DOT11_N_SUPPORT
	DBGPRINT(RT_DEBUG_TRACE, ("ApStartUp : 20MHz, ChannelWidth=%d, Channel=%d, ExtChanOffset=%d(%d) \n",
					pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth,
					pAd->CommonCfg.Channel,
					pAd->CommonCfg.RegTransmitSetting.field.EXTCHA,
					pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset));
#endif /* DOT11_N_SUPPORT */

	/* request by Gary 20070208 for middle and long range A Band*/
	if (pAd->CommonCfg.Channel > 14)
		bbp_val = 0x1D;
	else
		bbp_val = 0x2D;
	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R62, bbp_val);
	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R63, bbp_val);
	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R64, bbp_val);
	/*RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R86, bbp_val);*/

	/* Disable CCK packet detection in 5G band */
	if (IS_RT3572(pAd)) {
		bbp_val = (pAd->CommonCfg.Channel > 14) ? 0x00 : 0x0A;
		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, bbp_val);
	}
}
VOID RT35xxLoadRFSleepModeSetup(
	IN PRTMP_ADAPTER 	pAd)
{
	UCHAR RFValue;
	UINT32 MACValue;
#ifdef RELEASE_EXCLUDE
/*
	35xx will use this function; therefore, we could not remove the IS_RT3572
*/
#endif /* RELEASE_EXCLUDE */
#ifdef RT35xx
	if(IS_RT3572(pAd))
		RT30xxWriteRFRegister(pAd, RF_R08, 0x00);
#endif /* RT35xx */

	if(!IS_RT3572(pAd))
	{
			/* RF_BLOCK_en. RF R1 register Bit 0 to 0*/
			RT30xxReadRFRegister(pAd, RF_R01, &RFValue);
			RFValue &= (~0x01);
			RT30xxWriteRFRegister(pAd, RF_R01, RFValue);

			/* VCO_IC, RF R7 register Bit 4 & Bit 5 to 0*/
			RT30xxReadRFRegister(pAd, RF_R07, &RFValue);
			RFValue &= (~0x30);
			RT30xxWriteRFRegister(pAd, RF_R07, RFValue);

			/* Idoh, RF R9 register Bit 1, Bit 2 & Bit 3 to 0*/
			RT30xxReadRFRegister(pAd, RF_R09, &RFValue);
			RFValue &= (~0x0E);
			RT30xxWriteRFRegister(pAd, RF_R09, RFValue);

			/* RX_CTB_en, RF R21 register Bit 7 to 0*/
			RT30xxReadRFRegister(pAd, RF_R21, &RFValue);
			RFValue &= (~0x80);
			RT30xxWriteRFRegister(pAd, RF_R21, RFValue);
	}
#if 0
	/* Don't touch LDO_CFG0 for 3090F & 3593, possibly the board is single power scheme*/
	if (IS_RT3090(pAd) ||	/*IS_RT3090 including RT309x and RT3071/72*/
		IS_RT3572(pAd) ||
		(IS_RT3070(pAd) && ((pAd->MACVersion & 0xffff) < 0x0201)))
	{
		if (!IS_RT3572(pAd))
		{
			RT30xxReadRFRegister(pAd, RF_R27, &RFValue);
			RFValue |= 0x77;
			RT30xxWriteRFRegister(pAd, RF_R27, RFValue);
		}

		RTMP_IO_READ32(pAd, LDO_CFG0, &MACValue);
		MACValue |= 0x1D000000;
		RTMP_IO_WRITE32(pAd, LDO_CFG0, MACValue);
	}
#endif
}
#endif /* RT35xx */


es, _ := x509.CreateCertificate(rand.Reader, certOptions, certOptions, &priv.PublicKey, priv)
	pemcert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certBytes})
	key, err := x509.MarshalECPrivateKey(priv)
	if err != nil {
		return tls.Certificate{}, err
	}

	keyBytes := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: key})
	cert, err := tls.X509KeyPair(pemcert, keyBytes)
	if err != nil {
		return tls.Certificate{}, err
	}

	return cert, nil
}

func loadOrCreateCertificate(certFile, keyFile string, selfSigned bool) (tls.Certificate, error) {
	var cert tls.Certificate
	var err error
	if certFile != "" && keyFile != "" {
		cert, err = tls.LoadX509KeyPair(certFile, keyFile)
		if err != nil {
			return tls.Certificate{}, err
		}
		return cert, nil
	}
	if !selfSigned {
		return tls.Certificate{}, errors.New("must specify either a certificate file or enable self signed")
	}

	// Either CertFile or KeyFile was not specified, so make our own certificate
	cert, err = createSelfSignedCertificate()
	if err != nil {
		return tls.Certificate{}, err
	}
	return cert, nil
}
package io_test

import (
	"context"
	"fmt"
	"net/http"
	"strings"
	"testing"
	"time"

	"github.com/stretchr/testify/require"

	"github.com/warpstreamlabs/bento/internal/component/output"
	"github.com/warpstreamlabs/bento/internal/component/testutil"
	"github.com/warpstreamlabs/bento/internal/manager/mock"
	"github.com/warpstreamlabs/bento/internal/message"
)

func parseYAMLOutputConf(t testing.TB, formatStr string, args ...any) (conf output.Config) {
	t.Helper()
	var err error
	conf, err = testutil.OutputFromYAML(fmt.Sprintf(formatStr, args...))
	require.NoError(t, err)
	return
}

func TestHTTPServerOutputBasic(t *testing.T) {
	ctx, done := context.WithTimeout(context.Background(), time.Second*30)
	defer done()

	nTestLoops := 10

	port := getFreePort(t)
	conf := parseYAMLOutputConf(t, `
http_server:
  address: localhost:%v
  path: /testpost
`, port)

	h, err := mock.NewManager().NewOutput(conf)
	require.NoError(t, err)

	msgChan := make(chan message.Transaction)
	resChan := make(chan error)

	if err = h.Consume(msgChan); err != nil {
		t.Error(err)
		return
	}
	if err = h.Consume(msgChan); err == nil {
		t.Error("Expected error from double listen")
	}

	<-time.After(time.Millisecond * 100)

	// Test both single and multipart messages.
	for i := 0; i < nTestLoops; i++ {
		testStr := fmt.Sprintf("test%v", i)

		go func() {
			testMsg := message.QuickBatch([][]byte{[]byte(testStr)})
			select {
			case msgChan <- message.NewTransaction(testMsg, resChan):
			case <-time.After(time.Second):
				t.Error("Timed out waiting for message")
				return
			}
			select {
			case resMsg := <-resChan:
				if resMsg != nil {
					t.Error(resMsg)
				}
			case <-time.After(time.Second):
				t.Error("Timed out waiting for response")
			}
		}()

		res, err :=


def read_input(file_path):
    with open(file_path, 'r') as file:
        lines = file.readlines()

    # Extract register values
    registers = [0, 0, 0]
    for line in lines:
        if line.startswith("Register A"):
            registers[0] = int(line.split(":")[1].strip())
        elif line.startswith("Register B"):
            registers[1] = int(line.split(":")[1].strip())
        elif line.startswith("Register C"):
            registers[2] = int(line.split(":")[1].strip())

    # Extract program
    program = []
    for line in lines:
        if line.startswith("Program"):
            program = list(map(int, line.split(":")[1].strip().split(",")))

    return registers, program

def run_program(registers, program):
    # Initialize registers and instruction pointer
    A, B, C = registers
    ip = 0  # instruction pointer
    output = []

    # Helper function for combo operands
    def get_combo_value(operand):
        if operand in [0, 1, 2, 3]:  # Literal values
            return operand
        elif operand == 4:  # Register A
            return A
        elif operand == 5:  # Register B
            return B
        elif operand == 6:  # Register C
            return C
        else:
            raise ValueError("Invalid combo operand")

    # Main loop to run the program
    while ip < len(program):
        opcode = program[ip]
        operand = program[ip + 1]
        ip += 2  # Move to the next instruction unless overridden

        if opcode == 0:  # adv
            A //= 2 ** get_combo_value(operand)
        elif opcode == 1:  # bxl
            B ^= operand
        elif opcode == 2:  # bst
            B = get_combo_value(operand) % 8
        elif opcode == 3:  # jnz
            if A != 0:
                ip = operand
        elif opcode == 4:  # bxc
            B ^= C
        elif opcode == 5:  # out
            output.append(get_combo_value(operand) % 8)
        elif opcode == 6:  # bdv
            B = A // (2 ** get_combo_value(operand))
        elif opcode == 7:  # cdv
            C = A // (2 ** get_combo_value(operand))
        else:
            raise ValueError("Invalid opcode")

    # Join outputs with commas and return
    return ",".join(map(str, output))

# File path
input_file = "input.txt"

# Read input and run the program
registers, program = read_input(input_file)
result = run_program(registers, program)
print("Output:", result)


       field_id: id,
            data_type: String::from("String"),
            state: String::from("Enabled"),
        }),

        None => HttpResponse::build(StatusCode::NOT_FOUND).json(TerraformFieldNotFoundError {
            id: String::from("QL6LR-5P7KI-RAR20"),
            errors: vec![TerraformFieldResponseErrorField {
                code: String::from("field:doesnt_exist"),
                message: String::from("Field with the given id doesn't exist"),
                meta: TerraformFieldResponseErrorMetaField { id: id },
            }],
        }),
    }
}

#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TerraformFieldCreateRequest {
    field_name: String,
}

// This handler needs to keep the information about created fields because
// sumologic terraform provider looks up those fields after creation and if it
// cannot find it (via a GET request to /api/v1/fields) then it fails.
//
// ref: https://github.com/SumoLogic/terraform-provider-sumologic/blob/3275ce043e08873a8b1b843d4a5d473619044b4e/sumologic%2Fresource_sumologic_field.go#L95-L109
// ref: https://github.com/SumoLogic/terraform-provider-sumologic/blob/3275ce043e08873a8b1b843d4a5d473619044b4e/sumologic%2Fresource_sumologic_field.go#L60
//
pub async fn handler_terraform_fields_create(
    req: web::Json<TerraformFieldCreateRequest>,
    terraform_state: web::Data<TerraformState>,
) -> impl Responder {
    let mut fields = terraform_state.fields.lock().unwrap();
    let id: String = thread_rng()
        .sample_iter(Alphanumeric)
        .take(16)
        .map(char::from)
        .collect();
    let requested_name = req.field_name.clone();
    let exists = fields.iter().find_map(|(id, name)| {
        if name == &requested_name {
            Some(id)
        } else {
            None
        }
    });

    match exists {
        // Field with given ID already existed
        Some(_) => HttpResponse::from(json_str!({
            id: "E40YU-CU3Q7-RQDMO",
            errors: [
                {
                    code: "field:already_exists",
                    message: "Field with the given name already exists"
                }
            ]
        })),

        // New field can be inserted
        None => {
            let res = fields.insert(id.clone(), requested_name.clone());
            match res {
                None => HttpResponse::build(StatusCode::OK).json(TerraformFieldObject {
                    field_name: requested_name.clone(),
                    field_id: id,
                    data_type: String::from("String"),
                    state: String::from("Enabled"),
                }),

                // This theoretically shouldn't happen but just in case handle this
                Some(_) => HttpResponse::from(json_str!({
                    id: "E40YU-CU3Q7-RQDMO",
                    errors: [
                        {
                            code: "field:already_exists",
                            message: "Field with the given name already exists"
                        }
                    ]

                })),
            }
        }
    }
}

pub async fn handler_receiver(
    req: HttpRequest,
    body: bytes::Bytes,
    app_state: web::Data<AppState>,
    opts: web::Data<options::Options>,
) -> impl Responder {
    // Don't fail when we can't read remote address.


file) {
            // Look for any folders
            if (name.slice(-1) !== "/") {
                name += "/";
            }
            file = this.files[name];
        }

        if (file && !file.dir) {
            // file
            delete this.files[name];
        } else {
            // maybe a folder, delete recursively
            var kids = this.filter(function(relativePath, file) {
                return file.name.slice(0, name.length) === name;
            });
            for (var i = 0; i < kids.length; i++) {
                delete this.files[kids[i].name];
            }
        }

        return this;
    },

    /**
     * Generate the complete zip file
     * @param {Object} options the options to generate the zip file :
     * - compression, "STORE" by default.
     * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
     * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
     */
    generate: function(options) {
        throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
    },

    /**
     * Generate the complete zip file as an internal stream.
     * @param {Object} options the options to generate the zip file :
     * - compression, "STORE" by default.
     * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
     * @return {StreamHelper} the streamed zip file.
     */
    generateInternalStream: function(options) {
      var worker, opts = {};
      try {
          opts = utils.extend(options || {}, {
              streamFiles: false,
              compression: "STORE",
              compressionOptions : null,
              type: "",
              platform: "DOS",
              comment: null,
              mimeType: 'application/zip',
              encodeFileName: utf8.utf8encode
          });

          opts.type = opts.type.toLowerCase();
          opts.compression = opts.compression.toUpperCase();

          // "binarystring" is prefered but the internals use "string".
          if(opts.type === "binarystring") {
            opts.type = "string";
          }

          if (!opts.type) {
            throw new Error("No output type specified.");
          }

          utils.checkSupport(opts.type);

          // accept nodejs `process.platform`
          if(
              opts.platform === 'darwin' ||
              opts.platform === 'freebsd' ||
              opts.platform === 'linux' ||
              opts.platform === 'sunos'
          ) {
              opts.platform = "UNIX";
          }
          if (opts.platform === 'win32') {
              opts.platform = "DOS";
          }

          var comment = opts.comment || this.comment || "";
          worker = generate.generateWorker(this, opts, comment);
      } catch (e) {
        worker = new GenericWorker("error");
        worker.error(e);
      }
      return new StreamHelper(worker, opts.type || "string", opts.mimeType);
    },
    /**
     * Generate the complete zip file asynchronously.
     * @see generateInternalStream
     */
    generateAsync: function(options, onUpdate) {
        return this.generateInternalStream(options).accumulate(onUpdate);
    },
    /**
     * Generate the complete zip file asynchronously.
     * @see generateInternalStream
     */
    generateNodeStream: function(options, onUpdate) {
        options = options || {};
        if (!options.type) {
            opti


---Colors
 * -----Textfield
 * -----Switch
 * -----Spinner
 * -----Radio
 * -----Menu
 * -----List
 * -----Layout
 * -----Icon toggles
 * -----Footer
 * -----Column
 * -----Checkbox
 * -----Card
 * -----Button
 * -----Animation
 * -----Progress
 * -----Badge
 * -----Shadows
 * -----Grid
 * -----Data table
 * -----Dialog
 * -----Snackbar
 * -----Tooltip
 * -----Chip
 *
 * Even though all variables have the `!default` directive, most of them
 * should not be changed as they are dependent one another. This can cause
 * visual distortions (like alignment issues) that are hard to track down
 * and fix.
 */
/* ==========  TYPOGRAPHY  ========== */
/* We're splitting fonts into "preferred" and "performance" in order to optimize
   page loading. For important text, such as the body, we want it to load
   immediately and not wait for the web font load, whereas for other sections,
   such as headers and titles, we're OK with things taking a bit longer to load.
   We do have some optional classes and parameters in the mixins, in case you
   definitely want to make sure you're using the preferred font and don't mind
   the performance hit.
   We should be able to improve on this once CSS Font Loading L3 becomes more
   widely available.
*/
/* ==========  COLORS  ========== */
/**
*
* Material design color palettes.
* @see http://www.google.com/design/spec/style/color.html
*
**/
/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* ==========  Color Palettes  ========== */
/* colors.scss */
/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* ==========  IMAGES  ========== */
/* ==========  Color & Themes  ========== */
/* ==========  Typography  ========== */
/* ==========  Components  ========== */
/* ==========  Standard Buttons  ========== */
/* ==========  Icon Toggles  ========== */
/* ==========  Radio Buttons  ========== */
/* ==========  Ripple effect  ========== */
/* ==========  Layout  ========== */
/* ==========  Content Tabs  ========== */
/* ==========  Checkboxes  ========== */
/* ==========  Switches  ========== */
/* ==========  Spinner  ========== */
/* ==========  Text fields  ========== */
/* ==========  Card  ========== */
/* ==========  Sliders ========== */
/* ========== Progress ========== */
/* ==========  List ========== */
/* ==========  Item ========== */
/* ==========  Drop


// SPDX-FileCopyrightText: Copyright (C) 2015 swift Project Community / Contributors
// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1

//! \file

#ifndef SWIFT_GUI_ENABLEFORVIEWBASEDINDICATOR_H
#define SWIFT_GUI_ENABLEFORVIEWBASEDINDICATOR_H

#include "gui/swiftguiexport.h"

namespace swift::gui::views
{
    class CViewBaseNonTemplate;
}
namespace swift::gui
{
    //! Hand over indication task to an embedded view
    class SWIFT_GUI_EXPORT CEnableForViewBasedIndicator
    {
    public:
        //! Enable loading indicator
        void enableLoadIndicator(bool enable);

        //! Showing load indicator?
        bool isShowingLoadIndicator() const;

        //! Show loading indicator
        int showLoadIndicator(std::chrono::milliseconds timeout = std::chrono::milliseconds(0));

        //! Hide loading indicator
        void hideLoadIndicator();

    protected:
        //! Constructor
        CEnableForViewBasedIndicator(views::CViewBaseNonTemplate *viewWithIndicator = nullptr);

        //! Set the corresponding view
        void setViewWithIndicator(swift::gui::views::CViewBaseNonTemplate *viewWithIndicator);

    private:
        views::CViewBaseNonTemplate *m_viewWithIndicator = nullptr;
    };

} // namespace swift::gui

#endif // SWIFT_GUI_ENABLEFORVIEWBASEDINDICATOR_H


, InvocationID)
    GLCASE(Layer)
    GLCASE(ViewportIndex)
    GLCASE(TessLevelOuter)
    GLCASE(TessLevelInner)
    GLCASE(TessCoord)
    GLCASE(PatchVertices)
    GLCASE(FragCoord)
    GLCASE(PointCoord)
    GLCASE(FrontFacing)
    GLCASE2(SampleId, SampleID)
    GLCASE(SamplePosition)
    GLCASE(SampleMask)
    GLCASE(FragDepth)
    GLCASE(HelperInvocation)
    GLCASE2(NumWorkgroups, NumWorkGroups)
    GLCASE2(WorkgroupSize, WorkGroupSize)
    GLCASE2(WorkgroupId, WorkGroupID)
    GLCASE2(LocalInvocationId, LocalInvocationID)
    GLCASE2(GlobalInvocationId, GlobalInvocationID)
    GLCASE(LocalInvocationIndex)
    CASE(WorkDim)
    CASE(GlobalSize)
    CASE(EnqueuedWorkgroupSize)
    CASE(GlobalOffset)
    CASE(GlobalLinearId)
    CASE(SubgroupSize)
    CASE(SubgroupMaxSize)
    CASE(NumSubgroups)
    CASE(NumEnqueuedSubgroups)
    CASE(SubgroupId)
    CASE(SubgroupLocalInvocationId)
    GLCASE(VertexIndex)
    GLCASE(InstanceIndex)
    GLCASE(BaseInstance)
    CASE(SubgroupEqMaskKHR)
    CASE(SubgroupGeMaskKHR)
    CASE(SubgroupGtMaskKHR)
    CASE(SubgroupLeMaskKHR)
    CASE(SubgroupLtMaskKHR)
    default:
      break;
  }
#undef GLCASE
#undef GLCASE2
#undef CASE
}

spv_result_t FriendlyNameMapper::ParseInstruction(
    const spv_parsed_instruction_t& inst) {
  const auto result_id = inst.result_id;
  switch (spv::Op(inst.opcode)) {
    case spv::Op::OpName:
      SaveName(inst.words[1], spvDecodeLiteralStringOperand(inst, 1));
      break;
    case spv::Op::OpDecorate:
      // Decorations come after OpName.  So OpName will take precedence over
      // decorations.
      //
      // In theory, we should also handle OpGroupDecorate.  But that's unlikely
      // to occur.
      if (spv::Decoration(inst.words[2]) == spv::Decoration::BuiltIn) {
        assert(inst.num_words > 3);
        SaveBuiltInName(inst.words[1], inst.words[3]);
      }
      break;
    case spv::Op::OpTypeVoid:
      SaveName(result_id, "void");
      break;
    case spv::Op::OpTypeBool:
      SaveName(result_id, "bool");
      break;
    case spv::Op::OpTypeInt: {
      std::string signedness;
      std::string root;
      const auto bit_width = inst.words[2];
      switch (bit_width) {
        case 8:
          root = "char";
          break;
        case 16:
          root = "short";
          break;
        case 32:
          root = "int";
          break;
        case 64:
          root = "long";
          break;
        default:
          root = to_string(bit_width);
          signedness = "i";
          break;
      }
      if (0 == inst.words[3]) signedness = "u";
      SaveName(result_id, signedness + root);
    } break;
    case spv::Op::OpTypeFloat: {
      const auto bit_width = inst.words[2];
      switch (bit_width) {
        case 16:
          SaveName(result_id, "half");
          break;
        case 32:
          SaveName(result_id, "float");
          break;
        case 64:
          SaveName(result_id, "double");
          break;
        default:
          SaveName(result_id, std::string("fp") + to_string(bit_width));
          break;
      }
    } break;
    case spv::Op::OpType


E51.m1.3.3.1.1.2.cmml" xref="A1.E51.m1.3.3.1.1.2"></eq><apply id="A1.E51.m1.3.3.1.1.3.cmml" xref="A1.E51.m1.3.3.1.1.3"><times id="A1.E51.m1.3.3.1.1.3.1.cmml" xref="A1.E51.m1.3.3.1.1.3.1"></times><apply id="A1.E51.m1.3.3.1.1.3.2.cmml" xref="A1.E51.m1.3.3.1.1.3.2"><csymbol cd="ambiguous" id="A1.E51.m1.3.3.1.1.3.2.1.cmml" xref="A1.E51.m1.3.3.1.1.3.2">subscript</csymbol><ci id="A1.E51.m1.3.3.1.1.3.2.2.cmml" xref="A1.E51.m1.3.3.1.1.3.2.2">𝜌</ci><ci id="A1.E51.m1.3.3.1.1.3.2.3a.cmml" xref="A1.E51.m1.3.3.1.1.3.2.3"><mtext id="A1.E51.m1.3.3.1.1.3.2.3.cmml" mathsize="70%" xref="A1.E51.m1.3.3.1.1.3.2.3">clm</mtext></ci></apply><ci id="A1.E51.m1.2.2.cmml" xref="A1.E51.m1.2.2">𝑟</ci></apply><apply id="A1.E51.m1.3.3.1.1.1.cmml" xref="A1.E51.m1.3.3.1.1.1"><times id="A1.E51.m1.3.3.1.1.1.2.cmml" xref="A1.E51.m1.3.3.1.1.1.2"></times><apply id="A1.E51.m1.1.1.cmml" xref="A1.E51.m1.1.1"><divide id="A1.E51.m1.1.1.2.cmml" xref="A1.E51.m1.1.1"></divide><apply id="A1.E51.m1.1.1.1.cmml" xref="A1.E51.m1.1.1.1"><times id="A1.E51.m1.1.1.1.2.cmml" xref="A1.E51.m1.1.1.1.2"></times><apply id="A1.E51.m1.1.1.1.3.cmml" xref="A1.E51.m1.1.1.1.3"><csymbol cd="ambiguous" id="A1.E51.m1.1.1.1.3.1.cmml" xref="A1.E51.m1.1.1.1.3">subscript</csymbol><ci id="A1.E51.m1.1.1.1.3.2.cmml" xref="A1.E51.m1.1.1.1.3.2">𝑓</ci><ci id="A1.E51.m1.1.1.1.3.3a.cmml" xref="A1.E51.m1.1.1.1.3.3"><mtext id="A1.E51.m1.1.1.1.3.3.cmml" mathsize="70%" xref="A1.E51.m1.1


ation := s[0].Duration()

	for _, sample := range s[1:] {
		if sampleDuration := sample.Duration(); shortestDuration > sampleDuration {
			shortestDuration = sampleDuration
		}
	}

	return shortestDuration
}

func (s Samples) LongestDuration() time.Duration {
	longestDuration := s[0].Duration()

	for _, sample := range s[1:] {
		if sampleDuration := sample.Duration(); longestDuration < sampleDuration {
			longestDuration = sampleDuration
		}
	}

	return longestDuration
}

type TestSuite struct {
	Name  string
	Cases []*TestCase
}

func (s *TestSuite) GetTestCase(testName string) *TestCase {
	for _, testCase := range s.Cases {
		if testCase.Name == testName {
			return testCase
		}
	}

	return nil
}

func (s *TestSuite) NewTestCase(testName string, delegate TestDelegate) {
	s.Cases = append(s.Cases, &TestCase{
		Name:     testName,
		Delegate: delegate,
	})
}

type TestOutput struct {
	content strings.Builder
}

func (s *TestOutput) Print(value string) {
	s.content.WriteString(value)
}

func (s *TestOutput) Printf(format string, arguments ...any) {
	s.Print(fmt.Sprintf(format, arguments...))
}

func (s *TestOutput) String() string {
	return s.content.String()
}

func (s *TestSuite) Execute(db graph.Database) error {
	fmt.Printf("Database test suite %s executing\n", s.Name)

	var (
		suiteStart  = time.Now()
		tableWriter = table.NewWriter()
	)

	tableWriter.AppendHeader(table.Row{"Test Case", "Samples Taken", "Test Case Duration", "Shortest Sample Duration", "Longest Sample Duration", "Average Sample Duration"})

	for _, testCase := range s.Cases {
		caseStart := time.Now()

		if err := testCase.execute(db); err != nil {
			return fmt.Errorf("test case \"%s\" failed: %w", testCase.Name, err)
		}

		testCase.Duration = time.Since(caseStart)
		tableWriter.AppendRow(table.Row{testCase.Name, len(testCase.Samples), testCase.Duration, testCase.Samples.ShortestDuration(), testCase.Samples.LongestDuration(), testCase.Samples.AverageDuration()})
	}

	fmt.Print(tableWriter.Render())
	fmt.Printf("\nDatabase test suite %s completed in %d ms.\n", s.Name, time.Since(suiteStart).Milliseconds())

	return nil
}

type TestCase struct {
	Name     string
	Delegate TestDelegate
	Samples  Samples
	Duration time.Duration
}

// TODO: Plumb neo4j query analysis?
func (s TestCase) EnableAnalysis() {
	//pg.EnableQueryAnalysis()
}

// TODO: Plumb neo4j query analysis?
func (s TestCase) DisableAnalysis() {
	//pg.DisableQueryAnalysis()
}

func (s *TestCase) Sample(delegate func() error) error {
	// Track a new sample for this logic
	s.Samples = append(s.Samples, Sample{
		Start: time.Now(),
	})

	// Run the test logic
	err := delegate()

	// Set the end time of the last sample and then return the captured error
	s.Samples[len(s.Samples)-1].End = time.Now()
	return err
}

func (s *TestCase) execute(db graph.Database) error {
	switch typedDelegate := s.Delegate(s).(type) {
	case func(tx graph