 { Unsubscriber, Writable } from 'svelte/store';

export class PersistService<DataType> {
  constructor(options: LocalForageOptions) {
    this.storage = localforage.createInstance(options);
  }

  private storage: LocalForage | null = null;

  private async persistData(key: string, value: DataType): Promise<void> {
    try {
      await this.storage?.setItem(key, value);
    } catch (error) {
      console.error(`Unable to persist data. ${error}`);
    }
  }

  async getData(key: string): Promise<DataType | null> {
    try {
      const result = await this.storage?.getItem<DataType>(key);

      return result ?? null;
    } catch (error) {
      console.error(`Unable to get the data. ${error}`);
    }

    return null;
  }

  subscribe(store: Writable<DataType>, key: string): Unsubscriber {
    const unsubscribe = store.subscribe((value) => {
      this.persistData(key, value);
    });

    return unsubscribe;
  }
}
import {IBackstory} from '../interfaces/hero/hero.interface';

export const BackstoriesDict: {
	[backstoryID: string]: IBackstory
} = {
	errandRunner: {
		id:     'errandRunner',
		name:   'Errand Runner',
		desc:   'You spent your childhood running errands for the rector of the local Mage\'s college. Although you were considered too low of birth to ever become a proper mage, ' +
		        'you stole glances at dusty tomes and magical artifacts in your free time, and even managed to teach yourself a cantrip or two before you were caught and released ' +
		        'from the college\'s service.',
		traits: [
			'studious',
			'spineless'
		]
	},

	streetUrchin: {
		id:     'streetUrchin',
		name:   'Street Urchin',
		desc:   'You whiled away the better part of your youth thieving from shops and nobles alike. Neither glistening apple nor silver wristwatch were safe from your grasp. ' +
		        'Though you never had the courage to attempt the bigger scores, you were satisfied with the living you made by filching low-value wares and trinkets.',
		traits: [
			'stickyfingers',
			'immoral'
		]
	},

	junkRat: {
		id:     'junkRat',
		name:   'Junk Rat',
		desc:   'You grew up amongst the filth and garbage of an industrial junkyard, where you learned how to tinker and construct useful tools and apparatuses. You were always considered ' +
		        'to be a little eccentric by your peers, however, and never quite learned how to socialize and fit in with the group.',
		traits: [
			'tinkerer',
			'awkward'
		]
	},

	pamperedChild: {
		id:     'pamperedChild',
		name:   'Pampered Child',
		desc:   'You were never allowed to stray far from your mother\'s gaze, and you never knew any better. Your meals were served on silver plates and your every want and whim was ' +
		        'catered by your live-in butler. You attended the best of private schools where you always took the spotlight. Although you never worked a day in your life, ' +
		        'you were better-prepared for adulthood than all of your peers.',
		traits: [
			'attractive',
			'puny'
		]
	},

	blacksmithApprentice: {
		id:     'blacksmithApprentice',
		name:   `Blacksmith's Apprentice`,
		desc:   'In your younger years, you worked as a blacksmith\'s apprentice in the back alleys of a bustling city. You weren\'


using HarmonyLib;
using ROUtils;

namespace RealismOverhaul.Harmony
{
    [HarmonyPatch(typeof(KSPUtil))]
    internal class PatchKSPUtil
    {
        [HarmonyPrefix]
        [HarmonyPatch("PrintSI")]
        internal static bool Prefix_PrintSI(double amount, string unitName, int sigFigs, bool longPrefix, ref string __result)
        {
            __result = ResourceUnits.PrintSI(amount, unitName, sigFigs, longPrefix);
            return false;
        }

        [HarmonyPostfix]
        [HarmonyPatch("CheckVersion", typeof(int), typeof(int),


32/win_local.h"

#include <iptypes.h>
#include <iphlpapi.h>

static WSADATA	winsockdata;
static bool	winsockInitialized = false;

idCVar net_ip( "net_ip", "localhost", CVAR_SYSTEM, "local IP address" );
idCVar net_port( "net_port", "0", CVAR_SYSTEM | CVAR_INTEGER, "local IP port number" );
idCVar net_forceLatency( "net_forceLatency", "0", CVAR_SYSTEM | CVAR_INTEGER, "milliseconds latency" );
idCVar net_forceDrop( "net_forceDrop", "0", CVAR_SYSTEM | CVAR_INTEGER, "percentage packet loss" );

static SOCKET	ip_socket;

typedef struct {
	unsigned long ip;
	unsigned long mask;
} net_interface;

#define			MAX_INTERFACES	32
int				num_interfaces = 0;
net_interface	netint[MAX_INTERFACES];

//=============================================================================

/*
====================
NET_ErrorString
====================
*/
const char *NET_ErrorString( void ) {
	int		code;

	code = WSAGetLastError();
	switch( code ) {
	case WSAEINTR: return "WSAEINTR";
	case WSAEBADF: return "WSAEBADF";
	case WSAEACCES: return "WSAEACCES";
	case WSAEDISCON: return "WSAEDISCON";
	case WSAEFAULT: return "WSAEFAULT";
	case WSAEINVAL: return "WSAEINVAL";
	case WSAEMFILE: return "WSAEMFILE";
	case WSAEWOULDBLOCK: return "WSAEWOULDBLOCK";
	case WSAEINPROGRESS: return "WSAEINPROGRESS";
	case WSAEALREADY: return "WSAEALREADY";
	case WSAENOTSOCK: return "WSAENOTSOCK";
	case WSAEDESTADDRREQ: return "WSAEDESTADDRREQ";
	case WSAEMSGSIZE: return "WSAEMSGSIZE";
	case WSAEPROTOTYPE: return "WSAEPROTOTYPE";
	case WSAENOPROTOOPT: return "WSAENOPROTOOPT";
	case WSAEPROTONOSUPPORT: return "WSAEPROTONOSUPPORT";
	case WSAESOCKTNOSUPPORT: return "WSAESOCKTNOSUPPORT";
	case WSAEOPNOTSUPP: return "WSAEOPNOTSUPP";
	case WSAEPFNOSUPPORT: return "WSAEPFNOSUPPORT";
	case WSAEAFNOSUPPORT: return "WSAEAFNOSUPPORT";
	case WSAEADDRINUSE: return "WSAEADDRINUSE";
	case WSAEADDRNOTAVAIL: return "WSAEADDRNOTAVAIL";
	case WSAENETDOWN: return "WSAENETDOWN";
	case WSAENETUNREACH: return "WSAENETUNREACH";
	case WSAENETRESET: return "WSAENETRESET";
	case WSAECONNABORTED: return "WSWSAECONNABORTEDAEINTR";
	case WSAECONNRESET: return "WSAECONNRESET";
	case WSAENOBUFS: return "WSAENOBUFS";
	case WSAEISCONN: return "WSAEISCONN";
	case WSAENOTCONN: return "WSAENOTCONN";
	case WSAESHUTDOWN: return "WSAESHUTDOWN";
	case WSAETOOMANYREFS: return "WSAETOOMANYREFS";
	case WSAETIMEDOUT: return "WSAETIMEDOUT";
	case WSAECONNREFUSED: return "WSAECONNREFUSED";
	case WSAELOOP: return "WSAELOOP";
	case WSAENAMETOOLONG: return "WSAENAMETOOLO


thenAnswer((inv) {
        results.add({
          'from': inv.positionalArguments[0] as Offset,
          'to': inv.positionalArguments[1] as Offset,
          'paint_color': (inv.positionalArguments[2] as Paint).color,
          'paint_stroke_width':
              (inv.positionalArguments[2] as Paint).strokeWidth,
          'dash_array': inv.positionalArguments[3] as List<int>,
        });
      });

      lineChartPainter.drawGrid(mockCanvasWrapper, holder);
      expect(results.length, 2);

      expect(results[0]['from'], const Offset(0, 60));
      expect(results[0]['to'], const Offset(20, 60));
      expect(results[0]['paint_color'], isSameColorAs(MockData.color1));
      expect(results[0]['paint_stroke_width'], 11);
      expect(results[0]['dash_array'], [1, 1]);

      expect(results[1]['from'], const Offset(0, 40));
      expect(results[1]['to'], const Offset(20, 40));
      expect(results[1]['paint_color'], isSameColorAs(MockData.color2));
      expect(results[1]['paint_stroke_width'], 22);
      expect(results[1]['dash_array'], [2, 2]);
    });

    test('test 3 - vertical', () {
      const viewSize = Size(100, 20);

      final data = LineChartData(
        minY: 0,
        maxY: 10,
        minX: 0,
        maxX: 10,
        titlesData: const FlTitlesData(show: false),
        gridData: FlGridData(
          drawHorizontalLine: false,
          verticalInterval: 2,
          checkToShowVerticalLine: (value) => value != 2 && value != 8,
          getDrawingVerticalLine: (value) {
            if (value == 4) {
              return const FlLine(
                color: MockData.color1,
                strokeWidth: 11,
                dashArray: [1, 1],
              );
            } else if (value == 6) {
              return const FlLine(
                color: MockData.color2,
                strokeWidth: 22,
                dashArray: [2, 2],
              );
            } else {
              throw StateError("We shouldn't draw these lines");
            }
          },
        ),
      );

      final lineChartPainter = LineChartPainter();
      final holder =
          PaintHolder<LineChartData>(data, data, TextScaler.noScaling);
      final mockCanvasWrapper = MockCanvasWrapper();
      when(mockCanvasWrapper.size).thenAnswer((realInvocation) => viewSize);
      when(mockCanvasWrapper.canvas).thenReturn(MockCanvas());

      final mockUtils = MockUtils();
      Utils.changeInstance(mockUtils);
      when(mockUtils.getBestInitialIntervalValue(any, any, any))
          .thenAnswer((realInvocation) => 0);

      final results = <Map<String, dynamic>>[];
      when(
        mockCanvasWrapper.drawDashedLine(
          captureAny,
          captureAny,
          captureAny,
          captureAny,
        ),
      ).thenAnswer((inv) {
        results.add({
          'from': inv.positionalArguments[0] as Offset,
          'to': inv.positionalArguments[1] as Offset,
          'paint_color': (inv.positionalArguments[2] as Paint).color,
          'paint_stroke_width':
              (inv.positionalArguments[2] as Paint).strokeWidth,
          'dash_array': inv.positionalArguments[3] as List<int>,
        });
      });

      lineChartPainter.drawGrid(mockCanvasWrapper, holder);
      expect(results.length, 2);

      expect(results[0]['from'], const Offset(40, 0));
      expect(results[0]['to'], const Offset(40, 20));
      expect(results[0]['paint_color'], isSameColorAs(MockData.color1));
      expect(results[0]['paint_stroke_width'], 11);
      expect(results[0]['dash


 segment)
        } else if (usedHostSegments.first().length <= 2) {
            // The last segment has a length of 2 or less -> pick this segment too
            usedHostSegments.add(0, segment)
        } else {
            // We have everything we need. Bail out.
            break
        }
    }

    return usedHostSegments.joinToString(separator = ".")
}

/**
 * Return the truncated path only containing the first and last segment of the full path. If the
 * Uri does not have a path an empty String will be returned.
 *
 * Example:
 * /foo/bar/test/index.html -> /foo/…/index.html
 */
fun Uri.truncatedPath(): String {
    val segments = pathSegments

    return when (segments.size) {
        0 -> ""
        1 -> "/" + segments[0]
        2 -> "/" + segments.joinToString(separator = "/")
        else -> "/" + listOf(segments.first(), Char.ELLIPSIS, segments.last()).joinToString(separator = "/")
    }
}
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.focus.shortcut

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Build
import android.util.TypedValue
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import mozilla.components.support.ktx.kotlin.stripCommonSubdomains
import org.mozilla.focus.R

class IconGenerator {

    companion object {
        private val TEXT_SIZE_DP = 36f
        private val DEFAULT_ICON_CHAR = '?'

        /**
         * See [generateAdaptiveLauncherIcon] for more details.
         */
        @JvmStatic
        fun generateLauncherIcon(context: Context, url: String?): Bitmap {
            val startingChar = getRepresentativeCharacter(url)
            return generateCharacterIcon(context, startingChar)
        }

        /**
         * Generate an icon with the given character. The icon will be drawn
         * on top of a generic launcher icon shape that we provide.
         */
        private fun generateCharacterIcon(context: Context, character: Char) =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                generateAdaptiveLauncherIcon(context, character)
            } else {
                generateLauncherIconPreOreo(context, character)
            }

        /*
         * This method needs to be separate from generateAdaptiveLauncherIcon so that we can generate
         * the pre-Oreo icon to display in the Add To Home screen Dialog
         */
        @JvmStatic
        fun generateLauncherIconPreOreo(context: Context, character: Char): Bitmap {
            val options = BitmapFactory.Options()
            options.inMutable = true
            val shape = BitmapFactory.decodeResource(context.resources, R.drawable.ic_homescreen_shape, options)
            return drawCharacterOnBitmap(context, character, shape)
        }

        /**
         * Generates a launcher icon for versions of Android that support Adaptive Icons (Oreo+):
         * https://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive.html
         */
        private fun generateAdaptiveLauncherIcon(context: Context, character: Char): Bitmap {
            val res = context.resources
            val adaptiveIconDimen = res.getDimensionPixelSize(R.dimen.adaptive_icon_drawable_dimen)

            val bitmap = Bitmap.createBitmap(adaptiveIconDimen, adaptiveIconDimen, Bitmap.Config.ARGB_8888)
            val canvas = Canvas(bitmap)

            // Adaptive Icons have two layers: a background that fills the canvas and
            // a foreground that's centered. First, we draw the background...
            canvas


anim_from_left {
    animation-name: o_anim_zoom_in_left;
}

@keyframes o_anim_zoom_in_right {
    0% {
        opacity: 0;
        transform: scale(var(--wanim-zoom-in-scale)) translate(calc(0.1px * var(--wanim-intensity-squared)), 0);
        animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19);
    }
    10% {
        opacity: calc(0.15 + (0.85 * (var(--wanim-opacity-adjustment))));
    }
    60% {
        opacity: 1;
        transform: scale(var(--wanim-zoom-in-scale-60)) translate(calc(-0.2px * var(--wanim-intensity)), 0);
        animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1);
    }
}
.o_anim_zoom_in.o_anim_from_right {
    animation-name: o_anim_zoom_in_right;
}

// Flash / Pulse / Shake / Tada ///////////////////////////////////////////////

@keyframes o_anim_flash {
    0%, 50%, 100% {
        opacity: 1;
    }
    25%, 75% {
        opacity: calc(1 - (var(--wanim-intensity) / 100));
    }
}
.o_anim_flash {
    animation-name: o_anim_flash;
}

@keyframes o_anim_pulse {
    0% {
        transform: scale(1);
    }
    50% {
        transform: scale(calc(1.01 + (0.000016 * var(--wanim-intensity-squared))));
    }
    100% {
        transform: scale(1);
    }
}
.o_anim_pulse {
    animation-name: o_anim_pulse;
}

@keyframes o_anim_shake {
    0%, 100% {
        transform: translate(0, 0);
    }
    10%, 30%, 50%, 70%, 90% {
        transform: translate(calc(-1px - (0.0036px * var(--wanim-intensity-squared))), 0);
    }
    20%, 40%, 60%, 80% {
        transform: translate(calc(1px + (0.0036px * var(--wanim-intensity-squared))), 0);
    }
}
.o_anim_shake {
    animation-name: o_anim_shake;
}

@keyframes o_anim_tada {
    0% {
        transform: scale(1);
    }
    10%, 20% {
        transform: scale(calc(1 - (0.00004 * var(--wanim-intensity-squared)))) rotate(calc(-2deg - (0.02deg * var(--wanim-intensity))));
    }
    30%, 50%, 70%, 90% {
        transform: scale(calc(1 + (0.00004 * var(--wanim-intensity-squared)))) rotate(calc(2deg + (0.02deg * var(--wanim-intensity))));
    }
    40%, 60%, 80% {
        transform: scale(calc(1 + (0.00004 * var(--wanim-intensity-squared)))) rotate(calc(-2deg - (0.02deg * var(--wanim-intensity))));
    }
    100% {
        transform: scale(1);
    }
}
.o_anim_tada {
    animation-name: o_anim_tada;
}

// Flip in ////////////////////////////////////////////////////////////////////

@keyframes o_anim_flip_in_x {
    0% {
        transform: perspective(1000px) rotateX(calc(1deg * (5 + (var(--wanim-intensity) * 1.7))));
        opacity: 0;
    }
    50% {
        opacity: 1;
    }
}
.o_anim_flip_in_x {
    backface-visibility: visible;
    animation-name: o_anim_flip_in_x;
    transition-timing-function: ease-out;
}

@keyframes o_anim_flip_in_y {
    0% {
        transform: perspective(1


var_os("DOCS_RS").is_some();
	if !targets_hermit || runs_clippy || is_docs_rs {
		return;
	}

	let kernel_src = KernelSrc::local().unwrap_or_else(KernelSrc::download);

	kernel_src.build();
}

struct KernelSrc {
	src_dir: PathBuf,
}

impl KernelSrc {
	fn local() -> Option<Self> {
		let mut src_dir = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap());
		src_dir.set_file_name("libhermit-rs");
		src_dir.exists().then(|| Self { src_dir })
	}

	fn download() -> Self {
		let version = "0.4.0";
		let out_dir = out_dir();
		let src_dir = out_dir.join(format!("libhermit-rs-{version}"));

		if !src_dir.exists() {
			let url = format!(
				"https://github.com/hermitcore/libhermit-rs/archive/refs/tags/v{version}.tar.gz"
			);
			let response = ureq::get(url.as_str()).call().unwrap().into_reader();
			let tar = GzDecoder::new(response);
			let mut archive = Archive::new(tar);
			archive.unpack(src_dir.parent().unwrap()).unwrap();
		}

		Self { src_dir }
	}

	fn build(self) {
		let target_dir = target_dir();
		let manifest_path = self.src_dir.join("Cargo.toml");
		assert!(
			manifest_path.exists(),
			"kernel manifest path `{}` does not exist",
			manifest_path.display()
		);
		let arch = env::var_os("CARGO_CFG_TARGET_ARCH").unwrap();
		let profile = env::var("PROFILE").expect("PROFILE was not set");

		let mut cmd = Command::new("cargo");

		// Remove rust-toolchain-specific environment variables from kernel cargo
		cmd.env_remove("LD_LIBRARY_PATH");
		env::vars()
			.filter(|(key, _value)| key.starts_with("CARGO") || key.starts_with("RUST"))
			.for_each(|(key, _value)| {
				cmd.env_remove(&key);
			});

		cmd.current_dir(&self.src_dir)
			.arg("run")
			.arg("--package=xtask")
			.arg("--target-dir")
			.arg(&target_dir)
			.arg("--")
			.arg("build")
			.arg("--arch")
			.arg(&arch)
			.args(&[
				"--profile",
				match profile.as_str() {
					"debug" => "dev",
					profile => profile,
				},
			])
			.arg("--target-dir")
			.arg(&target_dir);

		if has_feature("instrument") {
			cmd.arg("--instrument-mcount");
		}

		// Control enabled features via this crate's features
		cmd.arg("--no-default-features");
		forward_features(
			&mut cmd,
			["acpi", "fsgsbase", "pci", "pci-ids", "smp", "vga"].into_iter(),
		);

		let status = cmd.status().expect("failed to start kernel build");
		assert!(status.success());

		let lib_location = target_dir
			.join(&arch)
			.join(&profile)
			.canonicalize()
			.unwrap();

		println!("cargo:rustc-link-search=native={}", lib_location.display());
		println!("cargo:rustc-link-lib=static=hermit");

		println!("cargo:rerun-if-changed={}", self.src_dir.display());
		// HERMIT_LOG_LEVEL_FILTER sets the log level filter at compile time
		println!("cargo:rerun-if-env-changed=HERMIT_LOG_LEVEL_FILTER");
	}
}

fn out_dir() -> PathBuf {
	env::var_os("OUT_DIR").unwrap().into()
}

fn target_dir() -> PathBuf {
	let mut target_dir = out_dir();
	target_dir.push("target");
	target_dir


ings::BotbMiniRankings(class BotbMiniRankings * const this /* r31 */) {
    // Local variables
    char * tok; // r0

    // References
    // -> class Debug TheDebug;
}

static class Symbol botb_mini_rank_vs_friend_score; // size: 0x4, address: 0x80A4E954
static class Symbol botb_mini_rank_vs_friend_streak; // size: 0x4, address: 0x80A4E95C
static class Symbol botb_mini_rank_vs_friend_mult; // size: 0x4, address: 0x80A4E964
static class Symbol botb_mini_rank_overall_score; // size: 0x4, address: 0x80A4E96C
static class Symbol botb_mini_rank_overall_streak; // size: 0x4, address: 0x80A4E974
static class Symbol botb_mini_rank_overall_mult; // size: 0x4, address: 0x80A4E97C
static class Symbol botb_mini_rank_top100_score; // size: 0x4, address: 0x80A4E984
static class Symbol botb_mini_rank_top100_streak; // size: 0x4, address: 0x80A4E98C
static class Symbol botb_mini_rank_top100_mult; // size: 0x4, address: 0x80A4E994
static class Symbol botb_mini_rank_champ; // size: 0x4, address: 0x80A4E99C
static class Symbol botb_mini_rank_no_rank; // size: 0x4, address: 0x80A4E9A4
// Range: 0x80210554 -> 0x80210A88
char * BotbMiniRankings::Description(const class BotbMiniRankings * const this /* r29 */, enum WinMetric winMetric /* r30 */) {
    // Local variables
    const char * string; // r28

    // References
    // -> class Debug TheDebug;
    // -> static class Symbol botb_mini_rank_no_rank;
    // -> static class Symbol botb_mini_rank_champ;
    // -> static class Symbol botb_mini_rank_top100_mult;
    // -> static class Symbol botb_mini_rank_top100_streak;
    // -> static class Symbol botb_mini_rank_top100_score;
    // -> static class Symbol botb_mini_rank_overall_mult;
    // -> static class Symbol botb_mini_rank_overall_streak;
    // -> static class Symbol botb_mini_rank_overall_score;
    // -> static class Symbol botb_mini_rank_vs_friend_mult;
    // -> static class Symbol botb_mini_rank_vs_friend_streak;
    // -> static class Symbol botb_mini_rank_vs_friend_score;
}

static class Symbol icon; // size: 0x4, address: 0x80A4E9AC
// Range: 0x80210A88 -> 0x80210B98
char * BotbRulesListProvider::Text(const class BotbRulesListProvider * const this /* r30 */, int data /* r31 */, class Symbol & slot /* r29 */) {
    // References
    // -> static class Symbol icon;
}

// Range: 0x80210B98 -> 0x80210BEC
unsigned char BotbRulesListProvider::IsActive() {}

// Range: 0x80210BEC -> 0x80210BF4
class RndMat * BotbRulesListProvider::Mat() {}

static class Symbol botb_years; // size: 0x4, address: 0x80A4E9B4
static class Symbol botb_days; // size: 0x4, address: 0x80A4E9BC
static class Symbol botb_hours; // size: 0x4, address: 0x80A4E9C4
static class Symbol botb_minutes; // size: 0x4, address: 0x80A4E9CC
static class Symbol botb_seconds; // size: 0x


.com/wp-content/uploads/2022/01/WhatsApp-Image-2022-01-10-at-5.38.49-PM-e1641898504107.jpeg" loading="lazy" class="lazyload" /></picture>

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAAGQAQAAAACoxAthAAAAAnRSTlMAAHaTzTgAAAAqSURBVHja7cExAQAAAMKg9U/tbwagAAAAAAAAAAAAAAAAAAAAAAAAAIA3T7AAAZRBGFwAAAAASUVORK5CYII=" alt=""  width="400" height="400"  style="display: inline-block;" data-src="https:


 ID. ])
-- @return string
-- @param int_1 int
function CDOTAGameManager:GetHeroUnitNameByID( int_1 ) end

---[[ CDOTAGameRules:AddBotPlayerWithEntityScript  Spawn a bot player of the passed hero name, player name, and team. ])
-- @return handle
-- @param string_1 string
-- @param string_2 string
-- @param int_3 int
-- @param string_4 string
-- @param bool_5 bool
function CDOTAGameRules:AddBotPlayerWithEntityScript( string_1, string_2, int_3, string_4, bool_5 ) end

---[[ CDOTAGameRules:AddEventMetadataLeaderboardEntry  Event-only ( string szNameSuffix, int nStars, int nMaxStars, int nExtraData1, int nExtraData2 ) ])
-- @return bool
-- @param string_1 string
-- @param unsigned_2 unsigned
-- @param unsigned_3 unsigned
-- @param unsigned_4 unsigned
-- @param unsigned_5 unsigned
-- @param unsigned_6 unsigned
-- @param unsigned_7 unsigned
-- @param unsigned_8 unsigned
-- @param unsigned_9 unsigned
function CDOTAGameRules:AddEventMetadataLeaderboardEntry( string_1, unsigned_2, unsigned_3, unsigned_4, unsigned_5, unsigned_6, unsigned_7, unsigned_8, unsigned_9 ) end

---[[ CDOTAGameRules:AddEventMetadataLeaderboardEntryRawScore  Event-only ( string szNameSuffix, int nScore, int nExtraData1, int nExtraData2 ) ])
-- @return bool
-- @param string_1 string
-- @param unsigned_2 unsigned
-- @param unsigned_3 unsigned
-- @param unsigned_4 unsigned
-- @param unsigned_5 unsigned
-- @param unsigned_6 unsigned
-- @param unsigned_7 unsigned
-- @param unsigned_8 unsigned
function CDOTAGameRules:AddEventMetadataLeaderboardEntryRawScore( string_1, unsigned_2, unsigned_3, unsigned_4, unsigned_5, unsigned_6, unsigned_7, unsigned_8 ) end

---[[ CDOTAGameRules:AddHeroIDToBlacklist  Add the hero ID to the hero blacklist if it is not already present ])
-- @return void
-- @param int_1 int
function CDOTAGameRules:AddHeroIDToBlacklist( int_1 ) end

---[[ CDOTAGameRules:AddHeroIDToWhitelist  Add the hero ID to the hero whitelist if it is not already present ])
-- @return void
-- @param int_1 int
function CDOTAGameRules:AddHeroIDToWhitelist( int_1 ) end

---[[ CDOTAGameRules:AddHeroToBlacklist  Add the hero to the hero blacklist if it is not already present ])
-- @return void
-- @param string_1 string
function CDOTAGameRules:AddHeroToBlacklist( string_1 ) end

---[[ CDOTAGameRules:AddHeroToPlayerAvailability  Adds hero of given ID to available heroes of player of given ID ])
-- @return void
-- @param int_1 int
-- @param int_2 int
function CDOTAGameRules:AddHeroToPlayerAvailability( int_1, int_2 ) end

---[[ CDOTAGameRules:AddHeroToWhitelist  Add the hero to the hero whitelist if it is not already present ])
-- @return void
-- @param string_1 string
function CDOTAGameRules:AddHeroToWhitelist( string_1 ) end

---[[ CDOTAGameRules:AddItemToWhiteList  Add an item to the whitelist ])
-- @return void
-- @param string_1 string
function CDOTAGameRules:AddItemToWhiteList( string_1 ) end

---[[ CDOTAGameRules:AddMinimapDebugPoint  Add a point on the minimap. ])
-- @return void
-- @param int_1 int
-- @param Vector_2 Vector
-- @param int_3 int
-- @param int_4 int
-- @param int_5 int
-- @param int_6 int
-- @param float_7 float
function CDOTAGameRules:AddMinimapDebugPoint( int_1, Vector


 l.ln.Close()
}

func (l *mtcpListener) Accept() (conn net.Conn, err error) {
	var ok bool
	select {
	case conn = <-l.cqueue:
		conn = limiter_wrapper.WrapConn(
			conn,
			l.options.TrafficLimiter,
			conn.RemoteAddr().String(),
			limiter.ScopeOption(limiter.ScopeConn),
			limiter.ServiceOption(l.options.Service),
			limiter.NetworkOption(conn.LocalAddr().Network()),
			limiter.SrcOption(conn.RemoteAddr().String()),
		)
	case err, ok = <-l.errChan:
		if !ok {
			err = listener.ErrClosed
		}
	}
	return
}

func (l *mtcpListener) listenLoop() {
	for {
		conn, err := l.ln.Accept()
		if err != nil {
			l.errChan <- err
			close(l.errChan)
			return
		}
		go l.mux(conn)
	}
}

func (l *mtcpListener) mux(conn net.Conn) {
	defer conn.Close()

	session, err := mux.ServerSession(conn, l.md.muxCfg)
	if err != nil {
		l.logger.Error(err)
		return
	}
	defer session.Close()

	for {
		stream, err := session.Accept()
		if err != nil {
			l.logger.Error("accept stream: ", err)
			return
		}

		select {
		case l.cqueue <- stream:
		default:
			stream.Close()
			l.logger.Warnf("connection queue is full, client %s discarded", stream.RemoteAddr())
		}
	}
}
package grpc

import (
	"time"

	mdata "github.com/go-gost/core/metadata"
	mdutil "github.com/go-gost/x/metadata/util"
)

const (
	defaultBacklog = 128
)

type metadata struct {
	backlog                      int
	insecure                     bool
	path                         string
	keepalive                    bool
	keepaliveMinTime             time.Duration
	keepaliveTime                time.Duration
	keepaliveTimeout             time.Duration
	keepalivePermitWithoutStream bool
	keepaliveMaxConnectionIdle   time.Duration
	mptcp                        bool
}

func (l *grpcListener) parseMetadata(md mdata.Metadata) (err error) {
	l.md.backlog = mdutil.GetInt(md, "grpc.backlog", "backlog")
	if l.md.backlog <= 0 {
		l.md.backlog = defaultBacklog
	}

	l.md.insecure = mdutil.GetBool(md, "grpc.insecure", "grpcInsecure", "insecure")
	l.md.path = mdutil.GetString(md, "grpc.path", "path")

	l.md.keepalive = mdutil.GetBool(md, "grpc.keepalive", "keepalive", "keepAlive")
	if l.md.keepalive {
		l.md.keepaliveMinTime = mdutil.GetDuration(md, "grpc.keepalive.minTime", "keepalive.minTime")
		if l.md.keepaliveMinTime <= 0 {
			l.md.keepaliveMinTime = 30 * time.Second
		}
		l.md.keepaliveTime = mdutil.GetDuration(md, "grpc.keepalive.time", "keepalive.time")
		if l.md.keepaliveTime <= 0 {
			l.md.keepaliveTime = 60 * time.Second
		}


SILK_ENC_INVALID_LOSS_RATE = -5;

    /** Complexity setting not valid, use 0, 1 or 2 */
    static final int SKP_SILK_ENC_INVALID_COMPLEXITY_SETTING = -6;

    /** Inband FEC setting not valid, use 0 or 1 */
    static final int SKP_SILK_ENC_INVALID_INBAND_FEC_SETTING = -7;

    /** DTX setting not valid, use 0 or 1 */
    static final int SKP_SILK_ENC_INVALID_DTX_SETTING = -8;

    /** Internal encoder error */
    static final int SKP_SILK_ENC_INTERNAL_ERROR = -9;

    /**************************/
    /* Decoder error messages */
    /**************************/

    /** Output sampling frequency lower than internal decoded sampling frequency */
    static final int SKP_SILK_DEC_INVALID_SAMPLING_FREQUENCY = -10;

    /** Payload size exceeded the maximum allowed 1024 bytes */
    static final int SKP_SILK_DEC_PAYLOAD_TOO_LARGE = -11;

    /** Payload has bit errors */
    static final int SKP_SILK_DEC_PAYLOAD_ERROR = -12;
}
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jitsi.impl.neomedia.codec.audio.silk;

/**
 * NLSF vector decoder.
 *
 * @author Dingxin Xu
 */
public class NLSFMSVQDecodeFLP
{
    /**
     * NLSF vector decoder.
     * @param pNLSF
     * @param psNLSF_CB_FLP
     * @param NLSFIndices
     * @param NLSFIndices_offset
     * @param LPC_order
     */
    static void SKP_Silk_NLSF_MSVQ_decode_FLP(
              float                 []pNLSF,             /* O    Decoded output vector [ LPC_ORDER ]     */
        final  SKP_Silk_NLSF_CB_FLP psNLSF_CB_FLP,     /* I    NLSF codebook struct                    */
        final int                   []NLSFIndices,       /* I    NLSF indices [ nStages ]                */
              int                   NLSFIndices_offset,
        final int                   LPC_order           /* I    LPC order used                          */
    )
    {
        float[] pCB_element;
        int pCB_element_offset;
        int     s;
        int     i;

        /* Check that each index is within valid range */
        assert( 0 <= NLSFIndices[ NLSFIndices_offset+0 ] && NLSFIndices[ NLSFIndices_offset+0 ] < psNLSF_CB_FLP.CBStages[ 0 ].nVectors );

        /* Point to the first vector element */
        pCB_element = psNLSF_CB_FLP.CBStages[ 0 ].CB;
        pCB_element_offset = ( NLSFIndices[ NLSFIndices_offset+0 ] * LPC_order );

        /* Initialize with the codebook vector from stage 0 */
        System.arraycopy(pCB_element, pCB_element_offset, pNLSF, 0, LPC_order);

        for( s = 1; s < psNLSF_CB_FLP.nStages; s++ ) {
            /* Check that each index is within valid range */
            assert( 0 <= NLSFIndices[ NLSFIndices_offset+s ] && NLSFIndices[ NLSFIndices_offset+s ] < psNLSF_CB_FLP.CBStages[ s ].nVectors );

            if( LPC_order == 16 ) {
                /* Point to the f


    28
#define GFT_RAM_LINE_TCP_FLAG_NS_MASK              0x1
#define GFT_RAM_LINE_TCP_FLAG_NS_SHIFT             29
#define GFT_RAM_LINE_DST_PORT_MASK                 0x1
#define GFT_RAM_LINE_DST_PORT_SHIFT                30
#define GFT_RAM_LINE_SRC_PORT_MASK                 0x1U
#define GFT_RAM_LINE_SRC_PORT_SHIFT                31
	__le32 hi;
#define GFT_RAM_LINE_DSCP_MASK                     0x1
#define GFT_RAM_LINE_DSCP_SHIFT                    0
#define GFT_RAM_LINE_OVER_IP_PROTOCOL_MASK         0x1
#define GFT_RAM_LINE_OVER_IP_PROTOCOL_SHIFT        1
#define GFT_RAM_LINE_DST_IP_MASK                   0x1
#define GFT_RAM_LINE_DST_IP_SHIFT                  2
#define GFT_RAM_LINE_SRC_IP_MASK                   0x1
#define GFT_RAM_LINE_SRC_IP_SHIFT                  3
#define GFT_RAM_LINE_PRIORITY_MASK                 0x1
#define GFT_RAM_LINE_PRIORITY_SHIFT                4
#define GFT_RAM_LINE_PROVIDER_VLAN_MASK            0x1
#define GFT_RAM_LINE_PROVIDER_VLAN_SHIFT           5
#define GFT_RAM_LINE_VLAN_MASK                     0x1
#define GFT_RAM_LINE_VLAN_SHIFT                    6
#define GFT_RAM_LINE_DST_MAC_MASK                  0x1
#define GFT_RAM_LINE_DST_MAC_SHIFT                 7
#define GFT_RAM_LINE_SRC_MAC_MASK                  0x1
#define GFT_RAM_LINE_SRC_MAC_SHIFT                 8
#define GFT_RAM_LINE_TENANT_ID_MASK                0x1
#define GFT_RAM_LINE_TENANT_ID_SHIFT               9
#define GFT_RAM_LINE_RESERVED1_MASK                0x3FFFFF
#define GFT_RAM_LINE_RESERVED1_SHIFT               10
};

/*
 * Used in the first 2 bits for gft_ram_line: Indication for vlan mask
 */
enum gft_vlan_select {
	INNER_PROVIDER_VLAN = 0,
	INNER_VLAN = 1,
	OUTER_PROVIDER_VLAN = 2,
	OUTER_VLAN = 3,
	MAX_GFT_VLAN_SELECT
};

#endif /* __ECORE_HSI_ETH__ */


 should contain file1.txt")
        assertTrue(targetFile2.exists(), "Target directory should contain file2.txt")

        // Modify source directory and validate sync
        sourceFile1.write("Updated file one content", overwrite = true, useTemporaryFile = true)
        val syncResult2 = targetDir.syncBySizeAndLastModification(sourceDir)
        assertTrue(syncResult2, "Sync should detect and apply changes to target directory")

        // Check removal behavior
        sourceFile2.delete()
        val syncResult3 = targetDir.syncBySizeAndLastModification(sourceDir, remove = true)
        assertTrue(syncResult3, "Sync should remove deleted files")
        assertFalse(targetFile2.exists(), "Target directory should no longer contain file2.txt")
    }

}/*
 * Copyright © 2020-2024, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license.
 */

package `fun`.adaptive.wireformat

import `fun`.adaptive.adat.AdatClass
import `fun`.adaptive.adat.AdatCompanion
import `fun`.adaptive.adat.metadata.AdatClassMetadata
import `fun`.adaptive.adat.metadata.AdatPropertyMetadata
import `fun`.adaptive.adat.wireformat.AdatClassWireFormat
import `fun`.adaptive.wireformat.builtin.ListWireFormat
import `fun`.adaptive.wireformat.builtin.PolymorphicWireFormat
import `fun`.adaptive.wireformat.signature.WireFormatTypeArgument
import kotlin.test.Test
import kotlin.test.assertEquals

abstract class AbstractPolymorphicTest<ST>(
    wireFormatProvider: WireFormatProvider
) : AbstractWireFormatTest<ST>(wireFormatProvider) {

    @Test
    fun basic() {
        WireFormatRegistry += C1.Companion
        WireFormatRegistry += C2.Companion

        C1(12).also { assertEquals(it, polymorphicActual(it, C1.Companion)) }
        C2(23).also { assertEquals(it, polymorphicActual(it, C2.Companion)) }
    }

    @Test
    fun list() {
        WireFormatRegistry += C1.Companion
        WireFormatRegistry += C2.Companion

        listOf(C1(12), C2(23)).also {
            @Suppress("UNCHECKED_CAST")
            assertEquals(it, polymorphicActual(it, ListWireFormat(WireFormatTypeArgument<CI>(PolymorphicWireFormat as WireFormat<CI>, false))))
        }
    }

    interface CI {
        var i: Int
    }

    data class C1(
        override var i: Int = 0
    ) : AdatClass, CI {

        override val adatCompanion: AdatCompanion<C1>
            get() = Companion

        override fun genGetValue(index: Int): Any {
            return i
        }

        override fun genSetValue(index: Int, value: Any?) {
            i = value as Int
        }

        companion object : AdatCompanion<C1> {

            override val wireFormatName: String
                get() = "fun.adaptive.wireformat.C1"

            override val adatMetadata = AdatClassMetadata(
                version = 1,
                name = "fun.adaptive.wireformat.C1",
                flags = 0,
                properties = listOf(
                    AdatPropertyMetadata("i", 0, 0, "I"),
                )
            )

            override val adatWireFormat = AdatClassWireFormat(this, adatMetadata)

            override fun wireFormatEncode(encoder: WireFormatEncoder, value: C1) =
                encoder.int(1, "i", value.i)

            override fun <ST> wireFormatDecode(source: ST, decoder: WireFormatDecoder<ST>?): C1 =


me.Ppvt())).SetFileName,
		uintptr(unsafe.Pointer(me.Ppvt())),
		uintptr(wName.EmptyIsNil(name)))
	return utl.ErrorAsHResult(ret)
}

// [SetFileNameLabel] method.
//
// [SetFileNameLabel]: https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifiledialog-setfilenamelabel
func (me *IFileDialog) SetFileNameLabel(label string) error {
	var wLabel wstr.BufEncoder
	ret, _, _ := syscall.SyscallN(
		(*_IFileDialogVt)(unsafe.Pointer(*me.Ppvt())).SetFileNameLabel,
		uintptr(unsafe.Pointer(me.Ppvt())),
		uintptr(wLabel.EmptyIsNil(label)))
	return utl.ErrorAsHResult(ret)
}

// [SetFileTypeIndex] method.
//
// The index is one-based.
//
// [SetFileTypeIndex]: https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifiledialog-setfiletypeindex
func (me *IFileDialog) SetFileTypeIndex(index int) error {
	if index < 1 {
		panic(fmt.Sprintf("Index is one-based: %d.", index))
	}

	ret, _, _ := syscall.SyscallN(
		(*_IFileDialogVt)(unsafe.Pointer(*me.Ppvt())).SetFileTypeIndex,
		uintptr(unsafe.Pointer(me.Ppvt())),
		uintptr(uint32(index)))
	return utl.ErrorAsHResult(ret)
}

// [SetFileTypes] method.
//
// Example:
//
//	var fd win.IFileDialog // initialized somewhere
//
//	_ = fd.SetFileTypes([]win.COMDLG_FILTERSPEC{
//		{Name: "MP3 audio files", Spec: "*.mp3"},
//		{Name: "All files", Spec: "*.*"},
//	})
//
// [SetFileTypes]: https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifiledialog-setfiletypes
func (me *IFileDialog) SetFileTypes(filterSpec []COMDLG_FILTERSPEC) error {
	nativeFilters := make([]_COMDLG_FILTERSPEC, 0, len(filterSpec))
	for _, fs := range filterSpec {
		nativeFilters = append(nativeFilters, _COMDLG_FILTERSPEC{
			PszName: (*uint16)(wstr.EncodeToPtr(fs.Name)),
			PszSpec: (*uint16)(wstr.EncodeToPtr(fs.Spec)),
		})
	}

	ret, _, _ := syscall.SyscallN(
		(*_IFileDialogVt)(unsafe.Pointer(*me.Ppvt())).SetFileTypes,
		uintptr(unsafe.Pointer(me.Ppvt())),
		uintptr(uint32(len(filterSpec))),
		uintptr(unsafe.Pointer(&nativeFilters[0])))
	return utl.ErrorAsHResult(ret)
}

// [SetFilter] method.
//
// [SetFilter]: https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifiledialog-setfilter
func (me *IFileDialog) SetFilter(filter *IShellItemFilter) error {
	ret, _, _ := syscall.SyscallN(
		(*_IFileDialogVt)(unsafe.Pointer(*me.Ppvt())).SetFilter,
		uintptr(unsafe.Pointer(me.Ppvt())),
		uintptr(unsafe.Pointer(filter.Ppvt())))
	return utl.ErrorAsHResult(ret)
}

// [SetFolder] method.
//
// [SetFolder]: https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifiledialog


pub black: Rgb,
    #[serde(deserialize_with = "failure_default")]
    pub red: Rgb,
    #[serde(deserialize_with = "failure_default")]
    pub green: Rgb,
    #[serde(deserialize_with = "failure_default")]
    pub yellow: Rgb,
    #[serde(deserialize_with = "failure_default")]
    pub blue: Rgb,
    #[serde(deserialize_with = "failure_default")]
    pub magenta: Rgb,
    #[serde(deserialize_with = "failure_default")]
    pub cyan: Rgb,
    #[serde(deserialize_with = "failure_default")]
    pub white: Rgb,
}

#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
struct NormalColors(AnsiColors);

impl Default for NormalColors {
    fn default() -> Self {
        NormalColors(AnsiColors {
            black: Rgb { r: 0x00, g: 0x00, b: 0x00 },
            red: Rgb { r: 0xd5, g: 0x4e, b: 0x53 },
            green: Rgb { r: 0xb9, g: 0xca, b: 0x4a },
            yellow: Rgb { r: 0xe6, g: 0xc5, b: 0x47 },
            blue: Rgb { r: 0x7a, g: 0xa6, b: 0xda },
            magenta: Rgb { r: 0xc3, g: 0x97, b: 0xd8 },
            cyan: Rgb { r: 0x70, g: 0xc0, b: 0xba },
            white: Rgb { r: 0xea, g: 0xea, b: 0xea },
        })
    }
}

#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
struct BrightColors(AnsiColors);

impl Default for BrightColors {
    fn default() -> Self {
        BrightColors(AnsiColors {
            black: Rgb { r: 0x66, g: 0x66, b: 0x66 },
            red: Rgb { r: 0xff, g: 0x33, b: 0x34 },
            green: Rgb { r: 0x9e, g: 0xc4, b: 0x00 },
            yellow: Rgb { r: 0xe7, g: 0xc5, b: 0x47 },
            blue: Rgb { r: 0x7a, g: 0xa6, b: 0xda },
            magenta: Rgb { r: 0xb7, g: 0x7e, b: 0xe0 },
            cyan: Rgb { r: 0x54, g: 0xce, b: 0xd6 },
            white: Rgb { r: 0xff, g: 0xff, b: 0xff },
        })
    }
}
use rustc_data_structures::fx::FxHashMap;
use std::collections::hash_map;
use std::slice;

#[derive(Copy, Clone, Debug)]
pub enum CounterOp {
    Add,
    Subtract,
}

pub enum CoverageKind {
    Counter,
    CounterExpression(u32, CounterOp, u32),
}

pub struct CoverageSpan {
    pub start_byte_pos: u32,
    pub end_byte_pos: u32,
}

pub struct CoverageRegion {
    pub kind: CoverageKind,
    pub coverage_span: CoverageSpan,
}

/// Collects all of the coverage regions associated with (a) injected counters, (b) counter
/// expressions (additions or subtraction), and (c) unreachable regions (always counted as zero),
/// for a given Function. Counters and counter expressions are indexed because they can be operands
/// in an expression.
///
/// Note, it's important to distinguish the `unreachable` region type from what LLVM's refers to as
/// a "gap region" (or "gap area"). A gap region is a code region within a counted region (either
/// counter or expression), but the line or lines in the gap region are not executable (such as
/// lines with only whitespace or comments). According to LLVM Code Coverage Mapping documentation,
/// "A count for a gap area is only used as the line execution count if there are no other regions
/// on a line."
#[derive(Default)]
pub struct FunctionCoverageRegions {
    indexed: FxHashMap<u32, CoverageReg


STILi100EEC2Ev
// CHECK-NTARGET-OMP-DEFAULT-SAME: (ptr noundef nonnull align 4 dereferenceable(912) [[THIS:%.*]]) unnamed_addr #[[ATTR1]] comdat {
// CHECK-NTARGET-OMP-DEFAULT-NEXT:  entry:
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    [[THIS_ADDR:%.*]] = alloca ptr, align 8
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    [[A:%.*]] = alloca i32, align 4
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    [[A_CASTED:%.*]] = alloca i64, align 8
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    store ptr [[THIS]], ptr [[THIS_ADDR]], align 8
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    [[THIS1:%.*]] = load ptr, ptr [[THIS_ADDR]], align 8
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    [[TMP0:%.*]] = load ptr, ptr @R, align 8
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    [[TMP1:%.*]] = load i32, ptr [[TMP0]], align 4
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    store i32 [[TMP1]], ptr [[A]], align 4
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    [[TMP2:%.*]] = load i32, ptr [[A]], align 4
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    store i32 [[TMP2]], ptr [[A_CASTED]], align 4
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    [[TMP3:%.*]] = load i64, ptr [[A_CASTED]], align 8
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    call void @{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}__ZN2STILi100EEC1Ev_l218(i64 [[TMP3]]) #[[ATTR2]]
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    [[TMP4:%.*]] = load i32, ptr [[A]], align 4
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    [[TMP5:%.*]] = load ptr, ptr @R, align 8
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    store i32 [[TMP4]], ptr [[TMP5]], align 4
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    ret void
//
//
// CHECK-NTARGET-OMP-DEFAULT-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}__ZN2STILi100EEC1Ev_l218
// CHECK-NTARGET-OMP-DEFAULT-SAME: (i64 noundef [[A:%.*]]) #[[ATTR3]] {
// CHECK-NTARGET-OMP-DEFAULT-NEXT:  entry:
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    [[A_ADDR:%.*]] = alloca i64, align 8
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    [[A_CASTED:%.*]] = alloca i64, align 8
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    store i64 [[A]], ptr [[A_ADDR]], align 8
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    [[TMP0:%.*]] = load i32, ptr [[A_ADDR]], align 4
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    store i32 [[TMP0]], ptr [[A_CASTED]], align 4
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    [[TMP1:%.*]] = load i64, ptr [[A_CASTED]], align 8
// CHECK-NTARGET-OMP-DEFAULT-NEXT:    call void (ptr, i32, ptr, ...) @__kmpc_fork_call(ptr @[[GLOB2]], i32 1, ptr @{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}__ZN2STILi100EEC1Ev_


fun ApplicationCall.requireParameter(name: String) = parameters[name] ?: throw MissingRequestParameterException(name)

/**
 * Get the ID parameter from this [ApplicationCall] or throw an exception if the parameter is null or not a valid ID.
 */
fun ApplicationCall.requireIdParameter(name: String): Long {
    val id = requireParameter(name).toLongOrNull()

    return if (id != null && id > 0) id else throw ParameterConversionException(name, "ID")
}

/**
 * Get the filter parameter from this [ApplicationCall] or return null if the parameter is null.
 */
fun ApplicationCall.filterParameter(name: String): FilterOptions? {
    val filter = parameters[name]?.let { filter ->
        FilterOptions(filter)
    }
    return filter
}

inline fun <reified T : Enum<T>> ApplicationCall.requireEnumParameter(name: String): T =
    runCatching { enumValueOf<T>(requireParameter(name)) }
        .getOrElse { throw ParameterConversionException(name, "Enum<${T::class.simpleName}>") }
/*
 * Copyright (C) 2023 The ORT Server Authors (See <https://github.com/eclipse-apoapsis/ort-server/blob/main/NOTICE>)
 *
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * License-Filename: LICENSE
 */

package org.eclipse.apoapsis.ortserver.shared.reporters

import java.io.File

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.withContext

import org.ossreviewtoolkit.downloader.Downloader
import org.ossreviewtoolkit.downloader.consolidateProjectPackagesByVcs
import org.ossreviewtoolkit.model.OrtResult
import org.ossreviewtoolkit.model.Package
import org.ossreviewtoolkit.model.PackageType
import org.ossreviewtoolkit.model.Provenance
import org.ossreviewtoolkit.model.RepositoryProvenance
import org.ossreviewtoolkit.model.SourceCodeOrigin
import org.ossreviewtoolkit.model.config.DownloaderConfiguration
import org.ossreviewtoolkit.model.licenses.LicenseCategorization
import org.ossreviewtoolkit.model.licenses.LicenseClassifications
import org.ossreviewtoolkit.model.licenses.LicenseInfoResolver
import org.ossreviewtoolkit.model.licenses.LicenseView
import org.ossreviewtoolkit.model.licenses.ResolvedLicenseInfo
import org.ossreviewtoolkit.model.utils.createLicenseInfoResolver
import org.ossreviewtoolkit.plugins.api.OrtPlugin
import org.ossreviewtoolkit.plugins.api.OrtPluginOption
import org.ossreviewtoolkit.plugins.api.PluginDescriptor
import org.ossreviewtoolkit.reporter.Reporter
import org.ossreviewtoolkit.reporter.ReporterFactory
import org.ossreviewtoolkit.reporter.ReporterInput
import org.ossreviewtoolkit.utils.common.encodeOrUnknown
import org.ossreviewtoolkit.utils.common.packZip
import org.ossreviewtoolkit.utils.common.safeDeleteRecursively
import org.ossreviewtoolkit.utils.ort.runBlocking
import org.ossreviewtoolkit.utils.spdx.SpdxLicenseChoice

import org.slf4j.LoggerFactory

const val SOURCE_BUNDLE_FILE_NAME = "source-bundle-archive.zip"
const val SOURCE_BUNDLE_SUB_DIR = "source_code_bundle"

data class SourceCodeBundleReporterConfig(
    /**
     * The license categories to consider when including packages in the source code bundle.
     */
    val includedLicenseCategories: List<String>?,

    /**
     * The type of package to include in the source co


is.hashMap.delete, [url]: api }
    return this
  }

  routes(): void {
    const apiHashMap = this.hashMap?.[this.method] || {}
    const filterApiPath = this.apiPathFilter(apiHashMap)
    const targetApiLen = filterApiPath.length

    if(targetApiLen === 0) {
      return this.errorResponse(404)
    }

    const targetApiUrl = filterApiPath[targetApiLen - 1]

    if(this.pathValidation(targetApiUrl)) {
      console.error("'slug' cannot be used as a key for query string.")
      return this.errorResponse(500)
    }

    const targetApi = apiHashMap[targetApiUrl]
    const request = this.addRequestPathParams(targetApiUrl)

    return targetApi(request, this.response)
  }
}

export default NextApiRouterimport { PropOptions } from 'vue'

/**
 * Creates a component with as many props as keys defined in computed. The generated component provides
 * a default scoped slot when you get back the same props provided to the component
 */
export declare function createLocalScope<
  Computed,
  Props = { [K in keyof Computed]: Computed[K] extends false ? never : PropOptions }
>(
  computed: Computed,
  propsOptions?: Props
): {
  props: Props
}
/**
 * Cloneable Interface
 *
 * Represents an object that can be copied completely (i.e. no references to
 * data are shared between the original object and its clone)
 */
interface ICloneable<T> {
  /**
   * Clone the object
   *
   * Return a deep copy of the object that contains no shared references to the
   * original object.
   *
   * @returns An object that contains the same data
   */
  clone(): T;
}

/**
 * Combinable Interface
 *
 * Represents an object that can be combined/merged together with another
 * object of the same type. The new merged object should contain no shared
 * references to neither the current nor the incoming object.
 */
interface ICombinable<T> {
  /**
   * Combine with another object
   *
   * Combine/merge the data in this object with an incoming object. The new
   * merged object should contain no shared references.
   *
   * @param other The other object to merge with this object
   * @returns An object that contains merged data
   */
  combine(other: T): T;
}

export { ICloneable, ICombinable };
import { CurrencyFormatter, CurrencySymbolPlacement } from '../CurrencyFormatter';

const DefaultCurrencyFormat = '#,##0.00';

describe('Currency Formatter', () => {
  beforeAll(() => {
    CurrencyFormatter.setCurrencySymbol('$', CurrencySymbolPlacement.Postfix);
  });

  describe('formatNumber', () => {
    beforeEach(() => {
      // Reset the currency format
      CurrencyFormatter.setFormat(DefaultCurrencyFormat);
    });

    it('should format correctly-denominated numbers according to the format', () => {
      CurrencyFormatter.setFormat('#0');
      expect(CurrencyFormatter.formatNumber('1')).toBe('1');
      expect(CurrencyFormatter.formatNumber('12')).toBe('12');
      expect(CurrencyFormatter.formatNumber('123')).toBe('123');
      expect(CurrencyFormatter.formatNumber('1234')).toBe('1234');
      expect(CurrencyFormatter.formatNumber('1.0')).toBe('1');
      expect(CurrencyFormatter.formatNumber('1.00')).toBe('1');

      CurrencyFormatter.setFormat('#,##0');
      expect(CurrencyFormatter.formatNumber('1')).toBe('1');
      expect(CurrencyFormatter.formatNumber('12')).toBe('12');
      expect(CurrencyFormatter.format


,
  /// you have access to this metric. To learn more, see \[Access and
  /// data-restriction
  /// management\](https://support.google.com/analytics/answer/10851388).
  core.List<core.String>? blockedReasons;

  /// The display name of the category that this metrics belongs to.
  ///
  /// Similar dimensions and metrics are categorized together.
  core.String? category;

  /// True if the metric is a custom metric for this property.
  core.bool? customDefinition;

  /// Still usable but deprecated names for this metric.
  ///
  /// If populated, this metric is available by either `apiName` or one of
  /// `deprecatedApiNames` for a period of time. After the deprecation period,
  /// the metric will be available only by `apiName`.
  core.List<core.String>? deprecatedApiNames;

  /// Description of how this metric is used and calculated.
  core.String? description;

  /// The mathematical expression for this derived metric.
  ///
  /// Can be used in \[Metric\](#Metric)'s `expression` field for equivalent
  /// reports. Most metrics are not expressions, and for non-expressions, this
  /// field is empty.
  core.String? expression;

  /// The type of this metric.
  /// Possible string values are:
  /// - "METRIC_TYPE_UNSPECIFIED" : Unspecified type.
  /// - "TYPE_INTEGER" : Integer type.
  /// - "TYPE_FLOAT" : Floating point type.
  /// - "TYPE_SECONDS" : A duration of seconds; a special floating point type.
  /// - "TYPE_MILLISECONDS" : A duration in milliseconds; a special floating
  /// point type.
  /// - "TYPE_MINUTES" : A duration in minutes; a special floating point type.
  /// - "TYPE_HOURS" : A duration in hours; a special floating point type.
  /// - "TYPE_STANDARD" : A custom metric of standard type; a special floating
  /// point type.
  /// - "TYPE_CURRENCY" : An amount of money; a special floating point type.
  /// - "TYPE_FEET" : A length in feet; a special floating point type.
  /// - "TYPE_MILES" : A length in miles; a special floating point type.
  /// - "TYPE_METERS" : A length in meters; a special floating point type.
  /// - "TYPE_KILOMETERS" : A length in kilometers; a special floating point
  /// type.
  core.String? type;

  /// This metric's name within the Google Analytics user interface.
  ///
  /// For example, `Event count`.
  core.String? uiName;

  MetricMetadata({
    this.apiName,
    this.blockedReasons,
    this.category,
    this.customDefinition,
    this.deprecatedApiNames,
    this.description,
    this.expression,
    this.type,
    this.uiName,
  });

  MetricMetadata.fromJson(core.Map json_)
    : this(
        apiName: json_['apiName'] as core.String?,
        blockedReasons:
            (json_['blockedReasons'] as core.List?)
                ?.map((value) => value as core.String)
                .toList(),
        category: json_['category'] as core.String?,
        customDefinition: json_['customDefinition'] as core.bool?,
        deprecatedApiNames:
            (json_['deprecatedApiNames'] as core.List?)
                ?.map((value) => value as core.String)
                .toList(),
        description: json_['description'] as core.String?,
        expression: json_['expression'] as core.String?,
        type: json_['type'] as core.String?,
        uiName: json_['uiName'] as core.String?,
      );

  core.Map<core.String, core.dynamic> toJson() => {
    if (apiName != null) 'apiName': a


          r.select();
            } else {
                node.focus()
            }
        }, 0 )
    };
    utils.loadFile(document,{
        href:editor.options.themePath + editor.options.theme + "/dialogbase.css?cache="+Math.random(),
        tag:"link",
        type:"text/css",
        rel:"stylesheet"
    });
    lang = editor.getLang(dialog.className.split( "-" )[2]);

    domUtils.on(window,'load',function () {

        var langImgPath = editor.options.langPath + editor.options.lang + "/images/";
        //针对静态资源
        for ( var i in lang["static"] ) {
            var dom = $G( i );
            if(!dom) continue;
            var tagName = dom.tagName,
                    content = lang["static"][i];
            if(content.src){
                //clone
                content = utils.extend({},content,false);
                content.src = langImgPath + content.src;
            }
            if(content.style){
                content = utils.extend({},content,false);
                content.style = content.style.replace(/url\s*\(/g,"url(" + langImgPath)
            }
            switch ( tagName.toLowerCase() ) {
                case "var":
                    dom.parentNode.replaceChild( document.createTextNode( content ), dom );
                    break;
                case "select":
                    var ops = dom.options;
                    for ( var j = 0, oj; oj = ops[j]; ) {
                        oj.innerHTML = content.options[j++];
                    }
                    for ( var p in content ) {
                        p != "options" && dom.setAttribute( p, content[p] );
                    }
                    break;
                default :
                    domUtils.setAttributes( dom, content);
            }
        }
    } );

})();

// Copyright (c) 2009, Baidu Inc. All rights reserved.
//
// Licensed under the BSD License
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http:// tangram.baidu.com/license.html
//
// 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.
 /**
 * @namespace T Tangram七巧板
 * @name T
 * @version 1.6.0
*/

/**
 * 声明baidu包
 * @author: allstar, erik, meizz, berg
 */
var T,
    baidu = T = baidu || {version: "1.5.0"};
baidu.guid = "$BAIDU$";
baidu.$$ = window[baidu.guid] = window[baidu.guid] || {global:{}};

/**
 * 使用flash资源封装的一些功能
 * @namespace baidu.flash
 */
baidu.flash = baidu.flash || {};

/**
 * 操作dom的方法
 *


hape = list(input_shapes[0])
        for i in range(len(ori_shape)):
            assert self.begin_pos[i] + ori_shape[i] <= self.output_shape[i]
        self.ori_shape = tuple(ori_shape)

        # here we save the information on device for GPU computation
        if self.on_gpu:
            ndim = len(ori_shape)
            gpu_buf = [0 for _ in range(3 * ndim)]
            for i in range(ndim):
                gpu_buf[i] = self.begin_pos[i]
                gpu_buf[ndim + i] = ori_shape[i]
                gpu_buf[2 * ndim + i] = self.output_shape[i]
            self.gpu_buffer = ndarray.array(
                gpu_buf, self.ctx, dtype=np.uintc)
        return self.output_shape

def split_op(node, axes, indices, splits, ctx=None):
    return SplitOp(node, axes, indices, splits, ctx=ctx)

def split_gradient_op(node, axes, indices, splits, ctx=None):
    return SplitGradientOp(node, axes, indices, splits, ctx=ctx)


M<$1.Device>(2, _omitFieldNames ? '' : 'device',
        subBuilder: $1.Device.create)
    ..hasRequiredFields = false;

  @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
  UserCardMultiReq clone() => deepCopy();
  @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
  UserCardMultiReq copyWith(void Function(UserCardMultiReq) updates) =>
      super.copyWith((message) => updates(message as UserCardMultiReq))
          as UserCardMultiReq;

  @$core.override
  $pb.BuilderInfo get info_ => _i;

  @$core.pragma('dart2js:noInline')
  static UserCardMultiReq create() => UserCardMultiReq._();
  @$core.override
  UserCardMultiReq createEmptyInstance() => create();
  static $pb.PbList<UserCardMultiReq> createRepeated() =>
      $pb.PbList<UserCardMultiReq>();
  @$core.pragma('dart2js:noInline')
  static UserCardMultiReq getDefault() => _defaultInstance ??=
      $pb.GeneratedMessage.$_defaultFor<UserCardMultiReq>(create);
  static UserCardMultiReq? _defaultInstance;

  @$pb.TagNumber(1)
  $pb.PbList<$fixnum.Int64> get mids => $_getList(0);

  @$pb.TagNumber(2)
  $1.Device get device => $_getN(1);
  @$pb.TagNumber(2)
  set device($1.Device value) => $_setField(2, value);
  @$pb.TagNumber(2)
  $core.bool hasDevice() => $_has(1);
  @$pb.TagNumber(2)
  void clearDevice() => $_clearField(2);
  @$pb.TagNumber(2)
  $1.Device ensureDevice() => $_ensure(1);
}

const $core.bool _omitFieldNames =
    $core.bool.fromEnvironment('protobuf.omit_field_names');
const $core.bool _omitMessageNames =
    $core.bool.fromEnvironment('protobuf.omit_message_names');
// This is a generated file - do not edit.
//
// Generated from bilibili/main/community/reply/v1.proto.

// @dart = 3.3

// ignore_for_file: annotate_overrides, camel_case_types, comment_references
// ignore_for_file: constant_identifier_names
// ignore_for_file: curly_braces_in_flow_control_structures
// ignore_for_file: deprecated_member_use_from_same_package, library_prefixes
// ignore_for_file: non_constant_identifier_names, unused_import

import 'dart:convert' as $convert;
import 'dart:core' as $core;
import 'dart:typed_data' as $typed_data;

@$core.Deprecated('Use detailListSceneDescriptor instead')
const DetailListScene$json = {
  '1': 'DetailListScene',
  '2': [
    {'1': 'REPLY', '2': 0},
    {'1': 'MSG_FEED', '2': 1},
    {'1': 'NOTIFY', '2': 2},
  ],
};

/// Descriptor for `DetailListScene`. Decode as a `google.protobuf.EnumDescriptorProto`.
final $typed_data.Uint8List detailListSceneDescriptor = $convert.base64Decode(
    'Cg9EZXRhaWxMaXN0U2NlbmUSCQoFUkVQTFkQABIMCghNU0dfRkVFRBABEgoKBk5PVElGWRAC');

@$core.Deprecated('Use editorIconStateDescriptor instead')
const EditorIconState$json = {
  '1': 'EditorIconState',
  '2': [
    {'1': 'EditorIconState_DEFAULT', '2': 0},
    {'1': 'EditorIconState_ENABLE', '2': 1},
    {'1': 'EditorIconState_DISABLE', '2': 2},
    {'1': 'EditorIconState_HIDE', '2': 3},
  ],
};

/// Descriptor for `EditorIconState`. Decode as a `google


-with-microsoft',
  'a2-english-for-developers': 'a2-english-for-developers',
  'rosetta-code': 'rosetta-code',
  'python-for-everybody': 'python-for-everybody',
  'b1-english-for-developers': 'b1-english-for-developers',
  'full-stack-developer': 'full-stack-developer',
  'a1-professional-spanish': 'a1-professional-spanish',
  'a2-professional-spanish': 'a2-professional-spanish',
  'a2-professional-chinese': 'a2-professional-chinese',
  'basic-html': 'basic-html',
  'semantic-html': 'semantic-html',
  'a1-professional-chinese': 'a1-professional-chinese',
  'dev-playground': 'dev-playground',
  'full-stack-open': 'full-stack-open',
  'responsive-web-design-v9': 'responsive-web-design-v9',
  'javascript-v9': 'javascript-v9',
  'front-end-development-libraries-v9': 'front-end-development-libraries-v9',
  'python-v9': 'python-v9',
  'relational-databases-v9': 'relational-databases-v9',
  'back-end-development-and-apis-v9': 'back-end-development-and-apis-v9'
};

const superBlockToFilename = Object.entries(superBlockNames).reduce(
  (map, entry) => {
    return { ...map, [entry[1]]: entry[0] };
  },
  {}
);

/**
 * Builds an array of superblock structures from a curriculum object

 * @param {string[]} superblocks - Array of superblock filename strings
 * @returns {Array<Object>} Array of superblock structure objects with filename, name, and blocks
 * @throws {Error} When a superblock file is not found
 */
function addSuperblockStructure(
  superblocks,
  showComingSoon = process.env.SHOW_UPCOMING_CHANGES === 'true'
) {
  debug(`Building structure for ${superblocks.length} superblocks`);

  const superblockStructures = superblocks.map(superblockFilename => {
    const superblockName = superBlockNames[superblockFilename];
    if (!superblockName) {
      throw new Error(`Superblock name not found for ${superblockFilename}`);
    }

    return {
      name: superblockName,
      blocks: transformSuperBlock(getSuperblockStructure(superblockFilename), {
        showComingSoon
      })
    };
  });

  debug(
    `Successfully built ${superblockStructures.length} superblock structures`
  );

  return superblockStructures;
}

function addBlockStructure(
  superblocks,
  _getBlockStructure = getBlockStructure
) {
  return superblocks.map(superblock => ({
    ...superblock,
    blocks: superblock.blocks.map((block, index) => ({
      ...block,
      ..._getBlockStructure(block.dashedName),
      order: index,
      superBlock: superblock.name
    }))
  }));
}

/**
 * Returns a list of all the superblocks that contain the given block
 * @param {string} block
 */
function getSuperblocks(
  block,
  _addSuperblockStructure = addSuperblockStructure
) {
  const { superblocks } = getCurriculumStructure();
  const withStructure = _addSuperblockStructure(superblocks);

  return withStructure
    .filter(({ blocks }) =>
      blocks.some(({ dashedName }) => dashedName === block)
    )
    .map(({ name }) => name);
}

function validateBlocks(superblocks, blockStructureDir) {
  const withSuperblockStructure = addSuperblockStructure(superblocks, true);
  const blockInSuperblocks = withSuperblockStructure
    .flatMap(({ blocks }) => blocks)
    .map(b => b.dashedName);
  for (const block of blockInSuperblocks) {
    const blockPath = getBlockStructurePath(block);
    if (!fs.existsSync(blockPath)) {
      throw Error(


loat *rank)
{
   x_ = cim->x_;
   y_ = cim->y_;
   bgLog("Computing confidence map...\n");
   float *pGx, *pGy, *pTemp;
   BgImage tcim(x_, y_);
   if (cim->colorIm_==1)
   {
	   tcim.SetImageFromRGB(cim->im_, x_, y_, false);
   } else
   {
	   tcim = *cim;
   }

   pGx = new float[x_*y_];
   pGy = new float[x_*y_];
   pTemp = new float[x_*y_];

   // compute gradient images
   bgLog("...smooth-differentiation filtering\n");
   GaussDiffFilter(&tcim, pGx, pGy, pTemp);

   // compute confidences (subspace estimate)
   bgLog("...subspace estimate\n");
   SubspaceEstim(pTemp, pGx, pGy, confMap);

   // compute edge strength from gradient image
   bgLog("...edge strengths\n");
   Strength(pGx, pGy, pTemp);

   // compute ranks of the strengths
   bgLog("...computing ranks\n");
   CompRanks(pTemp, rank);

   //de-allocate memory
   delete [] pTemp;
   delete [] pGy;
   delete [] pGx;
}
/*
void BgEdgeDetect::ComputeConfidenceMap1(BgImage* cim, float* confMap)
{
	ComputeConfidenceMap(cim, confMap);
	BgEdgeList el;
	DoEdgeDetect(cim, &el, RANK_NMX, CONF_NMX, RANK_H, CONF_H, RANK_L, CONF_L,
		NMIN, FC_ELLIPSE, FC_SQUARE_BOX, FC_ELLIPSE);
   BgImage tempImage(cim->x_, cim->y_);
   el.SetBinImage(&tempImage);
   int i;
   for (i=0; i<(cim->x_*cim->y_); i++)
	   if (tempImage.im_[i] == 0)
		   confMap[i] = 0;
}
*/
void BgEdgeDetect::DoEdgeDetect(BgImage* cim, BgEdgeList* cel, double nmxr, double nmxc,
                                double rh, double ch, double rl, double cl,
                                int nMin, int nmxType, int hystTypeHigh, int hystTypeLow)
{
   x_ = cim->x_;
   y_ = cim->y_;
   bgLog("Start edge detection...\n");
   permGx_ = new float[x_*y_];
   permGy_ = new float[x_*y_];
   permConf_ = new float[x_*y_];
   permRank_ = new float[x_*y_];
   permNmxRank_ = new float[x_*y_];
   permNmxConf_ = new float[x_*y_];
   havePerm_ = true;
   float* tr;
   float* tc;
   float* tdh;
   float* tdl;

   tr = new float[x_*y_];
   tc = new float[x_*y_];
   tdh = new float[x_*y_];
   tdl = new float[x_*y_];

   // compute gradient images
   bgLog("...smooth-differentiation filtering\n");
   GaussDiffFilter(cim, permGx_, permGy_, tr);

   // compute confidences (subspace estimate)
   bgLog("...subspace estimate\n");
   SubspaceEstim(tr, permGx_, permGy_, permConf_);

   // compute edge strength from gradient image
   bgLog("...edge strengths\n");
   Strength(permGx_, permGy_, tr);

   // compute ranks of the strengths
   bgLog("...computing ranks\n");
   CompRanks(tr, permRank_);

   // new nonmaxima supression


UMCHANNELS;
	s->len_chanlist	= NUMCHANNELS;
	s->maxdata	= 0x00ffffff;
	s->range_table	= &usbduxsigma_ai_range;
	s->insn_read	= usbduxsigma_ai_insn_read;
	s->do_cmdtest	= usbduxsigma_ai_cmdtest;
	s->do_cmd	= usbduxsigma_ai_cmd;
	s->cancel	= usbduxsigma_ai_cancel;

	/* Analog Output subdevice */
	s = &dev->subdevices[1];
	dev->write_subdev = s;
	s->type		= COMEDI_SUBD_AO;
	s->subdev_flags	= SDF_WRITABLE | SDF_GROUND | SDF_CMD_WRITE;
	s->n_chan	= 4;
	s->len_chanlist	= s->n_chan;
	s->maxdata	= 0x00ff;
	s->range_table	= &range_unipolar2_5;
	s->insn_write	= usbduxsigma_ao_insn_write;
	s->insn_read	= usbduxsigma_ao_insn_read;
	s->do_cmdtest	= usbduxsigma_ao_cmdtest;
	s->do_cmd	= usbduxsigma_ao_cmd;
	s->cancel	= usbduxsigma_ao_cancel;

	ret = comedi_alloc_subdev_readback(s);
	if (ret)
		return ret;

	/* Digital I/O subdevice */
	s = &dev->subdevices[2];
	s->type		= COMEDI_SUBD_DIO;
	s->subdev_flags	= SDF_READABLE | SDF_WRITABLE;
	s->n_chan	= 24;
	s->maxdata	= 1;
	s->range_table	= &range_digital;
	s->insn_bits	= usbduxsigma_dio_insn_bits;
	s->insn_config	= usbduxsigma_dio_insn_config;

	if (devpriv->high_speed) {
		/* Timer / pwm subdevice */
		s = &dev->subdevices[3];
		s->type		= COMEDI_SUBD_PWM;
		s->subdev_flags	= SDF_WRITABLE | SDF_PWM_HBRIDGE;
		s->n_chan	= 8;
		s->maxdata	= devpriv->pwm_buf_sz;
		s->insn_write	= usbduxsigma_pwm_write;
		s->insn_config	= usbduxsigma_pwm_config;

		usbduxsigma_pwm_period(dev, s, PWM_DEFAULT_PERIOD);
	}

	offset = usbduxsigma_getstatusinfo(dev, 0);
	if (offset < 0) {
		dev_err(dev->class_dev,
			"Communication to USBDUXSIGMA failed! Check firmware and cabling.\n");
		return offset;
	}

	dev_info(dev->class_dev, "ADC_zero = %x\n", offset);

	return 0;
}

static void usbduxsigma_detach(struct comedi_device *dev)
{
	struct usb_interface *intf = comedi_to_usb_interface(dev);
	struct usbduxsigma_private *devpriv = dev->private;

	usb_set_intfdata(intf, NULL);

	if (!devpriv)
		return;

	down(&devpriv->sem);

	/* force unlink all urbs */
	usbduxsigma_ai_stop(dev, 1);
	usbduxsigma_ao_stop(dev, 1);
	usbduxsigma_pwm_stop(dev, 1);

	usbduxsigma_free_usb_buffers(dev);

	up(&devpriv->sem);
}

static struct comedi_driver usbduxsigma_driver = {
	.driver_name	= "usbduxsigma",
	.module		= THIS_MODULE,
	.auto_attach	= usbduxsigma_auto_attach,
	.detach		= usbduxsigma_detach,
};

static int usbduxsigma_usb_probe(struct usb_interface *intf,
				 const struct usb_device_id *id)
{
	return comedi_usb_auto_config(intf, &usbduxsigma_driver, 0);
}

static const struct usb_device_id usbduxsigma_usb_table[] = {
	{ USB_DEVICE(0x13d8, 0x0020) },
	{ USB_DEVICE(0x13d8, 0x0021) },
	{ USB_DEVICE(0x13d8, 0x0022) },
	{ }
};
MODULE_DEVICE_TABLE(usb, usbduxsigma_usb_table);

static struct usb_driver usbduxsigma_usb_driver = {
	.name		= "usbduxsigma",
	.probe		= usbduxsigma_usb_probe,
	.disconnect	= comedi_usb_auto_unconfig,
	.id_table	= usbduxsigma_usb_table,
};
module_comedi_usb_driver(usbduxsigma_driver, usbduxsigma_usb_driver);

MODULE_AUTHOR("Bernd Porr, BerndPorr@f2s.com");
MODULE_DESCRIPTION("Stirling/ITL USB-DUX SIGMA -- Bernd.Porr@f2s.com");
MODULE_LICENSE("GPL");
MODULE_FIRMWARE(FIRMWARE);


e col stats computed purely with PyTorch
            # (without mapping back to pandas series).
            transformed_col_stats[col] = compute_col_stats(
                transformed_df[col], stype.numerical)

        self._transformed_stats = transformed_col_stats

    def _forward(self, tf: TensorFrame) -> TensorFrame:
        if stype.categorical not in tf.col_names_dict:
            logging.info(
                "The input TensorFrame does not contain any categorical "
                "columns. The original TensorFrame will be returned.")
            return tf
        tensor = self._replace_nans(
            tf.feat_dict[stype.categorical],
            NAStrategy.MOST_FREQUENT,
        )
        if not torch.is_floating_point(tf.y) and tf.y.max() > 1:
            num_rows, num_cols = tf.feat_dict[stype.categorical].shape
            transformed_tensor = torch.zeros(
                num_rows,
                num_cols * (self.num_classes - 1),
                dtype=torch.float32,
                device=tf.device,
            )
        else:
            transformed_tensor = torch.zeros_like(
                tf.feat_dict[stype.categorical],
                dtype=torch.float32,
            )
        target_mean = self.target_mean.to(tf.device)
        for i in range(len(tf.col_names_dict[stype.categorical])):
            col_name = tf.col_names_dict[stype.categorical][i]
            count = torch.tensor(
                self.col_stats[col_name][StatType.COUNT][1],
                device=tf.device,
            )
            feat = tensor[:, i]
            max_cat = feat.max()
            if max_cat >= len(count):
                raise RuntimeError(
                    f"'{col_name}' contains new category '{max_cat}' not seen "
                    f"during fit stage.")
            v = count[feat].unsqueeze(1).repeat(1, self.num_classes - 1)
            start = i * (self.num_classes - 1)
            end = (i + 1) * (self.num_classes - 1)
            transformed_tensor[:, start:end] = ((v + target_mean) /
                                                (self.data_size + 1))

        # turn the categorical features into numerical features
        if stype.numerical in tf.feat_dict:
            tf.feat_dict[stype.numerical] = torch.cat(
                (tf.feat_dict[stype.numerical], transformed_tensor),
                dim=1).to(torch.float32)
            tf.col_names_dict[stype.numerical] = tf.col_names_dict[
                stype.numerical] + self.new_columns
        else:
            tf.feat_dict[stype.numerical] = transformed_tensor
            tf.col_names_dict[stype.numerical] = self.new_columns
        # delete the categorical features
        tf.col_names_dict.pop(stype.categorical)
        tf.feat_dict.pop(stype.categorical)

        return tf


yjälle kauppapyynnön, sinulla on aikaikkuna suorittaa maksu loppuun ennen kuin myyjä voi peruuttaa kaupan (maksuikkuna vaihtelee kaupan maksutavan mukaan). Tänä aikana sinun on suoritettava maksu loppuun ja painettava Olen maksanut -painiketta. Myyjälle ilmoitetaan, että olet suorittanut maksun ja Moneroa pidetään välimiesmaksussa, kunnes myyjä saa kaupan päätökseen puolestasi nähdessään maksun tilillään. Jos maksoit ostoksen, mutta et merkinnyt maksua suoritetuksi ennen maksuaikaikkunan umpeutumista, ota yhteyttä myyjään kaupan kautta. Voit ottaa yhteyttä myyjään ja muihin olemassa oleviin kauppakontakteihisi $dashboard:lta $appName-käyttäjäprofiilissasi. Lähetä myyjälle viesti ja kerro ystävällisesti tilanne ja miksi et voinut suorittaa maksua aikaikkunassa. Jos myyjä ei vastaa tähän pyyntöön, ota yhteyttä $appName-tukeen käyttämällä $supportRequestForm ja mainitse kauppatunnuksesi.';
  }

  @override
  String get faq250Sbanswer8722Sb248722Sbdashboard => 'Kojelauta';

  @override
  String get faq250Sbanswer8722Sb248722Sbsupport8722Sbrequest8722Sbform => 'tukipyyntölomake';

  @override
  String faq250Sbanswer8722Sb2457Sbagoradesk(Object dashboard, Object appName, Object supportRequestForm) {
    return 'Kun olet lähettänyt kauppapyynnön, sinulla on aikaikkuna suorittaa maksu loppuun, ennen kuin toinen osapuoli voi peruuttaa kaupan. Tänä aikana sinun on suoritettava maksu ja painettava \"Olen maksanut\" -painiketta. Toiselle osapuolelle ilmoitetaan, että olet suorittanut maksun, ja kolikot pidetään välimiesmaksussa, kunnes toinen osapuoli viimeistelee kaupan puolestasi nähtyään maksun tilillään. Jos maksoit ostoksen, mutta et merkinnyt maksua suoritetuksi ennen maksuajan umpeutumista, ota yhteyttä toiseen osapuoleen kauppachatin kautta. Voit ottaa yhteyttä toiseen osapuoleen ja muihin olemassa oleviin kauppakontakteihisi $dashboard:lta. Lähetä viesti toiselle osapuolelle ja kerro ystävällisesti tilanne ja miksi et voinut suorittaa maksua aikaikkunassa. Jos toinen osapuoli ei vastaa tähän pyyntöön, ota yhteyttä $appName:n henkilökuntaan käyttämällä numeroa $supportRequestForm ja mainitse kauppatunnuksesi.';
  }

  @override
  String get faq250Sbanswer8722Sb25 => 'Kun ostaja tai myyjä riitauttaa kaupan, järjestelmänvalvoja astuu kauppakeskusteluun ja pyytää molemmilta osapuolilta todisteita ja ottaa huomioon chat-historian ja käyttäjien maineen tehdäkseen mahdollisimman oikeudenmukaisen päätöksen.';

  @override
  String faq250Sbanswer8722Sb26(Object appName) {
    return 'Monero-transakti


# RUN: llvm-mc -triple=hexagon -filetype=obj -o - %s | llvm-objdump -d - | FileCheck %s
# Hexagon Programmer's Reference Manual 11.10.8 XTYPE/SHIFT

# Shift by immediate
# CHECK: 10 df 14 80
r17:16 = asr(r21:20, #31)
# CHECK: 30 df 14 80
r17:16 = lsr(r21:20, #31)
# CHECK: 50 df 14 80
r17:16 = asl(r21:20, #31)
# CHECK: 11 df 15 8c
r17 = asr(r21, #31)
# CHECK: 31 df 15 8c
r17 = lsr(r21, #31)
# CHECK: 51 df 15 8c
r17 = asl(r21, #31)

# Shift by immediate and accumulate
# CHECK: 10 df 14 82
r17:16 -= asr(r21:20, #31)
# CHECK: 30 df 14 82
r17:16 -= lsr(r21:20, #31)
# CHECK: 50 df 14 82
r17:16 -= asl(r21:20, #31)
# CHECK: 90 df 14 82
r17:16 += asr(r21:20, #31)
# CHECK: b0 df 14 82
r17:16 += lsr(r21:20, #31)
# CHECK: d0 df 14 82
r17:16 += asl(r21:20, #31)
# CHECK: 11 df 15 8e
r17 -= asr(r21, #31)
# CHECK: 31 df 15 8e
r17 -= lsr(r21, #31)
# CHECK: 51 df 15 8e
r17 -= asl(r21, #31)
# CHECK: 91 df 15 8e
r17 += asr(r21, #31)
# CHECK: b1 df 15 8e
r17 += lsr(r21, #31)
# CHECK: d1 df 15 8e
r17 += asl(r21, #31)
# CHECK: 4c f7 11 de
r17 = add(#21, asl(r17, #23))
# CHECK: 4e f7 11 de
r17 = sub(#21, asl(r17, #23))
# CHECK: 5c f7 11 de
r17 = add(#21, lsr(r17, #23))
# CHECK: 5e f7 11 de
r17 = sub(#21, lsr(r17, #23))

# Shift by immediate and add
# CHECK: f1 d5 1f c4
r17 = addasl(r21, r31, #7)

# Shift by immediate and logical
# CHECK: 10 df 54 82
r17:16 &= asr(r21:20, #31)
# CHECK: 30 df 54 82
r17:16 &= lsr(r21:20, #31)
# CHECK: 50 df 54 82
r17:16 &= asl(r21:20, #31)
# CHECK: 90 df 54 82
r17:16 |= asr(r21:20, #31)
# CHECK: b0 df 54 82
r17:16 |= lsr(r21:20, #31)
# CHECK: d0 df 54 82
r17:16 |= asl(r21:20, #31)
# CHECK: 30 df 94 82
r17:16 ^= lsr(r21:20, #31)
# CHECK: 50 df 94 82
r17:16 ^= asl(r21:20, #31)
# CHECK: 11 df 55 8e
r17 &= asr(r21, #31)
# CHECK: 31 df 55 8e
r17 &= lsr(r21, #31)
# CHECK: 51 df 55 8e
r17 &= asl(r21, #31)
# CHECK: 91 df 55 8e
r17 |= asr(r21, #31)
# CHECK: b1 df 55 8e
r17 |= lsr(r21, #31)
# CHECK: d1 df 55 8e
r17 |= asl(r21, #31)
# CHECK: 31 df 95 8


- callback = function(player, states, oldStates)
context.onStatesChange = function(callback)
  return context.callback("onStatesChange", callback)
end

-- onGameEditText - callback = function(id, itemId, maxLength, text, writer, time)
context.onGameEditText = function(callback)
  return context.callback("onGameEditText", callback)
end

-- onSpellCooldown - callback = function(iconId, duration)
context.onSpellCooldown = function(callback)
  return context.callback("onSpellCooldown", callback)
end

-- onGroupSpellCooldown - callback = function(iconId, duration)
context.onGroupSpellCooldown = function(callback)
  return context.callback("onGroupSpellCooldown", callback)
end

-- onInventoryChange - callback = function(player, slot, item, oldItem)
context.onInventoryChange = function(callback)
  return context.callback("onInventoryChange", callback)
end

-- CUSTOM CALLBACKS

-- listen(name, callback) -- callback = function(text, channelId, pos)
context.listen = function(name, callback)
  if not name then return context.error("listen: invalid name") end


,
  -170733.0,
  -204586.0,
  -129620.0,
  108743.0,
  104755.0,
  10321.0,
  0.0,
  79661.0,
  -34782.0,
  -23210.0,
  -21636.0,
  24208.0,
  30824.0,
  -8379.0,
  -16675.0,
  -12831.0,
  -10445.0,
  -11650.0,
  14403.0,
  -7003.0,
  0.0,
  10056.0,
  6322.0,
  -9884.0,
  5751.0,
  0.0,
  -4950.0,
  4130.0,
  0.0,
  -3958.0,
  0.0,
  3258.0,
  2616.0,
  -1897.0,
  -2117.0,
  2354.0,
  0.0,
  0.0,
  -1423.0,
  -1117.0,
  -1571.0,
  -1739.0,
  0.0,
  -4421.0,
  0.0,
  0.0,
  0.0,
  0.0,
  1165.0,
  0.0,
  0.0,
  8752.0
];

const _tabLat = <double>[
  5128122.0,
  280602.0,
  277693.0,
  173237.0,
  55413.0,
  46271.0,
  32573.0,
  17198.0,
  9266.0,
  8822.0,
  8216.0,
  4324.0,
  4200.0,
  -3359.0,
  2463.0,
  2211.0,
  2065.0,
  -1870.0,
  1828.0,
  -1794.0,
  -1749.0,
  -1565.0,
  -1491.0,
  -1475.0,
  -1410.0,
  -1344.0,
  -1335.0,
  1107.0,
  1021.0,
  833.0,
  777.0,
  671.0,
  607.0,
  596.0,
  491.0,
  -451.0,
  439.0,
  422.0,
  421.0,
  -366.0,
  -351.0,
  331.0,
  315.0,
  302.0,
  -283.0,
  -229.0,
  223.0,
  223.0,
  -220.0,
  -220.0,
  -185.0,
  181.0,
  -177.0,
  176.0,
  166.0,
  -164.0,
  132.0,
  -119.0,
  115.0,
  107.0
];

const List<List<int>> _tabCoef1 = [
  [0, 0, 1, 0],
  [2, 0, -1, 0],
  [2, 0, 0, 0],
  [0, 0, 2, 0],
  [0, 1, 0, 0],
  [0, 0, 0, 2],
  [2, 0, -2, 0],
  [2, -1, -1, 0],
  [2, 0, 1, 0],
  [2, -1, 0, 0],
  [0, 1, -1, 0],
  [1, 0, 0, 0],
  [0, 1, 1, 0],
  [2, 0, 0, -2],
  [0, 0, 1, 2],
  [0, 0, 1, -2],
  [4, 0, -1, 0],
  [0, 0, 3, 0],
  [4, 0, -2, 0],
  [2, 1, -1, 0],
  [2, 1, 0, 0],
  [1, 0, -1, 0],
  [1, 1, 0, 0],
  [2, -1, 1, 0],
  [2, 0, 2, 0],
  [4, 0, 0, 0],
  [


CatsResponse>[]
) => {
  return {
    type: FETCH_FAVOURITE_CATS_SUCCESS,
    payload: {
      ids,
    },
  }
}

export const voteCat = (catId: string, value: number) => ({
  type: VOTE_CAT,
  payload: {
    catId,
    value,
  },
})

export const fetchVotes = () => ({
  type: FETCH_VOTES,
})

export const fetchVotesSuccess = (
  response: Partial<FetchVoteResponeType>[]
) => {
  return {
    type: FETCH_VOTES_SUCCESS,
    payload: {
      response,
    },
  }
}
export interface ISession {
    ip: string
    flagged: boolean
    score: number
    attempts: IAttempt[]
    _score: number
}

export interface IAttempt {
    email: string
    time: number
}

interface ISuccessResponse<T> {
    success: true
    data: T
}

interface IFailureResponse {
    success: true
    message: string
}

type IResponse<T> = ISuccessResponse<T> | IFailureResponse

export type IValidationResult = IResponse<ISession>import TelegramBot from "node-telegram-bot-api";
import { Redis } from "./../services";

export const answerHandler = (bot: TelegramBot, client: Redis) => {
    return async (msg: TelegramBot.Message, match: RegExpExecArray): Promise<void> => {
        const chatId = msg.chat.id;
        const resp = match[1];

        const quizQuestionData = await client.getValueByKey(String(chatId));

        if (!quizQuestionData) {
            await bot.sendMessage(chatId, "The time allotted for the answer has expired (5 min) 🕐🕐🕐🕐🕐!");
            return;
        }

        const parsedQuizQuestionData = JSON.parse(quizQuestionData);
        const questionAnswer = parsedQuizQuestionData.answer.split(" ").pop();

        if (resp === questionAnswer) {
            await bot.sendMessage(chatId, "Correct answer!");
            await bot.sendMessage(chatId, "🥳🥳🥳🥳👍👍👍");
        } else {
            await bot.sendMessage(chatId, "Wrong answer!");
            await bot.sendMessage(chatId, "🥶🥶🥶😭😭😭");
        }

        const explanation = parsedQuizQuestionData.explanation;
        if (explanation) {
            await bot.sendMessage(chatId, "Explanation!");
            await bot.sendMessage(chatId, explanation, { parse_mode: "Markdown" });
        }
    };
};
/**
 * Update attribute in object even if its deep
 * If this attribute does not exist, creates it
 *
 * @param obj Object to be updated
 * @param deepAttr Attribute value to update. Form: "a.b.c"
 * @param value Value to assign to this attribute
 */
export function updateObjectAttribute(obj: any, deepAttr: string, value: any) {
    recursiveUpdateObjectAttribute(obj, deepAttr.split("."), value);
}

function recursiveUpdateObjectAttribute(obj: any, chainedAttrs: string[], value: any) {
    const attr = chainedAttrs.shift();

    if (!obj.hasOwnProperty(attr)) {
        // Create new object
        obj[attr] = {};
    }

    if (chainedAttrs.length === 0) {
        // No more attribute, apply value
        obj[attr] = value;
    } else {
        recursiveUpdateObjectAttribute(obj[attr], chainedAttrs, value);
    }
}
export interface Mover {
  s: number[][]; // Shape vertices [[x, y], [x, y]]
  x: number; // x pos
  y: number; // y pos
  vx: number; // x velocity px/s
  vy: number; // y velocity px/s
}import {paginationI


*************************************************/
        /// <summary>
        /// Entry Method for the test case
        /// </summary>
        TestResult StartTest()
        {
            GlobalLog.LogStatus("Creating StackPanel, Border, TextPanel, Paragraph");
            StackPanel stackPanel = new StackPanel();
            Border border = new Border();
            FlowDocumentScrollViewer fdsv = new FlowDocumentScrollViewer();
            FlowDocument textPanel = fdsv.Document = new FlowDocument();

            GlobalLog.LogStatus("Creating ResourceDictionaryHelper");
            ResourceDictionaryHelper resourceDictionayHelper = new ResourceDictionaryHelper();

            GlobalLog.LogStatus("Setting FlowDocumentScrollViewer.Resources to new resources dictionary");
            textPanel.Resources = resourceDictionayHelper.CreateBrushesFontWeights();

            border.BorderThickness = new Thickness(2);

            Paragraph paragraph = new Paragraph();
            textPanel.Blocks.Add(paragraph);

            TextPointer pointer;
            pointer = (textPanel.ContentEnd);
            pointer = pointer.GetNextContextPosition(LogicalDirection.Backward);
            Paragraph para = (Paragraph)pointer.Parent;

            GlobalLog.LogStatus("Setting Paragraph.FontWeightProperty to value in the resource dictionary");
            para.SetResourceReference(Paragraph.FontWeightProperty, "FontBold");

            GlobalLog.LogStatus("Building the tree");

            border.Child = fdsv;
            stackPanel.Children.Add(border);

            //para.Append ("hello world or hello universe?").

            string fontWeight = para.FontWeight.ToString();
            ////            CheckResults(fontWeight == "Bold","Checking FontWight Property of Paragraph", "Bold", fontWeight).

            GlobalLog.LogStatus("Setting FontWeight property directly now and see if it works");
            para.FontWeight = FontWeights.ExtraBold;

            fontWeight = para.FontWeight.ToString();
            CheckResults(fontWeight == "ExtraBold", "Checking FontWight Property of Paragraph", "ExtraBold", fontWeight);

            //Any test failures will be caught by throwing an Exception during verification.
            return TestResult.Pass;
        }
        #endregion
    }
}


onvertedCode extends TerraformStack {
  constructor(scope: Construct, name: string) {
    super(scope, name);
    const fs = new EfsFileSystem(this, "fs", {
      creationToken: "my-product",
    });
    const policy = new DataAwsIamPolicyDocument(this, "policy", {
      statement: [
        {
          actions: [
            "elasticfilesystem:ClientMount",
            "elasticfilesystem:ClientWrite",
          ],
          condition: [
            {
              test: "Bool",
              values: ["true"],
              variable: "aws:SecureTransport",
            },
          ],
          effect: "Allow",
          principals: [
            {
              identifiers: ["*"],
              type: "AWS",
            },
          ],
          resources: [fs.arn],
          sid: "ExampleStatement01",
        },
      ],
    });
    const awsEfsFileSystemPolicyPolicy = new EfsFileSystemPolicy(
      this,
      "policy_2",
      {
        fileSystemId: fs.id,
        policy: Token.asString(policy.json),
      }
    );
    /*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
    awsEfsFileSystemPolicyPolicy.overrideLogicalId("policy");
  }
}

```

## Argument Reference

The following arguments are required:

* `fileSystemId` - (Required) The ID of the EFS file system.
* `policy` - (Required) The JSON formatted file system policy for the EFS file system. see [Docs](https://docs.aws.amazon.com/efs/latest/ug/access-control-overview.html#access-control-manage-access-intro-resource-policies) for more info.

The following arguments are optional:

* `bypassPolicyLockoutSafetyCheck` - (Optional) A flag to indicate whether to bypass the `aws_efs_file_system_policy` lockout safety check. The policy lockout safety check determines whether the policy in the request will prevent the principal making the request will be locked out from making future `PutFileSystemPolicy` requests on the file system. Set `bypassPolicyLockoutSafetyCheck` to `true` only when you intend to prevent the principal that is making the request from making a subsequent `PutFileSystemPolicy` request on the file system. The default value is `false`.

## Attribute Reference

This resource exports the following attributes in addition to the arguments above:

* `id` - The ID that identifies the file system (e.g., fs-ccfc0d65).

## Import

In Terraform v1.5.0 and later, use an [`import` block](https://developer.hashicorp.com/terraform/language/import) to import the EFS file system policies using the `id`. For example:

```typescript
// DO NOT EDIT. Code generated by 'cdktf convert' - Please report bugs at https://cdk.tf/bug
import { Construct } from "constructs";
import { TerraformStack } from "cdktf";
/*
 * Provider bindings are generated by running `cdktf get`.
 * See https://cdk.tf/provider-generation for more details.
 */
import { EfsFileSystemPolicy } from "./.gen/providers/aws/efs-file-system-policy";
class MyConvertedCode extends TerraformStack {
  constructor(scope: Construct, name: string) {
    super(scope, name);
    EfsFileSystemPolicy.generateConfigForImport(this, "foo", "fs-6fa144c6");
  }
}

```

Using `terraform import`, import the EFS file system policies using the `id`. For example:

```console
% terraform import aws_efs_file_system_policy.foo fs-6fa144c6
```

<!-- cache-key: cdktf-0.20.8 input-51ce0e6776bd5a12b73f8fd6edc2135ed20119de727978bb7a52e39fe7641ce


import glob
import json
import os

from jsonschema import ValidationError, validate

def load_json(file_path: str) -> dict:
    """Load a JSON file from the given file path."""
    with open(file_path) as file:
        return json.load(file)

def validate_model(model_path: str, schema: dict) -> None:
    """Validate a JSON model against the schema."""
    try:
        model = load_json(model_path)
        validate(instance=model, schema=schema)
        print(f"VALID: {model_path}")  # noqa: T201
    except ValidationError as e:
        print(f"INVALID: {model_path}\nError: {e.message}")  # noqa: T201
    except Exception as e:  # noqa: BLE001
        print(f"ERROR: {model_path}\nError: {e}")  # noqa: T201

def validate_models_with_glob(directory: str, schema_path: str) -> None:
    """Validate model.json files up to 2 subdirectory levels using glob."""
    schema = load_json(schema_path)
    pattern = os.path.join(directory, "*/*/model.json")
    for model_path in glob.glob(pattern):
        validate_model(model_path, schema)

if __name__ == "__main__":
    directory = os.path.join(os.path.dirname(__file__), "../../profile_library")
    schema_file_path = os.path.join(os.path.dirname(__file__), "../../profile_library/model_schema.json")

    validate_models_with_glob(directory, schema_file_path)


{
            Backup(opt) => commands::backup::backup(opt)?,
            CleanUnusedKernels => commands::clean_unused_kernels::run()?,
            Completions(opt) => commands::completion::generate_completion(opt),
            Infect(opt) => commands::infect::infect(opt)?,
            Info => commands::info::print_info()?,
            Setup(opt) => commands::setup::setup(opt)?,
            Template => commands::template::menu()?,
            Tmux(opt) => commands::tmux::handle_tmux_helpers(opt)?,
        }
    } else {
        launcher::main(cmdline)?;
    }
    Ok(())
}
use async_trait::async_trait;
use clap::Clap;

use crate::admin::topics::TopicDomain;
use crate::cmd::cmd::AsyncCmd;
use crate::context::PulsarContext;
use crate::error::Error;

#[derive(Clap, Debug, Clone)]
pub struct TopicsOpts {
    #[clap(subcommand)]
    pub cmd: Command,
}

#[async_trait]
impl AsyncCmd for TopicsOpts {
    async fn run(&self, pulsar_ctx: &mut PulsarContext) -> Result<(), Error> {
        let cmd: &dyn AsyncCmd = match &self.cmd {
            Command::List(opts) => opts,
            Command::Create(opts) => opts,
            Command::Delete(opts) => opts,
            Command::DeletePartitionedTopic(opts) => opts,
            Command::Lookup(opts) => opts,
            Command::Stats(opts) => opts,
            Command::Permissions(opts) => opts,
            Command::GrantPermissions(opts) => opts,
            Command::RevokePermissions(opts) => opts,
            Command::Subscriptions(opts) => opts,
            Command::Unsubscribe(opts) => opts,
        };
        cmd.run(pulsar_ctx).await?;
        Ok(())
    }
}

#[derive(Clap, Debug, Clone)]
pub enum Command {
    List(ListOpts),
    Create(CreateTopicOpts),
    Delete(DeleteTopicOpts),
    DeletePartitionedTopic(DeletePartitionedTopicOpts),
    Lookup(LookupOpts),
    Stats(StatsOpts),
    Permissions(PermissionsOpts),
    GrantPermissions(GrantPermissionsOpts),
    RevokePermissions(RevokePermissionsOpts),
    Subscriptions(SubscriptionsOpts),
    Unsubscribe(UnsubscribeOpts),
}

#[derive(Clap, Debug, Clone)]
pub struct ListOpts {
    pub namespace: String,

    #[clap(short = 'd', long, default_value = "Persistent")]
    pub domain: String,
}

#[async_trait]
impl AsyncCmd for ListOpts {
    async fn run(&self, pulsar_ctx: &mut PulsarContext) -> Result<(), Error> {
        let r = pulsar_ctx.admin().await?
            .topics()
            .list(self.namespace.as_str(), TopicDomain::parse(self.domain.as_ref())?)
            .await?;
        println!("{:?}", r);
        Ok(())
    }
}

#[derive(Clap, Debug, Clone)]
pub struct CreateTopicOpts {
    pub topic: String,

    #[clap(short = 'p', long, default_value = "0")]
    pub partitions: i32,
}

#[async_trait]
impl AsyncCmd for CreateTopicOpts {
    async fn run(&self, pulsar_ctx: &mut PulsarContext) -> Result<(), Error> {
        if self.partitions == 0 {
            pulsar_ctx.admin().await?
                .topics()
                .create_non_partitioned_topic(self.topic.as_str())
                .await?;
            Ok(())
        } else if self.partitions > 0 {
            pulsar_ctx.admin().await?
                .topics


 we init on the stack

            MLLoadString(IDS_ERROR,(LPTSTR) szTitle,MAX_PATH);
            MLLoadString(IDS_PICSRULES_OUTOFMEMORY,(LPTSTR) szMessage,MAX_PATH);

            MessageBox(NULL,(LPCTSTR) szMessage,(LPCTSTR) szTitle,MB_OK|MB_ICONERROR);

            return(E_OUTOFMEMORY);
        }

        pPRPolicyToCopy=g_pApprovedPRRS->m_arrpPRPolicy[iCounter];

        pPRPolicy->m_PRPolicyAttribute=pPRPolicyToCopy->m_PRPolicyAttribute;

        pPRByURL=new PICSRulesByURL;

        if(pPRByURL==NULL)
        {
            char    szTitle[MAX_PATH],szMessage[MAX_PATH];

            //out of memory, so we init on the stack

            MLLoadString(IDS_ERROR,(LPTSTR) szTitle,MAX_PATH);
            MLLoadString(IDS_PICSRULES_OUTOFMEMORY,(LPTSTR) szMessage,MAX_PATH);

            MessageBox(NULL,(LPCTSTR) szMessage,(LPCTSTR) szTitle,MB_OK|MB_ICONERROR);

            return(E_OUTOFMEMORY);
        }

        if(pPRPolicy->m_PRPolicyAttribute==PR_POLICY_ACCEPTBYURL)
        {
            pPRByURLToCopy=pPRPolicyToCopy->m_pPRAcceptByURL;

            pPRPolicy->m_pPRAcceptByURL=pPRByURL;
        }
        else
        {
            pPRByURLToCopy=pPRPolicyToCopy->m_pPRRejectByURL;

            pPRPolicy->m_pPRRejectByURL=pPRByURL;
        }

        pPRByURLExpression=new PICSRulesByURLExpression;

        if(pPRByURLExpression==NULL)
        {
            char    szTitle[MAX_PATH],szMessage[MAX_PATH];

            //out of memory, so we init on the stack

            MLLoadString(IDS_ERROR,(LPTSTR) szTitle,MAX_PATH);
            MLLoadString(IDS_PICSRULES_OUTOFMEMORY,(LPTSTR) szMessage,MAX_PATH);

            MessageBox(NULL,(LPCTSTR) szMessage,(LPCTSTR) szTitle,MB_OK|MB_ICONERROR);

            return(E_OUTOFMEMORY);
        }

        pPRByURLExpressionToCopy=pPRByURLToCopy->m_arrpPRByURL[0];

        if(pPRByURLExpressionToCopy==NULL)
        {
            char    *lpszTitle,*lpszMessage;

            //we shouldn't ever get here

            lpszTitle=(char *) GlobalAlloc(GPTR,MAX_PATH);
            lpszMessage=(char *) GlobalAlloc(GPTR,MAX_PATH);

            MLLoadString(IDS_ERROR,(LPTSTR) lpszTitle,MAX_PATH);
            MLLoadString(IDS_PICSRULES_NOAPPROVEDSAVE,(LPTSTR) lpszMessage,MAX_PATH);

            MessageBox(NULL,(LPCTSTR) lpszMessage,(LPCTSTR) lpszTitle,MB_OK|MB_ICONERROR);

            GlobalFree(lpszTitle);
            GlobalFree(lpszMessage);

            delete pPRPolicy;

            return(E_UNEXPECTED);
        }

        pPRByURLExpression->m_fInternetPattern=pPRByURLExpressionToCopy->m_fInternetPattern;
        pPRByURLExpression->m_bNonWild=pPRByURLExpressionToCopy->m_bNonWild;
        pPRByURLExpression->m_bSpecified=pPRByURLExpressionToCopy->m_bSpecified;
        pPRByURLExpression->m_etstrScheme.Set(pPRByURLExpressionToCopy->m_etstrScheme.Get());
        pPRByURLExpression->m_etstrUser.Set(pPRByURLExpressionToCopy->m_etstrUser.Get());
        pPRByURLExpression->m_etstrHost.Set(pPRByURLExpressionToCopy->m_etstrHost.Get());
        pPRByURLExpression->m_etstrPort.Set(pPRByURLExpressionToCopy->m_etstrPort.Get());