 under the License.

package outputs

import (
	"fmt"
	"sort"
	"strings"

	"github.com/google/gke-policy-automation/internal/policy"
)

const (
	defaultPolicyDocFileURLPrefix = "../"
	cisGKEURL                     = "https://cloud.google.com/kubernetes-engine/docs/concepts/cis-benchmarks#accessing-gke-benchmark"
)

type PolicyDocumentation interface {
	GenerateDocumentation() string
}

type MarkdownPolicyDocumentation struct {
	policies               []*policy.Policy
	policyDocFileURLPrefix string
}

type DocumentationBuilder func(policies []*policy.Policy) PolicyDocumentation

func NewMarkdownPolicyDocumentation(policies []*policy.Policy) PolicyDocumentation {
	return &MarkdownPolicyDocumentation{
		policies:               policies,
		policyDocFileURLPrefix: defaultPolicyDocFileURLPrefix,
	}
}

func (m *MarkdownPolicyDocumentation) GenerateDocumentation() string {
	sort.SliceStable(m.policies, func(i, j int) bool {
		if m.policies[i].Group == m.policies[j].Group {
			return m.policies[i].Title < m.policies[j].Title
		}
		return m.policies[i].Group < m.policies[j].Group
	})
	var sb strings.Builder
	sb.WriteString("|Name|Group|Description|CIS Benchmark|\n|-|-|-|-|\n")

	for _, p := range m.policies {
		policyFileURL := fmt.Sprintf("%s%s", m.policyDocFileURLPrefix, p.File)
		cis := ""
		if p.CisVersion != "" && p.CisID != "" {
			cis = fmt.Sprintf("[CIS GKE](%s) %s: %s", cisGKEURL, p.CisVersion, p.CisID)
		}
		sb.WriteString(fmt.Sprintf("|[%s](%s)|%s|%s|%s|\n", p.Title, policyFileURL, p.Group, p.Description, cis))
	}

	return sb.String()
}
// Copyright 2022 Google LLC
//
// 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.

package outputs

import (
	"fmt"
	"strings"
	"testing"

	"github.com/google/gke-policy-automation/internal/policy"
)

func buildPoliciesMetadata() []*policy.Policy {

	return []*policy.Policy{
		{
			Title:       "Second policy",
			Description: "Second description",
			Group:       "Group 2",
			File:        "gke-policies/file2.rego",
		},
		{
			Title:       "Third policy",
			Description: "Third description",
			Group:       "Group 1",
			File:        "gke-policies/file3.rego",
			CisVersion:  "1.2",
			CisID:       "5.3.1",
		},
		{
			Title:       "First policy",
			Description: "First description",
			Group:       "Group 1",
			File:        "gke-policies/file1.rego",
		},
	}
}

func TestMarkdownDocumention(t *testing.T) {
	var sb strings.Builder
	fmt.Fprintf(&sb, "|[First policy](%sgke-policies/file1.rego


);
		if ( iMarineIndex != -1 )
		{
			m_iKillsTotal += GetDebriefStats()->GetKills( iMarineIndex );
			m_iFFTotal += GetDebriefStats()->GetFriendlyFire( iMarineIndex );
			m_iDamageTotal += GetDebriefStats()->GetDamageTaken( iMarineIndex );
			m_iGamesTotal++;
			m_iGamesSuccess += ASWGameRules()->GetMissionSuccess() ? 1 : 0;
			m_fGamesSuccessPercent = m_iGamesSuccess / (float)m_iGamesTotal * 100.0f;
			m_iTimeTotal += GetDebriefStats()->m_fTimeTaken;
			if( ASWGameRules()->GetMissionSuccess() )
			{
				if( iDifficulty > m_iHighestDifficulty )
					m_iHighestDifficulty = iDifficulty;

				if( (unsigned int)m_iBestSpeedrunTimes[ iDifficulty - 1 ] > GetDebriefStats()->m_fTimeTaken )
				{
					m_iBestSpeedrunTimes[ iDifficulty - 1 ] = GetDebriefStats()->m_fTimeTaken;
				}
			}

			// Safely compute averages
			m_fKillsAvg = m_iKillsTotal / (float)m_iGamesTotal;
			m_fFFAvg = m_iFFTotal / (float)m_iGamesTotal;
			m_fDamageAvg = m_iDamageTotal / (float)m_iGamesTotal;
			m_iTimeAvg = m_iTimeTotal / (float)m_iGamesTotal;
		}
	}

	const char* szLevelName = NULL;
	if( !engine )
		return;

	szLevelName = engine->GetLevelNameShort();
	if( !szLevelName )
		return;

	// Send stats
	SEND_STEAM_STATS( CFmtStr( "%s%s", szLevelName, szGamesTotal ), m_iGamesTotal );
	SEND_STEAM_STATS( CFmtStr( "%s%s", szLevelName, szGamesSuccess ), m_iGamesSuccess );
	SEND_STEAM_STATS( CFmtStr( "%s%s", szLevelName, szGamesSuccessPercent ), m_fGamesSuccessPercent );
	SEND_STEAM_STATS( CFmtStr( "%s%s", szLevelName, szKillsTotal ), m_iKillsTotal );
	SEND_STEAM_STATS( CFmtStr( "%s%s", szLevelName, szDamageTotal ), m_iDamageTotal );
	SEND_STEAM_STATS( CFmtStr( "%s%s", szLevelName, szFFTotal ), m_iFFTotal );
	SEND_STEAM_STATS( CFmtStr( "%s%s", szLevelName, szTimeTotal ), m_iTimeTotal );
	SEND_STEAM_STATS( CFmtStr( "%s%s", szLevelName, szKillsAvg ), m_fKillsAvg );
	SEND_STEAM_STATS( CFmtStr( "%s%s", szLevelName, szDamageAvg ), m_fDamageAvg );
	SEND_STEAM_STATS( CFmtStr( "%s%s", szLevelName, szFFAvg ), m_fFFAvg );
	SEND_STEAM_STATS( CFmtStr( "%s%s", szLevelName, szTimeAvg ), m_iTimeAvg );
	SEND_STEAM_STATS( CFmtStr( "%s%s", szLevelName, szBestDifficulty ), m_iHighestDifficulty );
	SEND_STEAM_STATS( CFmtStr( "%s%s.%s", szLevelName, szBestTime, g_szDifficulties[ iDifficulty - 1 ] ), m_iBestSpeedrunTimes[ iDifficulty - 1 ] );
}

bool WeaponStats_t::FetchWeaponStats( CSteamAPIContext * pSteamContext, CSteamID playerSteamID, const char *sz


ting the requested MFALevel.
         *
         * @return The MFALevel related to the provided key, or {@link #UNKNOWN MFALevel.UNKNOWN} if the key is not recognized.
         */
        @Nonnull
        public static MFALevel fromKey(int key)
        {
            for (MFALevel level : values())
            {
                if (level.getKey() == key)
                    return level;
            }
            return UNKNOWN;
        }
    }

    /**
     * The Explicit-Content-Filter Level of a Guild.
     *
This decides whom's messages should be scanned for explicit content.
     */
    enum ExplicitContentLevel
    {
        OFF(0, "Don't scan any messages."),
        NO_ROLE(1, "Scan messages from members without a role."),
        ALL(2, "Scan messages sent by all members."),

        UNKNOWN(-1, "Unknown filter level!");

        private final int key;
        private final String description;

        ExplicitContentLevel(int key, String description)
        {
            this.key = key;
            this.description = description;
        }

        /**
         * The key for this level
         *
         * @return key
         */
        public int getKey()
        {
            return key;
        }

        /**
         * Description of this level in the official Discord Client (as of 5th May, 2017)
         *
         * @return Description for this level
         */
        @Nonnull
        public String getDescription()
        {
            return description;
        }

        @Nonnull
        public static ExplicitContentLevel fromKey(int key)
        {
            for (ExplicitContentLevel level : values())
            {
                if (level.key == key)
                    return level;
            }
            return UNKNOWN;
        }
    }

    /**
     * Represents the NSFW level for this guild.
     */
    enum NSFWLevel
    {
        /**
         * Discord has not rated this guild.
         */
        DEFAULT(0),
        /**
         * Is classified as a NSFW server
         */
        EXPLICIT(1),
        /**
         * Doesn't classify as a NSFW server
         */
        SAFE(2),
        /**
         * Is classified as NSFW and has an age restriction in place
         */
        AGE_RESTRICTED(3),
        /**
         * Placeholder for unsupported levels.
         */
        UNKNOWN(-1);

        private final int key;

        NSFWLevel(int key)
        {
            this.key = key;
        }

        /**
         * The Discord id key used to represent this NSFW level.
         *
         * @return Integer id for this NSFW level.
         */
        public int getKey()
        {
            return key;
        }

        /**
         * Used to retrieve a {@link net.dv8tion.jda.api.entities.Guild.NSFWLevel NSFWLevel} based
         * on the Discord id key.
         *
         * @param  key
         *         The Discord id key representing the requested NSFWLevel.
         *
         * @return The NSFWLevel related to the provided key, or {@link #UNKNOWN NSFWLevel.UNKNOWN} if the key is not recognized.
         */
        @Nonnull
        public static NSFWLevel fromKey(int key)
        {
            for (NSFWLevel level : values())
            {
                if (level.getKey() == key)
                    return level;
            }
            return UNKNOWN;
        }
    }

    /**
     * The boost tier for this guild.
     *
Each tier unlocks new perks for a guild that can be seen in the {@link #getFeatures() features}.
     *
     * @since  4.0.0
     */
    enum BoostTier
    {
        /**
         * The default tier.
         *
Unlocked at 0 boosters.
         */
        NONE(0, 96000, 50),
        /**
         * The first tier.
         *
Unlocked at 2 boosters.
         */
        TIER_1(


/****************************************************************************
 ****************************************************************************
 ***
 ***   This header was automatically generated from a Linux kernel header
 ***   of the same name, to make information necessary for userspace to
 ***   call into the kernel available to libc.  It contains only constants,
 ***   structures, and macros generated from the original header, and thus,
 ***   contains no copyrightable information.
 ***
 ***   To edit the content of this header, modify the corresponding
 ***   source file (e.g. under external/kernel-headers/original/) then
 ***   run bionic/libc/kernel/tools/update_all.py
 ***
 ***   Any manual change here will be lost the next time this script will
 ***   be run. You've been warned!
 ***
 ****************************************************************************
 ****************************************************************************/
#ifndef _UAPI_LINUX_UTSNAME_H
#define _UAPI_LINUX_UTSNAME_H
#define __OLD_UTS_LEN 8
struct oldold_utsname {
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 char sysname[9];
 char nodename[9];
 char release[9];
 char version[9];
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 char machine[9];
};
#define __NEW_UTS_LEN 64
struct old_utsname {
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 char sysname[65];
 char nodename[65];
 char release[65];
 char version[65];
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 char machine[65];
};
struct new_utsname {
 char sysname[__NEW_UTS_LEN + 1];
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 char nodename[__NEW_UTS_LEN + 1];
 char release[__NEW_UTS_LEN + 1];
 char version[__NEW_UTS_LEN + 1];
 char machine[__NEW_UTS_LEN + 1];
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 char domainname[__NEW_UTS_LEN + 1];
};
#endif


{

				while (B != E) {

					Vector3 *lv = vertex_hash.getptr(B->get());
					if (lv) {
						B->get().normal = lv->normalized();
					}

					B = B->next();
				}

			} else {
				B = E;
			}

			vertex_hash.clear();
			if (E) {
				smooth = smooth_groups[count];
				print_line("Smooth at " + itos(count) + ": " + itos(smooth));
			}
		}
	}

	format |= Mesh::ARRAY_FORMAT_NORMAL;

	if (was_indexed) {
		index();
		smooth_groups.clear();
	}
}

void SurfaceTool::set_material(const Ref<Material> &p_material) {

	material = p_material;
}

void SurfaceTool::clear() {

	begun = false;
	primitive = Mesh::PRIMITIVE_LINES;
	format = 0;
	last_bones.clear();
	last_weights.clear();
	index_array.clear();
	vertex_array.clear();
	smooth_groups.clear();
}

void SurfaceTool::_bind_methods() {

	ObjectTypeDB::bind_method(_MD("begin", "primitive"), &SurfaceTool::begin);

	ObjectTypeDB::bind_method(_MD("add_vertex", "vertex"), &SurfaceTool::add_vertex);
	ObjectTypeDB::bind_method(_MD("add_color", "color"), &SurfaceTool::add_color);
	ObjectTypeDB::bind_method(_MD("add_normal", "normal"), &SurfaceTool::add_normal);
	ObjectTypeDB::bind_method(_MD("add_tangent", "tangent"), &SurfaceTool::add_tangent);
	ObjectTypeDB::bind_method(_MD("add_uv", "uv"), &SurfaceTool::add_uv);
	ObjectTypeDB::bind_method(_MD("add_uv2", "uv2"), &SurfaceTool::add_uv2);
	ObjectTypeDB::bind_method(_MD("add_bones", "bones"), &SurfaceTool::add_bones);
	ObjectTypeDB::bind_method(_MD("add_weights", "weights"), &SurfaceTool::add_weights);
	ObjectTypeDB::bind_method(_MD("add_smooth_group", "smooth"), &SurfaceTool::add_smooth_group);

	ObjectTypeDB::bind_method(_MD("add_triangle_fan", "vertexes", "uvs", "colors", "uv2s", "normals", "tangents"), &SurfaceTool::add_triangle_fan, DEFVAL(Vector<Vector2>()), DEFVAL(Vector<Color>()), DEFVAL(Vector<Vector2>()), DEFVAL(Vector<Vector3>()), DEFVAL(Vector<Plane>()));

	ObjectTypeDB::bind_method(_MD("add_index", "index"), &SurfaceTool::add_index);

	ObjectTypeDB::bind_method(_MD("index"), &SurfaceTool::index);
	ObjectTypeDB::bind_method(_MD("deindex"), &SurfaceTool::deindex);
	ObjectTypeDB::bind_method(_MD("generate_normals"), &SurfaceTool::generate_normals);
	ObjectTypeDB::bind_method(_MD("generate_tangents"), &SurfaceTool::generate_tangents);

	ObjectTypeDB::bind_method(_MD("add_to_format", "flags"), &SurfaceTool::add_to_format);

	ObjectTypeDB::bind_method(_MD("set_material", "material:Material"), &SurfaceTool::set_material);

	ObjectTypeDB::bind_method(_MD("clear"), &SurfaceTool::clear);

	ObjectTypeDB::bind_method(_MD("create_from", "existing:Mesh", "surface"), &SurfaceTool::create_from);


quot;118", "GEOID": "2205", "GEOIDFQ": "5001800US2205", "LSAD": "C2", "NAMELSAD": "Congressional District 5", "STATEFP": "22", "hover_info": "No contracts"}, "type": "Feature"}, {"geometry": {"coordinates": [[[-82.859624, 28.174135], [-82.764103, 28.244345], [-82.73146, 28.325075], [-82.697433, 28.420166], [-82.6908136882946, 28.4333048573934], [-82.665055, 28.484434], [-82.656694, 28.544814], [-82.668149, 28.622411], [-82.6687096341287, 28.6940772618211], [-82.668722, 28.695658], [-82.712373, 28.720921], [-82.713121, 28.800283], [-82.730245, 28.850155], [-82.688864, 28.905609], [-82.723861, 28.953506], [-82.7555738086957, 29.0009301182604], [-82.712039, 29.030834], [-82.612653, 29.009271], [-82.535591, 29.044855], [-82.458566, 29.04765], [-82.349612, 28.988672], [-82.349429, 28.988848], [-82.348785, 28.988444], [-82.348359, 28.988884], [-82.347771, 28.989363], [-82.348672, 28.988262], [-82.347946, 28.987999], [-82.346926, 28.987977], [-82.346069, 28.987576], [-82.345512, 28.987202], [-82.345268, 28.987152], [-82.344417, 28.9874], [-82.344018, 28.987341], [-82.343154, 28.987369], [-82.341981, 28.987851], [-82.341251, 28.987943], [-82.340653, 28.98744], [-82.340548, 28.986935], [-82.340209, 28.986592], [-82.338332, 28.985722], [-82.337681, 28.985219], [-82.337315, 28.984004], [-82.337002, 28.983775], [-82.336064, 28.983639], [-82.3351, 28.983249], [-82.334552, 28.98286], [-82.334109, 28.982081], [-82.333796, 28.981852], [-82.333327, 28.982402], [-82.332234, 28.982494], [-82.331947, 28.982311], [-82.331503, 28.980937], [-82.331346, 28.980685], [-82.330408, 28.980478], [-82.329809, 28.980044], [-82.329496, 28.979129], [-82.329392, 28.979015], [-82.328715, 28.9789], [-82.328298, 28.979015], [-82.327413, 28.979106], [-82.326553, 28.978466], [-82.32564, 28.977526], [-82.324962, 28.977183], [-82.323764, 28.976954], [-82.323217, 28.976542], [-82.322435, 28.976244], [-82.323086, 28.975854], [-82.322747, 28.975374], [-82.3221


ckAddress && MmIsAddressValid((PVOID)CallbackAddress))
					{
						if (CallbackCount > sci->NumberOfCallbacks)
						{
							sci->CallbackEntry[sci->NumberOfCallbacks].Type = ct_NotifyCreateThread;
							sci->CallbackEntry[sci->NumberOfCallbacks].CallbackAddress = CallbackAddress;
							sci->CallbackEntry[sci->NumberOfCallbacks].Description = NotifyItem;
						}
						sci->NumberOfCallbacks++;
					}
				}
			}
		}
	}

	return TRUE;
}

/************************************************************************
*  Name : APGetPspLoadImageNotifyRoutineAddress
*  Param: void
*  Ret  : UINT_PTR
*  PspLoadImageNotifyRoutine
************************************************************************/
UINT_PTR
APGetPspLoadImageNotifyRoutineAddress()
{
	//  PsSetLoadImageNotifyRoutine ʹ PspLoadImageNotifyRoutine Ӳƫƻ
	/*
	Win7 x64:
	0: kd> u PsSetLoadImageNotifyRoutine l 10
	nt!PsSetLoadImageNotifyRoutine:
	fffff800`0429cb70 48895c2408      mov     qword ptr [rsp+8],rbx
	......
	fffff800`0429cb92 488d0d87c1d9ff  lea     rcx,[nt!PspLoadImageNotifyRoutine (fffff800`04038d20)]
	fffff800`0429cb99 4533c0          xor     r8d,r8d

	Win7 x86:
	0: kd> u PsSetLoadImageNotifyRoutine l 10
	nt!PsSetLoadImageNotifyRoutine:
	83f889ca 8bff            mov     edi,edi
	......
	83f889e1 7425            je      nt!PsSetLoadImageNotifyRoutine+0x3e (83f88a08)
	83f889e3 be40a8f583      mov     esi,offset nt!PspLoadImageNotifyRoutine (83f5a840)
	83f889e8 6a00            push    0
	*/

	UINT_PTR PspLoadImageNotifyRoutine = 0;
	UINT_PTR PsSetLoadImageNotifyRoutine = 0;

	APGetNtosExportVariableAddress(L"PsSetLoadImageNotifyRoutine", (PVOID*)&PsSetLoadImageNotifyRoutine);
	DbgPrint("%p\r\n", PsSetLoadImageNotifyRoutine);

	if (PsSetLoadImageNotifyRoutine)
	{
		PUINT8	StartSearchAddress = (PUINT8)PsSetLoadImageNotifyRoutine;
		PUINT8	EndSearchAddress = StartSearchAddress + 0x500;
		PUINT8	i = NULL;
		UINT8   v1 = 0, v2 = 0, v3 = 0;
		INT32   iOffset = 0;    // עƫƿɸ ܶUINT

		for (i = StartSearchAddress; i < EndSearchAddress; i++)
		{
#ifdef _WIN64
			if (MmIsAddressValid(i) && MmIsAddressValid(i + 1) && MmIsAddressValid(i + 2))
			{
				v1 = *i;
				v2 = *(i + 1);
				v3 = *(i + 2);
				if (v1 == 0x48 && v2 == 0x8d && v3 == 0x0d)		// Ӳ  lea rcx
				{
					RtlCopyMemory(&iOffset, i + 3, 4);
					PspLoadImageNotifyRoutine = (UINT_PTR)(iOffset + (UINT64)i + 7);
					break;
				}
			}
#else
			if (MmIsAddressValid(i) && MmIsAddressValid(i + 5) && MmIsAddressValid(i + 6))
			{
				v1 = *i;
				v2 = *(i + 5);
				v3 = *(i + 6);
				if (v1 == 0xbe && v2 == 0x6a && v3 == 0x00)		// Ӳ  lea rcx
				{
					RtlCopyMemory(&PspLoadImageNotifyRoutine, i + 1, 4);
					break;
				}
			}
#endif // _WIN64

		}
	}
	return PspLoadImageNotifyRoutine;
}

/************************************************************************
*  Name : APGetLoadImageCallbackNotify
*  Param: sci
*  Param: CallbackCount
*  Ret  : BOOLEAN
*  öټģص
************************************************************************/
BOOLEAN
APGetLoadImageCallbackNotify(OUT PSYS_CALLBACK_INFORMATION sci, IN UINT32 CallbackCount)
{
	UINT_PTR PspLoadImageNotifyRoutine = APGetPspLoadImageNotifyRoutineAddress();

	DbgPrint("%p\r\n", PspLoadImageNotifyRoutine);

	if (!PspLoadImageNotifyRoutine)
	{
		DbgPrint("PspLoadImageNotifyRoutineAddress NULL\r\n");
		return FALSE;
	}
	else
	{
		UINT32 i = 0;
		for (i = 0; i < PSP_MAX_LOAD_IMAGE_NOTIFY; i++)		// 64λСΪ64
		{
			UINT_PTR NotifyItem = 0;		// PspLoadImageNotifyRoutineÿһԱ
			UINT_PTR CallbackAddress = 0;	// ʵĻص̵ַ

			if (MmIsAddressValid((PVOID)(PspLoadImageNotifyRoutine + i * sizeof(UINT_PTR))))
			{
				NotifyItem = *(PUINT_PTR)(PspLoadImageNotifyRoutine + i * sizeof(UINT_PTR));

				if (NotifyItem > g_DynamicData.MinKernelSpaceAddress &&
					MmIsAddressValid((PVOID)(NotifyItem & ~7)))
				{
#ifdef _WIN64
					CallbackAddress = *(PUINT_PTR)(NotifyItem & ~7);
#else
					CallbackAddress = *(PUINT_PTR)((NotifyItem & ~7) + sizeof(UINT32));
#endif // _WIN64

					if (CallbackAddress && MmIsAddressValid((PVOID)CallbackAddress))
					{
						if (CallbackCount > sci->NumberOfCallbacks)
						{
							sci->CallbackEntry[sci->NumberOfCallbacks].Type = ct_NotifyLoadImage;
							sci->CallbackEntry[sci->NumberOfCallbacks].CallbackAddress = CallbackAddress;
							sci->CallbackEntry[sci->NumberOfCallbacks].Description = NotifyItem;
						}
						sci->NumberOfCallbacks++;
					}
				}
			}
		}
	}

	return TRUE;
}

//
// Win7֮ ListEntryṹ xp֮ǰ Vectorṹ
//
/*********************


(generateScoreFeedback(0)).toEqual('Oh no, please try again!')
    expect(generateScoreFeedback(1)).toEqual('Oh no, please try again!')
    expect(generateScoreFeedback(2)).toEqual('Oh no, please try again!')
    expect(generateScoreFeedback(3)).toEqual('I know you can do it better!')
    expect(generateScoreFeedback(4)).toEqual('I know you can do it better!')
    expect(generateScoreFeedback(5)).toEqual('I know you can do it better!')
    expect(generateScoreFeedback(6)).toEqual('You did it really good!')
    expect(generateScoreFeedback(7)).toEqual('You did it really good!')
    expect(generateScoreFeedback(8)).toEqual('Awesome! You are outstanding!')
    expect(generateScoreFeedback(9)).toEqual('Awesome! You are outstanding!')
    expect(generateScoreFeedback(10)).toEqual('Awesome! You are outstanding!')
  })
})
import { Directive, HostListener, Input, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { debounceTime, takeUntil } from 'rxjs/operators';

@Directive({
  // tslint:disable-next-line:directive-selector
  selector: 'input[name], textarea[name], select[name]'
})
export class InputNameDirective implements OnDestroy {
  /** subject to handle destroy */
  private destroy = new Subject<void>();
  /** subject to expose updates to the input */
  private valueSource = new Subject<any>();
  /** get the inputs name. Its always there as its part of the selector */
  @Input() name: string;
  /** get the inputs type. Optional, as none will be handled by the default handler */
  @Input() type: string;

  /**
   * Value$ is an observable that emits the value of
   * an input as soon as there are changes.
   */
  public value$ = this.valueSource.asObservable().pipe(
    /** make sure multiple events fire's don't mess up stuff. */
    debounceTime(50),
    /**
     * Note that we can't use distinctUntilChanged on this level
     * bcs the value of radio-buttons isn't related to its
     * changed status. We will take care of that in the
     * observable form upstream.
     */
    /** make sure it completes when the element gets destroyed. */
    takeUntil(this.destroy)
  );

  /**
   * Radio-buttons don't trigger change in a
   * particularly useful way. use a click for them.
   */
  @HostListener('click', ['$event']) private onClick(ev) {
    if (this.type !== 'radio') {
      /** only needed on radio buttons */
      return;
    }
    /**
     * handle radio button clicks, as the value stays the same,
     *  an onchange is unlikely to trigger switching radio
     * buttons. an upstream distinct will catch double's
     *
     * TODO: prevent double emit after form reset.
     */
    this.handleEvent(ev);
  }

  @HostListener('change', ['$event'])
  @HostListener('input', ['$event'])
  private handleEvent(ev) {
    switch (this.type) {
      case 'date':
        /** for date, use a real date, not the stringified version that seems allways off */
        this.valueSource.next(ev.target.valueAsDate);
        break;
      case 'number':
        /** Its s number, cast to a real number */
        this.valueSource.next(+ev.target.value);
        break;
      case 'checkbox':
        /** a checkbox is special, the checked properite holds its boolean value */
        this.valueSource.next(!!ev.target.checked);
        break;
      default:
        /** all other inputs, just emit the value of the input. */
        this.valueSource.next(ev.target.value);
    }
  }

  constructor() {}

  ngOnDestroy() {
    this.destroy.n


= "/tmp/itzo"
)

// when configuring these intervals we want the following constraints
// to be satisfied:
//
// 1. The pool interval should be longer than the heartbeat interval
// 2. The heartbeat interval should be longer than the heartbeat
// client timeout.
type NodeControllerConfig struct {
	PoolInterval           time.Duration
	HeartbeatInterval      time.Duration
	ReaperInterval         time.Duration
	ItzoVersion            string
	ItzoURL                string
	CellConfig             map[string]string
	UseCloudParameterStore bool
	DefaultIAMPermissions  string
}

type NodeController struct {
	Config             NodeControllerConfig
	NodeRegistry       *registry.NodeRegistry
	LogRegistry        *registry.LogRegistry
	PodReader          registry.PodLister
	NodeDispenser      *NodeDispenser
	NodeScaler         ScalingAlgorithm
	CloudClient        cloud.CloudClient
	NodeClientFactory  nodeclient.ItzoClientFactoryer
	Events             *events.EventSystem
	PoolLoopTimer      *stats.LoopTimer
	ImageIdCache       *timeoutmap.TimeoutMap
	CloudInitFile      *cloudinitfile.File
	CertificateFactory *certs.CertificateFactory
	BootLimiter        *InstanceBootLimiter
	BootImageSpec      cloud.BootImageSpec
}

func (c *NodeController) Start(quit <-chan struct{}, wg *sync.WaitGroup) {
	c.PoolLoopTimer = &stats.LoopTimer{}
	c.StopCreatingNodes()
	go c.ResumeWaits()
	go c.runHeartbeatsLoop(quit, wg)
	go c.reaperLoop(quit, wg)
	nodeBindingsUpdate := make(chan map[string]string)
	go c.updateBufferedNodesLoop(quit, wg, nodeBindingsUpdate)
	go c.dispatchNodesLoop(quit, wg, nodeBindingsUpdate)
	go c.ImageIdCache.Start(30 * time.Second)
}

func (c *NodeController) Dump() []byte {
	t := c.PoolLoopTimer.Copy()
	b, err := json.MarshalIndent(*t, "", "    ")
	if err != nil {
		klog.Errorln("Error dumping data from NodeController", err)
		return nil
	}
	return b
}

func (c *NodeController) updateBufferedNodesLoop(quit <-chan struct{}, wg *sync.WaitGroup, nodeBindingsUpdate chan map[string]string) {
	wg.Add(1)
	defer wg.Done()

	ticker := time.NewTicker(c.Config.PoolInterval)
	defer ticker.Stop()
	for {
		select {
		case <-quit:
			return
		default:
			select {
			case <-ticker.C:
				c.PoolLoopTimer.StartLoop()
				updatedBindings, err := c.doPoolsCalculation()
				if err != nil {
					klog.Errorln("Error adjusting node pools", err.Error())
				} else {
					nodeBindingsUpdate <- updatedBindings
				}
				c.PoolLoopTimer.EndLoop()
			case <-quit:
				return
			}
		}
	}
}

// Ensure that 2 instances of this don't run concurrently
// also ensure the node creation in the registry happens
// in this goroutine, otherwise our node scaling calculations
// will get thrown off
func (c *NodeController) doPoolsCalculation() (map[string]string, error) {
	nodes, err := c.NodeRegistry.ListNodes(registry.MatchAllNodes)
	if err != nil {
		return nil, util.WrapError(err, "Couldn't list nodes for pool calculation")
	}

	pods, err := c.PodReader.ListPods(func(p *api.Pod) bool {
		return registry.MatchAllLivePods(p)


 (fib) pending
check: hit Breakpoint 1
sameln: fib (n=3)
check: a = 0
check: b = 0
check: exited normally
"#,
    )?;
    Ok(())
}
#[cfg(target_os = "windows")]
use anyhow::anyhow;

use anyhow::Context;
use std::path::PathBuf;
use structopt::StructOpt;

mod output;
mod repos;
mod repostate;

#[derive(StructOpt)]
struct Options {
    top_dir: PathBuf,
}

fn main() -> anyhow::Result<()> {
    #[cfg(target_os = "windows")]
    ansi_term::enable_ansi_support()
        .map_err(|e| anyhow!("Failed to enable ANSI color support, error code: {}", e))?;

    let options = Options::from_args();
    output::print_changed(&options.top_dir)
        .with_context(|| format!("Failed to print changes of {}", options.top_dir.display()))?;
    Ok(())
}
<gh_stars>1-10
// run-rustfix
// aux-build:wildcard_imports_helper.rs

#![warn(clippy::wildcard_imports)]
//#![allow(clippy::redundant_pub_crate)]
#![allow(unused)]
#![warn(unused_imports)]

extern crate wildcard_imports_helper;

use crate::fn_mod::*;
use crate::mod_mod::*;
use crate::multi_fn_mod::*;
#[macro_use]
use crate::struct_mod::*;

#[allow(unused_imports)]
use wildcard_imports_helper::inner::inner_for_self_import;
use wildcard_imports_helper::inner::inner_for_self_import::*;
use wildcard_imports_helper::*;

use std::io::prelude::*;

struct ReadFoo;

impl Read for ReadFoo {
    fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
        Ok(0)
    }
}

mod fn_mod {
    pub fn foo() {}
}

mod mod_mod {
    pub mod inner_mod {
        pub fn foo() {}
    }
}

mod multi_fn_mod {
    pub fn multi_foo() {}
    pub fn multi_bar() {}
    pub fn multi_baz() {}
    pub mod multi_inner_mod {
        pub fn foo() {}
    }
}

mod struct_mod {
    pub struct A;
    pub struct B;
    pub mod inner_struct_mod {
        pub struct C;
    }

    #[macro_export]
    macro_rules! double_struct_import_test {
        () => {
            let _ = A;
        };
    }
}

fn main() {
    foo();
    multi_foo();
    multi_bar();
    multi_inner_mod::foo();
    inner_mod::foo();
    extern_foo();
    inner_extern_bar();

    let _ = A;
    let _ = inner_struct_mod::C;
    let _ = ExternA;

    double_struct_import_test!();
    double_struct_import_test!();
}

mod in_fn_test {
    pub use self::inner_exported::*;
    #[allow(unused_imports)]
    pub(crate) use self::inner_exported2::*;

    fn test_intern() {
        use crate::fn_mod::*;

        foo();
    }

    fn test_extern() {
        use wildcard_imports_helper::inner::inner_for_self_import::{self, *};
        use wildcard_imports_helper::*;

        inner_for_self_import::inner_extern_foo();
        inner_extern_foo();

        extern_foo();

        let _ = ExternA;
    }

    fn test_inner_nested() {


cher)
    }

inline var Button.textAllCaps: Boolean
    get() {
        return false
    }
    set(value) {
        isAllCaps = value
    }

inline var ConstraintHelper.referenceIds: String
    get() {
        return ""
    }
    set(value) {
        referencedIds = value.split(",").map { it.toLayoutId() }.toIntArray()
    }

var View.onClick: (View) -> Unit
    get() {
        return {}
    }
    set(value) {
        setOnClickListener { v -> value(v) }
    }

//</editor-fold>

//<editor-fold desc="View layout constant">
val match_parent = ViewGroup.LayoutParams.MATCH_PARENT
val wrap_content = ViewGroup.LayoutParams.WRAP_CONTENT

val visible = View.VISIBLE
val gone = View.GONE
val invisible = View.INVISIBLE

val horizontal = LinearLayout.HORIZONTAL
val vertical = LinearLayout.VERTICAL

val bold = Typeface.BOLD
val normal = Typeface.NORMAL
val italic = Typeface.ITALIC
val bold_italic = Typeface.BOLD_ITALIC

val gravity_center = Gravity.CENTER
val gravity_left = Gravity.LEFT
val gravity_right = Gravity.RIGHT
val gravity_bottom = Gravity.BOTTOM
val gravity_top = Gravity.TOP
val gravity_center_horizontal = Gravity.CENTER_HORIZONTAL
val gravity_center_vertical = Gravity.CENTER_VERTICAL

val scale_fix_xy = ImageView.ScaleType.FIT_XY
val scale_center_crop = ImageView.ScaleType.CENTER_CROP
val scale_center = ImageView.ScaleType.CENTER
val scale_center_inside = ImageView.ScaleType.CENTER_INSIDE
val scale_fit_center = ImageView.ScaleType.FIT_CENTER
val scale_fit_end = ImageView.ScaleType.FIT_END
val scale_matrix = ImageView.ScaleType.MATRIX
val scale_fit_start = ImageView.ScaleType.FIT_START

val spread = ConstraintLayout.LayoutParams.CHAIN_SPREAD
val packed = ConstraintLayout.LayoutParams.CHAIN_PACKED
val spread_inside = ConstraintLayout.LayoutParams.CHAIN_SPREAD_INSIDE

val parent_id = "0"
//</editor-fold>

//<editor-fold desc="layout helper function">
val Int.dp: Int
    get() {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            this.toFloat(),
            Resources.getSystem().displayMetrics
        ).toInt()
    }

fun ViewGroup.MarginLayoutParams.toConstraintLayoutParam() =
    ConstraintLayout.LayoutParams(width, height).also { it ->
        it.topMargin = this.topMargin
        it.bottomMargin = this.bottomMargin
        it.marginStart = this.marginStart
        it.marginEnd = this.marginEnd
    }

fun ViewGroup.LayoutParams.append(set: ConstraintLayout.LayoutParams.() -> Unit) =
    (this as? ConstraintLayout.LayoutParams)?.apply(set)
        ?: (this as? ViewGroup.MarginLayoutParams)?.toConstraintLayoutParam()?.apply(set)

fun String.toLayoutId(): Int {
    var id = java.lang.String(this).bytes.sum()
    if (id == 48) id = 0
    return id
}

fun <T : View> View.find(id: String): T? = findViewById(id.toLayoutId())

fun <T> View.observe(liveData: LiveData<T>?, action: (T) -> Unit) {
    (context as? LifecycleOwner)?.let { owner ->
        liveData?.observe(owner, Observer { action(it) })
    }
}

//</editor-fold>

//<editor-fold desc="listener helper class">
class TextWatcher(
    var beforeTextChanged: (
        text: CharSequence?,
        start: Int,
        count: Int,
        after: Int
    ) -> Unit = { _, _, _, _ ->


#region Disclaimer/Info

///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at subtext@googlegroups.com
//
// This project is licensed under the BSD license.  See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////

#endregion

using System;
using System.Collections.ObjectModel;
using MbUnit.Framework;
using Subtext.Framework.Infrastructure.Installation;

namespace UnitTests.Subtext.InstallationTests
{
    /// <summary>
    /// Tests of the <see cref="SqlInstallationProvider"/> class.
    /// </summary>
    [TestFixture]
    public class SqlInstallationProviderTests
    {
        /// <summary>
        /// Tests that we can properly list the installation scripts.
        /// </summary>
        [Test]
        public void ListInstallationScriptsReturnsCorrectScripts()
        {
            ReadOnlyCollection<string> scripts = SqlInstaller.ListInstallationScripts(null, new Version(1, 5, 0, 0));
            Assert.AreEqual(2, scripts.Count, "We expected to see two scripts.");
            Assert.AreEqual("Installation.01.00.00.sql", scripts[0], "Expected


%,transparent 100%)}}@media (min-width:1280px){.xl\:col-span-6{grid-column:span 6/span 6}.xl\:col-span-3{grid-column:span 3/span 3}.xl\:mt-0{margin-top:0}.xl\:block{display:block}.xl\:flex{display:flex}.xl\:hidden{display:none}.xl\:w-2\/5{width:40%}.xl\:items-center{align-items:center}.xl\:justify-between{justify-content:space-between}.xl\:text-7xl{font-size:4.5rem;line-height:1}}.\[\&_\.mention\]\:text-primary-600 .mention{--tw-text-opacity:1;color:rgb(var(--color-primary-600)/var(--tw-text-opacity))}.\[\&_\.mention\]\:text-white .mention{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity))}.\[\&_\.mention\]\:underline .mention{-webkit-text-decoration-line:underline;text-decoration-line:underline}.dark .dark\:\[\&_\.mention\]\:text-accent-blue .mention{--tw-text-opacity:1;color:rgb(var(--color-accent-blue)/var(--tw-text-opacity))}.\[\&_br\]\:hidden br,.\[\&_p\]\:hidden p{display:none}.\[\&_p\:first-child\]\:inline p:first-child{display:inline}.\[\&_p\:first-child\]\:truncate p:first-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
:root{--reach-combobox:1}[data-reach-combobox-popover]{--tw-bg-opacity:1;--tw-shadow:0 10px 15px -3px rgba(0,0,0,.1),0 4px 6px -4px rgba(0,0,0,.1);--tw-shadow-colored:0 10px 15px -3px var(--tw-shadow-color),0 4px 6px -4px var(--tw-shadow-color);background-color:rgb(255 255 255/var(--tw-bg-opacity));border-radius:.375rem;box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow);z-index:100}.dark [data-reach-combobox-popover]{--tw-bg-opacity:1;--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);--tw-ring-opacity:1;--tw-ring-color:rgb(var(--color-primary-700)/var(--tw-ring-opacity));background-color:rgb(var(--color-gray-900)/var(--tw-bg-opacity));box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}[data-reach-combobox-list]{list-style-type:none;margin:0;padding:.25rem 0;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}[data-reach-combobox-option]{--tw-text-opacity:1;color:rgb(var(--color-gray-700)/var(--tw-text-opacity));cursor:pointer;display:block;font-size:.875rem;line-height:1.25rem;padding:.625rem 1rem}.dark [data-reach-combobox-option]{--tw-text-opacity:1;color:rgb(var(--color-gray-500)/var(--tw-text-opacity))}[data-reach-combobox-option][aria-selected=true]{--tw-bg-o


local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)

function onCreatureAppear(cid)			npcHandler:onCreatureAppear(cid)			end
function onCreatureDisappear(cid)		npcHandler:onCreatureDisappear(cid)			end
function onCreatureSay(cid, type, msg)		npcHandler:onCreatureSay(cid, type, msg)		end
function onThink()		npcHandler:onThink()		end

local voices = {
	{ text = 'Precisely.' },
	{ text = 'So my initial calculations had been correct!' },
	{ text = 'Looks like I have to find another way then.' },
	{ text = 'Hm, I need to recapitulate my equipment...' }
}

npcHandler:addModule(VoiceModule:new(voices))

local function releasePlayer(cid)
	if not Player(cid) then
		return
	end

	npcHandler:releaseFocus(cid)
	npcHandler:resetNpc(cid)
end

local function creatureSayCallback(cid, type, msg)
	if not npcHandler:isFocused(cid) then
		return false
	end

	local player = Player(cid)
	if msgcontains(msg, 'mission') then
		local cStorage = player:getStorageValue(Storage.SeaOfLightQuest.Questline)
		if cStorage == -1 then
			npcHandler:say('Alright, you look bright enough to fulfil my requests - at least you do not fall asleep while standing there. Ahem... I heard about a certain inventor who created a {magic device} to actually sail the {sea of light}. Will you help me find him?', cid)
			npcHandler.topic[cid] = 1
		elseif cStorage == 1 then
			npcHandler:say('You should find the beggar somewhere in Edron. Stay persistent, I\'m sure he knows more than he wants to tell us.', cid)
		elseif cStorage == 2 then
			if not player:removeItem(10613, 1) then
				npcHandler:say('o have you talked to the beggar? What did he tell you? Where are the plans...? Wh...? He did? He is? You\'ve already got the plans? Beautiful!! Amazing! Alright it will take some time to recapitulate these plans.', cid)
				return true
			end

			player:addExperience(400, true)
			player:setStorageValue(Storage.SeaOfLightQuest.Questline, 3)
			player:setStorageValue(Storage.SeaOfLightQuest.Mission1, 3)
			player:setStorageValue(Storage.SeaOfLightQuest.StudyTimer, os.time() + 1800)
			npcHandler:say('So have you talked to the beggar? What did he tell you? Where are the plans...? Wh...? He did? He is? You\'ve already got the plans? Beautiful!! Amazing! Alright it will take some time to recapitulate these plans.', cid)
			addEvent(releasePlayer, 1000, cid)
		elseif cStorage == 3 then
			local timeStorage = player:getStorageValue(Storage.SeaOfLightQuest.StudyTimer)
			if timeStorage > os.time() then
				npcHandler:say('It will take some time to work out the initial problem of the device. Come back when I\'ve found the component needed to finish it. Alright, B connects to D and another two nails marked with S go... hmmm.', cid)
			elseif timeStorage > 0 and timeStorage < os.time() then
				npcHandler:say('...connects to N942. Alright!! That\'s it! I just finished a prototype device! And it looks like I figured out the initial failure. A very special crystal is needed for the device to work. Aren\'t you as curious as me to know what went wrong?', cid)
				npcHandler.topic[cid] = 2
			end
		elseif cStorage == 4 then
			npcHandler:say('Did you enter the Lost Mines yet? They are west of Edron, close to the sea. You will also need a pick once you get to the crystal deposit.', cid)
		elseif cS


rget({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER}) @interface TG {}
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER}) @interface TH {}
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER}) @interface TI {}
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER}) @interface TJ {}
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER}) @interface TK {}
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER}) @interface TL {}
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER}) @interface TM {}

@Repeatable(RTAs.class) @Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER}) @interface RTA {}
@Repeatable(RTBs.class) @Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER}) @interface RTB {}
@ContainerFor(RTA.class) @Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER}) @interface RTAs { RTA[] value(); }
@ContainerFor(RTB.class) @Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER}) @interface RTBs { RTB[] value(); }
@Target(value={ElementType.TYPE,ElementType.FIELD,ElementType.METHOD,ElementType.PARAMETER,ElementType.CONSTRUCTOR,ElementType.LOCAL_VARIABLE})
@interface Decl {}
/*
 * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.lang.annotation.*;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sun.tools.classfile.ClassFile;
import com.sun.tools.classfile.TypeAnnotation;
import com.sun.tools.classfile.TypeAnnotation.TargetType;

import static java.lang.String.format;

public class Driver {

    private static final PrintStream out = System.err;

    private final Object testObject;

    public Driver(Class<?> clazz) throws IllegalAccessException, InstantiationException {
        testObject = clazz.newInstance();
    }

    public static void main(String[] args) throws Exception {
        if (args.length == 0 || args.length > 1)
            throw new IllegalArgumentException("Usage: java Driver <test-name>");
        String name = args[0];
        new Driver(Class.forName(name)).runDriver();
    }

    private final String[][] extraParamsCombinations = new String[][] {
        new String[] { },
        new String[] { "-g" },
    };

    private final String[] retentionPolicies = {RetentionPolicy.CLASS.toString(), RetentionPolicy.RUNTIME.toString()};

    protected void runDriver() {
        int passed = 0, failed


glabel func_80A16618
/* 01398 80A16618 44800000 */  mtc1    $zero, $f0                 ## $f0 = 0.00
/* 0139C 80A1661C 27BDFFE8 */  addiu   $sp, $sp, 0xFFE8           ## $sp = FFFFFFE8
/* 013A0 80A16620 AFBF0014 */  sw      $ra, 0x0014($sp)
/* 013A4 80A16624 00803025 */  or      $a2, $a0, $zero            ## $a2 = 00000000
/* 013A8 80A16628 E480006C */  swc1    $f0, 0x006C($a0)           ## 0000006C
/* 013AC 80A1662C E4800070 */  swc1    $f0, 0x0070($a0)           ## 00000070
/* 013B0 80A16630 AFA60018 */  sw      $a2, 0x0018($sp)
/* 013B4 80A16634 24040005 */  addiu   $a0, $zero, 0x0005         ## $a0 = 00000005
/* 013B8 80A16638 0C01DF64 */  jal     Math_Rand_S16Offset

/* 013BC 80A1663C 24050023 */  addiu   $a1, $zero, 0x0023         ## $a1 = 00000023
/* 013C0 80A16640 8FA40018 *


"
	"reflect"
	"strings"
	"testing"

	"github.com/openbao/openbao/helper/identity"
	"github.com/openbao/openbao/helper/namespace"
	"github.com/openbao/openbao/sdk/v2/logical"
)

// Issue 5729
func TestIdentityStore_DuplicateAliases(t *testing.T) {
	c, _, _ := TestCoreUnsealed(t)

	resp, err := c.systemBackend.HandleRequest(namespace.RootContext(nil), &logical.Request{
		Path:      "auth",
		Operation: logical.ReadOperation,
	})
	if err != nil || (resp != nil && resp.IsError()) {
		t.Fatalf("bad: resp: %#v\nerr: %v", resp, err)
	}

	tokenMountAccessor := resp.Data["token/"].(map[string]interface{})["accessor"].(string)

	// Create an entity and attach an alias to it
	resp, err = c.identityStore.HandleRequest(namespace.RootContext(nil), &logical.Request{
		Path:      "entity-alias",
		Operation: logical.UpdateOperation,
		Data: map[string]interface{}{
			"mount_accessor": tokenMountAccessor,
			"name":           "testaliasname",
		},
	})
	if err != nil || (resp != nil && resp.IsError()) {
		t.Fatalf("bad: resp: %#v\nerr: %v", resp, err)
	}
	aliasID := resp.Data["id"].(string)

	// Create another entity without an alias
	resp, err = c.identityStore.HandleRequest(namespace.RootContext(nil), &logical.Request{
		Path:      "entity",
		Operation: logical.UpdateOperation,
	})
	if err != nil || (resp != nil && resp.IsError()) {
		t.Fatalf("bad: resp: %#v\nerr: %v", resp, err)
	}
	entityID2 := resp.Data["id"].(string)

	// Set the second entity ID as the canonical ID for the previous alias,
	// initiating an alias transfer
	resp, err = c.identityStore.HandleRequest(namespace.RootContext(nil), &logical.Request{
		Path:      "entity-alias/id/" + aliasID,
		Operation: logical.UpdateOperation,
		Data: map[string]interface{}{
			"canonical_id": entityID2,
		},
	})
	if err != nil || (resp != nil && resp.IsError()) {
		t.Fatalf("bad: resp: %#v\nerr: %v", resp, err)
	}

	// Read the new entity
	resp, err = c.identityStore.HandleRequest(namespace.RootContext(nil), &logical.Request{
		Path:      "entity/id/" + entityID2,
		Operation: logical.ReadOperation,
	})
	if err != nil || (resp != nil && resp.IsError()) {
		t.Fatalf("bad: resp: %#v\nerr: %v", resp, err)
	}

	// Ensure that there is only one alias
	aliases := resp.Data["aliases"].([]interface{})
	if len(aliases) != 1 {
		t.Fatalf("bad: length of aliases; expected: %d, actual: %d", 1, len(aliases))
	}

	// Ensure that no merging activity has taken place
	if len(aliases[0].(map[string]interface{})["merged_from_canonical_ids"].([]string)) != 0 {
		t.Fatal("expected no merging to take place")
	}
}

func TestIdentityStore_CaseInsensitiveEntityAliasName(t *testing.T) {
	ctx := namespace.RootContext(nil)
	i, accessor, _ := testIdentityStoreWithAppRoleAuth(ctx, t)

	// Create an entity
	resp, err := i.HandleRequest(ctx, &logical.Request{
		Path:      "entity",
		Operation: logical.UpdateOperation,
	})
	if err


@return {Zondy.LevelRenderer.Render} this。
     */
    addGroup(group) {
        this.storage.addRoot(group);
        return this;
    }

    /**
     * @function Zondy.LevelRenderer.Render.prototype.delShape
     * @description 从根节点删除图形形状。
     *
     * @param {string} shapeId - 图形对象唯一标识。
     * @return {Zondy.LevelRenderer.Render} this。
     */
    delShape(shapeId) {
        this.storage.delRoot(shapeId);
        return this;
    }

    /**
     * @function Zondy.LevelRenderer.Render.prototype.delGroup
     * @description 从根节点删除组。
     *
     * @param {string} groupId - 组对象唯一标识。
     * @return {Zondy.LevelRenderer.Render} this。
     */
    delGroup(groupId) {
        this.storage.delRoot(groupId);
        return this;
    }

    /**
     * @function Zondy.LevelRenderer.Render.prototype.modShape
     * @description 修改图形形状。
     *
     * @param {string} shapeId - 图形对象唯一标识。
     * @param {Zondy.LevelRenderer.Shape} shape - 图形对象。
     * @return {Zondy.LevelRenderer.Render} this。
     */
    modShape(shapeId, shape) {
        this.storage.mod(shapeId, shape);
        return this;
    }

    /**
     * @function Zondy.LevelRenderer.Render.prototype.modGroup
     * @description 修改组。
     *
     * @param {string} groupId - 组对象唯一标识。
     * @param {Zondy.LevelRenderer.Group} group - 组对象。
     * @return {Zondy.LevelRenderer.Render} this。
     */
    modGroup(groupId, group) {
        this.storage.mod(groupId, group);
        return this;
    }

    /**
     * @function Zondy.LevelRenderer.Render.prototype.modLayer
     * @description 修改指定 zlevel 的绘制配置项。
     *
     * @param {string} zLevel - 组对象唯一标识。
     * @param {Object} config - 配置对象。
     * @param {string} clearColor - 每次清空画布的颜色。默认值：0。
     * @param {boolean} motionBlur - 是否开启动态模糊。默认值：false。
     * @param {number}  lastFrameAlpha - 在开启动态模糊的时候使用，与上一帧混合的alpha值，值越大尾迹越明显。默认值：0.7。
     * @param {Array.<number>} position - 层的平移。
     * @param {Array.<number>} rotation - 层的旋转。
     * @param {Array.<number>} scale - 层的缩放。
     * @param {boolean} zoomable - 层是否支持鼠标缩放操作。默认值：false。
     * @param {boolean} panable - 层是否支持鼠标平移操作。默认值：false。
     * @return {Zondy.LevelRenderer.Render} this。
     */
    modLayer(zLevel, config) {
        this.painter.modLayer(zLevel, config);
        return this;
    }

    /**
     * @function Zondy.LevelRenderer.Render.prototype.addHoverShape
     * @description 添加额外高亮层显示，仅提供添加方法，每次刷新后高亮层图形均被清空。
     *
     * @param {Zondy.LevelRenderer.Shape} shape - 图形对象。
     * @return {Zondy.LevelRenderer.Render} this。
     */
    addHoverShape(shape) {
        this.storage.addHover(shape);
        return this


/*
 * Copyright (C) 2016 Red Hat, Inc.
 *
 * Author: Nikos Mavrogiannopoulos
 *
 * This file is part of GnuTLS.
 *
 * The GnuTLS is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

#ifndef GNUTLS_LIB_ACCELERATED_AARCH64_AARCH64_COMMON_H
# define GNUTLS_LIB_ACCELERATED_AARCH64_AARCH64_COMMON_H

#if !__ASSEMBLER__
#define NN_HASH(name, update_func, digest_func, NAME) {	\
 #name,						\
 sizeof(struct name##_ctx),			\
 NAME##_DIGEST_SIZE,				\
 NAME##_DATA_SIZE,				\
 (nettle_hash_init_func *) name##_init,		\
 (nettle_hash_update_func *) update_func,	\
 (nettle_hash_digest_func *) digest_func	\
}

void register_aarch64_crypto(void);
#endif

#define ARMV7_NEON      (1<<0)
#define ARMV7_TICK      (1<<1)
#define ARMV8_AES       (1<<2)
#define ARMV8_SHA1      (1<<3)
#define ARMV8_SHA256    (1<<4)
#define ARMV8_PMULL     (1<<5)
#define ARMV8_SHA512    (1<<6)

#endif /* GNUTLS_LIB_ACCELERATED_AARCH64_AARCH64_COMMON_H */


>Loading group information...

;
    }

    if (!group) {
        return (

Group Not Found

Cannot request to join a group that doesn't exist.

                <Link to="/portal/groups" className="btn-portal btn-portal-secondary">Back to Groups</Link>

        );
    }

    if (!group.isAcceptingNewMembers) {
        return (

Not Accepting New Members

This group, "{group.name}", is currently not accepting new member requests. Please check back later or contact the group leader.

                <Link to={`/portal/groups/details/${groupId}`} className="btn-portal btn-portal-secondary">View Group Details</Link>

        );
    }

    return (

 {/* Style .group-join-page */}

Request to Join: {group.name}

Led by: {group.leader}

            {submissionStatus === 'success' ? (

 {/* Style .portal-success */}

 Your request to join "{group.name}" has been sent to the group leader(s)!

They will be in touch with you soon regarding next steps.

                    <Link to={`/portal/groups/details/${groupId}`} className="btn-portal btn-portal-secondary" style={{marginRight: '10px'}}>View Group Details</Link>
                    <Link to="/portal/groups" className="btn-portal btn-portal-secondary">Back to All Groups</Link>

            ) : (
                <form onSubmit={handleSubmitJoinRequest} className="portal-form"> {/* Style .portal-form */}

Your name ({mockLoggedInUser.name}) and email ({mockLoggedInUser.email}) will be sent to the group leader(s) with your request.

                        Message to Leader(s) (Optional)
                        <textarea
                            id="message"
                            rows="4"
                            value={message}
                            onChange={(e) => setMessage(e.target.value)}
                            placeholder="e.g., I'm interested in learning more, any specific requirements for joining?"
                        ></textarea>

                        <button type="submit" className="btn-portal btn-portal-primary btn-lg" disabled={isSubmitting}>
                            {isSubmitting ? 'Sending Request...' : 'Send Join Request'}
                        </button>
                        <Link to={`/portal/groups/details/${groupId}`} className="btn-portal btn-portal-secondary" style={{marginLeft: '10px'}}>
                            Cancel
                        </Link>

                </form>
            )}

    );
};

export default GroupJoinPage;import React, { useState, useEffect,  } from 'react';
import './MyProfilePage.css';
import BackButton from '../BackButton';

// Mock Data - now more church-specific
const mockProfileData = {
    firstName: 'Valued',
    lastName: 'Member',
    birthDate: '1990-01-01',
    email: 'member@example.com',
    phoneMobile: '555-123-4567',
    addressStreet: '123 Church St, Anytown, TX',
    membershipStatus: 'Active Member',
    joinDate: '2018-05-12',
    maritalStatus: 'Married',
    allergies: 'Peanuts (anaphylactic)',
    spiritualGifts: ['Teaching', 'Hospitality'],
    family: [
        { id: 'f002', name: 'Jane Member', relationship: 'Spouse' },
        { id: 'f003', name: 'Sam Memb


ap() == 80 and MAX_LEVEL >= 85 and player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.EXPANDING_HORIZONS) == QUEST_AVAILABLE) then
        player:startEvent(10045, 0, 1, 2, 0)
    elseif (player:getMainLvl() >= 81 and player:levelCap() == 85 and MAX_LEVEL >= 90 and player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.BEYOND_THE_STARS) == QUEST_AVAILABLE) then
        player:startEvent(10045, 0, 1, 3, 0)
    elseif (player:getMainLvl() >= 86 and player:levelCap() == 90 and MAX_LEVEL >= 95 and player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.DORMANT_POWERS_DISLODGED) == QUEST_AVAILABLE) then
        player:startEvent(10045, 0, 1, 4, 0)
    elseif (player:getMainLvl() >= 91 and player:levelCap() == 95 and MAX_LEVEL == 99 and player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.PRELUDE_TO_PUISSANCE) == QUEST_AVAILABLE) then
        player:startEvent(10194)
    elseif player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.PRELUDE_TO_PUISSANCE) == QUEST_COMPLETED and player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.BEYOND_INFINITY) == QUEST_AVAILABLE and player:getLocalVar("MaybeAnotherTimeCS") == 1 then
        player:startEvent(10045, 0, 1, 5, 0, 1)
    elseif player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.PRELUDE_TO_PUISSANCE) == QUEST_COMPLETED and player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.BEYOND_INFINITY) == QUEST_AVAILABLE then
        player:startEvent(10045, 0, 1, 5)
    elseif player:getCharVar("BeyondInfinityCS") == 2 then
        player:startEvent(10139)
    elseif (player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.NEW_WORLDS_AWAIT) == QUEST_ACCEPTED) then
        player:startEvent(10045, 0, 1, 1, 1)
    elseif (player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.EXPANDING_HORIZONS) == QUEST_ACCEPTED) then
        player:startEvent(10045, 0, 1, 2, 1)
    elseif (player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.BEYOND_THE_STARS) == QUEST_ACCEPTED) then
        player:startEvent(10045, 0, 1, 3, 1)
    elseif (player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.DORMANT_POWERS_DISLODGED) == QUEST_ACCEPTED) then
        player:startEvent(10045, 0, 1, 4, 1)
    elseif (player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.PRELUDE_TO_PUISSANCE) == QUEST_ACCEPTED) then
        player:startEvent(10045, 0, 1, 6, 2)
    elseif  player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.BEYOND_INFINITY) == QUEST_ACCEPTED and player:hasKeyItem(tpz.ki.SOUL_GEM_CLASP) then
        player:startEvent(10045, 0, 1, 5, 1)
    elseif player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.BEYOND_INFINITY) == QUEST_ACCEPTED and player:getCharVar("BeyondInfinityCS") == 1 then
        if player:getMeritCount() >= 1 then
            player:startEvent(10045, 0, 1, 5, 3, 0, 0, 1)
        else


: "a",
			},
		},
		{
			Method:   "GET",
			Resource: "/api/2.0/preview/scim/v2/Users?excludedAttributes=roles&filter=userName%20eq%20%22searching_error%22",
			Status:   404,
			Response: apierr.APIError{
				Message: "searching_error",
			},
		},
		{
			Method:   "GET",
			Resource: "/api/2.0/preview/scim/v2/Users?excludedAttributes=roles&filter=userName%20eq%20%22empty_search%22",
			Response: UserList{},
		},
	}, func(ctx context.Context, client *common.DatabricksClient) {
		usersAPI := NewUsersAPI(ctx, client)
		user, err := getUser(usersAPI, "a", "")
		assert.NoError(t, err)
		assert.Equal(t, "a", user.ID)

		_, err = getUser(usersAPI, "", "searching_error")
		assert.EqualError(t, err, "searching_error")

		_, err = getUser(usersAPI, "", "empty_search")
		assert.EqualError(t, err, "cannot find user empty_search")
	})
}
package scim

import (
	"testing"

	"github.com/databricks/terraform-provider-databricks/qa"
	"github.com/stretchr/testify/assert"
)

func TestDataServicePrincipalReadByAppId(t *testing.T) {
	qa.ResourceFixture{
		Fixtures: []qa.HTTPFixture{
			{
				Method:   "GET",
				Resource: "/api/2.0/preview/scim/v2/ServicePrincipals?excludedAttributes=roles&filter=applicationId%20eq%20%22abc%22",
				Response: UserList{
					Resources: []User{
						{
							ID:            "abc",
							DisplayName:   "Example Service Principal",
							Active:        true,
							ApplicationID: "abc",
							Groups: []ComplexValue{
								{
									Display: "admins",
									Value:   "4567",
								},
								{
									Display: "ds",
									Value:   "9877",
								},
							},
						},
					},
				},
			},
		},
		Resource:    DataSourceServicePrincipal(),
		HCL:         `application_id = "abc"`,
		Read:        true,
		NonWritable: true,
		ID:          "abc",
	}.ApplyAndExpectData(t, map[string]any{
		"scim_id":          "abc",
		"id":               "abc",
		"application_id":   "abc",
		"display_name":     "Example Service Principal",
		"active":           true,
		"home":             "/Users/abc",
		"repos":            "/Repos/abc",
		"acl_principal_id": "servicePrincipals/abc",
	})
}

func TestDataServicePrincipalReadBySpId(t *testing.T) {
	qa.ResourceFixture{
		Fixtures: []qa.HTTPFixture{
			{
				Method:   "GET",
				Resource: "/api/2.0/preview/scim/v2/ServicePrincipals?excludedAttributes=roles&filter=id%20eq%20%22abc%22",
				Response: UserList{
					Resources: []User{
						{
							ID:            "abc",
							DisplayName:   "Example Service Principal",
							Active:        true,
							ApplicationID: "abc",
							Groups: []ComplexValue{
								{
									Display: "admins",
									Value:   "4567",
								},
								{
									Display: "ds",
									Value:   "9877",
								},
							},
						},
					},


icY2BkYGAwYwpmsGAAASYgZmQAiTkw6IEEABYoATcAeJydj0FqAkEQRX87oyBk4SILl4Vre+geYQgewKzcirhTGaRBpqHVRS6Sk+RCuUl+j7WJEAI2fOpR/OpfBeAFnzDIz2CCmfKA/bVygTm+lEtMTKE8JDfKI3Kg05RjdqSfyjzAFAvlAlvslEt6vpWHEPOqPCK/o8UNAZY6IqIjnckHJOypD6C9BRuOsbPncEj7xM6f1t+2VW+69jXhxCRBjQqOdUn9l3x3ed5k0VA1Jz3e+HHsrquYTq3UlZOlPG7Ill/YxtbO0/3EgRsOJVxoywPC3Jxc9TVvj02bLiF24pyvnHPyTMoP3RNYZgB4nG2SiXLaMBCG+cnBkQBNQpKm932r9/R9hLzYGmTJ6Ajl7fpmreQxpoVqxqP9P++udlfqdDv1+v2rcxM3dHbXj5p20cUBDnGEY/TQxwBDnOAUI4wxwR2c4RwXmOISV7jGXdzgHu7jAR7iER7jCZ7iGZ7jBV7iFV7jDd7iHd7jAxg+4hM+4wu+4hu+90RBYsHMUb0PhVGKhJdGj+accSVzzRTN/TQpa82KCWmFIpaZld6DyfNyF1qZF/58l4bqJCLBFemM21FtW/J1inGr6tirJAu6tUb/ffp/cAq+3sd1luk+D1Vypp+erOaKKakXzC1DPDmVO+eCZsZsUD+iXJkZpQZzY/KYoFLBNb/H/9JelClfaqzkVfzsguwgKkfciiI174z1jDtxurEzcqLXiEncvSzJNcWeJb2SPtbanDjckpQt6BRGWQq8lRmZOMKSLE9uaxN8mFEvt1wHRYeaO36grR9aWgZpKWOmvzEvXMZmPMuJcV8aVxVkacuEXTds0rIilFy7UasV19m4VUYQ11vpjOJ1vc0dmEFrp8pLqcOm5TRSqeemkcdRWucm237ipPk6DWzGrUtXtgzk0tttIv4AigAP/A==") format("woff");
  font-weight: 400;
  font-style: normal
}
.eui-icon {
  display: inline-block;
  font: normal normal normal 14px/1 eui-icon-library;
  font-size: inherit;
  text-rendering: auto;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale
}
.eui-nasa:before {
  content: "\f123"
}
.eui-sd-badge-atmosphere:before {
  content: "\f127"
}
.eui-sd-badge-cryosphere:before {
  content: "\f128"
}
.eui-sd-badge-humans:before {
  content: "\f129"
}
.eui-sd-bad


dices:
            box = boxes[i]
            left = box[0]
            top = box[1]
            width = box[2]
            height = box[3]
            frame = self.drawPred(frame, classIds[i], confidences[i], left, top, left + width, top + height)
        return frame

    def drawPred(self, frame, classId, conf, left, top, right, bottom):
        # Draw a bounding box.
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), thickness=4)

        label = '%.2f' % conf
        label = '%s:%s' % (self.classes[classId], label)

        # Display the label at the top of the bounding box
        labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
        top = max(top, labelSize[1])
        # cv.rectangle(frame, (left, top - round(1.5 * labelSize[1])), (left + round(1.5 * labelSize[0]), top + baseLine), (255,255,255), cv.FILLED)
        cv2.putText(frame, label, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), thickness=2)
        return frame

    def detect(self, srcimg):
        img, newh, neww, padh, padw = self.resize_image(srcimg)
        img = self.preprocess(img)
        # Sets the input to the network
        blob = np.expand_dims(np.transpose(img, (2, 0, 1)), axis=0)

        outs = self.net.run(None, {self.net.get_inputs()[0].name: blob})[0].squeeze(axis=0)

        # inference output
        row_ind = 0
        for i in range(self.nl):
            h, w = int(img.shape[0] / self.stride[i]), int(img.shape[1] / self.stride[i])
            length = int(self.na * h * w)
            if self.grid[i].shape[2:4] != (h, w):
                self.grid[i] = self._make_grid(w, h)

            outs[row_ind:row_ind + length, 0:2] = (outs[row_ind:row_ind + length, 0:2] * 2. - 0.5 + np.tile(
                self.grid[i], (self.na, 1))) * int(self.stride[i])
            outs[row_ind:row_ind + length, 2:4] = (outs[row_ind:row_ind + length, 2:4] * 2) ** 2 * np.repeat(
                self.anchor_grid[i], h * w, axis=0)
            row_ind += length
        srcimg = self.postprocess(srcimg, outs, padsize=(newh, neww, padh, padw))
        return srcimg

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--imgpath', type=str, default='images/bus.jpg', help="image path")
    parser.add_argument('--modelpath', type=str, default='weights/yolov5s.onnx')
    parser.add_argument('--confThreshold', default=0.3, type=float, help='class confidence')
    parser.add_argument('--nmsThreshold', default=0.5, type=float, help='nms iou thresh')
    parser.add_argument('--objThreshold', default=0.3, type=float, help='object confidence')
    args = parser.parse_args()

    yolonet = yolov5(args.modelpath, confThreshold=args.confThreshold, nmsThreshold=args.nmsThreshold,
                     objThreshold=args.objThreshold)
    srcimg = cv2.imread(args.imgpath)
    srcimg = yolonet.detect(srcimg)

    winName = 'Deep learning object detection in ONNXRuntime'
    cv2.namedWindow(winName, 0)
    cv2.imshow(winName, srcimg)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


data-togglable=":orca-api:dokkaHtml/main">
PreconfiguredStageParameter.ParameterType getType()<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path fill-rule="evenodd" clip-rule="evenodd" d="M5 4H15V16H5V4ZM17 7H19V18V20H17H8V18H17V7Z" fill="black"/>
                       </svg>
<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M18 9C18 14 14 18 9 18C4 18 0 14 0 9C0 4 4 0 9 0C14 0 18 4 18 9ZM14.2 6.2L12.8 4.8L7.5 10.1L5.3 7.8L3.8 9.2L7.5 13L14.2 6.2Z" fill="#4DBB5F"/>
</svg>Content copied to clipboard

setDefaultValue<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M21.2496 5.3C20.3496 4.5 19.2496 4 18.0496 4C16.8496 4 15.6496 4.5 14.8496 5.3L10.3496 9.8L11.7496 11.2L16.2496 6.7C17.2496 5.7 18.8496 5.7 19.8496 6.7C20.8496 7.7 20.8496 9.3 19.8496 10.3L15.3496 14.8L16.7496 16.2L21.2496 11.7C22.1496 10.8 22.5496 9.7 22.5496 8.5C22.5496 7.3 22.1496 6.2 21.2496 5.3Z"/>
    <path d="M8.35 16.7998C7.35 17.7998 5.75 17.7998 4.75 16.7998C3.75 15.7998 3.75 14.1998 4.75 13.1998L9.25 8.6998L7.85 7.2998L3.35 11.7998C1.55 13.5998 1.55 16.3998 3.35 18.1998C4.25 19.0998 5.35 19.4998 6.55 19.4998C7.75 19.4998 8.85 19.0998 9.75 18.1998L14.25 13.6998L12.85 12.2998L8.35 16.7998Z"/>
</svg>

<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M18 9C18 14 14 18 9 18C4 18 0 14 0 9C0 4 4 0 9 0C14 0 18 4 18 9ZM14.2 6.2L12.8 4.8L7.5


/**
     * Returns peer of the given client component. If the given client component
     * doesn't have peer, peer of the native container of the client is returned.
     */
    protected ComponentPeer getPeer(Component client) {
        XComponentPeer peer;

        if (log.isLoggable(Level.FINE)) log.fine("Client is " + client);
        peer = (XComponentPeer)XToolkit.targetToPeer(client);
        while (client != null && peer == null) {
            client = getParent(client);
            peer = (XComponentPeer)XToolkit.targetToPeer(client);
        }
        log.log(Level.FINE, "Peer is {0}, client is {1}", new Object[] {peer, client});

        if (peer != null)
            return peer;

        return null;
    }

    /*
     * Subclasses should override disposeImpl() instead of dispose(). Client
     * code should always invoke dispose(), never disposeImpl().
     */
    protected synchronized void disposeImpl() {
        super.disposeImpl();
        clientComponentWindow = null;
    }

    protected void awtLock() {
        XToolkit.awtLock();
    }

    protected void awtUnlock() {
        XToolkit.awtUnlock();
    }

    long getCurrentParentWindow() {
        return (long)((XWindow)clientComponentWindow.getPeer()).getContentWindow();
    }

    /*
     * Native methods
     */
    private native boolean openXIMNative(long display);
    private native boolean createXICNative(long window);
    private native void setXICFocusNative(long window,
                                    boolean value, boolean active);
    private native void adjustStatusWindow(long window);
}
/*
 * Copyright 2003-2007 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

package sun.awt.X11;

import java.awt.*;
import sun.awt.*;
import java.util.logging.*;
import java.util.*;

public class XBaseWindow implements XConstants, XUtilConstants {
    private static final Logger log = Logger.getLogger("sun.awt.X11.XBaseWindow");
    private static final Logger insLog = Logger.getLogger("sun.awt.X11.insets.XBaseWindow");
    private static final Logger eventLog = Logger.getLogger("sun.awt.X11.event.XBaseWindow");
    private static final Logger focusLog = Logger.getLogger("sun.awt.X11.focus.XBaseWindow");
    private static final Logger grabLog = Logger.getLogger("sun.awt.X11.grab.XBaseWindow");

    public static final String
        PARENT_WINDOW = "parent window", // parent window, Long
        BOUNDS = "bounds", // bounds of the window, Rectangle
        OVERRIDE_REDIRECT = "overrideRedirect", // override_redirect setting, Boolean
        EVENT_MASK = "event mask", // event mask, Integer
        VALUE_MASK = "value mask", // value mask, Long
        BORDER_PIXEL = "b


() > 0 && atoms_b.len() > 0{
            ppenergyset.atom_contact_energy.push(pp_energy::AtomContactEnergy{
                atoms_a:atoms_a,
                atoms_b:atoms_b,
                threshold:6.0,//ここ CB の時は 8.0 にする
                linear_penalty:0.1,
                energy:*v
            });
        }else{
            eprintln!("???contact {:?} was not found. a {} b {}", (c1,r1,c2,r2,v) ,atoms_a.len(),atoms_b.len());
        }
    }

    if residue_missing.len() > 0{
        //Missing 領域の作成
        if let Some(p1) = missing_params.as_ref(){
        build_missing(
            &mut ppenergyset
            , &sorted_atoms
            , &residue_missing
            , &fixflag
            , p1.fix_omega
            , &mut rgen
            , 1.0
            , p1.phipsi_top_x
            , &p1.param1
            , &p1.param2
            ,p1.num_structures_step1
            ,p1.num_structures_step2);
        }
    }

    let mut atom_based_energies:Vec<f64> = vec![0.0;num_atoms];
    let mut check_count:usize = 0;
    for rebuilder in 0..(rebuild_param.rebuild_iter+1){
        if rebuilder > 0 && rebuild_param.rebuild_region > 0{
            if let Some(p1) = missing_params.as_ref(){
                /*
                ppenergyset.update_distance();
                for aa in atom_based_energies.iter_mut(){
                    *aa = 0.0;
                }
                ppenergyset.calc_energy(&mut atom_based_energies);
                let mut res_energies:Vec<(String,usize,f64)> = vec![];
                for (kk,vv) in sorted_atoms.iter(){
                    for (vii,vvv) in vv.iter().enumerate(){
                        let mut scc:f64 = 0.0;
                        for aa in vvv.iter(){
                            scc += atom_based_energies[*aa];
                        }
                        res_energies.push((kk.clone(),vii,scc));
                    }
                }
                res_energies.sort_by(|a,b|(a.2).partial_cmp(&b.2).unwrap());
                */

                for (kk,vv) in sorted_atoms.iter(){
                    let rnum:usize = vv.len();
                    let mut partial:Vec<(f64,Vec<usize>)> = vec![];

                    ppenergyset.update_distance();
                    zerofill(&mut atom_based_energies);
                    let _scoree = ppenergyset.calc_energy(&mut atom_based_energies);
                    let plen:usize = rebuild_param.rebuild_region;//構築を試みる領域の長さ
                    let num_region:usize = rebuild_param.rebuild_num;//構築を試みる領域の数
                    let loopnum = rnum/plen+1;
                    for _ in 0..loopnum{
                        let s:usize = rgen.gen_range(0,rnum);
                        let mut pp:Vec<usize> = vec![s];
                        for o in 1..(plen/2){
                            let po:i64 = s as i64 - o as i64;
                            if po > -1{
                                pp.push(po as usize);
                            }
                            let po:i64 = s as i64 + o as i64;
                            if po < rnum as i64{
                                pp.push(po as usize);
                            }
                        }
                        pp.sort();
                        let mut pscore:f64 = 0.0;
                        for ppp in pp.iter(){
                            for aaa in vv[*ppp].iter(){
                                pscore += atom_based_energies[*aaa];
                            }
                        }


!= NULL && (insert_list != _insert_list || insert_idx != _insert_idx)) {
    // insert position changed -> resolve current mappings
    resolve_mappings();
  }

  if (insert_list != _insert_list) {
    // block changed -> append insertion_buffer because it is
    // bound to a specific block and create a new insertion_buffer
    append_insertion_buffer();
    create_insertion_buffer(insert_list);
  }

  _insert_list = insert_list;
  _insert_idx = insert_idx;
}

void MoveResolver::add_mapping(Interval* from_interval, Interval* to_interval) {
  TRACE_LINEAR_SCAN(4, tty->print_cr("MoveResolver: adding mapping from %d (%d, %d) to %d (%d, %d)", from_interval->reg_num(), from_interval->assigned_reg(), from_interval->assigned_regHi(), to_interval->reg_num(), to_interval->assigned_reg(), to_interval->assigned_regHi()));

  _mapping_from.append(from_interval);
  _mapping_from_opr.append(LIR_OprFact::illegalOpr);
  _mapping_to.append(to_interval);
}

void MoveResolver::add_mapping(LIR_Opr from_opr, Interval* to_interval) {
  TRACE_LINEAR_SCAN(4, tty->print("MoveResolver: adding mapping from "); from_opr->print(); tty->print_cr(" to %d (%d, %d)", to_interval->reg_num(), to_interval->assigned_reg(), to_interval->assigned_regHi()));
  assert(from_opr->is_constant(), "only for constants");

  _mapping_from.append(NULL);
  _mapping_from_opr.append(from_opr);
  _mapping_to.append(to_interval);
}

void MoveResolver::resolve_and_append_moves() {
  if (has_mappings()) {
    resolve_mappings();
  }
  append_insertion_buffer();
}

// **** Implementation of Range *************************************

Range::Range(int from, int to, Range* next) :
  _from(from),
  _to(to),
  _next(next)
{
}

// initialize sentinel
Range* Range::_end = NULL;
void Range::initialize(Arena* arena) {
  _end = new (arena) Range(max_jint, max_jint, NULL);
}

int Range::intersects_at(Range* r2) const {
  const Range* r1 = this;

  assert(r1 != NULL && r2 != NULL, "null ranges not allowed");
  assert(r1 != _end && r2 != _end, "empty ranges not allowed");

  do {
    if (r1->from() < r2->from()) {
      if (r1->to() <= r2->from()) {
        r1 = r1->next(); if (r1 == _end) return -1;
      } else {
        return r2->from();
      }
    } else if (r2->from() < r1->from()) {
      if (r2->to() <= r1->from()) {
        r2 = r2->next(); if (r2 == _end) return -1;
      } else {
        return r1->from();
      }
    } else { // r1->from() == r2->from()
      if (r1->from() == r1->to()) {
        r1 = r1->next(); if (r1 == _end) return -1;
      } else if (r2->from() == r2->to()) {
        r2 = r2->next(); if (r2 == _end) return -1;
      } else {
        return r1->from();
      }
    }
  } while (true);
}

#ifndef PRODUCT
void Range::print(outputStream* out) const {
  out->print("[%d, %d[ ", _from, _to);
}
#endif

// **** Implementation of Interval **********************************

// initialize sentinel
Interval* Interval::_end = NULL;
void Interval::initialize(Arena* arena) {
  Range::initialize(arena);
  _end = new (arena) Interval(-1);
}

Interval::Interval(int reg_num) :


def score_search(text: str, query: str) -> int:
    if not text or not query:
        return 0

    search_text = text.lower()
    score = 0
    p = 0  # Position within the `text`
    consecutive_bonus = 2  # Bonus for consecutive matches

    query_length = len(query)
    for i in range(query_length):
        index = search_text.find(query[i], p)
        if index < 0:
            index = search_text.find(query[i])
            if index < 0:
                continue

        score += 1
        if index - p < 2:
            score += consecutive_bonus
            if index == p:
                consecutive_bonus *= 2
        else:
            consecutive_bonus = 2

        p = index + 1

    if query in search_text:
        score += 2

    if score >= len(query):
        return score

    return 0

# a few testcases
# print(score_search('sing', 'ED SH ing'))
# print(score_search("I Don't care", 'DON‘T CARE CHERYL'))
# print(score_search("Cheryl", 'DON‘T CARE CHERYL'))
# print(score_search('Good Enough', 'GOOD EN'))
# print(score_search('God Save the Queen', 'GOOD EN'))
# print(score_search('Del Shannon', 'ed shran'))
# print(score_search('Ed Sheeran', 'ed shran'))


 EndpointChoiceA<N> = SessionMpst<OfferAfromB<N>, End, QueueFullA, RoleA<RoleEnd>>;

/// For B
type ChooseBtoA<N> = ChooseMpst<
    BtoAAdd<N>,
    End,
    BtoANeg<N>,
    End,
    <QueueOfferA as Role>::Dual,
    <QueueOfferA as Role>::Dual,
    RoleADual<RoleEnd>,
>;
type ChooseBtoC = ChooseMpst<End, End, End, End, RoleEnd, RoleEnd, RoleCDual<RoleEnd>>;
type EndpointChoiceB<N> = SessionMpst<ChooseBtoA<N>, ChooseBtoC, QueueFullB, RoleB<RoleEnd>>;

/// For C
type EndpointCAdd = SessionMpst<End, End, QueueOfferC, RoleC<RoleEnd>>;
type EndpointCNeg = SessionMpst<End, End, QueueOfferC, RoleC<RoleEnd>>;

type OfferCfromB = OfferMpst<End, End, End, End, QueueOfferC, QueueOfferC, RoleC<RoleEnd>>;
type EndpointChoiceC = SessionMpst<End, OfferCfromB, QueueFullC, RoleC<RoleEnd>>;

/// Functions related to endpoints
fn simple_store_server(s: EndpointChoiceA<i32>) -> Result<(), Box<dyn Error>> {
    offer_mpst_session_to_a_from_b(
        s,
        |s: EndpointAAdd<i32>| {
            let (x, s) = recv_mpst_a_to_b(s)?;
            close_mpst(s)?;

            assert_eq!(x, 1);
            Ok(())
        },
        |s: EndpointANeg<i32>| {
            let (x, s) = recv_mpst_a_to_b(s)?;
            close_mpst(s)?;

            assert_eq!(x, 2);
            Ok(())
        },
    )
}

fn simple_store_client_left(s: EndpointChoiceB<i32>) -> Result<(), Box<dyn Error>> {
    {
        let s = choose_left_mpst_session_b_to_all::<
            End,
            End,
            BtoAAdd<i32>,
            End,
            BtoANeg<i32>,
            End,
            <QueueOfferA as Role>::Dual,
            <QueueOfferA as Role>::Dual,
            RoleEnd,
            RoleEnd,
            QueueChoiceB,
            QueueChoiceB,
        >(s);
        let s = send_mpst_b_to_a(1, s);
        close_mpst(s)?;
    }
    Ok(())
}

fn simple_store_client_right(s: EndpointChoiceB<i32>) -> Result<(), Box<dyn Error>> {
    {
        let s = choose_right_mpst_session_b_to_all::<
            End,
            End,
            BtoAAdd<i32>,
            End,
            BtoANeg<i32>,
            End,
            <QueueOfferA as Role>::Dual,
            <QueueOfferA as Role>::Dual,
            RoleEnd,
            RoleEnd,
            QueueChoiceB,
            QueueChoiceB,
        >(s);
        let s = send_mpst_b_to_a(2, s);
        close_mpst(s)?;
    }
    Ok(())
}

fn simple_store_pawn(s: EndpointChoiceC) -> Result<(), Box<dyn Error>> {
    offer_mpst_session_to_c_from_b(
        s,
        |s: EndpointCAdd| {
            close_mpst(s)?;
            Ok(())
        },
        |s: EndpointCNeg| {
            close_mpst(s)?;
            Ok(())
        },
    )
}

#[test]
fn simple_choice() {
    assert!(|| -> Result<(), Box<dyn Error>> {
        // Test the left branch.
        {
            let (thread_a, thread_b, thread_c) = fork_mpst(
                simple_store_server,


 (json['scanlinePad'] as num?)?.toInt()
  ..transparentPixel = (json['transparentPixel'] as num?)?.toInt()
  ..type = (json['type'] as num?)?.toInt()
  ..width = (json['width'] as num?)?.toInt()
  ..x = (json['x'] as num?)?.toInt()
  ..y = (json['y'] as num?)?.toInt();

Map<String, dynamic> _$VImageDataToJson(VImageData instance) =>
    <String, dynamic>{
      'alpha': instance.alpha,
      'alphaData': ImageUtils.serializeByteArray(instance.alphaData),
      'bytesPerLine': instance.bytesPerLine,
      'data': ImageUtils.serializeByteArray(instance.data),
      'delayTime': instance.delayTime,
      'depth': instance.depth,
      'disposalMethod': instance.disposalMethod,
      'height': instance.height,
      'maskData': ImageUtils.serializeByteArray(instance.maskData),
      'maskPad': instance.maskPad,
      'scanlinePad': instance.scanlinePad,
      'transparentPixel': instance.transparentPixel,
      'type': instance.type,
      'width': instance.width,
      'x': instance.x,
      'y': instance.y,
    };
import 'package:flutter/widgets.dart';
import 'package:json_annotation/json_annotation.dart';
import '../comm/comm.dart';
import '../gen/color.dart';
import '../gen/composite.dart';
import '../gen/control.dart';
import '../gen/ctabitem.dart';
import '../gen/image.dart';
import '../gen/rectangle.dart';
import '../impl/ctabfolder_evolve.dart';
import 'event.dart';
import 'widgets.dart';

part 'ctabfolder.g.dart';

class CTabFolderSwt<V extends VCTabFolder> extends CompositeSwt<V> {
  const CTabFolderSwt({super.key, required super.value});

  @override
  State createState() =>
      CTabFolderImpl<CTabFolderSwt<VCTabFolder>, VCTabFolder>();

  void sendCTabFolderitemClosed(V val, VEvent? payload) {
    sendEvent(val, "CTabFolder/itemClosed", payload);
  }

  void sendCTabFolder2close(V val, VEvent? payload) {
    sendEvent(val, "CTabFolder2/close", payload);
  }

  void sendCTabFolder2maximize(V val, VEvent? payload) {
    sendEvent(val, "CTabFolder2/maximize", payload);
  }

  void sendCTabFolder2minimize(V val, VEvent? payload) {
    sendEvent(val, "CTabFolder2/minimize", payload);
  }

  void sendCTabFolder2restore(V val, VEvent? payload) {
    sendEvent(val, "CTabFolder2/restore", payload);
  }

  void sendCTabFolder2showList(V val, VEvent? payload) {
    sendEvent(val, "CTabFolder2/showList", payload);
  }

  void sendSelectionDefaultSelection(V val, VEvent? payload) {
    sendEvent(val, "Selection/DefaultSelection", payload);
  }

  void sendSelectionSelection(V val, VEvent? payload) {
    sendEvent(val, "Selection/Selection", payload);
  }
}

@JsonSerializable()
class VCTabFolder extends VComposite {
  VCTabFolder() : this.empty();
  VCTabFolder.empty() {
    swt = "CTabFolder";
  }

  bool? borderVisible;
  List<VColor>? gradientColors;
  List<int>? gradientPercents;
  bool? gradientVertical;
  bool? highlightEnabled;
  List<VCTabItem>? items;
  bool? mRUVisible;
  bool? maximizeVisible;
  bool? maximized;
  bool? minimizeVis


-left: 3rem;
}

@media only screen and (max-width: 992px) {
  .input-field .prefix ~ input {
    width: 86%;
    width: calc(100% - 3rem);
  }
}

@media only screen and (max-width: 600px) {
  .input-field .prefix ~ input {
    width: 80%;
    width: calc(100% - 3rem);
  }
}

/* Search Field */
.input-field input[type=search] {
  display: block;
  line-height: inherit;
  -webkit-transition: .3s background-color;
  transition: .3s background-color;
}

.nav-wrapper .input-field input[type=search] {
  height: inherit;
  padding-left: 4rem;
  width: calc(100% - 4rem);
  border: 0;
  -webkit-box-shadow: none;
          box-shadow: none;
}

.input-field input[type=search]:focus:not(.browser-default) {
  background-color: #fff;
  border: 0;
  -webkit-box-shadow: none;
          box-shadow: none;
  color: #444;
}

.input-field input[type=search]:focus:not(.browser-default) + label i,
.input-field input[type=search]:focus:not(.browser-default) ~ .mdi-navigation-close,
.input-field input[type=search]:focus:not(.browser-default) ~ .material-icons {
  color: #444;
}

.input-field input[type=search] + .label-icon {
  -webkit-transform: none;
          transform: none;
  left: 1rem;
}

.input-field input[type=search] ~ .mdi-navigation-close,
.input-field input[type=search] ~ .material-icons {
  position: absolute;
  top: 0;
  right: 1rem;
  color: transparent;
  cursor: pointer;
  font-size: 2rem;
  -webkit-transition: .3s color;
  transition: .3s color;
}

/* Textarea */
textarea {
  width: 100%;
  height: 3rem;
  background-color: transparent;
}

textarea.materialize-textarea {
  line-height: normal;
  overflow-y: hidden;
  /* prevents scroll bar flash */
  padding: .8rem 0 .8rem 0;
  /* prevents text jump on Enter keypress */
  resize: none;
  min-height: 3rem;
  -webkit-box-sizing: border-box;
          box-sizing: border-box;
}

.hiddendiv {
  visibility: hidden;
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow-wrap: break-word;
  /* future version of deprecated 'word-wrap' */
  padding-top: 1.2rem;
  /* prevents text jump on Enter keypress */
  position: absolute;
  top: 0;
  z-index: -1;
}

/* Autocomplete */
.autocomplete-content li .highlight {
  color: #444;
}

.autocomplete-content li img {
  height: 40px;
  width: 40px;
  margin: 5px 15px;
}

/* Character Counter */
.character-counter {
  min-height: 18px;
}

/* Radio Buttons
   ========================================================================== */
[type="radio"]:not(:checked),
[type="radio"]:checked {
  position: absolute;
  opacity: 0;
  pointer-events: none;
}

[type="radio"]:not(:checked) + span,
[type="radio"]:checked + span {
  position: relative;
  padding-left: 35px;
  cursor: pointer;
  display: inline-block;
  height: 25px;
  line-height: 25px;
  font-size: 1rem;


IPS_INS_SDXC1,
    MIPS_INS_SEB,
    MIPS_INS_SEH,
    MIPS_INS_SELEQZ,
    MIPS_INS_SELNEZ,
    MIPS_INS_SEL,
    MIPS_INS_SEQ,
    MIPS_INS_SEQI,
    MIPS_INS_SH,
    MIPS_INS_SH16,
    MIPS_INS_SHF,
    MIPS_INS_SHILO,
    MIPS_INS_SHILOV,
    MIPS_INS_SHLLV,
    MIPS_INS_SHLLV_S,
    MIPS_INS_SHLL,
    MIPS_INS_SHLL_S,
    MIPS_INS_SHRAV,
    MIPS_INS_SHRAV_R,
    MIPS_INS_SHRA,
    MIPS_INS_SHRA_R,
    MIPS_INS_SHRLV,
    MIPS_INS_SHRL,
    MIPS_INS_SLDI,
    MIPS_INS_SLD,
    MIPS_INS_SLL,
    MIPS_INS_SLL16,
    MIPS_INS_SLLI,
    MIPS_INS_SLLV,
    MIPS_INS_SLT,
    MIPS_INS_SLTI,
    MIPS_INS_SLTIU,
    MIPS_INS_SLTU,
    MIPS_INS_SNE,
    MIPS_INS_SNEI,
    MIPS_INS_SPLATI,
    MIPS_INS_SPLAT,
    MIPS_INS_SRA,
    MIPS_INS_SRAI,
    MIPS_INS_SRARI,
    MIPS_INS_SRAR,
    MIPS_INS_SRAV,
    MIPS_INS_SRL,
    MIPS_INS_SRL16,
    MIPS_INS_SRLI,
    MIPS_INS_SRLRI,
    MIPS_INS_SRLR,
    MIPS_INS_SRLV,
    MIPS_INS_SSNOP,
    MIPS_INS_ST,
    MIPS_INS_SUBQH,
    MIPS_INS_SUBQH_R,
    MIPS_INS_SUBQ,
    MIPS_INS_SUBQ_S,
    MIPS_INS_SUBSUS_U,
    MIPS_INS_


pc_tcp_trace.enabled()) {
    gpr_log(GPR_DEBUG,
            "CFStream endpoint:%p create readStream:%p writeStream: %p",
            ep_impl, read_stream, write_stream);
  }
  ep_impl->base.vtable = &vtable;
  gpr_ref_init(&ep_impl->refcount, 1);
  ep_impl->read_stream = read_stream;
  ep_impl->write_stream = write_stream;
  CFRetain(read_stream);
  CFRetain(write_stream);
  ep_impl->stream_sync = stream_sync;
  CFSTREAM_HANDLE_REF(ep_impl->stream_sync, "endpoint create");

  ep_impl->peer_string = gpr_strdup(peer_string);
  ep_impl->read_cb = nil;
  ep_impl->write_cb = nil;
  ep_impl->read_slices = nil;
  ep_impl->write_slices = nil;
  GRPC_CLOSURE_INIT(&ep_impl->read_action, ReadAction,
                    static_cast<void*>(ep_impl), grpc_schedule_on_exec_ctx);
  GRPC_CLOSURE_INIT(&ep_impl->write_action, WriteAction,
                    static_cast<void*>(ep_impl), grpc_schedule_on_exec_ctx);
  ep_impl->resource_user =
      grpc_resource_user_create(resource_quota, peer_string);
  grpc_resource_user_slice_allocator_init(&ep_impl->slice_allocator,
                                          ep_impl->resource_user,
                                          CFStreamReadAllocationDone, ep_impl);

  return &ep_impl->base;
}

#endif /* GRPC_CFSTREAM_ENDPOINT */
/*
 *
 * Copyright 2018 gRPC authors.
 *
 * 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.
 *
 */

#include <grpc/support/port_platform.h>

#include "src/core/lib/iomgr/tcp_server.h"

grpc_tcp_server_vtable* grpc_tcp_server_impl;

grpc_error* grpc_tcp_server_create(grpc_closure* shutdown_complete,
                                   const grpc_channel_args* args,
                                   grpc_tcp_server** server) {
  return grpc_tcp_server_impl->create(shutdown_complete, args, server);
}

void grpc_tcp_server_start(grpc_tcp_server* server, grpc_pollset** pollsets,
                           size_t pollset_count,
                           grpc_tcp_server_cb on_accept_cb, void* cb_arg) {
  grpc_tcp_server_impl->start(server, pollsets, pollset_count, on_accept_cb,
                              cb_arg);
}

grpc_error* grpc_tcp_server_add_port(grpc_tcp_server* s,
                                     const grpc_resolved_address* addr,
                                     int* out_port) {
  return grpc_tcp_server_impl->add_port(s, addr, out_port);
}

unsigned grpc_tcp_server_port_fd_count(grpc_tcp_server* s,
                                       unsigned port_index) {
  return grpc_tcp_server_impl->port_fd_count(s, port_index);
}

int grpc_tcp_server_port_fd(grpc_tcp_server* s, unsigned port_index,
                            unsigned fd_index) {
  return grpc_tcp_server_impl->port_fd


env.insfd("$", directed_job_func));
    try!(env.insfd("run", run_func));
    try!(env.insfd("get", get_func));
    try!(env.insfd("setp", setp_func));
    try!(env.insfd("jobs", jobs_func));
    try!(env.insfd("job", job_func));
    try!(env.insfd("fg", fg_func));
    try!(env.insfd("ftime", ftime_func));
    try!(env.insfd("dot", dot_func));
    try!(env.insfd("prompt", prompt_func));
    try!(env.insfd("subprompt", subprompt_func));
    try!(env.insfd("equal?", equal_func));
    try!(env.insfd("not?", not_func));
    try!(env.insfd("re_equal?", re_equal_func));
    try!(env.insfd("open_input", open_input_func));
    try!(env.insfd("open_output", open_output_func));
    try!(env.insfd("run_failed?", run_failed_func));
    try!(env.insfd("getall", getall_func));
    try!(env.insfd("flatten_eqlist", flatten_eqlist_func));

    // commands that aren't really meant to be called by users
    try!(env.insfd("describe_process_output", describe_process_output));

    return Ok(Empty);
}
<reponame>haraldmaida/arangodb-rust-driver<gh_stars>10-100
use std::collections::HashMap;

use serde_json;

use super::*;
use rincon_core::api::types::JsonString;

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct MyContent {
    a: String,
    b: i32,
}

#[test]
fn serialize_struct_document_without_key() {
    let content = MyContent {
        a: "Hugo".to_owned(),
        b: 42,
    };

    let new_document = NewDocument::from_content(content);
    let json = serde_json::to_string(&new_document).unwrap();

    assert_eq!(r#"{"a":"Hugo","b":42}"#, &json);
}

#[test]
fn serialize_struct_document_with_key() {
    let content = MyContent {
        a: "Hugo".to_owned(),
        b: 42,
    };

    let new_document = NewDocument::from_content(content).with_key(DocumentKey::new("29384"));
    let json = serde_json::to_string(&new_document).unwrap();

    assert_eq!(r#"{"_key":"29384","a":"Hugo","b":42}"#, &json);
}

#[test]
fn serialize_hashmap_document_without_key() {
    let mut content = HashMap::new();
    content.insert("a", json!("Hugo"));
    content.insert("b", json!(42));
    let content = content;

    let new_document = NewDocument::from_content(content);
    let json = serde_json::to_string(&new_document).unwrap();

    assert!(r#"{"a":"Hugo","b":42}"# == &json || r#"{"b":42,"a":"Hugo"}"# == &json);
}

#[test]
fn serialize_hashmap_document_with_key() {
    let mut content = HashMap::new();
    content.insert("a", json!("Hugo"));
    content.insert("b", json!(42));
    let content = content;

    let new_document = NewDocument::from_content(content).with_key(DocumentKey::new("29384"));
    let json = serde_json::to_string(&new_document).unwrap();

    assert!(
        r#"{"_key":"29384","a":"Hugo","b":42}"# == &json
            || r#"{"_key":"29384","b":42,"a":"Hugo"}"# == &json
    );
}


	movm.l		&0x0303,EXC_DREGS(%a6)	# save d0-d1/a0-a1
	fmovm.l		%fpcr,%fpsr,USER_FPCR(%a6) # save ctrl regs
	fmovm.x		&0xc0,EXC_FP0(%a6)	# save fp0/fp1

	fmov.l		&0x0,%fpcr		# zero FPCR

#
#	copy, convert, and tag input argument
#
	lea		FP_SRC(%a6),%a0
	mov.l		0x8+0x0(%a6),0x0(%a0)	# load ext input
	mov.l		0x8+0x4(%a6),0x4(%a0)
	mov.l		0x8+0x8(%a6),0x8(%a0)
	bsr.l		tag			# fetch operand type
	mov.b		%d0,STAG(%a6)
	mov.b		%d0,%d1

	andi.l		&0x00ff00ff,USER_FPSR(%a6)

	clr.l		%d0
	mov.b		FPCR_MODE(%a6),%d0	# pass rnd mode,prec

	tst.b		%d1
	bne.b		_L8_2x
	bsr.l		satanh			# operand is a NORM
	bra.b		_L8_6x
_L8_2x:
	cmpi.b		%d1,&ZERO		# is operand a ZERO?
	bne.b		_L8_3x			# no
	bsr.l		src_zero			# yes
	bra.b		_L8_6x
_L8_3x:
	cmpi.b		%d1,&INF		# is operand an INF?
	bne.b		_L8_4x			# no
	bsr.l		t_operr			# yes
	bra.b		_L8_6x
_L8_4x:
	cmpi.b		%d1,&QNAN		# is operand a QNAN?
	bne.b		_L8_5x			# no
	bsr.l		src_qnan			# yes
	bra.b		_L8_6x
_L8_5x:
	bsr.l		satanhd			# operand is a DENORM
_L8_6x:

#
#	Result is now in FP0
#
	movm.l		EXC_DREGS(%a6),&0x0303	# restore d0-d1/a0-a1
	fmovm.l		USER_FPCR(%a6),%fpcr,%fpsr # restore ctrl regs
	fmovm.x		EXC_FP1(%a6),&0x40	# restore fp1
	unlk		%a6
	rts

#########################################################################
# MONADIC TEMPLATE							#
#########################################################################
	global		_ftans_
_ftans_:
	link		%a6,&-LOCAL_SIZE

	movm.l		&0x0303,EXC_DREGS(%a6)	# save d0-d1/a0-a1
	fmovm.l		%fpcr,%fpsr,USER_FPCR(%a6) # save ctrl regs
	fmovm.x		&0xc0,EXC_FP0(%a6)	# save fp0/fp1

	fmov.l		&0x0,%fpcr		# zero


/ 2;
							end,
	displayBorder = function(value)
								RAID_BORDERS_SHOWN = value;
								DefaultCompactUnitFrameSetupOptions.displayBorder = value;
								DefaultCompactMiniFrameSetUpOptions.displayBorder = value;
								CompactRaidFrameManager_SetSetting("ShowBorders", value);
							end,

	--State
	locked = CompactUnitFrameProfiles_GenerateRaidManagerSetting("Locked"),
	shown = CompactUnitFrameProfiles_GenerateRaidManagerSetting("IsShown"),
}


data.cards ||
        response.data.promptCards ||
        response.data.prompts ||
        response.data;
      return {
        promptCards: Array.isArray(promptCards)
          ? promptCards.map(mapBackendToFrontend.promptCard)
          : [],
        count: response.data.count || promptCards.length,
      };
    } catch (error) {
      console.error("프롬프트 카드 목록 조회 실패:", error);
      throw error;
    }
  },

  createPromptCard: async (promptData) => {
    try {
      console.log("프롬프트 카드 생성 요청:", promptData);

      // 프론트엔드 데이터를 백엔드 형식으로 변환
      const backendData = mapFrontendToBackend.promptCard(promptData);
      const response = await api.post(`/prompts`, backendData);
      console.log("프롬프트 카드 생성 응답:", response.data);

      // 응답을 프론트엔드 형식으로 변환
      return mapBackendToFrontend.promptCard(response.data);
    } catch (error) {
      console.error("프롬프트 카드 생성 실패:", error);
      throw error;
    }
  },

  updatePromptCard: async (promptId, promptData) => {
    try {
      // 프론트엔드 데이터를 백엔드 형식으로 변환
      const backendData = mapFrontendToBackend.promptCard(promptData);
      const response = await api.put(`/prompts/${promptId}`, backendData);
      // 응답을 프론트엔드 형식으로 변환
      return mapBackendToFrontend.promptCard(response.data);
    } catch (error) {
      console.error("프롬프트 카드 업데이트 실패:", error);
      throw error;
    }
  },

  getPromptContent: async (promptId) => {
    try {
      const response = await api.get(`/prompts/${promptId}`);
      return response.data;
    } catch (error) {
      console.error("프롬프트 내용 조회 실패:", error);
      throw error;
    }
  },

  deletePromptCard: async (promptId) => {
    try {
      const response = await api.delete(`/prompts/${promptId}`, {
        data: {
          adminId: "143834d8-70e1-704d-2f1e-974c63817a67"
        }
      });
      return response.data;
    } catch (error) {
      console.error("프롬프트 카드 삭제 실패:", error);
      throw error;
    }
  },

  reorderPromptCards: async (reorderData) => {
    try {
      const updatePromises = reorderData.map(({ promptId, stepOrder }) =>
        api.put(`/prompts/${promptId}`, { stepOrder })
      );

      const responses = await Promise.all(updatePromises);
      return {
        message: "프롬프트 카드 순서가 업데이트되었습니다.",
        updatedCards: responses.map((r) =>
          mapBackendToFrontend.promptCard(r.data)
        ),
      };
    } catch (error) {
      console.error("프롬프트 카드 순서 변경 실패:", error);
      throw error;


-color-scheme-setting
  // local storage is used to override OS theme settings
  let pre_js_and_css = String::from(r###"

<link media="all" rel="stylesheet" href=""###)
  + AR5IV_CSS_URL
  + "\"><link media=\"all\" rel=\"stylesheet\" href=\""
  + SITE_CSS_URL
  + "\">
";

  main_content = END_HEAD.replace(&main_content, pre_js_and_css).to_string();
  main_content = END_BODY.replace(&main_content, active_js).to_string();
  main_content
}

pub fn log_to_html(conversion_report: &str, id_arxiv: &str) -> String {
  String::from(
    r###"<!DOCTYPE html>

<title>Conversion report for arXiv article "###,
  ) + id_arxiv
    + r###"</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex">
<link media="all" rel="stylesheet" href=""###
    + AR5IV_CSS_URL
    + r###"">

LaTeXML conversion report ("
    + id_arxiv
    + r###")

"### + &conversion_report
    .split('\n')
    .map(|line| {
      let line = line.replace('\t', " ");
      if line.starts_with("Warning:") {
        "

".to_string() + &line + ""
      } else if line.starts_with("Error:") {
        "

".to_string() + &line + ""
      } else if line.starts_with("Info:") {
        "

".to_string() + &line + ""
      } else if line.starts_with("Fatal:") {
        "

".to_string() + &line + ""
      } else if line.starts_with("Conversion complete:")
        || line.starts_with("Post-processing complete:")
      {
        // provide a colored final status
        if line.contains(" fatal") {
          "

<sp