(List<Object?>? params) {
    _ensureMatchingParameters(params);
    if (params == null || params.isEmpty) return;

    // variables in sqlite are 1-indexed
    for (var i = 1; i <= params.length; i++) {
      final Object? param = params[i - 1];

      _bindParam(param, i);
    }

    _latestArguments = params;
  }

  void _bindMapParams(Map<String, Object?> params) {
    final expectedLength = parameterCount;
    final paramsAsList = List<Object?>.filled(expectedLength, null);

    if (params.isEmpty) {
      if (expectedLength != 0) {
        throw ArgumentError.value(params, 'params',
            'Expected $expectedLength parameters, but none were set.');
      }
      return;
    }

    for (final key in params.keys) {
      final Object? param = params[key];
      final i = statement.sqlite3_bind_parameter_index(key);

      // SQL parameters are 1-indexed, so 0 indicates that no parameter with
      // that name was found.
      if (i == 0) {
        throw ArgumentError.value(params, 'params',
            'This statement contains no parameter named `$key`');
      }
      _bindParam(param, i);
      paramsAsList[i - 1] = param;
    }

    // If we reached this point. All parameters from [params] were bound. Check
    // if the statement contains no additional parameters.
    if (expectedLength != params.length) {
      throw ArgumentError.value(
          params, 'params', 'Expected $expectedLength parameters');
    }

    _latestArguments = paramsAsList;
  }

  void _bindParam(Object? param, int i) {
    final rc = switch (param) {
      null => statement.sqlite3_bind_null(i),
      int() => statement.sqlite3_bind_int64(i, param),
      BigInt() => statement.sqlite3_bind_int64BigInt(i, param.checkRange),
      bool() => statement.sqlite3_bind_int64(i, param ? 1 : 0),
      double() => statement.sqlite3_bind_double(i, param),
      String() => statement.sqlite3_bind_text(i, param),
      List<int>() => statement.sqlite3_bind_blob64(i, param),
      _ => _bindCustomParam(param, i)
    };

    if (rc != SqlError.SQLITE_OK) {
      throwException(
        database,
        rc,
        operation: 'binding parameter',
        previousStatement: sql,
        statementArgs: _latestArguments,
      );
    }
  }

  int _bindCustomParam(Object param, int i) {
    if (param is CustomStatementParameter) {
      param.applyTo(this, i);
      return 0;
    }

    throw ArgumentError.value(
      param,
      'params[$i]',
      'Allowed parameters must either be null or bool, int, num, String or '
          'List<int>.',
    );
  }

  void _bindParams(StatementParameters parameters) {
    switch (parameters) {
      case IndexedParameters():
        _bindIndexedParams(parameters.parameters);
      case NamedParameters():
        _bindMapParams(parameters.parameters);
      case CustomParameters():
        parameters.bind(this);
    }
  }

  @override
  void reset() {
    _reset(invalidateArgs: false);
  }

  @override
  void dispose() {
    if (!finalizable._closed) {
      disposeFinalizer.detach(this);
      finalizable.dispose();

      database.handleFinalized(this);
    }
  }

  @override
  ResultSet selectWith(StatementParameters parameters) {
    _ensureNotFinalized();

    _reset();
    _bindParams(parameters);

    return _selectResults();
  }

  @override
  void executeWith(StatementParameters parameters) {
    _ensureNotFinalized();

    _reset();
    _bindParams


 Component<O, B>): Component<O, B> {
    return new FlatMapComponent(this, f);
  }
  chain<B>(f: (a: A) => Component<O, B>): Component<O, B> {
    return new FlatMapComponent(this, f);
  }
  output<P>(f: (a: A) => P): Component<O & P, A>;
  output<B extends Record<string, keyof A>>(
    remaps: B
  ): Component<O & Remap<A, B>, A>;
  output(handler: any): Component<any, A> {
    if (typeof handler === "function") {
      return new HandleOutput((e, o) => mergeObj(e, handler(o)), this);
    } else {
      return new HandleOutput(
        (e, o) => mergeObj(e, copyRemaps(handler, o)),
        this
      );
    }
    // return new OutputComponent(remaps, this);
  }
  static multi: boolean = false;
  multi: boolean = false;
  abstract run(
    parent: DomApi,
    destroyed: Future<boolean>
  ): { explicit: O; output: A };
  // Definitions below are inserted by Jabz
  flatten: <B>() => Component<O, B>;
  map: <B>(f: (a: A) => B) => Component<O, B>;
  mapTo: <B>(b: B) => Component<O, B>;
  ap: <B, P>(a: Component<P, (a: A) => B>) => Component<O, B>;
  lift: (f: Function, ...ms: any[]) => Component<O, any>;
}

class OfComponent<A> extends Component<{}, A> {
  constructor(private value: A) {
    super();
  }
  run(_1: Node, _2: Future<boolean>): { explicit: {}; output: A } {
    return { explicit: {}, output: this.value };
  }
}

class PerformComponent<A> extends Component<{}, A> {
  constructor(private cb: () => A) {
    super();
  }
  run(_1: Node, _2: Future<boolean>): { explicit: {}; output: A } {
    return { explicit: {}, output: this.cb() };
  }
}

/**
 * Takes a callback, potentially with side-effects. The callback is invoked when
 * the component is run and the return value becomes the components output.
 */
export function performComponent<A>(callback: () => A): Component<{}, A> {
  return new PerformComponent(callback);
}

export function liftNow<A>(now: Now<A>): Component<{}, A> {
  return performComponent(() => runNow(now));
}

class OutputComponent extends Component<any, any> {
  constructor(
    private remaps: Record<string, string>,
    private comp: Component<any, any>
  ) {
    super();
    // this.explicitOutput = Object.keys(remaps);
  }
  run(parent: DomApi, destroyed: Future<boolean>): any {
    const { explicit, output } = this.comp.run(parent, destroyed);
    const newExplicit = copyRemaps(this.remaps, output);
    const finalExplicit = mergeObj(output, newExplicit);
    return { explicit: newExplicit, output };
  }
}

class HandleOutput<O, A, P> extends Component<P, A> {
  constructor(
    private readonly handler: (explicit: O, output: A) => P,
    private readonly c: Component<O, A>
  ) {
    super();
  }
  run(parent: DomApi, destroyed: Future<boolean>): Out<P, A> {
    const { explicit, output } = this.c.run(parent, destroyed);
    const newExplicit = this.handler(explicit, output);
    return { explicit: newExplicit, output };
  }
}

type AnyValues<A extends Record<string, any>> = { [K in keyof A]: any };

export type Remap<
  A extends Record<any, any>,
  B extends Record<any, keyof A>
> = { [K in keyof B]: A[B[K]] };

expor


ecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            if (Stats.UseWebProxy && Stats.SucceededTestProxy) {
                WebProxy webproxy = new WebProxy($"{Stats.ProxyAddress}:{(!string.IsNullOrEmpty(Stats.ProxyPort) ? Stats.ProxyPort : "80")}", false) {
                    BypassProxyOnLocal = false
                };

                if (Stats.EnableProxyAuthentication && !string.IsNullOrEmpty(Stats.ProxyUsername) && !string.IsNullOrEmpty(Stats.ProxyPassword)) {
                    webproxy.Credentials = new NetworkCredential(Stats.ProxyUsername, Stats.ProxyPassword);
                }

                request.Proxy = webproxy;
            }

            return request;
        }
    }
}


uint32_t			st_cmd_active;
	uint32_t			st_cmd_inactive;
	uint32_t			st_cmd_pending;
	uint32_t			st_cmd_waiting;
	uint32_t			st_rx_active;
	uint32_t			st_rx_inactive;
	uint32_t			st_tx_active;
	uint32_t			st_tx_inactive;
	uint32_t			st_tx_pending;
};
#define	UATH_STAT_INC(sc, var)		(sc)->sc_stat.var++
#define	UATH_STAT_DEC(sc, var)		(sc)->sc_stat.var--

struct uath_vap {
	struct ieee80211vap		vap;
	int				(*newstate)(struct ieee80211vap *,
					    enum ieee80211_state, int);
};
#define	UATH_VAP(vap)			((struct uath_vap *)(vap))

struct uath_softc {
	struct ieee80211com		sc_ic;
	struct mbufq			sc_snd;
	device_t			sc_dev;
	struct usb_device		*sc_udev;
	void				*sc_cmd_dma_buf;
	void				*sc_tx_dma_buf;
	struct mtx			sc_mtx;
	uint32_t			sc_debug;

	struct uath_stat		sc_stat;
	int				(*sc_newstate)(struct ieee80211com *,
					    enum ieee80211_state, int);

	struct usb_xfer		*sc_xfer[UATH_N_XFERS];
	struct uath_cmd			sc_cmd[UATH_CMD_LIST_COUNT];
	uath_cmdhead			sc_cmd_active;
	uath_cmdhead			sc_cmd_inactive;
	uath_cmdhead			sc_cmd_pending;
	uath_cmdhead			sc_cmd_waiting;
	struct uath_data		sc_rx[UATH_RX_DATA_LIST_COUNT];
	uath_datahead			sc_rx_active;
	uath_datahead			sc_rx_inactive;
	struct uath_data		sc_tx[UATH_TX_DATA_LIST_COUNT];
	uath_datahead			sc_tx_active;
	uath_datahead			sc_tx_inactive;
	uath_datahead			sc_tx_pending;

	uint32_t			sc_msgid;
	uint32_t			sc_seqnum;
	int				sc_tx_timer;
	struct callout			watchdog_ch;
	struct callout			stat_ch;
	/* multi-chunked support  */
	struct mbuf			*sc_intrx_head;
	struct mbuf			*sc_intrx_tail;
	uint8_t				sc_intrx_nextnum;
	uint32_t			sc_intrx_len;
#define	UATH_MAX_INTRX_SIZE		3616

	struct uath_devcap		sc_devcap;
	uint8_t				sc_serial[16];

	/* unsorted  */
	uint32_t			sc_flags;
#define	UATH_FLAG_INVALID		(1 << 1)
#define	UATH_FLAG_INITDONE		(1 << 2)

	struct	uath_rx_radiotap_header	sc_rxtap;
	struct	uath_tx_radiotap_header	sc_txtap;
};

#define	UATH_LOCK(sc)			mtx_lock(&(sc)->sc_mtx)
#define	UATH_UNLOCK(sc)			mtx_unlock(&(sc)->sc_mtx)
#define	UATH_ASSERT_LOCKED(sc)		mtx_assert(&(sc)->sc_mtx, MA_OWNED)

#define	UATH_RESET_INTRX(sc) do {		\
	(sc)->sc_intrx_head = NULL;		\
	(sc)->sc_intrx_tail = NULL;		\
	(sc)->sc_intrx_nextnum = 0;		\
	(sc)->sc_intrx_len = 0;			\
} while (0)


>(suuntoExpiresAtTag);

      // load the data into Get
      await registerToken(localToken.accessToken, localToken.refreshToken, localToken.expiresAt);
    } catch (error) {
      debugPrint('Error while retrieving the token');
      localToken.accessToken = null;
      localToken.expiresAt = null;
    }

    if (localToken.expiresAt != null) {
      final dateExpired = DateTime.fromMillisecondsSinceEpoch(localToken.expiresAt!);
      final details =
          '${dateExpired.day.toString()}/${dateExpired.month.toString()} '
          '${dateExpired.hour.toString()} hours';
      debugPrint(
        'stored token ${localToken.accessToken} ${localToken.expiresAt} expires: $details',
      );
    }

    return localToken;
  }

  /// Get the authorization code from SUUNTO server
  ///
  Future<void> _getSuuntoCode(String clientId) async {
    debugPrint('Entering getSuuntoCode');

    final encodedRedirectUrl = Uri.encodeQueryComponent(redirectUrl);
    final params = "?response_type=code&client_id=$clientId&redirect_uri=$encodedRedirectUrl";
    final oAuth2Url = authorizationEndpoint + params;

    debugPrint(oAuth2Url);

    StreamSubscription? sub;

    launchUrlString(oAuth2Url, mode: LaunchMode.externalApplication);

    //--------  NOT working yet on web
    debugPrint('Running on iOS or Android');

    // Attach a listener to the stream
    sub = AppLinks().uriLinkStream.listen(
      (Uri? uri) {
        if (uri == null) {
          debugPrint('Subscription was null');
          sub?.cancel();
        } else {
          // Parse the link and warn the user, if it is not correct
          debugPrint('Got a link!! $uri');
          if (uri.scheme.compareTo('${redirectUrlScheme}_$clientId') != 0) {
            debugPrint('This is not the good scheme ${uri.scheme}');
          }
          final code = uri.queryParameters["code"] ?? notAvailable;
          final error = uri.queryParameters["error"];

          debugPrint('code $code, error $error');

          closeInAppWebView();
          onCodeReceived.add(code);

          debugPrint('Got the new code: $code');

          sub?.cancel();
        }
      },
      onError: (err) {
        // Handle exception by warning the user their action did not succeed
        debugPrint('Found an error $err');
        sub?.cancel();
      },
    );
  }

  Future<bool> hasValidToken() async {
    final prefService = Get.find<BasePrefService>();
    String? accessToken = prefService.get<String>(suuntoAccessTokenTag);
    if (accessToken == null || accessToken.isEmpty) {
      return false;
    }
    final SuuntoToken tokenStored = await _getStoredToken();
    accessToken = tokenStored.accessToken;
    return (accessToken?.length ?? 0) > 0;
  }

  /// Do SUUNTO Authentication.
  ///
  /// clientId: ID of your Suunto app
  /// secret: Secret of your Suunto app
  Future<bool> oauth(String clientId, String secret, String subscriptionKey) async {
    debugPrint('Welcome to SUUNTO OAuth');
    bool isAuthOk = false;

    final tokenStored = await _getStoredToken();
    final token = tokenStored.accessToken;

    final isExpired = _isTokenExpired(tokenStored);
    debugPrint('is token expired? $isExpired');

    bool storedBefore = token != null && token.isNotEmpty && token != "null";
    if (storedBefore) {
      debugPrint(
        'token has been stored before! '
        '${tokenStored.accessToken}  exp. ${tokenStored.expiresAt}',
      );


                                  # sim_11 = self.calculate(sim_10, sim_11)
                                                confidence_11 = AC_calculate(sim_11)
                                                if confidence_11[0] >= confidence_threshold[10]:
                                                    is_early = True
                                                    return 10, confidence_11[1], is_early,confidence_11[0]

                                                else:
                                                    layer_id = 11
                                                    is_early = False
                                                    if self.include_top:
                                                        output = self.avgpool(x11)
                                                        output = torch.flatten(output, 1)
                                                        output = self.fc(output)
                                                    ans = (output.argmax(1)).item()
                                                    return layer_id, ans, is_early,output.argmax(1)

def resnet34(num_classes=10, include_top=True):
    # https://download.pytorch.org/models/resnet34-333f7ec4.pth
    return ResNet(BasicBlock, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], num_classes=num_classes, include_top=include_top)

def resnet50(num_classes=10, include_top=True):
    # https://download.pytorch.org/models/resnet50-19c8e357.pth
    return ResNet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes, include_top=include_top)

def resnet101(num_classes=10, include_top=True):
    # https://download.pytorch.org/models/resnet101-5d3b4d8f.pth
    return ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes, include_top=include_top)

def resnext50_32x4d(num_classes=10, include_top=True):
    # https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth
    groups = 32
    width_per_group = 4
    return ResNet(Bottleneck, [3, 4, 6, 3],
                  num_classes=num_classes,
                  include_top=include_top,
                  groups=groups,
                  width_per_group=width_per_group)

def resnext101_32x8d(num_classes=10, include_top=True):
    # https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth
    groups = 32
    width_per_group = 8
    return ResNet(Bottleneck, [3, 4, 23, 3],
                  num_classes=num_classes,
                  include_top=include_top,
                  groups=groups,
                  width_per_group=width_per_group)

# data_transform = {
#     "train": transforms.Compose([transforms.RandomResizedCrop(120),
#                                  transforms.RandomHorizontalFlip(),
#                                  transforms.ToTensor(),
#                                  transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]),
#     "val": transforms.Compose([transforms.Resize((120, 120)),  # cannot 224, must (224, 224)
#                                transforms.ToTensor(),
#                                transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])}
#
# train_data = torchvision.datasets.ImageFolder(root="./train", transform=data_transform["train"])
#
# traindata = DataLoader(dataset=train_data, batch_size=128, shuffle=True, num_workers=0)  # 将训练数据以每次32张图片的形式抽出进行训练
#
# test_data = torchvision.datasets.ImageFolder(root="./test", transform=data_transform["val"])
#
# train_size = len(train_data)  # 训练集的长度
# test_size = len(test_data)  # 测试集的长度
# print(train_size)  # 输出训练集长度看一下，相当于看看有几张图片
# print(test_size)  # 输出测试集长度看一下，相当于看看有几张图片
# testdata = DataLoader(dataset=test_data, batch_size=128, shuffle=True, num_workers=0)  # 将训练数据以每次32张图片的形式抽出进行测试
semantic_center = torch.load('ResNet_semantic_center_1112.pth')

net = resnet34()
new_m = net.to(device)
# 测试所保存的模型
m_state_dict = torch.load('Resnet_1110.pth')
new_m.load_state_dict(m_state_dict)

mytransforms = transforms.Compose([
    transforms.Resize((7, 7)),
    transforms.ToTensor(),
    transforms.Normalize((0.1307),(0.3081))])

test1 = torch.ones(1, 1, 7, 7)  # 测试一下输出的形状大小 输入一个64,3,120,120的向量
test1.to(device)
macs, params = profile(new_m, inputs=(test1.to(device),))

print('macs:',macs,'params:',params)

f = open(r'calculate_resnet11_1112_1.txt', 'a')
print("macs:{}, params: {}".format(macs, params), file=f)
f.close()


Program.I().cardDescription.shiftCardShower(false);
        }
        if (gameInfo.queryHashedButton("hide_all_card") == true)
        {
            if (flagForTimeConfirm)
            {
                flagForTimeConfirm = false;
                MessageBeginTime = Program.TimePassed();
            }
            clearAllShowed();
        }
        else
        {
            if (Program.I().setting.setting.spyer.value == false)
                if (leftExcited)
                {
                    if (Input.GetKey(KeyCode.A) == false)
                    {
                        leftExcited = false;
                        //gameInfo.keepChain_set(false);
                    }

                }
        }
        base.ES_mouseUpEmpty();
    }

    public override void ES_mouseUpGameObject(GameObject gameObject)
    {
        if (gameObject==gameInfo.instance_lab.gameObject)
        {
            ES_mouseUpEmpty();
            return;
        }
        if (leftExcited)
        {
            if (Input.GetKey(KeyCode.A) == false)
            {
                leftExcited = false;
                //gameInfo.keepChain_set(false);
            }
        }
        base.ES_mouseUpGameObject(gameObject);
    }

    public override void ES_mouseUpRight()
    {
        base.ES_mouseUpRight();
        if (rightExcited)
        {
            if (Input.GetKey(KeyCode.S) == false)
            {
                rightExcited = false;
                //gameInfo.ignoreChain_set(false);
            }
        }
        if (gameInfo.queryHashedButton("sendSelected") == true)
        {
            sendSelectedCards();
            return;
        }
        if (flagForCancleChain)
        {
            flagForCancleChain = false;
            clearAllShowedB = true;
            BinaryMaster binaryMaster = new BinaryMaster();
            binaryMaster.writer.Write((Int32)(-1));
            sendReturn(binaryMaster.get());
            return;
        }
        if (gameInfo.queryHashedButton("hide_all_card") == true)
        {
            if (flagForTimeConfirm)
            {
                flagForTimeConfirm = false;
                MessageBeginTime = Program.TimePassed();
                clearAllShowed();
                return;
            }
        }
        if (gameInfo.queryHashedButton("cancleSelected") ==


ions.empty()) {
            leafCount++;
        }
    }

    // Prepare to accumulate error messages if any conditions are violated
    std::stringstream errors;

    if (rootCount != 1) {
        cout << "Error: There should be exactly one root node, found " << rootCount << ".\n";
    }

    if (leafCount != 1) {
        cout << "Error: There should be exactly one leaf node, found " << leafCount << ".\n";
    }

    // If there are any error messages, throw an exception
    if (!errors.str().empty()) {
        print_nfa(states);
        generate_nfa_diagram(states, "error_diagram\\ERROR");
        throw std::runtime_error(errors.str());
    }

    // std::cout << "The NFA configuration is correct." << std::endl;
}

// Function to generate a filename with a timestamp
std::string get_unique_filename(const std::string& base_name, const std::string& extension) {
    // Get current time
    std::time_t now = std::time(nullptr);  // Current time as time_t
    std::tm* now_tm = std::localtime(&now); // Convert time_t to tm as local time

    // Buffer to hold the formatted date and time string
    char buffer[80];

    // Format the time using strftime
    strftime(buffer, sizeof(buffer), "%Y%m%d_%H%M%S", now_tm);

    // Create a stringstream to format the filename
    std::stringstream ss;
    ss << base_name << "_" << buffer << "." << extension;

    return ss.str();
}

void generate_nfa_diagram(const std::vector<state*>& states,std::string base_filename) {
    return;
    std::string dot_filename = get_unique_filename(base_filename, "dot");
    std::string png_filename = get_unique_filename(base_filename, "png");

    // Write to dot file
    std::ofstream dot_file(dot_filename);
    if (!dot_file) {
        std::cerr << "Failed to open file for writing: " << dot_filename << std::endl;
        return;
    }

    dot_file << "digraph NFA {" << std::endl;
    dot_file << "    rankdir=LR;" << std::endl;
    dot_file << "    node [shape = circle];" << std::endl;

    for (size_t i = 0; i < states.size(); ++i) {
        for (const auto& trans : states[i]->transitions) {
            dot_file << "    " << i << " -> " << trans.next_state_idx
                     << " [label=\"" << trans.txt << "\"];" << std::endl;
        }
    }

    dot_file << "    " << 0 << " [shape=doublecircle, label=\"Start\"];" << std::endl;
    if (states.size() > 1) {
        dot_file << "    " << 1 << " [shape=doublecircle, label=\"End\"];" << std::endl;
    }

    dot_file << "}" << std::endl;
    dot_file.close();

    // Generate PNG using Graphviz
    std::string command = "dot -Tpng " + dot_filename + " -o " + png_filename;
    std::system(command.c_str());
}

std::string pre_process_regex(std::string reg)
{
    int j =0 ;
    bool skip_next = false;
    for(int i = 0; i < ((int)reg.length()-1); i++)
    {
        // printf("pre_processessing iter %d",i);
        if(skip_next)
        {
            skip_next = false;
            continue;
        }
        if((reg[i] == '+' || reg[i] == '*'|| reg[i] == '?'|| reg[i] == ')') && (reg[i+1] != '@'&& reg[i+1] != '+' &&  reg[i+


s = {}
    handlers = setmetatable({},{__mode="v"})
end

local function add_prepare_hook(hook)
    table.insert(g_prepare_hooks, hook)
end

local function run(expect_events)
    assert((expect_events == nil) or (expect_events >= 0))
    local n_events = 0
    while true do
        local wait_timeout = -1
        for i = 1, #g_prepare_hooks do
            local t,to_exit = g_prepare_hooks[i]()
            if to_exit == true then return n_events end
            if t and t >= 0 then
                if wait_timeout == -1 or t < wait_timeout then
                    wait_timeout = t
                end
            end
        end

        -- print("# pid=" .. C.getpid() .. " epoll_wait enter...")
        local n = C.epoll_wait(g_epoll_fd, ev_set, MAX_EPOLL_EVENT, wait_timeout)
        -- print("# pid=" .. C.getpid() .. " epoll_wait exit...")

        if n == -1 then return n_events, utils.strerror() end

        if n > 0 then
            for ev_idx = 0, n-1 do
                local fd = ev_set[ev_idx].data.fd
                n_events = n_events + 1
                if handlers[fd] then
                    handlers[fd].handler(handlers[fd], ev_set[ev_idx].events)
                end
            end
        end

        if expect_events and n_events >= expect_events then
            return n_events
        end
    end
end

return {
    add_event = add_event,
    del_event = del_event,
    add_prepare_hook = add_prepare_hook,
    init = init,
    run = run,
}


i - 1, ret);
    }

    @Test
    void level2MissPlus1() {
        final int i = (1 << (SHIFT3 + SHIFT2)) + 1;
        set.set(i);
        final int ret = set.previousClearBit(i);

        assertEquals(i - 1, ret);
    }

    @Test
    void level2MissMinus1() {
        final int i = (1 << (SHIFT3 + SHIFT2)) - 1;
        set.set(i);
        final int ret = set.previousClearBit(i);

        assertEquals(i - 1, ret);
    }

    @Test
    void level3Miss() {
        final int i = (1 << SHIFT3);
        set.set(i);
        final int ret = set.previousClearBit(i);

        assertEquals(i - 1, ret);
    }

    @Test
    void level3MissPlus1() {
        final int i = (1 << SHIFT3) + 1;
        set.set(i);
        final int ret = set.previousClearBit(i);

        assertEquals(i - 1, ret);
    }

    @Test
    void level3MissMinus1() {
        final int i = (1 << SHIFT3) - 1;
        set.set(i);
        final int ret = set.previousClearBit(i);

        assertEquals(i - 1, ret);
    }

    @Test
    void noneBelow() {
        set.set(1);
        final int ret = set.previousClearBit(1);

        assertEquals(0, ret);
    }

    @Test
    void oneBelow() {
        set.set(1);
        final int ret = set.previousClearBit(2);

        assertEquals(2, ret);
    }

    @Test
    void threeNo() {
        set.set(1);
        final int ret = set.previousClearBit(3);

        assertEquals(3, ret);
    }

    @Test
    void three() {
        set.set(3);
        final int ret = set.previousClearBit(3);

        assertEquals(2, ret);
    }

    @Test
    void topBit() {
        final int i = Integer.MAX_VALUE - 1;
        final int ret = set.previousClearBit(i);

        assertEquals(i, ret);
    }

    @Test
    void randomSingleEntry() {
        final Random random = new Random(0);
        for (int i = 0; i < 10000; ++i) {
            set = of();
            final int x = Math.abs(random.nextInt() + 1);
            final int ret = set.previousClearBit(x);
            assertEquals(x, ret, "Failed on i = " + i);
        }
    }

    @Test
    void bug15() {
        set.set(1);
        set.set(64);
        assertEquals(63, set.previousClearBit(64));
        set.clear(0);
        set.set(1);
        assertEquals(63, set.previousClearBit(64));
    }

    @Test
    void randomMultiEntry() {
        if (getClass() != SparseBitSetTest.class) {
            // skip this for non-sparse bit set test
            return;
        }
        final Random random = new Random(0);
        final Set<Integer> values = new HashSet<>();
        for (int i = 0; i < 10000; ++i) {
            IBitSet set = of();
            for (int j = 0; j < 1000; ++j) {
                final int x = Math.abs(random.nextInt() + 1);
                set.set(x);
                values.add(x);
            }
            final int x = Math.abs(random.nextInt() + 1);
            int expected = x;
            while (values.contains(expected)) {
                --expected;
            }
            final int ret = set.previousClearBit(x);
            assertEquals(expected, ret, "Failed on i = " + i + " x = " + x);
            values.clear();
        }
    }

    // ------------------------------------------------------------------------
    // test previousSetBit(int)


     * @static
     */
    public static isMBID(mbid:string):boolean {
        return /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(mbid);
    }
}

interface LastFmRestError {
    error: number,
    message: string
}
/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */

import {Tensor} from '../tensor';
import {convertToTensor} from '../tensor_util_env';
import {TensorLike} from '../types';
import {assert, assertShapesMatch, getTypedArrayFromDType} from '../util';
import {tensor} from './tensor';

/**
 * Returns whether the targets are in the top K predictions.
 *
 * ```js
 * const predictions = tf.tensor2d([[20, 10, 40, 30], [30, 50, -20, 10]]);
 * const targets = tf.tensor1d([2, 0]);
 * const precision = await tf.inTopKAsync(predictions, targets);
 * precision.print();
 * ```
 * @param predictions 2-D or higher `tf.Tensor` with last dimension being
 *     at least `k`.
 * @param targets 1-D or higher `tf.Tensor`.
 * @param k Optional Number of top elements to look at for computing precision,
 *     default to 1.
 *
 * @doc {heading: 'Operations', subheading: 'Evaluation'}
 */
async function inTopKAsync_<T extends Tensor, U extends Tensor>(
    predictions: T|TensorLike, targets: U|TensorLike, k = 1): Promise<U> {
  const $predictions = convertToTensor(predictions, 'predictions', 'inTopK');
  const $targets = convertToTensor(targets, 'targets', 'inTopK');

  assert(
      $predictions.rank > 1,
      () => 'inTopK() expects the predictions to be of rank 2 or higher, ' +
          `but got ${$predictions.rank}`);
  assert(
      $predictions.rank - 1 === $targets.rank,
      () => `predictions rank should be 1 larger than ` +
          `targets rank, but got predictions rank ` +
          `${$predictions.rank} and targets rank ${$targets.rank}`);
  assertShapesMatch(
      $predictions.shape.slice(0, $predictions.shape.length - 1),
      $targets.shape,
      `predictions's shape should be align with the targets' shape, ` +
          'except the last dimension.');
  const lastDim = $predictions.shape[$predictions.shape.length - 1];
  assert(
      k > 0 && k <= lastDim,
      () => `'k' passed to inTopK() must be > 0 && <= the predictions last ` +
          `dimension (${lastDim}), but got ${k}`);

  const predictionsVals = await $predictions.data();
  const targetsVals = await $targets.data();

  // Reshape predictionsVals into a 2d tensor [batch, lastDim]
  // and look up topK along lastDim.
  const [batch, size] = [predictionsVals.length / lastDim, lastDim];
  const precision = getTypedArrayFromDType('bool', batch);

  for (let b = 0; b < batch; b++) {
    const offset = b * size;
    const vals = predictionsVals.subarray(offset, offset + size);
    const valA


ne->base.id, sti_plane_to_str(plane));

	plane->status = STI_PLANE_DISABLING;
}

static const struct drm_plane_helper_funcs sti_cursor_helpers_funcs = {
	.atomic_check = sti_cursor_atomic_check,
	.atomic_update = sti_cursor_atomic_update,
	.atomic_disable = sti_cursor_atomic_disable,
};

static int sti_cursor_late_register(struct drm_plane *drm_plane)
{
	struct sti_plane *plane = to_sti_plane(drm_plane);
	struct sti_cursor *cursor = to_sti_cursor(plane);

	cursor_debugfs_init(cursor, drm_plane->dev->primary);

	return 0;
}

static const struct drm_plane_funcs sti_cursor_plane_helpers_funcs = {
	.update_plane = drm_atomic_helper_update_plane,
	.disable_plane = drm_atomic_helper_disable_plane,
	.destroy = drm_plane_cleanup,
	.reset = sti_plane_reset,
	.atomic_duplicate_state = drm_atomic_helper_plane_duplicate_state,
	.atomic_destroy_state = drm_atomic_helper_plane_destroy_state,
	.late_register = sti_cursor_late_register,
};

struct drm_plane *sti_cursor_create(struct drm_device *drm_dev,
				    struct device *dev, int desc,
				    void __iomem *baseaddr,
				    unsigned int possible_crtcs)
{
	struct sti_cursor *cursor;
	size_t size;
	int res;

	cursor = devm_kzalloc(dev, sizeof(*cursor), GFP_KERNEL);
	if (!cursor) {
		DRM_ERROR("Failed to allocate memory for cursor\n");
		return NULL;
	}

	/* Allocate clut buffer */
	size = 0x100 * sizeof(unsigned short);
	cursor->clut = dma_alloc_wc(dev, size, &cursor->clut_paddr,
				    GFP_KERNEL | GFP_DMA);

	if (!cursor->clut) {
		DRM_ERROR("Failed to allocate memory for cursor clut\n");
		goto err_clut;
	}

	cursor->dev = dev;
	cursor->regs = baseaddr;
	cursor->plane.desc = desc;
	cursor->plane.status = STI_PLANE_DISABLED;

	sti_cursor_init(cursor);

	res = drm_universal_plane_init(drm_dev, &cursor->plane.drm_plane,
				       possible_crtcs,
				       &sti_cursor_plane_helpers_funcs,
				       cursor_supported_formats,
				       ARRAY_SIZE(cursor_supported_formats),
				       NULL, DRM_PLANE_TYPE_CURSOR, NULL);
	if (res) {
		DRM_ERROR("Failed to initialize universal plane\n");
		goto err_plane;
	}

	drm_plane_helper_add(&cursor->plane.drm_plane,
			     &sti_cursor_helpers_funcs);

	sti_plane_init_property(&cursor->plane, DRM_PLANE_TYPE_CURSOR);

	return &cursor->plane.drm_plane;

err_plane:
	dma_free_wc(dev, size, cursor->clut, cursor->clut_paddr);
err_clut:
	devm_kfree(dev, cursor);
	return NULL;
}


ateAngles);
            StrokeThicknessProperty.OverrideDefaultValue<ProgressRing>(20);
            AffectsRender<ProgressRing>(StartAngleProperty, SweepAngleProperty);
        }

        /// <inheritdoc cref="ProgressBar.IsIndeterminate"/>
        public bool IsIndeterminate
        {
            get => GetValue(IsIndeterminateProperty);
            set => SetValue(IsIndeterminateProperty, value);
        }

        /// <inheritdoc cref="Shape.StrokeThickness"/>
        public double StrokeThickness
        {
            get => GetValue(StrokeThicknessProperty);
            set => SetValue(StrokeThicknessProperty, value);
        }

        /// <inheritdoc cref="Arc.StartAngle"/>
        public double StartAngle
        {
            get => GetValue(StartAngleProperty);
            set => SetValue(StartAngleProperty, value);
        }

        /// <inheritdoc cref="Arc.SweepAngle"/>
        public double SweepAngle
        {
            get => GetValue(SweepAngleProperty);
            private set => SetValue(SweepAngleProperty, value);
        }

        private static void CalibrateAngles(AvaloniaPropertyChangedEventArgs<double> e)
        {
            if (e.Sender is ProgressRing pr)
                pr.SweepAngle = (pr.Value - pr.Minimum) / (pr.Maximum - pr.Minimum) * 360;
        }
    }
}


local Config = require('opus.config')
local UI     = require('opus.ui')

local colors = _G.colors
local fs     = _G.fs

local config = Config.load('multishell')

local tab = UI.Tab {
	title = 'Launcher',
	description = 'Set the application launcher',
	[1] = UI.Window {
		x = 2, y = 2, ex = -2, ey = 5,
	},
	launcherLabel = UI.Text {
		x = 3, y = 3,
		value = 'Launcher',
	},
	launcher = UI.Chooser {
		x = 13, y = 3, width = 12,
		choices = {
			{ name = 'Overview', value = 'sys/apps/Overview.lua' },
			{ name = 'Shell',    value = 'sys/apps/ShellLauncher.lua'    },
			{ name = 'Custom',   value = 'custom'                },
		},
	},
	custom = UI.TextEntry {
		x = 13, ex = -3, y = 4,
		shadowText = 'File name',
	},
	button = UI.Button {
		x = -8, ex = -2, y = -2,
		text = 'Apply',
		event = 'update',
	},
	labelText = UI.TextArea {
		x = 2, ex = -2, y = 6, ey = -4,
		backgroundColor = colors.black,
		textColor = colors.yellow,
		marginLeft = 1, marginRight = 1, marginTop = 1,
		value = 'Choose an application launcher',
	},
}


AiLz48L3N2Zz4=)
}

.ui-dropdown:active .ui-dropdown-label {
    border: 1px solid #9898ae;
    box-shadow: 0 5px 8px 0 rgba(82,77,148,.15)
}

.ui-dropdown label.ui-dropdown-label {
    cursor: pointer
}

.ui-dropdown input.ui-dropdown-label {
    cursor: default
}

.ui-dropdown.ui-dropdown-open .ui-dropdown-label {
    box-shadow: 0 5px 8px 0 rgba(82,77,148,.15);
    border: 1px solid #9898ae
}

.ui-dropdown .ui-dropdown-panel {
    min-width: 100%;
    position: absolute;
    height: auto;
    border-radius: 5px;
    background: #fff
}

.ui-dropdown .ui-dropdown-panel .ui-dropdown-items-wrapper {
    overflow: auto
}

.ui-dropdown .ui-dropdown-panel .ui-dropdown-items-wrapper::-webkit-scrollbar {
    width: 6px
}

.ui-dropdown .ui-dropdown-panel .ui-dropdown-items-wrapper::-webkit-scrollbar-track {
    box-shadow: inset 0 0 5px #dedee3;
    border-radius: 10px
}

.ui-dropdown .ui-dropdown-panel .ui-dropdown-items-wrapper::-webkit-scrollbar-thumb {
    background: #b8b8bf;
    border-radius: 10px
}

.ui-dropdown .ui-dropdown-panel .ui-dropdown-items-wrapper::-webkit-scrollbar-button:end:increment {
    height: 107px;
    display: block;
    background-color: transparent
}

.ui-dropdown .ui-dropdown-panel .ui-dropdown-items-wrapper::-webkit-scrollbar-button:start:decrement {
    height: 125px;
    display: block;
    background-color: transparent
}

.ui-dropdown .ui-dropdown-items {
    padding: 5px 0
}

.ui-dropdown .ui-dropdown-item {
    padding: 8px 10px;
    cursor: pointer;
    font-weight: 700;
    margin: 0 5px;
    border-radius: 5px
}

.ui-dropdown .ui-dropdown-item:hover {
    background: #f7f7fa
}

.ui-dropdown .ui-dropdown-item.ui-state-highlight {
    background: #4768fd;
    color: #fff
}

.ui-dropdown.ui-dropdown--tall .ui-dropdown-label {
    line-height: 38px;
    padding: 0 40px 0 20px
}

@media (max-width: 767px) {
    .ui-dropdown.ui-dropdown--tall .ui-dropdown-label {
        padding:0 40px 0 15px
    }
}

.ui-dropdown.ui-dropdown--tall .ui-dropdown-trigger {
    cursor: pointer;
    width: 40px
}

.ui-dropdown.ui-dropdown--tall .ui-dropdown-item {
    padding: 8px 10px
}

@media screen {
    .ui-dropdown.ui-dropdown--month .ui-dropdown--tall,.ui-dropdown.ui-dropdown--month .ui-dropdown-label {
        text-overflow: clip!important
    }
}

.ui-dropdown.ui-state-disabled {
    pointer-events: none
}

.ui-dropdown.ui-state-disabled,.ui-dropdown.ui-state-disabled .ui-dropdown-label,.ui-dropdown.ui-state-disabled .ui-dropdown-trigger {
    cursor: not-allowed
}

.ui-dropdown.ui-state-disabled .ui-dropdown-label {
    color: rgba(51,51,51,.3)!important
}

.ui-dropdown__clean {
    background: transparent
}

.ui-dropdown__clean .ui-dropdown-label {
    background: transpa


> KonanTarget.MACOS_ARM64
    else -> error(
      "mainOS key $os unknown. " +
          "Supported keys are [linux, windows, macosX64, macosArm64]"
    )
  }

val KotlinTarget.enabled get() = buildHost == HostManager.host/*
 * Copyright (c) 2015 Mark Platvoet<mplatvoet@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package nl.komponents.kovenant.incubating

import nl.komponents.kovenant.*
import java.util.*

/**
 * Undocumented API. Added as a public testable experimental feature. Implementation and signature might change.
 */
fun <V, R> Sequence<V>.mapEach(context: Context = Kovenant.context, bind: (V) -> R): Promise<List<R>, Exception> {
    val deferred = deferred<List<R>, Exception>(context)
    context.workerContext.offer {
        //TODO ArrayList is jvm only
        val promises = ArrayList<Promise<R, Exception>>()
        forEach {
            value ->
            promises.add(task(context) { bind(value) })
        }
        val masterPromise = all(promises)
        masterPromise success {
            deferred resolve it
        }
        masterPromise fail {
            deferred reject it
        }
    }

    return deferred.promise
}

/*
 * Copyright (c) 2016 Mark Platvoet<mplatvoet@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * THE SOFTWARE.


FavoriteDto {
  @IsString()
  @IsNotEmpty()
  readonly movie_id: string;
}

export class ToggleFavoriteResponse {
  readonly movie: Movie;
  readonly is_favorite: boolean;

  constructor(res: { movie: Movie, is_favorite: boolean }) {
    Object.assign(this, res);
  }
}

export class FavoriteResponse {
  readonly movie: Movie;
  readonly is_favorite: boolean;

  constructor(res: { movie: Movie, is_favorite: boolean }) {
    Object.assign(this, res);
  }
}import { useCallback } from "react";

export function useGoto(): (hash: string) => void;
export function useGoto(hash: string): (hash?: string) => void;
export function useGoto(hash?: string): (hash?: string) => void {
  return useCallback(
    (hash1) => {
      window.location.replace(`#${hash1 ?? hash}`);
    },
    [hash]
  );
}

export function useGotoClick(hash: string): () => void {
  const goto = useGoto(hash);
  return useCallback(() => {
    goto();
  }, [goto]);
}
export enum FeedEnum {
  us2020 = 'WatchCollection_US2020',
  covid19 = 'WatchCollection_COVID19',
  wikitrust = 'WatchCollection_WIKITRUST',
  ores = 'WatchCollection_ORES',
  lastbad = 'WatchCollection_LASTBAD'
}

export class WatchCollectionFeed {
  /**
   * Randomly sample a list of revision ids.
   *
   * Note: we require the collection to be in the schema of WatchCollectionItem
   * @param collectionName
   * @param sampleSize
   */
  public static async sampleRevisions(collectionName: string, sampleSize: number):Promise<number[]> {
    const mongoose = require('mongoose');
    const ret = await mongoose.connection.db.collection(collectionName)
        .aggregate([
        // TODO: add wiki filtering
          {
            $group: {
              _id: {
                revIds: '$revIds',
                wiki: '$wiki',
              },
            },
          },
          {
            $sample: {
              size: sampleSize,
            },
          },
          {
            $project: {
              _id: 0.0,
              revId: '$_id.revIds',
              wiki: '$_id.wiki',
            },
          },
          {
            $unwind: {
              path: '$revId',
            },
          },
          {
            $project: {
              wikiRevId: {
                $concat: [
                  '$wiki',
                  ':',
                  {
                    $substr: [
                      '$revId',
                      0.0,
                      -1.0,
                    ],
                  },
                ],
              },
            },
          },
        ])
        .toArray();
    return ret.map((i) => i.wikiRevId);
  }
}
export default class CacheEntry<T> {
  key: string;
  value: T;
  length: number;
  now: number;
  ttl: number;

  constructor(key: string, value: T, length: number, now: number, ttl: number) {
    this.key = key;
    this.value = value;
    this.length = length;
    this.now = now;
    this.ttl = ttl;
  }
}
/* eslint-disable @typescript-eslint/no-unused-vars */
import { Field, Int, ObjectType } from '@nestjs/graphql';

@ObjectT


ice;
            this.BarcodeResult = barcodeResult;
        }

        public BarcodeResult BarcodeResult { get; }

        public IAsyncRelayCommand BarcodeResultTappedCommand
        {
            get => this.barcodeResultTappedCommand ??= new AsyncRelayCommand(this.OnBarcodeResultTapped);
        }

        private async Task OnBarcodeResultTapped()
        {
            try
            {
                await this.navigationService.PushAsync("BarcodeResultDetailPage", this.BarcodeResult);
            }
            catch (Exception ex)
            {
                this.logger.LogError(ex, "OnBarcodeResultTapped failed with exception");
            }
        }
    }
}


ingAssignStmt {
            op: ast::AssignOp::Identity,
            ..
        } => {
            let id = cx.map_ast_with_parent(AstNode::Stmt(stmt), parent_id);
            ids.push(id);
        }
        _ => {
            cx.emit(
                DiagBuilder2::error(format!("{:#} is not a valid genvar initialization", stmt))
                    .span(stmt.human_span()),
            );
            error!("Offending AST is {:#02?}", stmt);
            return Err(());
        }
    }
    Ok(ids)
}

/// Allocate node IDs for a parameter declaration.
fn alloc_param_decl<'gcx>(
    cx: &impl Context<'gcx>,
    param: &'gcx ast::ParamDecl<'gcx>,
    mut next_rib: NodeId,
    into: &mut Vec<NodeId>,
) -> NodeId {
    match param.kind {
        ast::ParamKind::Type(ref decls) => {
            for decl in decls {
                let id = cx.map_ast(AstNode::TypeParam(param, decl));
                cx.set_parent(id, next_rib);
                next_rib = id;
                into.push(id);
            }
        }
        ast::ParamKind::Value(ref decls) => {
            for decl in decls {
                let id = cx.map_ast(AstNode::ValueParam(param, decl));
                cx.set_parent(id, next_rib);
                next_rib = id;
                into.push(id);
            }
        }
    }
    next_rib
}

/// Allocate node IDs for a variable declaration.
fn alloc_var_decl<'gcx>(
    cx: &impl Context<'gcx>,
    decl: &'gcx ast::VarDecl<'gcx>,
    mut next_rib: NodeId,
    into: &mut Vec<NodeId>,
) -> NodeId {
    let type_id = cx.map_ast_with_parent(AstNode::Type(&decl.ty), next_rib);
    next_rib = type_id;
    for name in &decl.names {
        let decl_id = cx.map_ast_with_parent(AstNode::VarDecl(name, decl, type_id), next_rib);
        next_rib = decl_id;
        into.push(decl_id);
    }
    next_rib
}

/// Allocate node IDs for a net declaration.
fn alloc_net_decl<'gcx>(
    cx: &impl Context<'gcx>,
    decl: &'gcx ast::NetDecl<'gcx>,
    mut next_rib: NodeId,
    into: &mut Vec<NodeId>,
) -> NodeId {
    let type_id = cx.map_ast_with_parent(AstNode::Type(&decl.ty), next_rib);
    next_rib = type_id;
    for name in &decl.names {
        let decl_id = cx.map_ast_with_parent(AstNode::NetDecl(name, decl, type_id), next_rib);
        next_rib = decl_id;
        into.push(decl_id);
    }
    next_rib
}

/// Allocate node IDs for a struct member.
fn alloc_struct_member<'gcx>(
    cx: &impl Context<'gcx>,
    member: &'gcx ast::StructMember<'gcx>,
    mut next_rib: NodeId,
    into: &mut Vec<NodeId>,
) -> NodeId {
    let type_id = cx.map_ast_with_parent(AstNode::Type(&member.ty), next_rib);
    next_rib = type_id;
    for name in &member.names {
        let member_id =
            cx.map_ast_with_parent(AstNode::StructMember(name, member, type_id), next_rib);
        next_rib = member_id;
        into.push(member_id);
    }
    next_rib
}

/// Lower a package to HIR.
///
/// This allocates node IDs to everything in the package and registers AST n


 ses->xts_schedule,
		    ses->rounds);
	}

	return (0);
}

int
aesni_cipher_setup(struct aesni_session *ses, struct cryptoini *encini)
{
	int error = 0;
#if 0
	struct thread *td;
	int saved_ctx;
#endif

#if 0
	td = curthread;
	if (!is_fpu_kern_thread(0)) {
		error = fpu_kern_enter(td, &ses->fpu_ctx, FPU_KERN_NORMAL);
		saved_ctx = 1;
	} else {
		error = 0;
		saved_ctx = 0;
	}
#endif
	if (error == 0) {
		error = aesni_cipher_setup_common(ses, encini->cri_key,
		    encini->cri_klen);
#if 0
		if (saved_ctx)
			fpu_kern_leave(td, &ses->fpu_ctx);
#endif
	}
	return (error);
}

int
aesni_cipher_process(struct aesni_session *ses, struct cryptodesc *enccrd,
    struct cryptop *crp)
{
	uint8_t *buf;
	int error = 0, allocated;
#if 0
	struct thread *td;
	int saved_ctx;
#endif

	buf = aesni_cipher_alloc(enccrd, crp, &allocated);
	if (buf == NULL)
		return (ENOMEM);

#if 0
	td = curthread;
	if (!is_fpu_kern_thread(0)) {
		error = fpu_kern_enter(td, &ses->fpu_ctx, FPU_KERN_NORMAL);
		if (error != 0)
			goto out;
		saved_ctx = 1;
	} else {
		saved_ctx = 0;
		error = 0;
	}
#endif

	if ((enccrd->crd_flags & CRD_F_KEY_EXPLICIT) != 0) {
		error = aesni_cipher_setup_common(ses, enccrd->crd_key,
		    enccrd->crd_klen);
		if (error != 0)
			goto out;
	}

	if ((enccrd->crd_flags & CRD_F_ENCRYPT) != 0) {
		if ((enccrd->crd_flags & CRD_F_IV_EXPLICIT) != 0)
			bcopy(enccrd->crd_iv, ses->iv, AES_BLOCK_LEN);
		if ((enccrd->crd_flags & CRD_F_IV_PRESENT) == 0)
			crypto_copyback(crp->crp_flags, crp->crp_buf,
			    enccrd->crd_inject, AES_BLOCK_LEN, ses->iv);
		if (ses->algo == CRYPTO_AES_CBC) {
			aesni_encrypt_cbc(ses->rounds, ses->enc_schedule,
			    enccrd->crd_len, buf, buf, ses->iv);
		} else /* if (ses->algo == CRYPTO_AES_XTS) */ {
			aesni_encrypt_xts(ses->rounds, ses->enc_schedule,
			    ses->xts_schedule, enccrd->crd_len, buf, buf,
			    ses->iv);
		}
	} else {
		if ((enccrd->crd_flags & CRD_F_IV_EXPLICIT) != 0)
			bcopy(enccrd->crd_iv, ses->iv, AES_BLOCK_LEN);
		else
			crypto_copydata(crp->crp_flags, crp->crp_buf,
			    enccrd->crd_inject, AES_BLOCK_LEN, ses->iv);
		if (ses->algo == CRYPTO_AES_CBC) {
			aesni_decrypt_cbc(ses->rounds, ses->dec_schedule,
			    enccrd->crd_len, buf, ses->iv);
		} else /* if (ses->algo == CRYPTO_AES_XTS) */ {
			aesni_decrypt_xts(ses->rounds, ses->dec_schedule,
			    ses->xts_schedule, enccrd->crd_len, buf, buf,
			    ses->iv);
		}
	}
#if 0
	if (saved_ctx)
		fpu_kern_leave(td, &ses->fpu_ctx);
#endif
	if (allocated)
		crypto_copyback(crp->crp_flags, crp->crp_buf, enccrd->crd_skip,
		    enccrd->crd_len, buf);
	if ((enccrd->crd_flags & CRD_F_ENCRYPT) != 0)
		crypto_copydata(crp->crp_flags, crp->crp_buf,
		    enccrd->crd_skip + enccrd->crd_len - AES_BLOCK_LEN,
		    AES_BLOCK_LEN, ses->iv);
 out:
	if (allocated) {
		bzero(buf, enccrd->crd_len);
		kfree(buf, M_AESNI);
	}
	return (error);
}

static device_method_t aesni_methods[] = {
	DEVMETHOD(device_identify, aesni_identify),
	DEVMETHOD(device_probe, aesni_probe),
	DEVMETHOD(device_attach, aesni_attach),
	DEVMETHOD(device_detach, aesni_detach),

	DEVMETHOD(cryptodev_newsession, aesni_newsession),
	DEVMETHOD(cryptodev_freesession, aesni_freesession),
	DEVMETHOD(cryptodev_process, aesni_process),

	DEVMETHOD_END
};

static driver_t aesni_driver = {
	"aesni",
	aesni_methods,
	sizeof(struct aesni_softc),
};
static devclass_t aesni_devclass;

DRIVER_MODULE(aesni, nexus, aesni_driver, aesni_devclass, NULL, NULL);
MODULE_VERSION(aesni, 1);
MODULE_DEPEND(aesni, crypto, 1, 1, 1);


操作
        st.markdown("---")
        col1, col2, col3 = st.columns(3)

        with col1:
            if st.button("📖 全部標記為已讀"):
                _mark_all_as_read(filtered_notifications)
                st.success("已標記所有通知為已讀")
                st.rerun()

        with col2:
            if st.button("🗑 清除已讀通知"):
                _clear_read_notifications()
                st.success("已清除所有已讀通知")
                st.rerun()

        with col3:
            if st.button("🧹 清除所有通知"):
                _clear_all_notifications()
                st.success("已清除所有通知")
                st.rerun()

    else:
        st.info("📭 沒有符合條件的通知")

def _filter_notifications(
    notifications: List[Dict[str, Any]],
    type_filter: List[str],
    priority_filter: int,
    date_filter: List,
    search_text: str
) -> List[Dict[str, Any]]:
    """過濾通知"""
    filtered = []

    for notification in notifications:
        # 類型過濾
        if notification["type"] not in type_filter:
            continue

        # 優先級過濾
        if notification.get("priority", 1) < priority_filter:
            continue

        # 日期過濾
        if len(date_filter) == 2:
            notif_date = notification["timestamp"].date()
            if not (date_filter[0] <= notif_date <= date_filter[1]):
                continue

        # 搜索過濾
        if search_text and search_text.lower() not in notification["message"].lower():
            continue

        filtered.append(notification)

    # 按時間倒序排列
    filtered.sort(key=lambda x: x["timestamp"], reverse=True)
    return filtered

def _render_notification_item(notification: Dict[str, Any], index: int) -> None:
    """渲染單個通知項目"""
    # 通知容器
    with st.container():
        col1, col2, col3, col4 = st.columns([1, 6, 2, 1])

        # 優先級指示器
        with col1:
            priority = notification.get("priority", 1)
            priority_icons = {
                1: "🔵",  # 低
                2: "🟡",  # 普通
                3: "🟠",  # 高
                4: "🔴"   # 緊急
            }
            st.write(priority_icons.get(priority, "⚪"))

        # 通知內容
        with col2:
            # 標題和時間
            timestamp = notification["timestamp"].strftime("%Y-%m-%d %H:%M:%S")
            read_status = "✅" if notification.get("read", False) else "🔘"

            st.markdown(f"**{read_status} {notification['message']}**")
            st.caption(f"📅 {timestamp} | 🏷 {notification['type']}")

            # 元數據
            if notification.get("metadata"):
                with st.expander("詳細信息"):
                    st.json(notification["metadata"])

        # 類型指示器
        with col3:
            type_icons = {
                "info": "ℹ",
                "success": "✅",
                "warning": "⚠",
                "error": "❌",
                "trading": "💰",
                "risk": "⚡",
                "system": "🔧"
            }
            icon = type_icons.get(notification["type"], "📝")
            st.write(f"{icon} {notification['type']}")

        # 操作按鈕
        with col4:
            if not notification.get("read", False):
                if st.button("✓", key=f"read_{index}", help="標記為已讀"):
                    _mark_notification_as_read(notification["id"])
                    st.rerun()

        st.markdown("---")

def _mark_notification_as_read(notification_id: str) -> None:
    """標記通知為已讀"""
    for notification in st.session_state.notifications:
        if notification["id"] == notification_id:
            notification["read"] = True
            break

def _mark_all_as_read(notifications: List[Dict[str, Any]]) -> None:
    """標記所有通知為已讀"""
    for notification in st.session_state.notifications:
        notification["read"] = True

def _clear_read_notifications() -> None:
    """清除已讀通知"""
    st.session_state.notifications = [
        n for n in st.session_state.notifications
        if not n.get("read", False)
    ]

def _clear_all_notifications() -> None:
    """清除所有通知"""
    st.session_state.notifications = []

def alert_badge(count: Optional[int] = None) -> None:
    """顯示通知徽章 (增強版)

    Args:
        count: 未讀通知數量，None 表示自動計算
    """
    if count is None:
        count = len([n for n in st.session_state.get("notifications", []) if not n.get("read", False)])

    if count > 0:
        # 根據優先級確定顏色
        urgent_count = len([
            n for n in st.session_state.get("notifications", [])
            if not n.get("read", False) and n.get("priority", 1) >= NotificationPriority.URGENT.value
        ])

        badge_colo


constants';
import {
  PutRecordsInput,
  PutRecordsRequestEntry,
} from 'aws-sdk/clients/kinesis';

import { Kinesis } from 'aws-sdk';
import { KinesisEvent } from './kinesis-event.interface';
import { KinesisPublisherModuleOptions } from './module-config';

@Injectable()
export class BatchKinesisPublisher {
  private readonly baseLogger: Logger;
  private static readonly ONE_MEG = 1024 * 1024;
  protected entries: PutRecordsRequestEntry[] = [];
  protected STREAM_NAME: string;
  private dataSize = 0;
  constructor(
    @Inject(KINESIS) protected readonly kinesis: Kinesis,
    @Inject(NEST_KINESIS_PUBLISHER_CONFIG)
    protected readonly options: KinesisPublisherModuleOptions,
  ) {
    this.baseLogger = new Logger(BatchKinesisPublisher.name);
  }

  /**
   * Sends the data records to the stream. Handling the data conversion to a buffer if needed, or
   *
   * @param streamName the stream name
   * @param events data is the format of KinesisEvent, PartitionKey is a string, and Data is either JSON.stringify() or a buffer.
   * if it is JSON.stringify() the data will be buffered prior to sending to kinesis.
   */
  async putRecords(streamName: string, events: KinesisEvent[]): Promise<void> {
    // tslint:disable-next-line
    this.options.enableDebugLogs ||
      this.baseLogger.log(
        `putRecords() invoked for ${events.length} records on stream ${streamName}`,
      );
    this.STREAM_NAME = streamName;
    for (const x of events) {
      await this.addEntry({
        Data: this.getDataBytes(x.Data),
        PartitionKey: x.PartitionKey.toString(),
      });
    }
    await this.flush();
    // tslint:disable-next-line
    this.options.enableDebugLogs ||
      this.baseLogger.log(
        `putRecords() completed for ${events.length} records`,
      );
  }
  protected getDataBytes(data: string): Buffer {
    if (Buffer.isBuffer(data)) {
      return data;
    } else if (typeof data === 'string') {
      return Buffer.from(data, 'utf8');
    }
    throw Error(
      'Unable to transform event Data into buffer to send to kinesis.',
    );
  }

  protected async flush(): Promise<void> {
    if (this.entries.length < 1) {
      return;
    }
    const putRecordsInput: PutRecordsInput = {
      StreamName: this.STREAM_NAME,
      Records: this.entries,
    };
    await this.kinesis.putRecords(putRecordsInput).promise();
    this.entries = [];
  }

  protected async addEntry(entry: PutRecordsRequestEntry): Promise<void> {
    const entryDataSize: number =
      entry.Data.toString('utf8').length + entry.PartitionKey.length;
    if (Number.isNaN(entryDataSize)) {
      this.baseLogger.error(
        `Cannot produce data size of partitionKey: ${
          entry.PartitionKey
        }  |  Data: ${entry.Data.toString('utf8')}`,
      );
      return;
    }
    if (entryDataSize > BatchKinesisPublisher.ONE_MEG) {
      this.baseLogger.error(
        `FATAL: entry exceeds maximum size of 1M and will not be published, partitionkey: ${entry.PartitionKey}`,
      );
      return;
    }

    const newDataSize = this.dataSize + entryDataSize;
    if (
      newDataSize <= 5 * BatchKinesisPublisher.ONE_MEG &&
      this.entries.length < 500
    ) {
      this.dataSize = newDataSize;
      this.entries.push(entry);
    } else {
      await this.flush();
      this.dataSize = 0;
      await this.addEntry(entry);
    }
  }
}
import {AppService} from "./app.service";
import {OnInit} from "../../lib/model


) + 1; // +1 for the border
		function scroll() {
			slotScroller.scrollTop(top);
		}
		scroll();
		setTimeout(scroll, 0); // overrides any previous scroll state made by the browser
	}

	function beforeHide() {
		savedScrollTop = slotScroller.scrollTop();
	}

	function afterShow() {
		slotScroller.scrollTop(savedScrollTop);
	}

	/* Slot/Day clicking and binding
	-----------------------------------------------------------------------*/

	function dayBind(cells) {
		cells.click(slotClick)
			.mousedown(daySelectionMousedown);
	}

	function slotBind(cells) {
		cells.click(slotClick)
			.mousedown(slotSelectionMousedown);
	}

	function slotClick(ev) {
		if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick
			var col = Math.min(colCnt-1, Math.floor((ev.pageX - dayTable.offset().left - axisWidth) / colWidth));
			var date = colDate(col);
			var rowMatch = this.parentNode.className.match(/fc-slot(\d+)/); // TODO: maybe use data
			if (rowMatch) {
				var mins = parseInt(rowMatch[1]) * opt('slotMinutes');
				var hours = Math.floor(mins/60);
				date.setHours(hours);
				date.setMinutes(mins%60 + minMinute);
				trigger('dayClick', dayBodyCells[col], date, false, ev);
			}else{
				trigger('dayClick', dayBodyCells[col], date, true, ev);
			}
		}
	}

	/* Semi-transparent Overlay Helpers
	-----------------------------------------------------*/

	function renderDayOverlay(startDate, endDate, refreshCoordinateGrid) { // endDate is exclusive
		if (refreshCoordinateGrid) {
			coordinateGrid.build();
		}
		var visStart = cloneDate(t.visStart);
		var startCol, endCol;
		if (rtl) {
			startCol = dayDiff(endDate, visStart)*dis+dit+1;
			endCol = dayDiff(startDate, visStart)*dis+dit+1;
		}else{
			startCol = dayDiff(startDate, visStart);
			endCol = dayDiff(endDate, visStart);
		}
		startCol = Math.max(0, startCol);
		endCol = Math.min(colCnt, endCol);
		if (startCol < endCol) {
			dayBind(
				renderCellOverlay(0, startCol, 0, endCol-1)
			);
		}
	}

	function renderCellOverlay(row0, col0, row1, col1) { // only for all-day?
		var rect = coordinateGrid.rect(row0, col0, row1, col1, slotLayer);
		return renderOverlay(rect, slotLayer);
	}

	function renderSlotOverlay(overlayStart, overlayEnd) {
		var dayStart = cloneDate(t.visStart);
		var dayEnd = addDays(cloneDate(dayStart), 1);
		for (var i=0; i<colCnt; i++) {
			var stretchStart = new Date(Math.max(dayStart, overlayStart));
			var stretchEnd = new Date(Math.min(dayEnd, overlayEnd));
			if (stretchStart < stretchEnd) {
				var col = i*dis+dit;
				var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // only use it for horizontal coords
				var top = timePosition(dayStart, stretchStart);
				var bottom = timePosition(dayStart, stretchEnd);
				rect.top = top;
				rect.height = bottom - top;
				slotBind(
					renderOverlay(rect, slotContent)
				);
			}
			addDays(dayStart, 1);


ринцип підстановки Лісков**
Функції, які використовують базовий тип, повинні мати можливість використовувати підтипи базового типу, не знаючи про це. Тобто поведінка в похідних класах не повинна суперечити поведінці, заданій базовим класом.

Об'єкти в програмі можуть бути заміненими їх нащадками без зміни коду програми. Клас-нащадок повинен доповнювати, а не змінювати базовий. Це вимагає суворого дотримання контрактів та інтерфейсів, визначених у базовому класі, у всіх його похідних класах.

- Принцип про правильне наслідування.
- Проектування конктракту - контракт інформує авторів клієнтського коду про бажану поведінку класу. Контракт визначає вхідні і вихідні параметри.

*Links*

- [Все, що ви хотіли знати про принципи SOLID. Частина третя: LSP - dou.ua](https://dou.ua/forums/topic/54053/)

### I - Interface Segregation Principle

**I - Interface Segregation Principle - ISP - Принцип розділення інтерфейсу.**
Багато спеціалізованих інтерфейсів краще за один універсальний. Інтерфейс може бути поділений на спеціалізовані ще на стадіях проектування, заради майбутньої гнучкості програмних компонентів.

- Клієнти не повинні залежати від методів, які вони не використовують.
- Занадто товсті інтерфейси необхідно розділяти на менші та специфічні, щоб їх клієнти знали лише про ті методи, що необхідні для них у роботі. Як результат, при зміні певног функціоналу, незмінними мають лишатися ті класи, як не використовують його. Тобто виконання цього принципу допомагає системі залишатись гнучкою при внесенні до неї змін.

```python
# wrong
# In this design the `Car` class must implement the `fly()` method from the `Vehicle` class that the `Car` class doesn’t use. Therefore, this design violates the interface segregation principle.

class Vehicle(ABC):
	@abstractmethod
	def go(self): pass
	@abstractmethod
	def fly(self): pass

class Aircraft(Vehicle):
	def go(self): print("Taxiing")
	def fly(self): print("Flying")

class Car(Vehicle):
	def go(self): print("Going")
	def fly(self): raise Exception('The car cannot fly')

# To fix this, you need to split the `Vehicle` class into small ones and inherits from these classes from the `Aircraft` and `Car` classes:

class Movable(ABC):
	@abstractmethod
	def go(self): pass

class Flyable(Movable):
	@abstractmethod
	def fly(self): pass

class Aircraft(Flyable):
	def go(self): print("Taxiing")
	def fly(self): print("Fl


      dim += 1;
        let mut line_string : String = line.unwrap();
        let mut data = line_string
        .trim()
        .split_whitespace()
        .map(|x| x.parse::<f32>())
        .collect::<Result<Vec<_>, _>>().unwrap();
        //println!("{:?}", data);
        numbers.append(&mut data);
    }
    let d = numbers.len() / dim;
    let t = unsafe {Array::from_shape_vec_unchecked((dim, d), numbers)};
    t
}

fn main() {
    let vec = load_from_file("C:\\Users\\Jens-Uwe.Ulrich\\source\\repos\\osprey\\build\\basecall.txt");

    let t0 = load_small_table("C:\\Users\\Jens-Uwe.Ulrich\\source\\repos\\osprey\\small_tables_0");
    let t1 = load_small_table("C:\\Users\\Jens-Uwe.Ulrich\\source\\repos\\osprey\\small_tables_1");
    let t2 = load_small_table("C:\\Users\\Jens-Uwe.Ulrich\\source\\repos\\osprey\\small_tables_2");
    let t3 = load_small_table("C:\\Users\\Jens-Uwe.Ulrich\\source\\repos\\osprey\\small_tables_3");
    let t4 = load_small_table("C:\\Users\\Jens-Uwe.Ulrich\\source\\repos\\osprey\\small_tables_4");
    let t5 = load_small_table("C:\\Users\\Jens-Uwe.Ulrich\\source\\repos\\osprey\\small_tables_5");
    let t6 = load_small_table("C:\\Users\\Jens-Uwe.Ulrich\\source\\repos\\osprey\\small_tables_6");

    let mut dtab = DecoderTab::new(t0, t1, t2, t3, t4, t5, t6);
    let mut seqt = dtab.beam_search(&vec, vec.len(), 5, 0.1);
    println!("sequence : {}", seqt);
}
*/use alloc::string::String;

use crate::common::{
    DebugAddrBase, DebugAddrIndex, DebugInfoOffset, DebugLineStrOffset, DebugLocListsBase,
    DebugLocListsIndex, DebugRngListsBase, DebugRngListsIndex, DebugStrOffset, DebugStrOffsetsBase,
    DebugStrOffsetsIndex, DebugTypesOffset, Encoding, LocationListsOffset, RangeListsOffset,
    SectionId, UnitSectionOffset,
};
use crate::constants;
use crate::read::{
    Abbreviations, AttributeValue, CompilationUnitHeader, CompilationUnitHeadersIter, DebugAbbrev,
    DebugAddr, DebugInfo, DebugLine, DebugLineStr, DebugStr, DebugStrOffsets, DebugTypes,
    DebuggingInformationEntry, EntriesCursor, EntriesRaw, EntriesTree, Error,
    IncompleteLineProgram, LocListIter, LocationLists, Range, RangeLists, Reader, ReaderOffset,
    ReaderOffsetId, Result, RngListIter, Section, TypeUnitHeader, TypeUnitHeadersIter, UnitHeader,
    UnitOffset,
};

/// All of the commonly used DWARF sections, and other common information.
#[derive(Debug, Default)]
pub struct Dwarf<R> {
    /// The `.debug_abbrev` section.
    pub debug_abbrev: DebugAbbrev<R>,

    /// The `.debug_addr` section.
    pub debug_addr: DebugAddr<R>,

    /// The `.debug_info` section.
    pub debug_info: DebugInfo<R>,

    /// The `.debug_line` section.
    pub debug_line: DebugLine<R>,

    /// The `.debug_line_str` section.
    pub debug_line_str: DebugLineStr<R>,

    /// The `.debug_str` section.
    pub debug_str: DebugStr<R>,

    /// The `.debug_str_offsets` section.
    pub debug_str_


ellij.dlanguage.psi.DTokenSets
import io.github.intellij.dlanguage.psi.DlangTypes

class DBraceMatcher : PairedBraceMatcher {
    override fun getPairs(): Array<BracePair> {
        return PAIRS
    }

    override fun isPairedBracesAllowedBeforeType(
        lbraceType: IElementType,
        contextType: IElementType?
    ): Boolean {
        return (alwaysMatch.contains(lbraceType)
                || DTokenSets.WHITESPACES.contains(contextType)
                || DTokenSets.LINE_COMMENTS.contains(contextType)
                || DTokenSets.BLOCK_COMMENTS.contains(contextType)) || DlangTypes.OP_PAR_RIGHT === contextType || null == contextType
    }

    override fun getCodeConstructStart(file: PsiFile, openingBraceOffset: Int): Int {
        return openingBraceOffset
    }

    companion object {
        private val PAIRS = arrayOf(
            BracePair(DlangTypes.OP_PAR_LEFT, DlangTypes.OP_PAR_RIGHT, false),
            BracePair(DlangTypes.OP_BRACES_LEFT, DlangTypes.OP_BRACES_RIGHT, true),
            BracePair(DlangTypes.OP_BRACKET_LEFT, DlangTypes.OP_BRACKET_RIGHT, false)
        )
        private val alwaysMatch = TokenSet.create(DlangTypes.OP_BRACES_LEFT)
    }
}
package io.github.intellij.dlanguage.inspections

import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.util.PsiTreeUtil
import io.github.intellij.dlanguage.DlangBundle
import io.github.intellij.dlanguage.psi.DlangVisitor
import io.github.intellij.dlanguage.psi.interfaces.DNamedElement
import io.github.intellij.dlanguage.psi.named.DLanguageClassDeclaration
import io.github.intellij.dlanguage.psi.named.DLanguageStructDeclaration
import io.github.intellij.dlanguage.psi.named.DLanguageUnionDeclaration
import io.github.intellij.dlanguage.quickfix.MakeStaticImmutable
import io.github.intellij.dlanguage.utils.AutoAssignment

/**
 * Created by francis on 1/5/2018.
 */
class EnumArrayLiteralsInClassDeclaration : LocalInspectionTool() {
    override fun getDescriptionFileName(): String = "EnumArrayLiteralsInClassDeclaration.html"
    override fun getDisplayName(): String = "EnumArrayLiteralsInClassDeclaration"
    override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): DlangVisitor = EnumArrayLiteralsInClassDeclarationVisitor(holder)
    override fun getGroupDisplayName(): String = DlangBundle.message("d.inspections.groupname")
}

class EnumArrayLiteralsInClassDeclarationVisitor(val holder: ProblemsHolder) : DlangVisitor() {
    override fun visitClassDeclaration(o: DLanguageClassDeclaration) {
        checkForEnumLiterals(o)
    }

    override fun visitUnionDeclaration(o: DLanguageUnionDeclaration) {
        checkForEnumLiterals(o)
    }

    override fun visitStructDeclaration(o: DLanguageStructDeclaration) {
        checkForEnumLiterals(o)
    }

    fun checkForEnumLiterals(o: DNamedElement) {
        for (decl in PsiTreeUtil.findChildrenOfType(o, AutoAssignment::class.java)) {
            if (decl.isEnum) {
                if (decl.initializer?.kW_VOID != null)
                    continue
                holder.registerProblem(decl, "This enum may lead to unnecessary allocation at run-time. Use \"static immutable instead\"", MakeStaticImmutable(decl))
                // TODO when type deduction becomes a thing use that instead of checking initializers
            }
        }
    }
}
package io.github.intellij.dlanguage.structure

import com.intellij.ide.navigationToolbar.StructureAwareNavBarModelExtension
import com.intellij.lang.Language
import com.intellij.psi.PsiElement
import io.github.intellij.dlanguage.DLanguage
import


一致性哈希" class="headerlink" title="2 一致性哈希">2 一致性哈希

梳理完传统负载均衡方案的流程以及存在的痛点后，下面引入我们今天的主题——一致性哈希算法.

2.1 哈希环

2.1.1 哈希环构造

现在，我们需要打破固有的数据与节点之间的点对点映射关系.

我们首先构造出一个 **哈希环（Hash Ring）**：

哈希环是一个首尾衔接的环

起点位置数值为 0

终点位置数值为 2^32，与 0 重合

环上每个刻度对应一个 0~2^32 - 1 之间的数值

哈希环的构造图如下所示：

2.1.2 节点入环

接下来，每个节点需要在哈希环中找到找到属于自己的位置. 入环的方式是，针对于节点的标识键 index 取 hash 值，然后使用该 hash 值对 2^32 取模，最后得到的结果就是该节点在哈希环上对应的位置.

遵循上述流程，我们可以依次把集群中的各个节点加入哈希环中.

<a href="#2-1-3-数据出-入环" class="headerlink" title="2.


import torch
import torch.nn.functional as F
from sklearn.preprocessing import normalize
from torch import Tensor
from transformers import AutoTokenizer, AutoModel
from sentence_transformers import SentenceTransformer
from sentence_transformers.util import cos_sim

def last_token_pool(last_hidden_states: Tensor,
                    attention_mask: Tensor) -> Tensor:
    left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
    if left_padding:
        return last_hidden_states[:, -1]
    else:
        sequence_lengths = attention_mask.sum(dim=1) - 1
        batch_size = last_hidden_states.shape[0]
        return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), sequence_lengths]

def get_detailed_instruct(task_description: str, query: str) -> str:
    return f'Instruct: {task_description}\nQuery: {query}'

class EmbeddingQwen2Instrcut7B:
    def __init__(self):
        model_dir = "./model_hub/embedding/iic/gte_Qwen2-7B-instruct"
        # from sentence_transformers import SentenceTransformer
        # self.model = SentenceTransformer(model_dir, trust_remote_code=True, device="cuda")
        self.tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True, )
        self.model = AutoModel.from_pretrained(model_dir, trust_remote_code=True, device_map="auto")
        self.model.eval()
        self.model.max_seq_length = 8192
        self.task = 'Given a web search query, retrieve relevant passages that answer the query'

    def encode_text(self, text, prompt_name=None):
        if isinstance(text, str):
            if prompt_name is not None:
                text = [self.task + text]
            else:
                text = [text]
        elif isinstance(text, list):
            if prompt_name is not None:
                text = [self.task + i for i in text]
        batch_dict = self.tokenizer(text, max_length=self.model.max_seq_length, padding=True, truncation=True,
                                    return_tensors='pt')
        batch_dict = batch_dict.to(self.model.device)
        with torch.no_grad():
            outputs = self.model(**batch_dict)
        embeddings = last_token_pool(outputs.last_hidden_state, batch_dict['attention_mask'])
        embeddings = F.normalize(embeddings, p=2, dim=1)
        return embeddings

    def cal_similarity(self, text1, text2):
        query_embeddings = self.encode_text(text1, prompt_name="query")
        doc_embeddings = self.encode_text(text2)

        scores = (query_embeddings @ doc_embeddings.T) * 100
        # print(scores.tolist())
        # [[70.00668334960938, 8.184843063354492], [14.62419319152832, 77.71407318115234]]
        return scores.tolist()

class EmbeddingBGE:
    def __init__(self, device="cuda"):
        model_dir = "./model_hub/embedding/AI-ModelScope/bge-large-zh-v1___5"
        # from sentence_transformers import SentenceTransformer
        self.model = SentenceTransformer(model_dir, device=device)
        self.instruction = "为这个句子生成表示以用于检索相关文章："

    def encode_text(self, text, prompt_name=None):
        if isinstance(text, str):
            if prompt_name is not None:
                text = [self.instruction + text]
            else:
                text = [text]
        elif isinstance(text, list):
            if prompt_name is not None:
                text = [self.instruction + i for i in text]
        embeddings = self.model.encode(text, normalize_embeddings=True)
        # print(embeddings)
        return embeddings

    def cal_similarity(self, text1, text2):
        query_embeddings = self.encode_text(text1, prompt_name="query")
        doc_embeddings = self.encode_text(text2)

        scores = (query_embeddings @ doc_embeddings.T) * 100
        # print(scores.tolist())
        # [[70.00668334960938, 8.184843063354492], [14.62419319152832, 77.71407318115234]]
        return scores.tolist()

class EmbeddingGTE:
    def __init__(self, device="cuda"):
        model_dir = "./model_hub/embedding/AI-ModelScope/gte-large-zh"
        # from sentence_transformers import SentenceTransformer
        self.model = SentenceTransformer(model_dir, device=device)

    def encode_text(self, text):
        if isinstance(text, str):
                text = [text]
        embeddings = self.model.encode(text, normalize_embeddings=True)
        # print(embeddings)
        return embeddings

    def cal_similarity(self, text1, text2):
        query_embeddings = self.encode_text(text1)
        doc_embe


#region license
// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//     * Neither the name of Ayende Rahien nor the names of its
//     contributors may be used to endorse or promote products derived from this
//     software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
namespace Rhino.Mocks.Tests.FieldsProblem
{
	using System;
	using Xunit;
	using Rhino.Mocks.Constraints;

	public class ClassWithFinalizer
	{
		~ClassWithFinalizer()
		{
			Console.WriteLine(5);
		}
	}

	public


.d, #65280
// CHECK-NOT: [[@LINE-1]]:{{[0-9]+}}:

movprfx z0.d, p0/z, z7.d
uqsub     z0.d, z0.d, z0.d
// CHECK: [[@LINE-1]]:{{[0-9]+}}: error: instruction is unpredictable when following a movprfx, suggest replacing movprfx with mov
// CHECK-NEXT: uqsub     z0.d, z0.d, z0.d
// CHECK


	elseif type( args[2] ) == 'string' then

		-- named color HDR
		color = NAMED_COLORS and NAMED_COLORS[ args[2] ]
		if not color then
			color = { 1, 1, 1 }
			print('\n')
			print( 'ERROR dmc_kolor: named color not found', tostring( args[2] ) )
			print('\n')
		end
		color[4] = args[3]

	else
		print('\n')
		print( 'ERROR dmc_kolor: invalid HDR color type', type( args[2] ) )
		print('\n')
	end

	return color
end

--====================================================================--
-- Display Class Setup
--====================================================================--

Display = {}

setmetatable( Display, { __index=_DISPLAY } )

-- imbue object with fillColor magic
--
function Display._modifySetFillColor( o )
	-- print( 'modifySetFillColor' )

	-- cached version
	--[[
	function createClosure( obj, translate )
		local f = function( ... )
			local args = { ... }
			local key, color
			if type( args[2] ) == 'number' and dmc_kolor_data.cache_is_active == true then
				-- check cache
				key = table.concat( { tostring(args[2]), tostring(args[3]), tostring(args[4]), tostring(args[5]) }, '-' )
				color = CACHED_COLORS[key]
			end
			if color == nil then
				color = translate( ... )
				if key then CACHED_COLORS[ key ] = color end
			end
			-- print( color[1], color[2], color[3], color[4] )
			obj:_setFillColor( unpack( color ) )
		end
		return f
	end
	--]]

	function createClosure( obj, translate )
		local f = function( ... )
			local color = translate( ... )
			obj:_setFillColor( unpack( color ) )
		end
		return f
	end

	o._setFillColor = o.setFillColor

	o.setFillRGB = createClosure( o, translateRGBToHDR )
	o.setFillHDR = createClosure( o, translateHDRToHDR )

end

-- imbue object with strokeColor magic
--
function Display._modifySetStrokeColor( o )
	-- print( 'Display._modifySetStrokeColor' )

	-- cached version
	--[[
	function createClosure( obj, translate )
		local f = function( ... )
			local args = { ... }
			local key, color
			if type( args[2] ) == 'number' and dmc_kolor_data.cache_is_active == true then
				-- check cache
				key = table.concat( { tostring(args[2]), tostring(args[3]), tostring(args[4]), tostring(args[5]) }, '-' )
				color = CACHED_COLORS[key]
			end
			if color == nil then
				color = translate( ... )
				if key then CACHED_COLORS[ key ] = color end
			end
			-- print( color[1], color[2], color[3], color[4] )
			obj:_setStrokeColor( unpack( color ) )
		end
		return f
	end
	--]]

	function createClosure( obj, translate )
		-- print('createClosure stroke')
		local f = function( ... )
			local color = translate( ... )
			obj:_setStrokeColor( unpack( color ) )
		end
		return f
	end

	o._setStrokeColor = o.setStrokeColor

	o.setStrokeRGB = createClosure


                    EndRange();
                        }
                    }
                }
            }

            if (next == FC_CHARSET_DONE)
            {
                break;
            }

            if (in_range && next != offset + (bitmap.Length * 32))
            {
                EndRange();
            }

            offset = FcCharSetNextPage(cs, ref bitmap[0], ref next);
        }

        return sb.ToString();
    }
}


  ) -> Self {
        Self {
            _marker: PhantomData,
            ipfs_path,
            keypair,
            bootstrap,
            mdns,
        }
    }
}

impl<T: IpfsTypes> Default for IpfsOptions<T> {
    /// Create `IpfsOptions` from environment.
    ///
    /// # Panics
    ///
    /// Can panic if two threads call this method at the same time due to race condition on
    /// creating a configuration file under `IPFS_PATH` and other thread failing to read the just
    /// created empty file. Because of this, the implementation has been disabled in tests.
    fn default() -> Self {
        use self::config::ConfigFile;

        if cfg!(test) {
            // making this implementation conditional on `not(test)` results in multiple dead_code
            // lints on config.rs but for rustc 1.42.0 at least having this `cfg!(test)` branch
            // does not result in the same.
            panic!(
                "This implementation must not be invoked when testing as it cannot be safely
                used from multiple threads"
            );
        }

        let ipfs_path = if let Ok(path) = std::env::var("IPFS_PATH") {
            PathBuf::from(path)
        } else {
            let root = if let Some(home) = dirs::home_dir() {
                home
            } else {
                std::env::current_dir().unwrap()
            };
            root.join(".rust-ipfs").into()
        };
        let config_path = dirs::config_dir()
            .unwrap()
            .join("rust-ipfs")
            .join("config.json");
        let config = ConfigFile::new(config_path).unwrap();
        let keypair = config.secio_key_pair();
        let bootstrap = config.bootstrap();

        IpfsOptions {
            _marker: PhantomData,
            ipfs_path,
            keypair,
            bootstrap,
            mdns: true,
        }
    }
}

/// Ipfs struct creates a new IPFS node and is the main entry point
/// for interacting with IPFS.
#[derive(Clone, Debug)]
pub struct Ipfs<Types: IpfsTypes> {
    repo: Arc<Repo<Types>>,
    dag: IpldDag<Types>,
    ipns: Ipns<Types>,
    keys: DebuggableKeypair<Keypair>,
    to_task: Sender<IpfsEvent>,
}

type Channel<T> = OneshotSender<Result<T, Error>>;

/// Events used internally to communicate with the swarm, which is executed in the the background
/// task.
#[derive(Debug)]
enum IpfsEvent {
    /// Connect
    Connect(
        Multiaddr,
        OneshotSender<SubscriptionFuture<Result<(), String>>>,
    ),
    /// Addresses
    Addresses(Channel<Vec<(PeerId, Vec<Multiaddr>)>>),
    /// Local addresses
    Listeners(Channel<Vec<Multiaddr>>),
    /// Connections
    Connections(Channel<Vec<Connection>>),
    /// Disconnect
    Disconnect(Multiaddr, Channel<()>),
    /// Request background task to return the listened and external addresses
    GetAddresses(OneshotSender<Vec<Multiaddr>>),
    PubsubSubscribe(String, OneshotSender<Option<SubscriptionStream>>),
    PubsubUnsubscribe(String, OneshotSender<bool>),
    PubsubPublish(String, Vec<u8>, OneshotSender<()>),
    PubsubPeers(Option<String>, OneshotSender<Vec<PeerId>>),
    PubsubSubscribed(OneshotSender<Vec<String>>),
    WantList(Option


dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject

/**
 * Implementation of the AutoMuteService for API 29 (Q) and above.
 *
 * This implementation utilizes the DND Access API to setup an AutomaticZenRule.
 * It is visible in the system settings and can be managed using a configuration activity.
 *
 * Since this approach is based on conditions (which depend on the user id),
 * it is possible to have multiple rules for different users.
 * When Auto-Mute is enabled for multiple users, each user will have their own schedule
 * and Zen mode will be enabled if any of them are active.
 */
@RequiresApi(Build.VERSION_CODES.Q)
class AutoMuteServiceZenRuleImpl @Inject constructor(
	@ApplicationContext private val context: Context,
	private val notificationManager: NotificationManager,
) : AutoMuteService {
	private lateinit var conditionUri: Uri
	private lateinit var ruleId: String
	private lateinit var user: User

	fun setUser(user: User) {
		this.user = user

		conditionUri = Uri.Builder()
			.scheme(Condition.SCHEME)
			.authority(BuildConfig.APPLICATION_ID)
			.appendPath("automute")
			.appendQueryParameter("userId", user.id.toString())
			.build();

		try {
			// Load existing rule, remove duplicates (if any)
			notificationManager.automaticZenRules.filter {
				it.value.conditionId == conditionUri
			}.keys.forEachIndexed { index, key ->
				if (index == 0) {
					ruleId = key
				} else {
					notificationManager.removeAutomaticZenRule(key)
				}
			}
		} catch (e: SecurityException) {
			// Permission was revoked
		}
	}

	fun getRule(ruleId: String?): AutomaticZenRule? {
		return ruleId?.let { notificationManager.getAutomaticZenRule(it) }
	}

	override fun isPermissionGranted(): Boolean =
		notificationManager.isNotificationPolicyAccessGranted

	override fun isAutoMuteEnabled(): Boolean =
		this::ruleId.isInitialized && notificationManager.getAutomaticZenRule(ruleId).isEnabled

	override fun autoMuteEnable() {
		val rule = AutomaticZenRule(
			context.getString(R.string.automute_zen_rule_name, user.getDisplayedName(context)),
			null,
			ComponentName(context, AutoMuteConfigurationActivity::class.java),
			conditionUri,
			null,
			NotificationManager.INTERRUPTION_FILTER_PRIORITY,
			true
		)

		if (this::ruleId.isInitialized) {
			notificationManager.updateAutomaticZenRule(ruleId, rule)
		} else {
			ruleId = notificationManager.addAutomaticZenRule(rule)
		}
	}

	override fun autoMuteDisable() {
		if (this::ruleId.isInitialized) {
			notificationManager.getAutomaticZenRule(ruleId)?.apply {
				isEnabled = false
			}?.let {
				notificationManager.updateAutomaticZenRule(ruleId, it)
			}
		}
	}

	override fun autoMuteStateOn() {
		notificationManager.setAutomaticZenRuleState(
			ruleId,
			Condition(conditionUri, "Active", Condition.STATE_TRUE)
		)
	}

	override fun autoMuteStateOff() {
		notificationManager.setAutomaticZenRuleState(
			ruleId,
			Condition(conditionUri, "Inactive", Condition.STATE_FALSE)
		)
	}

	fun zenRuleRemove() {
		notificationManager.automaticZenRules
			.filter {
				it.value.conditionId.equals(conditionUri)
			}
			.forEach {
				notificationManager.removeAutomaticZenRule(it.key)
			}
	}
}
package com.sapuseven.untis.ui.weekview

import java.time.Clock
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.


        return true;
    }

    public async Task<InputFormatterResult> ReadAsync(InputFormatterContext context)
    {
        if (!_methods.TryGetValue(context.ModelType, out var method))
        {
            method = _deserializeMethod.MakeGenericMethod(context.ModelType);
            _methods.TryAdd(context.ModelType, method);
        }

        var request = context.HttpContext.Request;
        var json = string.Empty;
        if (request.Body is not null)
        {
            using var streamReader = new StreamReader(request.Body);
            json = await streamReader.ReadToEndAsync();
        }

        if (string.IsNullOrWhiteSpace(json))
        {
            json = EmptyJson;
        }

        var result = method.Invoke(_serializer, new object[] {json});

        return await InputFormatterResult.SuccessAsync(result);
    }
}


 fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('text', models.TextField(verbose_name='Question')),
                ('quiz', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='questions', to='classroom.quiz')),
            ],
        ),
        migrations.CreateModel(
            name='Answer',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('text', models.CharField(max_length=255, verbose_name='Answer')),
                ('is_correct', models.BooleanField(default=False, verbose_name='Correct answer')),
                ('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='answers', to='classroom.question')),
            ],
        ),
        migrations.CreateModel(
            name='TakenQuiz',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('score', models.IntegerField()),
                ('percentage', models.FloatField()),
                ('date', models.DateTimeField(auto_now_add=True)),
                ('quiz', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='taken_quizzes', to='classroom.quiz')),
                ('student', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='taken_quizzes', to='classroom.student')),
            ],
        ),
        migrations.CreateModel(
            name='StudentAnswer',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('answer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to='classroom.answer')),
                ('student', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='quiz_answers', to='classroom.student')),
            ],
        ),
        migrations.AddField(
            model_name='student',
            name='quizzes',
            field=models.ManyToManyField(through='classroom.TakenQuiz', to='classroom.Quiz'),
        ),
    ]


BoxStyle.SINGLE_LONG);
                break;
            case 2:
                branchBox.setX(parentBox.getX() + 2*parentBox.getWidth()/5 + 20);
                branchBox.setType(StyleManager.SMALL);
                StyleManager.stylize(branchBox, SmallBoxStyle.SINGLE_LONG);
                break;
            case 3:
                branchBox.setX(parentBox.getX() + 2*parentBox.getWidth()/5 + 20);
                branchBox.setType(StyleManager.MINI);
                StyleManager.stylize(branchBox, MiniBoxStyle.SINGLE);
                break;
            case 4:
                branchBox.setX(parentBox.getX() + 2*parentBox.getWidth()/3 + 20);
                branchBox.setType(StyleManager.TINY);
                StyleManager.stylize(branchBox, TinyBoxStyle.SINGLE);
                break;
            case 5:
                branchBox.setX(parentBox.getX() + parentBox.getWidth()/2 + 20);
                branchBox.setType(StyleManager.TINY);
                StyleManager.stylize(branchBox, TinyBoxStyle.SINGLE);
                break;
            default:
                branchBox.setX(parentBox.getX() + parentBox.getWidth()/2 + 20);
                branchBox.setType(StyleManager.TINY);
                StyleManager.stylize(branchBox, TinyBoxStyle.SINGLE);
                break;
        }
    }
}import { ErrorModel } from '../models/error-model';
import { ErrorCode } from '../exposed/squid';
import { Google } from '../services/google';
import { GoogleAuthHelper } from './google-auth-helper';
import { AuthToken } from './auth-token';
import { TokenType } from './token-type';
import { Identity } from './identity';
import * as express from 'express';
import * as tex from '../core/typed-express'
import * as winston from 'winston';

class GoogleAuth {

    /** Creates a new instance. */
    constructor(private readonly google: Google) { }

    /**
     * Authenticate a request.
     *
     * Two types of tokens are received by the service:
     * * Google ID tokens, sent by the Android app.
     * * Google access tokens, sent by the chrome extension.
     *
     * ID tokens contain the user ID.
     * Access tokens do not contain the user ID, but we obtain it by making a call to Google getUserInfo.
     * @returns a user if the request has AuthZ, and throws otherwise.
     */
    public authenticate(req: express.Request): Promise<Identity> {
        return Promise.resolve(null)
            .then(result =>  GoogleAuth.parseAuthHeader(req))
            .then(parsedAuthHeader => {
                winston.debug(`Google ${parsedAuthHeader.tokenType} received. Validating...`);

                switch(parsedAuthHeader.tokenType) {
                    case TokenType.Access:
                        return this.google.getAccessTokenUser(parsedAuthHeader.token);
                    case TokenType.Id:
                        return this.google.getIdTokenUser(parsedAuthHeader.token);
                    default:
                        throw new ErrorModel(ErrorCode.Authorization, 'Unknown Google auth token received');
                }
            });
    }

    /**
     * Parses the authentication header in format "<auth header prefix>: <token value>" into a token type and value
     */
    private static parseAuthHeader(req: express.Request): AuthToken {
        // Extract the token and return an error immediately if not found
        let authHeader: string = req.get('Authorization');
        if(!authHeader) {
            winston.warn('AuthZ failed. No token was found');
            throw new ErrorModel(ErrorCode.Authorization, 'Authorization header must be sent with Google token');
        }


/*
© Siemens AG, 2017-2019
Author: Dr. Martin Bischoff (martin.bischoff@siemens.com)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

<http://www.apache.org/licenses/LICENSE-2.0>.

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

using UnityEngine;
using UnityEditor;
using System.Linq;
using System.IO;

namespace RosSharp
{
    public class StlAssetPostProcessor : AssetPostprocessor
    {
        private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPath)
        {
            foreach (string stlFile in importedAssets.Where(x => x.ToLowerInvariant().EndsWith(".stl")))
                createStlPrefab(stlFile);
        }

        private static void createStlPrefab(string stlFile)
        {
            GameObject gameObject = CreateStlParent(stlFile);
            if (gameObject == null)
                return;

            PrefabUtility.SaveAsPrefabAsset(gameObject, getPrefabAssetPath(stlFile));
            Object.DestroyImmediate(gameObject);
        }

        private static GameObject CreateStlParent(string stlFile)
        {


  @$core.Deprecated(
  'Using this can add significant overhead to your binary. '
  'Use [GeneratedMessageGenericExtensions.deepCopy] instead. '
  'Will be removed in next major version')
  SequenceState clone() => SequenceState()..mergeFromMessage(this);
  @$core.Deprecated(
  'Using this can add significant overhead to your binary. '
  'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
  'Will be removed in next major version')
  SequenceState copyWith(void Function(SequenceState) updates) => super.copyWith((message) => updates(message as SequenceState)) as SequenceState; // ignore: deprecated_member_use
  $pb.BuilderInfo get info_ => _i;
  @$core.pragma('dart2js:noInline')
  static SequenceState create() => SequenceState._();
  SequenceState createEmptyInstance() => create();
  static $pb.PbList<SequenceState> createRepeated() => $pb.PbList<SequenceState>();
  @$core.pragma('dart2js:noInline')
  static SequenceState getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<SequenceState>(create);
  static SequenceState? _defaultInstance;

  @$pb.TagNumber(1)
  $core.int get sequence => $_getIZ(0);
  @$pb.TagNumber(1)
  set sequence($core.int v) { $_setUnsignedInt32(0, v); }
  @$pb.TagNumber(1)
  $core.bool hasSequence() => $_has(0);
  @$pb.TagNumber(1)
  void clearSequence() => clearField(1);

  @$pb.TagNumber(2)
  $core.String get name => $_getSZ(1);
  @$pb.TagNumber(2)
  set name($core.String v) { $_setString(1, v); }
  @$pb.TagNumber(2)
  $core.bool hasName() => $_has(1);
  @$pb.TagNumber(2)
  void clearName() => clearField(2);

  @$pb.TagNumber(3)
  $core.bool get active => $_getBF(2);
  @$pb.TagNumber(3)
  set active($core.bool v) { $_setBool(2, v); }
  @$pb.TagNumber(3)
  $core.bool hasActive() => $_has(2);
  @$pb.TagNumber(3)
  void clearActive() => clearField(3);

  @$pb.TagNumber(4)
  $core.double get rate => $_getN(3);
  @$pb.TagNumber(4)
  set rate($core.double v) { $_setDouble(3, v); }
  @$pb.TagNumber(4)
  $core.bool hasRate() => $_has(3);
  @$pb.TagNumber(4)
  void clearRate() => clearField(4);
}

class GetSequenceRequest extends $pb.GeneratedMessage {
  static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'GetSequenceRequest', package: const $pb.PackageName(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'mizer.sequencer'), createEmptyInstance: create)
    ..a<$core.int>(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'sequence', $pb.PbFieldType.OU3)
    ..hasRequiredFields = false
  ;

  GetSequenceRequest._() : super();
  factory GetSequenceRequest({
    $core.int? sequence,
  }) {
    final _result = create();
    if (sequence != null) {
      _result.sequence = sequence;
    }
    return _result;
  }
  factory GetSequenceRequest.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r);
  factory GetSequenceRequest.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r);