)에서 제공하는 설정을 통해 더 고급으로 변환할 시간입니다.
---
title: Esempio di configurazione
author: Franco Colussi
contributors: Steven Spencer, Ganna Zhyrnova
tested_with: 8.7, 9.1
tags:
  - nvchad
  - coding
  - plugins
---

# Esempio di configurazione

!!! danger "Non più fornito"

    L'esempio di configurazione non viene più fornito durante l'installazione di NvChad; di conseguenza, questa pagina è obsoleta e verrà rimossa nella nuova versione della guida. Le istruzioni verranno aggiornate al più presto.

## :material-message-outline: Introduzione

La versione 2.0 di NvChad introduce la possibilità di creare una cartella ==custom== durante la fase di installazione. La sua creazione è il punto di partenza per personalizzare l'editor modificando i suoi file. Installato al bootstrap permette, al primo avvio, di avere un editor con le caratteristiche di base di un IDE, ma può essere incluso anche dopo l'installazione di NvChad.

L'aspetto più importante della sua installazione è la creazione delle strutture di base per l'inclusione di alcune funzionalità avanzate come i server linguistici, i linters e i formattatori. Queste strutture consentono di integrare le funzionalità necessarie con poche modifiche.

La cartella viene creata da un modello della repository di NvChad di GitHub: ([example-config](https://github.com/NvChad/example_config)).

## :material-monitor-arrow-down-variant: Installazione

=== "Installazione all'avvio"

    Per crearla durante l'installazione, rispondere "y" alla domanda che viene posta all'inizio dell'installazione:

    > Do you want to install example custom config? (y/N):

    Una risposta affermativa avvierà un processo che clonerà il contenuto della cartella *example-config* da GitHub in **~/.config/nvim/lua/custom/** e, una volta terminato, rimuoverà la cartella **.git** da essa.
    Rimuovendola, la cartella può essere posta sotto un controllo di versione personale.

    La cartella è pronta e verrà utilizzata al successivo avvio di NvChad per inserire le configurazioni personalizzate nell'editor.

=== "Installazione dal repository"

    L'installazione della configurazione fornita da ==example-config== può essere fatta anche dopo l'installazione di NvChad, nel qual caso il repository è ugualmente utilizzato ma viene recuperato con un'operazione manuale.

    L'installazione standard senza ==example-config== crea comunque una cartella *custom* in cui salvare il file ==chadrc.lua== per le personalizzazioni dell'utente e deve essere cancellata o salvata in un ==backup== per consentire l'esecuzione del clone. Salvare quindi la configurazione esistente con:

    ```bash
    mv ~/.config/nvim/lua/custom/ ~/.config/nvim/lua/custom.bak
    ```

    E clonare il repository GitHub nella propria configurazione:

    ```bash
    git clone https://github.com/NvChad/example_config.git ~/.config/nvim/lua/custom
    ```

    Il comando copia l'intero contenuto dei repository trovati online nella cartella `~/.config/nvim/lua/custom/`, copiando la cartella nascosta `.git`, che è necessario cancellare manualmente p


latePressure": true,
			"pressures": []
		},
		{
			"type": "freedraw",
			"version": 62,
			"versionNonce": 1442291541,
			"isDeleted": false,
			"id": "8SYSKlVZ2O7gcTjcSo-li",
			"fillStyle": "solid",
			"strokeWidth": 0.5,
			"strokeStyle": "solid",
			"roughness": 1,
			"opacity": 100,
			"angle": 0,
			"x": -1091.1361491858615,
			"y": 117.11728807203275,
			"strokeColor": "#2f9e44",
			"backgroundColor": "transparent",
			"width": 1.710419220726635,
			"height": 32.49827015611169,
			"seed": 1709036635,
			"groupIds": [],
			"frameId": null,
			"roundness": null,
			"boundElements": [],
			"updated": 1714557485078,
			"link": null,
			"locked": false,
			"points": [
				[
					0,
					0
				],
				[
					0.5701270334793662,
					5.131295782468044
				],
				[
					0.5701270334793662,
					6.841715003194622
				],
				[
					0.5701270334793662,
					8.552172344209566
				],
				[
					0,
					11.973048905951089
				],
				[
					-0.5701651537679027,
					13.68346812667761
				],
				[
					-0.5701651537679027,
					15.393925467692554
				],
				[
					-1.1402921872472689,
					17.104344688419133
				],
				[
					-1.1402921872472689,
					18.244636875666288
				],
				[
					-1.1402921872472689,
					19.384929062913443
				],
				[
					-1.1402921872472689,
					20.525221250160655
				],
				[
					-1.1402921872472689,
					22.235640470887176
				],
				[
					-1.1402921872472689,
					23.37593265813433
				],
				[
					-1.1402921872472689,
					24.516224845381544
				],
				[
					-1.1402921872472689,
					25.6565170326287
				],
				[
					-1.1402921872472689,
					26.796809219875854
				],
				[
					-1.1402921872472689,
					27.366974373643643
				],
				[
					-1.1402921872472689,
					28.5072665608908
				],
				[
					-1.1402921872472689,
					29.077393594370164
				],
				[
					-1.1402921872472689,
					30.217685781617377
				],
				[
					-1.1402921872472689,
					30.787812815096743
				],
				[
					-1.1402921872472689,
					31.35797796886453
				],
				[
					-1.1402921872472689,
					31.928105002343898
				],
				[
					-1.1402921872472689,
					32.49827015611169
				],
				[
					-1.1402921872472689,
					32.49827015611169
				]
			],
			"lastCommittedPoint": null,
			"simulatePressure": true


core';
import { SketchMSData } from '@xlayers/sketchtypes';

@Injectable({
  providedIn: 'root',
})
export class VueDocGenService {
  aggregate(data: SketchMSData) {
    return [
      {
        uri: 'README.md',
        value: this.renderReadme(data.meta.app),
        language: 'markdown',
        kind: 'text',
      },
    ];
  }

  private renderReadme(name: string) {
    return `\
## How to use the ${name} Vue module

1. Download and extract the exported module into your workspace,

2. Import the component into your App component or other container.
\`\`\`
<template>
  <div id="app">
    <MyComponent />
  </div>
</template>

<script>
import MyComponent from \'./components/MyComponent.vue\'

export default {
  name: \'app\
  components: {
    MyComponent
  }
}
</script>
\`\`\`

3. Enjoy.`;
  }
}
import { isPrime, countPrimeEqualOrLessNum, getAllPrimesEqualOrLessNum } from '../src/libs/number';

describe('test isPrime util', () => {
  test('should get true when num is prime', () => {
    expect(isPrime(2)).toBeTruthy();
    expect(isPrime(3)).toBeTruthy();
    expect(isPrime(11)).toBeTruthy();
    expect(isPrime(101)).toBeTruthy();
  });
  test('should get false when num is not prime', () => {
    expect(isPrime(1)).toBeFalsy();
    expect(isPrime(4)).toBeFalsy();
    expect(isPrime(9)).toBeFalsy();
    expect(isPrime(102)).toBeFalsy();
  });
});

describe('test countPrimeEqualOrLessNum', () => {
  test('should get prime count not greater then num', () => {
    expect(countPrimeEqualOrLessNum(1)).toBe(0);
    expect(countPrimeEqualOrLessNum(2)).toBe(1);
    expect(countPrimeEqualOrLessNum(20)).toBe(8);
  });
});

describe('test getAllPrimesEqualOrLessNum', () => {
  test('should get all primes not greater then num', () => {
    expect(getAllPrimesEqualOrLessNum(1)).toEqual([]);
    expect(getAllPrimesEqualOrLessNum(2)).toEqual([2]);
    expect(getAllPrimesEqualOrLessNum(20)).toEqual([2, 3, 5, 7, 11, 13, 17, 19]);
  });
});
import { createContext } from 'react';
import CryptoType from '../enums/CryptoType';

export type PriceState = {
  elPrice: number
  ethPrice: number
  bnbPrice: number;
  gasPrice: string;
  bscGasPrice: string;
  priceLoaded: boolean;
}

export interface IPriceContext extends PriceState {
  getCryptoPrice: (cryptoType: CryptoType) => number
}

export const initialPriceState = {
  ethPrice: 1679251,
  elPrice: 0.009799,
  bnbPrice: 276.64,
  gasPrice: '6800000000',
  bscGasPrice: '19950000000',
  priceLoaded: false,
}

export const initialPriceContext = {
  ...initialPriceState,
  getCryptoPrice: (_cryptoType: CryptoType) => 0,
}

const PriceContext = createContext<IPriceContext>(initialPriceContext);

export default PriceContext;
import * as cache from '../cache/hero';
import * as hahowService from '../services/hahowHero';

export interface HeroProfile {
  str: number;
  int: number;
  agi: number;
  luk: number;
}

export type HeroData = {
  id: string;
  name: string;
  image: string;
  profile?: HeroProfile;
};

export class Hero {
  id: string;
  name: string;
  image: string;
  profile?: Her


      result => panic!("Unexpected result: {:?}", result),
    }
}

#[test]
fn pull_request_page_url_without_branch_outside_git_repo() {
    let mut cfg = config_for_pr(None, "ssh://git@github.com:22/rhysd/git-brws.git", None);
    cfg.cwd = get_root_dir();
    match build_page_url(&OPEN_PR, &cfg).unwrap_err().kind() {
        ErrorKind::GitCommandError { .. } => { /* OK */ }
        err => panic!("Unexpected error: {} at {:?}", err, &cfg.cwd),
    }
}

#[test]
fn pull_request_unsupported_services() {
    let urls = &[
        "https://gitlab.com/foo/bar.git",
        "https://gitlab.yourcompany.com/foo/bar.git",
        "https://bitbucket.org/foo/bar.git",
        "ssh://git@gitlab.com:22/foo/bar.git",
        "ssh://git@gitlab.yourcompany.com:22/foo/bar.git",
        "ssh://git@bitbucket.org:22/foo/bar.git",
    ];
    for url in urls {
        let cfg = config_for_pr(None, url, None);
        match build_page_url(&OPEN_PR, &cfg).unwrap_err().kind() {
            ErrorKind::PullReqNotSupported { .. } => { /* OK */ }
            err => panic!("Unexpected error for URL {}: {}", url, err),
        }
    }
}

#[test]
fn pull_request_github_enterprise_with_no_token() {
    let cfg = config_for_pr(None, "https://github.yourcompany.com/foo/bar.git", None);
    match build_page_url(&OPEN_PR, &cfg).unwrap_err().kind() {
        ErrorKind::GheTokenRequired => { /* OK */ }
        err => panic!("Unexpected error: {}", err),
    }
}

#[test]
fn tab_page_for_github_and_gitlab() {
    let hosts = &[
        "github.com",
        "github.yourcompany.com",
        "gitlab.com",
        "gitlab.yourcompany.com",
    ];
    let page = Page::Tag {
        tagname: "tag".to_string(),
        commit: "01234cdef".to_string(),
    };
    for host in hosts {
        let expected = format!("https://{}/foo/bar/tree/tag", host);
        for url in &[
            format!("https://{}/foo/bar.git", host),
            format!("ssh://git@{}:22/foo/bar.git", host),
        ] {
            let c = config(url, None, None);
            let actual = build_page_url(&page, &c).unwrap();
            assert_eq!(actual, expected, "{}", url);
        }
    }
}

#[test]
fn tab_page_for_bitbucket() {
    let page = Page::Tag {
        tagname: "tag".to_string(),
        commit: "01234cdef".to_string(),
    };
    let expected = "https://bitbucket.org/user/repo/commits/01234cdef";
    for url in &[
        "https://bitbucket.org/user/repo",
        "ssh://git@bitbucket.org:22/user/repo.git",
    ] {
        let c = config(url, None, None);
        let actual = build_page_url(&page, &c).unwrap();
        assert_eq!(actual, expected, "{}", url);
    }
}

#[test]
fn subgroups_for_gitlab() {
    for repo in &[
        "https://gitlab.com/group/sub1/repo.git",
        "https://gitlab.com/group/sub1/repo",
        "https://gitlab.com/group/sub1/


〼〔〖〴〄】〚〻〯〴〣〮〦〧〣〵〼〚〾〫〼〣〔〚〽『〵〒【【〝〹〮》『〨〜〠〸〠〵〨〙【〧〸〈》〱〗【〓〤】〰】】、〩〽〈〸〔「〵〻〙〓〰〇〚〞〗〙〢々〭〜〈　。〧〿〧〨〵〾〝〬【』〫〦〸〬〈、〒〢〉〞〵〒〼〝》〻〫〧〤〶〹〼〩〛〫〣】〿」〴》〺〬〤〕〲〕〙〔〪〰〿〬〒〔〞〆〻〴〘〩〨〤》〩〪〭〳〇〣〚〟〚〕〓〴〱　〵〃〠〭〠〚〗〃〃〸〰〢〡〿〭『〗〉、〲〕〧「〛〛〓〜〰〮』〱〨〬〨〽〸〽〶〣〯〫、〯々、〴　」〕〥』〻】〖〴」〨。〖〤『〜〰〩〣〣〸、〫〝、〯〹〷〳〚〄〷【〃」〼「〤】　〢〖　〣〙〺〽〽〱〤〔〓々〣〭〽〘〦〻〪〿〞〝〱、《〆」〸〷〛〓〕〹〜〪〹〶、〵〦〛〲〒〹〪〦〃〥「〸〪〙〧〱〠〰〝〆〠〯《〼　〛〚〔〟〽〗」、〲〥〞〴〃、「『〖〼〞〪〼〇』〿〶々〙〻》〥、〵〛〞〠〫〟　　〹〾〵』〤〿〣〪〗〃〖〬〩〴〗々〓〝〥〥〜〲〯〗〤》〛〮》々〚〘〫「〙〉【〆〽〨〹〮〧〷「〴〝〬〷〗『〔〷〮〟〲〬〸〸〟〹〆〖〨。〣〄』〴〚】〘〲〚〚〦〈〛〗〞〉〞〯〆〵〸　〗〕、》【〸〮〵〉〥〨〕〟〭【〾〇〵〬〾」〱〹〚〟〛〡」〩〃〄〬〱〭〚〱〆〛》〣』〝〡〦〣〫〒〗〛〿〤〇〼〠〲〢〬〿〓〠」〚〇〛〈〴《〦〱〤〹〝〱〶〟〙〴〶〣〝〮　〜〲〱〿〳〪〄〝〃〰〙〖〼〰、


been "downloaded" from the remote repositiory, and installed
      // in our local cache:
      cacheDir.toPath().resolve("org/test/dependencyA/0.1.0/bundle/src").exists().shouldBeTrue()
      cacheDir.toPath().resolve("org/test/dependencyA/0.1.0/bundle/src/types.taxi").exists().shouldBeTrue()
      cacheDir.toPath().resolve("org/test/dependencyA/0.1.0/bundle/taxi.conf").exists().shouldBeTrue()
   }
}

class NexusContainer : GenericContainer<NexusContainer>(DockerImageName.parse("sonatype/nexus3"))
package org.taxilang.packagemanager.repository.nexus

import lang.taxi.packages.Credentials
import lang.taxi.packages.PackageIdentifier
import lang.taxi.packages.Repository
import lang.taxi.packages.TaxiPackageProject
import org.http4k.core.Response
import java.io.File
import java.io.InputStream
import java.nio.file.Path

/**
 * Represents a service for inteeracting with a remote package service,
 * such as Nexus.
 * Responsible for donwload/upload of packages.
 *
 * You don't need a PackageService for interacting with git repositories
 */
interface PackageService {
   fun upload(zip: File, taxiConfFilePath: Path, project: TaxiPackageProject): Response
   fun attemptDownload(identifier: PackageIdentifier): InputStream?

   val repositoryType: String
}

/**
 * Responsible for creating the correct PackageService with credentials to access the
 * requested Repository
 */
interface PackageServiceFactory {
   fun get(repository: Repository, credentials: List<Credentials>): PackageService
}

/**
 * Always returns the same service
 */
class SingleServiceFactory(private val service: PackageService) : PackageServiceFactory {
   override fun get(repository: Repository, credentials: List<Credentials>): PackageService {
      return service
   }

}

object DefaultPackageServiceFactory : PackageServiceFactory {
   private val knownRepositoryTypes = listOf(
      NexusPackageService.REPOSITORY_TYPE,
   )

   override fun get(repository: Repository, credentials: List<Credentials>): PackageService {
      val repositoryCredentials = credentials.firstOrNull { it.repositoryName == repository.name }
      return when (repository.type) {
         NexusPackageService.REPOSITORY_TYPE -> NexusPackageService(repository, repositoryCredentials)
         else -> error("Unknown type of repository : ${repository.type} - expected one of ${knownRepositoryTypes.joinToString()}")
      }
   }

}
package lang.taxi.types

import com.winterbe.expekt.expect
import com.winterbe.expekt.should
import org.junit.jupiter.api.Test

class QualifiedNameParserTest {

   @Test
   fun parsesNameWithUnderscoresCorrectly() {
      val fqn = "foo.baz.Bar_Bop".fqn()
      expect(fqn.typeName).to.equal("Bar_Bop")
      expect(fqn.fullyQualifiedName).to.equal("foo.baz.Bar_Bop")
      expect(fqn.parameters).to.be.empty
   }

   @Test
   fun parsesUnderscoresInGenericsCorrectly() {
      val genericFqn = "foo.baz.Bar_Bop<foo.baz.Sup_Dog>".fqn()
      expect(genericFqn.typeName).to.equal("Bar_Bop")
      expect(genericFqn.fullyQualifiedName).to.equal("foo.baz.Bar_Bop")
      expect(genericFqn.parameters).to.have.size(1)
      expect(genericFqn.parameters[0].typeName).to.equal("Sup_Dog")
      expect(genericFqn.parameters[0].fullyQualifiedName).to.equal("foo.baz.Sup_Dog")
      expect(genericFqn.parameters[0].parameters).to.be.empty
   }

   @Test
   fun parsesNamesCorrectly() {
      val fqn = "foo.baz.Bar".fqn()
      expect(fqn.typeName).to.equal("Bar")
      expect(fqn.fullyQualifiedName).to.equal("foo.baz


/** @file
  AsmCpuid function.

  Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.<BR>
  This program and the accompanying materials
  are licensed and made available under the terms and conditions of the BSD License
  which accompanies this distribution.  The full text of the license may be found at
  http://opensource.org/licenses/bsd-license.php.

  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.

**/

/**
  Retrieves CPUID information.

  Executes the CPUID instruction with EAX set to the value specified by Index.
  This function always returns Index.
  If Eax is not NULL, then the value of EAX after CPUID is returned in Eax.
  If Ebx is not NULL, then the value of EBX after CPUID is returned in Ebx.
  If Ecx is not NULL, then the value of ECX after CPUID is returned in Ecx.
  If Edx is not NULL, then the value of EDX after CPUID is returned in Edx.
  This function is only available on IA-32 and x64.

  @param  Index         The 32-bit value to load into EAX prior to invoking the CPUID
                        instruction.
  @param  RegisterEax   A pointer to the 32-bit EAX value returned by the CPUID
                        instruction. This is an optional parameter that may be NULL.
  @param  RegisterEbx   A pointer to the 32-bit EBX value returned by the CPUID
                        instruction. This is an optional parameter that may be NULL.
  @param  RegisterEcx   A pointer to the 32-bit ECX value returned by the CPUID
                        instruction. This is an optional parameter that may be NULL.
  @param  RegisterEdx   A pointer to the 32-bit EDX value returned by the CPUID
                        instruction. This is an optional parameter that may be NULL.

  @return Index.

**/
UINT32
EFIAPI
AsmCpuid (
  IN      UINT32                    Index,
  OUT     UINT32                    *RegisterEax,  OPTIONAL
  OUT     UINT32                    *RegisterEbx,  OPTIONAL
  OUT     UINT32                    *RegisterEcx,  OPTIONAL
  OUT     UINT32                    *RegisterEdx   OPTIONAL
  )
{
  _asm {
    mov     eax, Index
    cpuid
    push    ecx
    mov     ecx, RegisterEax
    jecxz   SkipEax
    mov     [ecx], eax
SkipEax:
    mov     ecx, RegisterEbx
    jecxz   SkipEbx
    mov     [ecx], ebx
SkipEbx:
    pop     eax
    mov     ecx, RegisterEcx
    jecxz   SkipEcx
    mov     [ecx], eax
SkipEcx:
    mov     ecx, RegisterEdx
    jecxz   SkipEdx
    mov     [ecx], edx
SkipEdx:
    mov     eax, Index
  }
}


 MEM_CST+56(%rip)
	movl	$0, MEM_CST+60(%rip)
	ja	.L10
	xorl	%eax, %eax
	cmpl	$257, %esi
	movl	%esi, SHA3_S+268(%rip)
	setge	%al
	movslq	%esi,%rsi
	movl	$SHA3_S, %edx
	leal	4(,%rax,4), %eax
	xorl	%ecx, %ecx
	movl	%eax, SHA3_S+272(%rip)
	.p2align 4,,10
	.p2align 3
.L13:
	addl	$1, %ecx
	movq	%rsi, (%rdx)
	movq	$0, 8(%rdx)
	addq	$16, %rdx
	cmpl	%ecx, %eax
	jg	.L13
	cmpl	$15, %eax
	jg	.L14
	addl	%eax, %eax
	.p2align 4,,10
	.p2align 3
.L15:
	movslq	%eax,%rdx
	movq	$0, SHA3_S(,%rdx,8)
	leal	1(%rax), %edx
	addl	$2, %eax
	cmpl	$32, %eax
	movslq	%edx,%rdx
	movq	$0, SHA3_S(,%rdx,8)
	jne	.L15
.L14:
	movq	$0, SHA3_S+256(%rip)
	movl	$0, SHA3_S+264(%rip)
	xorl	%eax, %eax
.L10:
	rep
	ret
.L23:
	leaq	16(%rdx), %rax
	movl	$SHA3_S, %ecx
	cmpq	%rax, %rcx
	ja	.L17
.L5:
	xorl	%eax, %eax
	.p2align 4,,10
	.p2align 3
.L8:
	movq	SHA3_S(%rax), %rcx
	movq	%rcx, (%rdx,%rax)
	addq	$8, %rax
	cmpq	$288, %rax
	jne	.L8
	jmp	.L4
	.cfi_endproc
.LFE540:
	.size	Init, .-Init
	.p2align 4,,15
.globl Update
	.type	Update, @function
Update:
.LFB541:
	.cfi_startproc
	pushq	%r15
	.cfi_def_cfa_offset 16
	pushq	%r14
	.cfi_def_cfa_offset 24
	pushq	%r13
	.cfi_def_cfa_offset 32
	pushq	%r12
	.cfi_def_cfa_offset 40
	pushq	%rbp
	.cfi_def_cfa_offset 48
	pushq	%rbx
	.cfi_def_cfa_offset 56
	movq	%rsi, %rbx
	.cfi_offset 3, -56
	.cfi_offset 6, -48
	.cfi_offset 12, -40
	.cfi_offset 13, -32
	.cfi_offset 14, -24
	.cfi_offset 15, -16
	subq	$8, %rsp
	.cfi_def_cfa_offset 64
	movq	%rdx, (%rsp)
	movq	SHA3_S+280(%rip), %rdx
	cmpq	%rdi, %rdx
	je	.L25
	testb	$15, %dl
	movl	$SHA3_S, %esi
	jne	.L26
	cmpq	$SHA3_S+16, %rdx
	jbe	.L75
.L58:
	xorl	%eax, %eax
	.p2align 4,,10
	.p2align 3
.L28:
	movd


using Grand.Core;
using Grand.Framework.Controllers;
using Grand.Framework.Mvc.Filters;
using Grand.Framework.Security;
using Grand.Plugin.ExternalAuth.Facebook.Models;
using Grand.Services.Authentication.External;
using Grand.Services.Configuration;
using Grand.Services.Localization;
using Grand.Services.Security;
using Grand.Services.Stores;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Facebook;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Grand.Plugin.ExternalAuth.Facebook.Controllers
{
    public class FacebookAuthenticationController : BasePluginController
    {
        #region Fields

        private readonly FacebookExternalAuthSettings _facebookExternalAuthSettings;
        private readonly IExternalAuthenticationService _externalAuthenticationService;
        private readonly ILocalizationService _localizationService;
        private readonly IPermissionService _permissionService;
        private readonly ISettingService _settingService;

        #endregion

        #region Ctor

        public FacebookAuthenticationController(FacebookExternalAuthSettings facebookExternalAuthSettings,
            IExternalAuthenticationService externalAuthenticationService,
            ILocalizationService localizationService,
            IPermissionService permissionService,
            ISettingService settingService)
        {
            _facebookExternalAuthSettings = facebookExternalAuthSettings;
            _externalAuthenticationService = externalAuthenticationService;
            _localizationService = localizationService;
            _permissionService = permissionService;
            _settingService = settingService;
        }

        #endregion

        #region Methods

        [AuthorizeAdmin]
        [Area("Admin")]
        public async Task<IActionResult> Configure()
        {
            if (!await _permissionService.Authorize(StandardPermissionProvider.ManageExternalAuthenticationMethods))
                return AccessDeniedView();

            var model = new ConfigurationModel
            {
                ClientId = _facebookExternalAuthSettings.ClientKeyIdentifier,
                ClientSecret = _facebookExternalAuthSettings.ClientSecret,
            };

            return View("~/Plugins/ExternalAuth.Facebook/Views/Configure.cshtml", model);
        }

        [HttpPost]
        [AutoValidateAntiforgeryToken]
        [AuthorizeAdmin]
        [Area("Admin")]
        public async Task<IActionResult> Configure(ConfigurationModel model)
        {
            if (!await _permissionService.Authorize(StandardPermissionProvider.ManageExternalAuthenticationMethods))
                return AccessDeniedView();

            if (!ModelState.IsValid)
                return await Configure();

            _facebookExternalAuthSettings.ClientKeyIdentifier = model.ClientId;
            _facebookExternalAuthSettings.ClientSecret = model.ClientSecret;
            await _settingService.Sav


#!/usr/bin/env python3

import os

import numpy as np

import shared
from jobmonitor.api import (
    kubernetes_schedule_job,
    kubernetes_schedule_job_queue,
    register_job,
    upload_code_package,
)
from jobmonitor.connections import mongo

gpus = 1
seed = 42

basename = os.path.basename(__file__).replace(".py", "")
experiment = f"neurips19_{basename}"
description = """
Here, we evaluate whether reuse brings us closer to a power iteration with more steps
""".strip()

code_package = shared.upload_code()

registered_ids = []

n_workers = 16

learning_rate = 0.1

for rank in [1]:
    for reuse in [True, False]:
        if reuse:
            reducer = f"Rank {rank} (EF)"
        else:
            reducer = f"Rank {rank} w/o reuse (EF)"

        name = f"{reducer}"
        if mongo.job.count_documents({"job": name, "experiment": experiment}) > 0:
            # We have this one already
            continue
        job_id = register_job(
            user="vogels",
            project="sgd",
            experiment=experiment,
            job=name,
            n_workers=n_workers,
            priority=5,
            config_overrides={
                "seed": seed,
                "distributed_backend": "nccl",
                "optimizer_scale_lr_with_factor": n_workers,
                "num_epochs": 300,
                "log_verbosity": 1,
                **shared.sgd_config(learning_rate, momentum=0.9, weight_decay=0.0001),
                **shared.optimizer_config(reducer),
            },
            runtime_environment={"clone": {"code_package": code_package}, "script": "train.py"},
            annotations={"description": description},
        )
        print("{} - {}".format(job_id, name))
        registered_ids.append(job_id)

    # Higher quality baseline with more power iteration steps
    reducer = f"HQ Rank {rank} w/o reuse (EF)"
    name = f"{reducer}"
    if mongo.job.count_documents({"job": name, "experiment": experiment}) > 0:
        # We have this one already
        continue
    job_id = register_job(
        user="vogels",
        project="sgd",
        experiment=experiment,
        job=name,
        n_workers=n_workers,
        priority=10,
        config_overrides={
            "seed": seed,
            "distributed_backend": "nccl",
            "optimizer_scale_lr_with_factor": n_workers,
            "num_epochs": 300,
            "log_verbosity": 1,
            **shared.sgd_config(learning_rate, momentum=0.9, weight_decay=0.0001),
            **shared.optimizer_config(reducer),
        },
        runtime_environment={"clone": {"code_package": code_package}, "script": "train.py"},
        annotations={"description": description},
    )
    print("{} - {}".format(job_id, name))
    registered_ids.append(job_id)

# kubernetes_schedule_job_queue(
#     registered_ids,
#     "ic-registry.epfl.ch/mlo/vogels_experiment",
#     volumes=["pv-mlodata1"],
#     gpus=gpus,
#     parallelism=4,
#     results_dir="/pv-mlodata1/vogels/results",
#     environment_variables={"DATA": "/pv-mlodata1/vogels"},
# )


width != viddev->width || height != viddev->height ||
        freq != viddev->freq || tuner_number != viddev->tuner_number || norm != viddev->norm) {
        unsigned int skip = conf->roundrobin_skip, i;

        if (freq) {
            memset(&vid_tuner, 0, sizeof(struct video_tuner));
            vid_tuner.tuner = tuner_number;

            if (ioctl (dev, VIDIOCGTUNER, &vid_tuner) == -1) {
                MOTION_LOG(ERR, TYPE_VIDEO, SHOW_ERRNO, "%s: ioctl (VIDIOCGTUNER) tuner number %d",
                           tuner_number);
            } else {
                if (vid_tuner.flags & VIDEO_TUNER_LOW)
                    frequnits = freq * 16; /* steps of 1/16 KHz */
                else
                    frequnits = (freq * 10) / 625;

                if (ioctl(dev, VIDIOCSFREQ, &frequnits) == -1) {
                    MOTION_LOG(ERR, TYPE_VIDEO, SHOW_ERRNO, "%s: ioctl (VIDIOCSFREQ) Frequency %ul",
                               frequnits);
                    return;
                }

                 MOTION_LOG(NTC, TYPE_VIDEO, NO_ERRNO, "%s: Set Tuner to %d Frequency to %ul",
                            tuner_number, frequnits);
            }
        }

        memset(&vid_chnl, 0, sizeof(struct video_channel));
        vid_chnl.channel = input;

        if (ioctl (dev, VIDIOCGCHAN, &vid_chnl) == -1) {
            MOTION_LOG(ERR, TYPE_VIDEO, SHOW_ERRNO, "%s: ioctl (VIDIOCGCHAN) Input %d",
                       input);
        } else {
            vid_chnl.channel = input;
            vid_chnl.norm = norm;

            if (ioctl (dev, VIDIOCSCHAN, &vid_chnl) == -1) {
                MOTION_LOG(ERR, TYPE_VIDEO, SHOW_ERRNO, "%s: ioctl (VIDIOCSCHAN) Input %d"
                           " Standard method %d", input, norm);
                return;
            }

            MOTION_LOG(NTC, TYPE_VIDEO, NO_ERRNO, "%s: Set Input to %d Standard method to %d",
                       input, norm);
        }

        v4l_picture_controls(cnt, viddev);
        conf->input = viddev->input = input;
        conf->width = viddev->width = width;
        conf->height = viddev->height = height;
        conf->frequency = viddev->freq = freq;
        conf->tuner_number = viddev->tuner_number = tuner_number;
        conf->norm = viddev->norm = norm;
        /* skip a few frames if needed */
        for (i = 0; i < skip; i++)
            v4l_next(viddev, map, width, height);
    } else {
        /* No round robin - we only adjust picture controls */
        v4l_picture_controls(cnt, viddev);
    }
}
#endif /* !WITHOUT_V4L */


 Returns the luminosity for a specified color
 * @param {color} The color to check
 * @return {measurement}
 */
/**
 * Returns the contrast ratio between two colors
 * @param {color1} The color to check
 * @return {measurement}
 */
/**
 * Colors the text of an element based on lightness of its background.
 *
 *     .my-element {
 *       @include color-by-background(#fff); // Colors text black.
 *     }
 *
 *     .my-element {
 *       @include color-by-background(#fff, 40%); // Colors text gray.
 *     }
 *
 * @param {color} $bg-color Background color of element.
 * @param {percent} $contrast Contrast of text color to its background.
 *
 */
/**
 * @class Global_CSS
 */
/**
 * Adds basic styles to :before or :after pseudo-elements.
 *
 *     .my-element:after {
 *       @include insertion(50px, 50px);
 *     }
 *
 * @param {measurement} $width Height of pseudo-element.
 * @param {measurement} $height Height of pseudo-element.
 * @param {measurement} $top Top positioning of pseudo-element.
 * @param {measurement} $left Left positioning of pseudo-element.
 *
 */
/**
 * Makes the element text overflow to use ellipsis.
 */
/**
 * Includes an icon to be used on Button or Tab components. The $name is the name of the icon, or the character
 * of the font being used.
 *
 *     @include icon('attachment');
 *
 * @param {string} $name The name of the icon to be included. This is then usable as the iconCls in your app.
 * @param {string} $character The character
 * @param {string} $font-family The `font-family` used for this icon. Defaults to the `Pictos` font.
 */
/* line 2, /home/teamcity/buildAgent/work/b52f9c8a2f79967b/touch/resources/themes/stylesheets/sencha-touch/base/src/layout/_Abstract.scss */
html,
body {
  position: relative;
  width: 100%;
  height: 100%;
}

/* line 8, /home/teamcity/buildAgent/work/b52f9c8a2f79967b/touch/resources/themes/stylesheets/sencha-touch/base/src/layout/_Abstract.scss */
.x-fullscreen {
  position: absolute !important;
}

/* line 12, /home/teamcity/buildAgent/work/b52f9c8a2f79967b/touch/resources/themes/stylesheets/sencha-touch/base/src/layout/_Abstract.scss */
.x-body {
  position: relative;
  z-index: 0;
}

/* line 18, /home/teamcity/buildAgent/work/b52f9c8a2f79967b/touch/resources/themes/stylesheets/sencha-touch/base/src/layout/_Abstract.scss */
.x-inner,
.x-body {
  width: 100%;
  height: 100%;
}

/* line 23, /home/teamcity/buildAgent/work/b52f9c8a2f79967b/touch/resources/themes/stylesheets/sencha-touch/base/src/layout/_Abstract.scss */
.x-sized {
  position: relative;
}

/* line 27, /home/teamcity/buildAgent/work/b52f9c8a2f79967b/touch/resources/themes/stylesheets/sencha-touch/base/src/layout/_Abstract.scss */
.x-innerhtml {
  wid


#pragma once

#include "quantum.h"

/* This a shortcut to help you visually see your layout.
 *
 * The first section contains all of the arguments representing the physical
 * layout of the board and position of the keys.
 *
 * The second converts the arguments into a two-dimensional array which
 * represents the switch matrix.
 */
#define LAYOUT_ortho_5x4( \
    K00, K01, K02, K03, \
    K10, K11, K12, K13, \
    K20, K21, K22, K23, \
    K30, K31, K32, K33, \
    K40, K41, K42, K43  \
) \
{ \
    { K00,   K01,   K02,   K03 }, \
    { K10,   K11,   K12,   K13 }, \
    { K20,   K21,   K22,   K23 }, \
    { K30,   K31,   K32,   K33 }, \
    { K40,   K41,   K42,   K43 }, \
}
#define LAYOUT_numpad_5x4( \
    K00, K01, K02, K03, \
    K10, K11, K12,      \
    K20, K21, K22, K13, \
    K30, K31, K32,      \
    K40,      K42, K33  \
) \
{ \
    { K00,   K01,   K02,   K03   }, \
    { K10,   K11,   K12,   K13   }, \
    { K20,   K21,   K22,   KC_NO }, \
    { K30,   K31,   K32,   K33   }, \
    { K40,   KC_NO, K42,   KC_NO }, \
}


import numpy as np

def integral(g, a, x, N=20):
    index_set = range(N+1)
    x = np.linspace(a, x, N+1)
    g_ = np.zeros_like(x)
    f = np.zeros_like(x)
    g_[0] = g(x[0])
    f[0] = 0

    for n in index_set[1:]:
        g_[n] = g(x[n])
        f[n] = f[n-1] + 0.5*(x[n] - x[n-1])*(g_[n-1] + g_[n])
    return x, f

def _verify():
    """
    Check that the trapezoidal method implemented
    via difference equations works perfectly with linear g.
    """
    def g_test(t):
        """Linear integrand."""
        return 2*t + 1

    def f_test(x, a):
        """Exact integral of g_test."""
        return x**2 + x - (a**2 + a)

    a = 2
    x, f = integral(g_test, a, x=10)
    f_exact = f_test(x, a)
    if not np.allclose(f_exact, f):
        print 'ERROR in _verify'

def application1():
    """Integrate the Gaussian function."""

    from numpy import sqrt, pi, exp
    def g(t):
        return 1./sqrt(2*pi)*exp(-t**2)

    x, f = integral(g, a=-3, x=3, N=200)
    integrand = g(x)
    from scitools.std import plot
    plot(x, f, 'r-',
         x, integrand, 'y-',
         legend=('f', 'g'),
         legend_loc='upper left',
         savefig='tmp.eps')

_verify()
application1()


_decodeRowResult.length > 1 &&
          _startendEncoding
              .contains(String.fromCharCode(alphaBet[charOffset]))) {
        break;
      }
    } while (nextStart <
        _counterLength); // no fixed end pattern so keep on reading while data is available

    // Look for whitespace after pattern:
    final trailingWhitespace = _counters[nextStart - 1];
    int lastPatternSize = 0;
    for (int i = -8; i < -1; i++) {
      lastPatternSize += _counters[nextStart + i];
    }

    // We need to see whitespace equal to 50% of the last pattern size,
    // otherwise this is probably a false positive. The exception is if we are
    // at the end of the row. (I.e. the barcode barely fits.)
    if (nextStart < _counterLength &&
        trailingWhitespace < lastPatternSize / 2) {
      throw NotFoundException.instance;
    }

    _validatePattern(startOffset);

    // Translate character table offsets to actual characters.
    for (int i = 0; i < _decodeRowResult.length; i++) {
      _decodeRowResult.setCharAt(i, alphaBet[_decodeRowResult.codePointAt(i)]);
    }
    // Ensure a valid start and end character
    final startchar = _decodeRowResult.charAt(0);
    if (!_startendEncoding.contains(startchar)) {
      throw NotFoundException.instance;
    }
    final endchar = _decodeRowResult.charAt(_decodeRowResult.length - 1);
    if (!_startendEncoding.contains(endchar)) {
      throw NotFoundException.instance;
    }

    // remove stop/start characters character and check if a long enough string is contained
    if (_decodeRowResult.length <= _minCharacterLength) {
      // Almost surely a false positive ( start + stop + at least 1 character)
      throw NotFoundException.instance;
    }

    if (!(hints?.returnCodabarStartEnd ?? false)) {
      _decodeRowResult.deleteCharAt(_decodeRowResult.length - 1);
      _decodeRowResult.deleteCharAt(0);
    }

    int runningCount = 0;
    for (int i = 0; i < startOffset; i++) {
      runningCount += _counters[i];
    }
    final left = runningCount.toDouble();
    for (int i = startOffset; i < nextStart - 1; i++) {
      runningCount += _counters[i];
    }
    final right = runningCount.toDouble();

    final result = Result(
      _decodeRowResult.toString(),
      null,
      [
        ResultPoint(left, rowNumber.toDouble()),
        ResultPoint(right, rowNumber.toDouble()),
      ],
      BarcodeFormat.codabar,
    );
    result.putMetadata(ResultMetadataType.symbologyIdentifier, ']F0');
    return result;
  }

  void _validatePattern(int start) {
    // First, sum up the total size of our four categories of stripe sizes;
    final sizes = [0, 0, 0, 0];
    final counts = [0, 0, 0, 0];
    final end = _decodeRowResult.length - 1;

    // We break out of this loop in the middle, in order to handle
    // inter-character spaces properly.
    int pos = start;
    for (int i = 0; i <= end; i++) {
      int pattern = characterEncodings[_decodeRowResult.codePointAt(i)];
      for (int j = 6; j >= 0; j--) {
        // Even j = bars, while odd j = spaces. Categories 2 and 3 are for
        // long stripes, while 0 and 1 are for short stripes.
        final category = (j & 1) + (pattern & 1) * 2;
        sizes[category] += _counters[pos + j];
        counts[category]++;
        pattern >>= 1;
      }
      // We ignore the inter-character space - it could be of any size.
      pos += 8;
    }

    // Calculate our allowable size thresholds using fixed-point math.
    final


 /// </summary>
        /// <value>
        /// The override tool strip renderer.
        /// </value>
        public ToolStripRenderer OverrideToolStripRenderer
        {
            set
            {
                tmsMenuStrip.Renderer = value;

                tmsStatusStrip.Renderer = value;

                tmsToolStrip.Renderer = value;

                tmsToolStripContainer.TopToolStripPanel.Renderer = value;

                tmsToolStripContainer.BottomToolStripPanel.Renderer = value;

                tmsToolStripContainer.LeftToolStripPanel.Renderer = value;

                tmsToolStripContainer.RightToolStripPanel.Renderer = value;

                tmsToolStripContainer.ContentPanel.Renderer = value;
            }
        }
        #endregion
    }
}


	if (!stream) {
		Log::Print(Log::LOG_ERROR, "Couldn't open file '%s'!", filename);
		delete resource;
		(*list)[index] = NULL;
		return -1;
	}

	Source = MediaSource::CreateSourceFromStream(stream);
	if (!Source) {
		delete resource;
		stream->Close();
		(*list)[index] = NULL;
		return -1;
	}

	Player = MediaPlayer::Create(Source,
		Source->GetBestStream(MediaSource::STREAMTYPE_VIDEO),
		Source->GetBestStream(MediaSource::STREAMTYPE_AUDIO),
		Source->GetBestStream(MediaSource::STREAMTYPE_SUBTITLE),
		Scene::Views[0].Width,
		Scene::Views[0].Height);
	if (!Player) {
		Source->Close();
		delete resource;
		(*list)[index] = NULL;
		return -1;
	}

	PlayerInfo playerInfo;
	Player->GetInfo(&playerInfo);
	VideoTexture = Graphics::CreateTexture(playerInfo.Video.Output.Format,
		SDL_TEXTUREACCESS_STATIC,
		playerInfo.Video.Output.Width,
		playerInfo.Video.Output.Height);
	if (!VideoTexture) {
		Player->Close();
		Source->Close();
		delete resource;
		(*list)[index] = NULL;
		return -1;
	}

	if (Player->GetVideoStream() > -1) {
		Log::Print(Log::LOG_WARN, "VIDEO STREAM:");
		Log::Print(Log::LOG_INFO,
			"    Resolution:  %d x %d",
			playerInfo.Video.Output.Width,
			playerInfo.Video.Output.Height);
	}
	if (Player->GetAudioStream() > -1) {
		Log::Print(Log::LOG_WARN, "AUDIO STREAM:");
		Log::Print(
			Log::LOG_INFO, "    Sample Rate: %d", playerInfo.Audio.Output.SampleRate);
		Log::Print(Log::LOG_INFO,
			"    Bit Depth:   %d-bit",
			playerInfo.Audio.Output.Format & 0xFF);
		Log::Print(Log::LOG_INFO, "    Channels:    %d", playerInfo.Audio.Output.Channels);
	}

	MediaBag* newMediaBag = new (std::nothrow) MediaBag;
	newMediaBag->Source = Source;
	newMediaBag->Player = Player;
	newMediaBag->VideoTexture = VideoTexture;

	resource->AsMedia = newMediaBag;
	return (int)index;
#else
	return -1;
#endif
}

ResourceType* Scene::GetSpriteResource(int index) {
	if (index < 0 || index >= (int)Scene::SpriteList.size()) {
		return NULL;
	}

	if (!Scene::SpriteList[index]) {
		return NULL;
	}

	return Scene::SpriteList[index];
}
ResourceType* Scene::GetImageResource(int index) {
	if (index < 0 || index >= (int)Scene::ImageList.size()) {
		return NULL;
	}

	if (!Scene::ImageList[index]) {
		return NULL;
	}

	return Scene::ImageList[index];
}

void Scene::DisposeInScope(Uint32 scope) {
	// Models
	for (size_t i = 0, i_sz = Scene::ModelList.size(); i < i_sz; i++) {
		if (!Scene::ModelList[i]) {
			continue;
		}
		if (Scene::ModelList[i]->UnloadPolicy > scope) {
			continue;
		}

		delete Scene::ModelList[i]->AsModel;
		delete Scene::ModelList[i];
		Scene::ModelList[i] = NULL;
	}
	// Images
	for (size_t i = 0, i_sz = Scene::ImageList.size(); i < i_sz; i++) {
		if


#
# ArcEmu MMORPG Server
# Copyright (C) 2008-2023 <http://www.ArcEmu.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#
import arcemu
from arcemu import Unit

GNOMEREGAN_PRIDE_SPELLID = 75531

def GnomereganPride_handleAura( i, aura, apply ):
	target = aura.getTarget()

	if apply:
		target.setDisplayId( 31654 )
		print( "Applying gp aura" )
	else:
		target.setDisplayId( target.getNativeDisplayId() )
		print( "Removing gp aura" )

arcemu.RegisterDummyAuraHandler( GNOMEREGAN_PRIDE_SPELLID, GnomereganPride_handleAura )


nage_neuron::Command, ManageNeuron, ManageNeuronResponse, Motion, Proposal,
};

const MANAGE_NEURON_METHOD: &str = "manage_neuron";

/// Submit a motion to the IC.
#[derive(CandidType, Clap, Clone)]
pub struct MotionOpts {
    /// The text of the motion.
    motion_text: String,
}

pub async fn exec(
    opts: MotionOpts,
    proposal_opts: super::SubmitProposalOpts,
    env: Env,
) -> NnsCliResult {
    let proposal = Proposal {
        summary: proposal_opts.summary,
        url: proposal_opts.url,
        action: Some(Action::Motion(Motion {
            motion_text: opts.motion_text,
        })),
    };
    let manage_neuron = ManageNeuron {
        id: Some(NeuronIdProto::from(NeuronId(proposal_opts.neuron_id))),
        command: Some(Command::MakeProposal(Box::<Proposal>::new(proposal))),
    };

    let arg = Encode!(&manage_neuron)?;

    let result = env
        .agent
        .update(&governance_canister_id(), MANAGE_NEURON_METHOD)
        .with_arg(arg)
        .call_and_wait(create_waiter())
        .await?;
    let manage_neuron_response = Decode!(&result, ManageNeuronResponse)?;

    match manage_neuron_response.command {
        Some(Error(gov_err)) => println!("{}", gov_err),
        Some(MakeProposal(response)) => match response.proposal_id {
            Some(proposal_id) => println!("{:?}", proposal_id),
            None => eprintln!("Propsal sent but did not receive a proposal id in response."),
        },
        _ => eprintln!("Received an invalid response."),
    };

    NnsCliResult::Ok(())
}
//!
//! Functions for parsing WAL records.
//!
use bytes::{Buf, Bytes};
use postgres_ffi::pg_constants;
use postgres_ffi::xlog_utils::{TimestampTz, XLOG_SIZE_OF_XLOG_RECORD};
use postgres_ffi::XLogRecord;
use postgres_ffi::{BlockNumber, OffsetNumber};
use postgres_ffi::{MultiXactId, MultiXactOffset, MultiXactStatus, Oid, TransactionId};
use serde::{Deserialize, Serialize};
use tracing::*;

use crate::repository::ZenithWalRecord;

/// DecodedBkpBlock represents per-page data contained in a WAL record.
#[derive(Default)]
pub struct DecodedBkpBlock {
    /* Is this block ref in use? */
    //in_use: bool,

    /* Identify the block this refers to */
    pub rnode_spcnode: u32,
    pub rnode_dbnode: u32,
    pub rnode_relnode: u32,
    // Note that we have a few special forknum values for non-rel files.
    pub forknum: u8,
    pub blkno: u32,

    /* copy of the fork_flags field from the XLogRecordBlockHeader */
    pub flags: u8,

    /* Information on full-page image, if any */
    pub has_image: bool,   /* has image, even for consistency checking */
    pub apply_image: bool, /* has image that should be restored */
    pub will_init: bool,   /* record doesn't need previous page version to apply */
    //char	   *bkp_image;
    pub hole_offset: u16,
    pub hole_length: u16,
    pub bimg_offset: u32,
    pub bimg_len: u16,
    pub bimg_info: u8,

    /* Buffer holding the rmgr-specific data associated with this block */
    has_data: bool,
    data_len: u16,
}

impl DecodedBkpBlock {
    pub fn new() -> DecodedBkpBlock {
        Default::default()
    }
}

pub struct DecodedWALRecord {
    pub xl_xid: TransactionId,


)Edges.AllCorners;
			}

			// Mapping of shrouded directions -> sprite index
			edgesToSpriteIndexOffset = new byte[spriteCount + 1];
			for (var i = 0; i < info.Index.Length; i++)
				edgesToSpriteIndexOffset[info.Index[i]] = (byte)i;

			if (info.OverrideFullShroud != null)
				edgesToSpriteIndexOffset[info.OverrideShroudIndex] = (byte)(variantStride - 1);

			world.RenderPlayerChanged += WorldOnRenderPlayerChanged;
		}

		void IWorldLoaded.WorldLoaded(World w, WorldRenderer wr)
		{
			// Initialize tile cache
			// This includes the region outside the visible area to cover any sprites peeking outside the map
			foreach (var uv in w.Map.AllCells.MapCoords)
			{
				var pos = w.Map.CenterOfCell(uv.ToCPos(map));
				var screen = wr.Screen3DPosition(pos - new WVec(0, 0, pos.Z));
				var variant = (byte)Game.CosmeticRandom.Next(info.ShroudVariants.Length);
				tileInfos[uv] = new TileInfo(screen, variant);
			}

			// All tiles are visible in the editor
			if (w.Type == WorldType.Editor)
				cellVisibility = puv => map.Contains(puv) ? Shroud.CellVisibility.Visible | Shroud.CellVisibility.Explored : Shroud.CellVisibility.Explored;
			else
				cellVisibility = puv => map.Contains(puv) ? Shroud.CellVisibility.Visible | Shroud.CellVisibility.Explored : Shroud.CellVisibility.Hidden;

			var shroudBlend = shroudSprites[0].Sprite.BlendMode;
			if (shroudSprites.Any(s => s.Sprite.BlendMode != shroudBlend))
				throw new InvalidDataException("Shroud sprites must all use the same blend mode.");

			var fogBlend = fogSprites[0].Sprite.BlendMode;
			if (fogSprites.Any(s => s.Sprite.BlendMode != fogBlend))
				throw new InvalidDataException("Fog sprites must all use the same blend mode.");

			var emptySprite = new Sprite(shroudSprites[0].Sprite.Sheet, Rectangle.Empty, TextureChannel.Alpha);
			shroudPaletteReference = wr.Palette(info.ShroudPalette);
			fogPaletteReference = wr.Palette(info.FogPalette);
			shroudLayer = new TerrainSpriteLayer(w, wr, emptySprite, shroudBlend, false);
			fogLayer = new TerrainSpriteLayer(w, wr, emptySprite, fogBlend, false);

			WorldOnRenderPlayerChanged(world.RenderPlayer);
		}

		Shroud.CellVisibility[] GetNeighborsVisbility(PPos puv)
		{
			var cell = ((MPos)puv).ToCPos(map);
			neighbors[(int)Neighbor.Top] = cellVisibility((PPos)(cell + new CVec(0, -1)).ToMPos(map));
			neighbors[(int)Neighbor.Right] = cellVisibility((PPos)(cell + new CVec(1, 0)).ToMPos(map));
			neighbors[(int)Neighbor.Bottom] = cellVisibility((PPos)(cell + new CVec(0, 1)).ToMPos(map));
			neighbors[(int)Neighbor.Left] = cellVisibility((PPos)(cell + new CVec(-1, 0)).ToMPos(map));

			neighbors[(int)Neighbor.TopLeft] = cellVisibility((PPos)(cell + new CVec(-1, -1)).ToMPos(map));
			neighbors[(int)Neighbor.TopRight] = cellVisibility((PPos)(cell + new CVec(1, -1)).ToMPos(map));
			neighbors[(int)Neighbor.BottomRight] = cellVisibility((PPos)(cell + new CVec(1, 1)).ToMPos(map));
			neighbors[(int)Neighbor.BottomLeft] = cellVisibility(


dirname, '../../../../node_modules/.bin/sequelize ')} model:generate --name ${context.modelName.upperCase
    } --attributes ${sequelizeAttributes}`;
  execSync(sequelizeCommand);

  const modelPath = `${path.join(__dirname, '../../../../src/sequelize/models/')}${_.toLower(
    context.modelName.camelCase,
  )}.js`;

  // deleting sequelize model file because it is created by our own scaffolding tool
  fs.unlinkSync(modelPath);
}
import _ from 'lodash';
import { assert } from 'chai';
import { encodeKeys, decodeKeys } from '../encoder';

describe('Encoder', () => {
  const decodedDollarTestObj = {
    a: 1,
    a$b: 2,
    a$b$c: 3,
    a$b$c$d: 4,
  };

  const encodedDollarTestObj = {
    a: 1,
    'a[dollar]b': 2,
    'a[dollar]b[dollar]c': 3,
    'a[dollar]b[dollar]c[dollar]d': 4,
  };

  const decodedDotTestObj = {
    a: 1,
    'a.b': 2,
    'a.b.c': 3,
    'a.b.c.d': 4,
  };

  const encodedDotTestObj = {
    a: 1,
    'a[dot]b': 2,
    'a[dot]b[dot]c': 3,
    'a[dot]b[dot]c[dot]d': 4,
  };

  const decodedDotDollarTestObj = {
    a: 1,
    'a.$b': 2,
    'a.b$c': 3,
    'a.b$c.d': 4,
  };

  const encodedDotDollarTestObj = {
    a: 1,
    'a[dot][dollar]b': 2,
    'a[dot]b[dollar]c': 3,
    'a[dot]b[dollar]c[dot]d': 4,
  };

  describe('encode keys', () => {
    it("should replace '$' with '[dollar]'", () => {
      const actualEncodedObj = encodeKeys(_.cloneDeep(decodedDollarTestObj));
      assert.deepEqual(actualEncodedObj, encodedDollarTestObj);
    });

    it("should replace '.' with '[dot]'", () => {
      const actualEncodedObj = encodeKeys(_.cloneDeep(decodedDotTestObj));
      assert.deepEqual(actualEncodedObj, encodedDotTestObj);
    });

    it("should replace '$' with '[dollar]' and " + "'.' with '[dot]'", () => {
      const actualEncodedObj = encodeKeys(_.cloneDeep(decodedDotDollarTestObj));
      assert.deepEqual(actualEncodedObj, encodedDotDollarTestObj);
    });
  });

  describe('decode keys', () => {
    it("should replace '[dollar]' with '$'", () => {
      const actualDecodedObj = decodeKeys(_.cloneDeep(encodedDollarTestObj));
      assert.deepEqual(actualDecodedObj, decodedDollarTestObj);
    });

    it("should replace '[dot]' with '.'", () => {
      const actualDecodedObj = decodeKeys(_.cloneDeep(encodedDotTestObj));
      assert.deepEqual(actualDecodedObj, decodedDotTestObj);
    });

    it("should replace '[dollar]' with '$' and " + "'[dot]' with '.'", () => {
      const actualDecodedObj = decodeKeys(_.cloneDeep(encodedDotDollarTestObj));
      assert.deepEqual(actualDecodedObj, decodedDotDollarTestObj);
    });
  });
});
import { ext } from 'src/const';
import { shoutemUrls } from 'src/services';
import { create, find, remove, update } from '@shoutem/redux-io';
import { FONTS } from '../const';

export function loadAllFonts(appId) {
  const config = {
    schema: FONTS,
    request: {
      endpoint: shoutemUrls.appsApi(`v1/apps/${appId}/fonts/all`),


a.ref.nanosec;

  set sec(int val) => data.ref.sec = val;
  set nanosec(int val) => data.ref.nanosec = val;
}

// Required ROS2 struct definitions (these should be in your generated bindings)
base class std_msgs__msg__ColorRGBA extends ffi.Struct {
  @ffi.Float()
  external double r;
  @ffi.Float()
  external double g;
  @ffi.Float()
  external double b;
  @ffi.Float()
  external double a;
}

base class std_msgs__msg__Header extends ffi.Struct {
  external builtin_interfaces__msg__Time stamp;
  external rosidl_runtime_c__String frame_id;
}

base class builtin_interfaces__msg__Time extends ffi.Struct {
  @ffi.Int32()
  external int sec;
  @ffi.Uint32()
  external int nanosec;
}

base class builtin_interfaces__msg__Duration extends ffi.Struct {
  @ffi.Int32()
  external int sec;
  @ffi.Uint32()
  external int nanosec;
}
import 'package:flutter/material.dart';

class ConnectingStateWidget extends StatelessWidget {
  final AnimationController animation;
  final String host;
  final String port;

  const ConnectingStateWidget({
    super.key,
    required this.animation,
    required this.host,
    required this.port,
  });

  @override
  Widget build(BuildContext context) {
    final pulseAnimation = Tween<double>(
      begin: 0.8,
      end: 1.0,
    ).animate(CurvedAnimation(parent: animation, curve: Curves.easeInOut));

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          AnimatedBuilder(
            animation: pulseAnimation,
            builder: (context, child) {
              return Transform.scale(
                scale: pulseAnimation.value,
                child: Container(
                  padding: const EdgeInsets.all(32),
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: Colors.white.withValues(alpha: 0.5),
                      width: 2,
                    ),
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(Icons.wifi, size: 48, color: Colors.white),
                ),
              );
            },
          ),
          const SizedBox(height: 32),
          const Text(
            'Connecting to MPD Server...',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20,
              fontWeight: FontWeight.w600,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '$host:$port',
            style: TextStyle(
              color: Colors.white.withValues(alpha: 0.6),
              fontSize: 16,
            ),
          ),
        ],
      ),
    );
  }
}
import 'package:flutter/material.dart';
import 'package:rxdart_flutter/rxdart_flutter.dart';

import 'api/github_api.dart';
import 'bloc/search_bloc.dart';
import 'bloc/search_state.dart';
import 'widget/empty_result_widget.dart';
import 'widget/search_error_widget.dart';
import 'widget/search_intro_widget.dart';
import 'widget/search_loading_widget.dart';
import 'widget/search_result_widget.dart';


的博物馆？|
|产品比较|比较一下苹果手机和华为手机的相机性能？|
|菜品介绍|请介绍一下地道的日本料理有哪些种类？|
|历史知识|请讲解一下第二次世界大战的起因和过程？|
|生活技巧|如何有效减肥并保持健康的体型？|
|科学研究|最新的量子计算机研究成果有哪些？|
|旅游攻略|去巴厘岛旅游需要注意哪些事项？|
|生物学|请解释光合作用的过程。|
|历史|请说明第二次世界大战的根本原因是什么？|
|文化|请列举一些具有代表性的中国传统节日及其庆祝方式。|
|医学|请描述人体中免疫系统如何对抗外来细菌和病毒入侵。|
|金融|请解释什么是股票市场，以及在其中进行交易的基本规则。|
|社会学|请比较和解释社会阶层与社会流动性之间的关系。|
|科技|请介绍一些新兴的人工智能技术应用，并讨论其未来发展前景。|
|政治|请解释什么是民主制度，以及它与专制制度的区别是什么？|
|艺术|请比较并分析巴洛克与文艺复兴两种不同风格的艺术特征。|
|教育|请讨论一下现代教育理念及其实践的核心价值观。|
| 流行歌曲 | 可以推荐几首最近非常流行的歌曲吗？ |
| 情感分析 | 对于一篇文章，您如何确定它是正面的还是负面的？ |
| 国际新闻 | 您认为目前世界上最令人关注的国际新闻是什么？ |
| 股票市场 | 如果我想在股票市场上投资，应该怎样进行投资策略规划？ |
| 疫苗接种 | 疫苗接种有哪些不良反应？如何避免或减轻疫苗接种后的不良反应？ |
| 旅游攻略 | 如果我想去旅游，你可以提供一些经验和建议吗？ |
| 电子商务 | 如何提高电子商务平台的销售量？ |
| 儿童教育 | 怎样的儿童教育方式更适合培养孩子的创造力？ |
| 美食推荐 | 你能给我推荐一些必吃的美食吗？ |
| 网络安全 | 我们如何保护自己的隐私并确保网络安全？ ||标题|问题|
|----|----|
|电影推荐|能否根据我最近喜欢的电影类型，推荐一部值得一看的新电影？|
|旅游攻略|有没有比较详细的旅游攻略，介绍该城市的美食、景点和特色文化等方面？|
|股票分析|现在买入这支股票是否划算，未来会不会有不良影响？|
|菜谱查询|请问有哪些简单易学的健康菜谱推荐？|
|音乐推荐|能否帮我推荐一些适合听写作业时用的安静舒缓的音乐？|
|汉字笔画查询|我想查询“鹿”的笔画数是多少，该怎么操作？|
|疾病咨询|最近感到身体不适，想了解一下可能患上了哪种


.btn{position:absolute;width:80px;height:24px;z-index:2;}.clct_ratestar a{float:left;width:16px;height:20px;text-indent:-9999px;overflow:hidden;}.clct_ratestar .star{position:absolute;width:0;height:24px;background:url(../../static/image/common/fav.gif) repeat-x 0 0;z-index:1;}.clct_ratestar .star1{width:16px;}.clct_ratestar .star2{width:32px;}.clct_ratestar .star3{width:48px;}.clct_ratestar .star4{width:64px;}.clct_ratestar .star5{width:80px;}.tbmu{padding-left:10px;line-height:23px;}.ctag{padding:1px 3px;font-weight:400;border-radius:3px;}.ctag0{background:#F6C5BE;color:#822111;}.ctag1{background:#FEF1D1;color:#AA8831;}.ctag2{background:#EEE;color:#666;}#calendar{padding:5px;text-align:left;border:1px solid #DDD;background:#FFF;margin-bottom:0.8em;}#calendar td{padding:2px;font-weight:700;}#calendar_week td{height:2em;line-height:2em;border-bottom:1px solid #C2D5E3;}#calendar_week a{color:#369;}#hourminute td{padding:4px 2px;border-top:1px solid #C2D5E3;}.calendar_expire,.calendar_expire a:link,.calendar_expire a:visited{color:#666;font-weight:normal;}.calendar_default,.calendar_default a:link,.calendar_default a:visited{color:#369;}.calendar_checked,.calendar_checked a:link,.calendar_checked a:visited{color:#F26C4F;font-weight:bold;}td.calendar_checked,span.calendar_checked{background:#C2D5E3;}.calendar_today,.calendar_today a:link,.calendar_today a:visited{color:#444;font-weight:bold;}#calendar_header td{width:30px;height:20px;border-bottom:1px solid #C2D5E3;font-weight:normal;}#calendar_year{display:none;line-height:130%;background:#FFF;position:absolute;z-index:10;}#calendar_year .col{float:left;background:#FFF;margin-left:1px;border:1px solid #C2D5E3;padding:4px;}#calendar_month{display:none;background:#FFF;line-height:130%;border:1px solid #DDD;padding:4px;position:absolute;z-index:11;}channel{font-size:12px;background:white;font-family:,,verdana,arial,helvetica,sans-serif;margin:0px auto;width:100%;padding:10px 10px 15px 10px;text-align:center;}channel title{display:block;font-weight:bold;font-size:18px;z-index:1;position:relative;height:auto;}item{padding:10px 10px 2px 10px;display:block;font-size:14px;margin:20px 0px;width:90%;line-height:100%;text-align:left;}image,image title,image height,image width,image url,category,ttl,generator,guid,language,docs,comments,pubDate{display:none;}rss,item title,item link,item description,item pubDate,item author,item{display:block;font-weight:normal;font-size:14px;margin:5px;background:#F0F8FB;}item title{font-weight:bold;font-size:16px;display:block;height:auto;position:relative;z-index:


6:	9805      	ldr	r0, [sp, #20]
 80054d8:	449a      	add	sl, r3
 80054da:	fa1f fa8a 	uxth.w	sl, sl
 80054de:	fbba f9f2 	udiv	r9, sl, r2
 80054e2:	fb02 aa19 	mls	sl, r2, r9, sl
 80054e6:	fb0c fa0a 	mul.w	sl, ip, sl
 80054ea:	fb00 aa09 	mla	sl, r0, r9, sl
 80054ee:	f10a 0a04 	add.w	sl, sl, #4
 80054f2:	eb01 090a 	add.w	r9, r1, sl
      if (_NIFFS_IS_FREE(phdr) && _NIFFS_IS_CLEA(phdr)) {
 80054f6:	f831 a00a 	ldrh.w	sl, [r1, sl]
 80054fa:	f64f 70ff 	movw	r0, #65535	; 0xffff
 80054fe:	4582      	cmp	sl, r0
 8005500:	d105      	bne.n	800550e <niffs_gc+0x92>
 8005502:	f8b9 a002 	ldrh.w	sl, [r9, #2]
 8005506:	4582      	cmp	sl, r0
 8005508:	d104      	bne.n	8005514 <niffs_gc+0x98>
        p_free++;
 800550a:	3701      	adds	r7, #1
 800550c:	e010      	b.n	8005530 <niffs_gc+0xb4>
      } else if (_NIFFS_IS_DELE(phdr) || !_NIFFS_IS_FLAG_VALID(phdr)) {
 800550e:	f1ba 0f00 	cmp.w	sl, #0
 8005512:	d009      	beq.n	8005528 <niffs_gc+0xac>
 8005514:	f8b9 9002 	ldrh.w	r9, [r9, #2]
 8005518:	f64f 70fc 	movw	r0, #65532	; 0xfffc
 800551c:	f1a9 0902 	sub.w	r9, r9, #2
 8005520:	fa1f f989 	uxth.w	r9, r9
 8005524:	4581      	cmp	r9, r0
 8005526:	d802      	bhi.n	800552e <niffs_gc+0xb2>
        p_dele++;
 8005528:	f108 0801 	add.w	r8, r8, #1
 800552c:	e000      	b.n	8005530 <niffs_gc+0xb4>
      } else {
        p_busy++;
 800552e:	3601      	adds	r6, #1
    u32_t p_free = 0;
    u32_t p_dele = 0;
    u32_t p_busy = 0;

    niffs_page_ix ipix;
    for (ipix = 0; ipix < fs->pages_per_sector; ipix++) {
 8005530:	3301      	adds	r3, #1
 8005532:	b29b      	uxth	r3, r3
 8005534:	e7cb      	b.n	80054ce <niffs_gc+0x52>
    }

    niffs_erase_cnt era_cnt_diff_typed = fs->max_era - shdr_era_cnt;
    u32_t era_cnt_diff = (u32_t)era_cnt_diff_typed;

    NIFFS_DBG("    gc: sector %2i era:%6i era_d:%4i free:%2i dele:%2i busy:%2i  -- ", sector, shdr_era_cnt, era_cnt_diff, p_free,


prings(scene, data);

  data->fn_clothes = fn_clothes.c_str();
  data->fn_fluid = fn_fluid.c_str();
  data->fn_hairs = fn_hairs.c_str();
  data->fn_external_boundaries = fn_external_boundaries.c_str();
  data->fn_internal_boundaries = fn_internal_boundaries.c_str();
  data->fn_springs = fn_springs.c_str();

  std::thread t(std::bind(serialize_subprog, data));
  t.detach();
}

void TwoDSceneSerializer::serializePositionOnly(TwoDScene& scene,
                                                const std::string& fn_pos) {
  SerializePosPacket* data = new SerializePosPacket;
  data->fn_pos = fn_pos.c_str();
  data->m_pos = scene.getX();
  data->m_d_gauss = scene.getGaussd();

  std::thread t(std::bind(serialize_pos_subprog, data));
  t.detach();
}

void TwoDSceneSerializer::loadPosOnly(TwoDScene& scene,
                                      std::ifstream& inputstream) {
  VectorXs& x = scene.getX();
  int bufsize;
  inputstream.read((char*)&bufsize, sizeof(int));
  inputstream.read((char*)x.data(), bufsize);

  MatrixXs& d_gauss = scene.getGaussd();
  inputstream.read((char*)&bufsize, sizeof(int));
  inputstream.read((char*)d_gauss.data(), bufsize);
}

void TwoDSceneSerializer::updateHairs(const TwoDScene& scene,
                                      SerializePacket* data) {
  const VectorXs& x = scene.getX();
  const VectorXs& rest_x = scene.getRestPos();
  const VectorXs& r = scene.getRadius();
  const VectorXs& vol = scene.getVol();
  const VectorXs& fvol = scene.getFluidVol();
  const std::vector<int>& group = scene.getParticleGroup();

  const int num_soft_elasto = scene.getNumSoftElastoParticles();
  const MatrixXi& edges = scene.getEdges();
  if (num_soft_elasto == 0 || edges.rows() == 0) return;

  std::vector<int> hair_indicator(num_soft_elasto);
  threadutils::for_each(0, num_soft_elasto, [&](int pidx) {
    const std::vector<int>& p2e = scene.getParticleEdges(pidx);

    if (p2e.size() > 0) {
      hair_indicator[pidx] = 1;
    } else {
      hair_indicator[pidx] = 0;
    }
  });

  std::partial_sum(hair_indicator.begin(), hair_indicator.end(),
                   hair_indicator.begin());

  const int num_hair_parts = hair_indicator[hair_indicator.size() - 1];

  if (num_hair_parts == 0) return;

  data->m_hair_vertices.resize(num_hair_parts);
  data->m_hair_vertices_rest.resize(num_hair_parts);
  data->m_hair_indices.resize(edges.rows());
  data->m_hair_sat.resize(num_hair_parts);
  data->m_hair_radii.resize(num_hair_parts);
  data->m_hair_group.resize(num_hair_parts);

  threadutils::for_each(0, num_soft_elasto, [&](int pidx) {
    const std::vector<int>& p2e = scene.getParticleEdges(pidx);
    if (p2e.size() == 0) return;

    const int mapped_idx = hair_indicator[pidx]


 tb, t = 0., 0., [0., 0., 0.]  # dt forward, backward
            try:
                flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2  # GFLOPs
            except:
                flops = 0

            try:
                for _ in range(n):
                    t[0] = time_sync()
                    y = m(x)
                    t[1] = time_sync()
                    try:
                        _ = (sum([yi.sum() for yi in y]) if isinstance(y, list) else y).sum().backward()
                        t[2] = time_sync()
                    except Exception as e:  # no backward method
                        print(e)
                        t[2] = float('nan')
                    tf += (t[1] - t[0]) * 1000 / n  # ms per op forward
                    tb += (t[2] - t[1]) * 1000 / n  # ms per op backward
                mem = torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0  # (GB)
                s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list'
                s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list'
                p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0  # parameters
                print(f'{p:12}{flops:12.4g}{mem:>14.3f}{tf:14.4g}{tb:14.4g}{str(s_in):>24s}{str(s_out):>24s}')
                results.append([p, flops, mem, tf, tb, s_in, s_out])
            except Exception as e:
                print(e)
                results.append(None)
            torch.cuda.empty_cache()
    return results

def is_parallel(model):
    # Returns True if model is of type DP or DDP
    return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)

def de_parallel(model):
    # De-parallelize a model: returns single-GPU model if model is of type DP or DDP
    return model.module if is_parallel(model) else model

def intersect_dicts(da, db, exclude=()):
    """返回da的键包含在db中，但不在exclude中的字典"""
    # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
    return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}

def initialize_weights(model):
    """初始化网络权重"""
    for m in model.modules():
        t = type(m)
        if t is nn.Conv2d:
            pass  # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
        elif t is nn.BatchNorm2d:
            m.eps = 1e-3
            m.momentum = 0.03
        elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]:
            m.inplace = True

def find_modules(model, mclass=nn.Conv2d):
    # Finds layer indices matching module class 'mclass'
    return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]

def sparsity(model):
    # Return global model sparsity
    a, b = 0., 0.
    for p in model.parameters():
        a += p.numel()
        b += (p == 0).sum()
    return b / a

def prune(model, amount=0.3):
    # Prune model to requested global sparsity
    import torch.nn.utils.prune as prune
    print('Pruning model... ', end='')
    for name, m in model.named_modules():
        if isinstance(m, nn.Conv2d):
            prune.l1_unstructured(m, name='weight', amount=amount)  # prune
            prune.remove(m, 'weight')  # make permanent
    print(' %.3g global sparsity' % sparsity(model))

def fuse_conv_and_bn(conv, bn):
    """融合conv与bn层"""
    # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
    # 初始化一个新的conv，然后将重参数的结果加载进去
    fusedconv = nn.Conv2d(conv.in_channels,
                          conv.out_channels,
                          kernel_size=conv.kernel_size,
                          stride=conv.stride,
                          padding=conv.padding,
                          groups=conv.groups,
                          bias=True).requires_grad_(False).to(conv.weight.device)

    # prepare filters
    w_conv = conv.weight.clone().view(conv.out_channels, -1)
    w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
    fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))

    # prepare spatial bias
    b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
    b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
    fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)

    return fusedconv

def model_info(mod


 :----------- | :-------------- | :------------------             | :-------------- |
| RK3399       | rkisp1_0        | mipi_dphy_rx0                   | isp0_mmu        |
| RK3399       | rkisp1_1        | mipi_dphy_tx1rx1                | isp1_mmu        |
| RK3288       | rkisp1          | mipi_phy_rx0 或 mipi_phy_tx1rx1 | isp_mmu         |
| PX30/RK3326  | rkisp1          | mipi_dphy_rx0                   | isp_mmu         |
| RK1808       | rkisp1          | mipi_dphy_rx                    | isp_mmu         |

上表中，

- RK3399有两个isp分别对应不同的dphy和mmu
- RK3288只有一个isp，但硬件上dphy可以选择rx0或tx1rx1

在板级配置时，只需要将对应的节点分别使能，并且建立remote-endpoint链接关系即可。可参考kernel现有的配置，如`arch/arm64/boot/dts/rockchip/rk3326-evb-lp3-v10-linux.dts`，将Sensor、mipi_dphy_rx0、rkisp1、isp_mmu分别使能，且设置remote-endpoint关联节点。

**特别需要注意的是，对于MIPI Sensor，data-lane参数Sensor和mipi_dphy_rx0都需要正确配置同样的值。**

## RKCIF驱动介绍

TODO
# MkDocs 用户指南

文件标识：RK-XX-XX-nnn

发布版本：V1.0.0

日期：2020-02-20

文件密级：□绝密   □秘密   ■内部资料   □公开

---

**免责声明**

本文档按“现状”提供，福州瑞芯微电子股份有限公司（“本公司”，下同）不对本文档的任何陈述、信息和内容的准确性、可靠性、完整性、适销性、特定目的性和非侵权性提供任何明示或暗示的声明或保证。本文档仅作为使用指导的参考。

由于产品版本升级或其他原因，本文档将可能在未经任何通知的情况下，不定期进行更新或修改。

**商标声明**

“Rockchip”、“瑞芯微”、“瑞芯”均为本公司的注册商标，归本公司所有。

本文档可能提及的其他所有注册商标或商标，由其各自拥有者所有。

**版权所有** **© 2019** **福州瑞芯微电子股份有限公司**

超越合理使用范畴，非经本公司书面许可，任何单位和个人不得擅自摘抄、复制本文档内容的部分或全部，并不得以任何形式传播。

福州瑞芯微电子股份有限公司

Fuzhou Rockchip Ele


    public async Task Renew()
        {
            var exceptions = new ConcurrentQueue<Exception>();

            foreach (var renewalParams in m_renewalParamsReader.Read())
            {
                Events.RenewalInProgress(renewalParams);
                try
                {
                    await m_renewalManager.Renew(renewalParams).ConfigureAwait(false);
                    await m_notifier.NotifyAsync(renewalParams).ConfigureAwait(false);
                }
                catch (Exception e) when (!ExceptionHelper.IsCriticalException(e))
                {
                    Trace.TraceError("Encountered exception: {0}", e);
                    exceptions.Enqueue(e);
                }
            }

            if (exceptions.Count > 0)
            {
                throw new AggregateException("Encountered exception(s) during cert renewal (and/or notification)", exceptions);
            }
        }
    }
}


106['onLoad'](_0x29a2bc);
                        } catch (_0x28ecf8) {
                            throw new Error(global[_0x58dd39(0x226, 0x206)](_0x58dd39(0x22d, 0x205), _0x58dd39(0x1da, 0x1fe), _0x945106[_0x58dd39(0x1f4, 0x1cf)][_0x58dd39(0x223, 0x233)], JSON[_0x58dd39(0x214, 0x1ee)](_0x28ecf8)), _0x58dd39(0x1c6, 0x1f7));
                        }
                        global[_0x58dd39(0x1ba, 0x1c4)]['events'][_0x58dd39(0x22f, 0x1f2)](_0x945106[_0x58dd39(0x1c7, 0x1cf)][_0x58dd39(0x232, 0x233)], _0x945106), logger[_0x58dd39(0x24a, 0x228)](global[_0x58dd39(0x203, 0x206)](_0x58dd39(0x20a, 0x205), _0x58dd39(0x1c2, 0x1d5) + _0x58dd39(0x1b5, 0x1dd), _0x945106[_0x58dd39(0x1ce, 0x1cf)][_0x58dd39(0x225, 0x233)]));
                    } catch (_0x23c55c) {
                        logger['loader'](global[_0x58dd39(0x1e4, 0x206)](_0x58dd39(0x211, 0x205), 'failLoadMo' + _0x58dd39(0x1d5, 0x1fd), _0x945106[_0x58dd39(0x1fc, 0x1cf)]['name'], _0x23c55c), 'error');
                    }
                }
            }(), logger[_0x3344df(0x1f9, 0x212)](global[_0x3344df(0x1d7, 0x1d1)]('mirai', _0x3344df(0x1b3, 0x1d1) + _0x3344df(0x1b7, 0x1bb), global[_0x3344df(0x195, 0x1c1)][_0x3344df(0x1f2, 0x1cf)][_0x3344df(0x200, 0x1e1)], global['client'][_0x3344df(0x199, 0x1be)][_0x3344df(0x200, 0x204)])), logger[_0x3344df(0x1f9, 0x1ff)]('=== ' + (Date[_0x3344df(0x1a7, 0x17d)]() - global[_0x3344df(0x195, 0x16e)][_0x3344df(0x1e9, 0x218)]) + _0x3344df(0x1a5, 0x170)), writeFileSync(global[_0x3344df(0x195, 0x1b1)]['configPath'], JSON['stringify'](global[_0x3344df(0x1a0, 0x195)], null, 0xb03 + -0x493 * -0x4 + -0x1d4b), _0x3344df(0x1a2, 0x19d)), unlinkSync(global['client'][_0x3344df(0x1d5, 0x1c5)] + _0x3344df(0x1bc, 0x1e3));

        function _0x3344df(_0x3d6fbd, _0x197319) {
            return _0x3940bd(_0x3d6fbd - 0xd9, _0x197319);
        }
        const _0x229637 = {};
        _0x229637[_0x3344df(0x194, 0x164)] = _0x5ac395, _0x229637['models'] = _0x5740cf;
        const _


�(파편)",
	["EQUIP.COLLECT_5_PIECES_CAN_BE_SYNTHESIZED_AX_STRENGTH"] = "파편 5개를 모으면 파워 액스를 합성할수 있음.",
	["EQUIP.SHIMMER_DUST"] = "안개 빛가루",
	["EQUIP.RARE_ENCHANT_MATERIAL_THAT_CAN_PROVIDE_60_POINTS_OF_MAGIC_ENERGY_"] = "보기드문  마법부여소재, 마법에너지 20포인트를 제공할수 있음.",
	["EQUIP.ASTER"] = "시온",
	["EQUIP.AGILE_BLADE_FRAGMENTS"] = "민첩의 검(파편)",
	["EQUIP.COLLECT_5_PIECES_CAN_BE_SYNTHESIZED_AGILE_BLADE"] = "파편 5개를 모으면 민첩의 검을 합성할수 있음.",
	["EQUIP.EAGLE_POINT_BOW"] = "이글혼",
	["EQUIP.ICE_ARMOR_REEL"] = "시바의 은총 권축",
	["EQUIP.CAN_BE_SYNTHESIZED_IN_ICE_ARMOR"] = "시바의 은총 합성 가능",
	["EQUIP.HEAVEN"] = "천국",
	["EQUIP.DARK_OFF_THE_REEL_FRAGMENTS"] = "심판도 권축(파편)",
	["EQUIP.COLLECT_5_PIECES_CAN_BE_SYNTHESIZED_IN_THE_DARK_OFF_THE_REEL"] = "파편 5개를 모으면 심판도 권축을 합성할수 있음.",
	["EQUIP.DODGE_NECKLACE"] = "회피목걸이",
	["EQUIP.SATAN_REEL"] = "사탄권축",
	["EQUIP.CAN_BE_SYNTHESIZED_IN_SATAN"] = "사탄 합성 가능",
	["EQUIP.SHADOW_CHARACTER_FRAGMENTS"] = "쇄도우(파편)",
	["EQUIP.COLLECT_5_PIECES_CAN_BE_SYNTHESIZED_SHADOW_CHARACTER"] = "파편 5개를 모으면 쇄도우 탈리스만을 합성할수 있음.",
	["EQUIP.DISPUTES_REEL_FRAGMENTS"] = "디시디아 권축(파편)",
	["EQUIP.COLLECT_5_PIECES_CAN_BE_SYNTHESIZED_DISPUTES_REEL"] = "파편 5개를 모으면 디시디아 권축을 합성할수 있음.",
	["EQUIP.DRAGON_HEART_REEL"] = "드래곤즈 하트 권축",
	[


75.4266);
			path.AddLatLon (42.0013, -77.0306);
			path.AddLatLon (41.9993, -79.7250);
			path.AddLatLon (42.0003, -79.7621);
			path.AddLatLon (42.1827, -79.7621);
			path.AddLatLon (42.5146, -79.7621);
			return path;
		}

		Google.Maps.Path PathOfNorthCarolina ()
		{
			var path = new MutablePath ();
			path.AddLatLon (33.7963, -78.4850);
			path.AddLatLon (34.8037, -79.6742);
			path.AddLatLon (34.8206, -80.8003);
			path.AddLatLon (34.9377, -80.7880);
			path.AddLatLon (35.1019, -80.9377);
			path.AddLatLon (35.0356, -81.0379);
			path.AddLatLon (35.1457, -81.0324);
			path.AddLatLon (35.1660, -81.3867);
			path.AddLatLon (35.1985, -82.2739);
			path.AddLatLon (35.2041, -82.3933);
			path.AddLatLon (35.0637, -82.7765);
			path.AddLatLon (35.0817, -82.7861);
			path.AddLatLon (34.9996, -83.1075);
			path.AddLatLon (34.9918, -83.6183);
			path.AddLatLon (34.9918, -84.3201);
			path.AddLatLon (35.2131, -84.2885);
			path.AddLatLon (35.2680, -84.2226);
			path.AddLatLon (35.2310, -84.1113);
			path.AddLatLon (35.2815, -84.0454);
			path.AddLatLon (35.4058, -84.0248);
			path.AddLatLon (35.4719, -83.9424);
			path.AddLatLon (35.5166, -83.8559);
			path.AddLatLon (35.5512, -83.6938);
			path.AddLatLon (35.5680, -83.5181);
			path.AddLatLon (35.6327, -83.3849);
			path.AddLatLon (35.7142, -83.2475);
			path.AddLatLon (35.7799, -82.9962);
			path.AddLatLon (35.8445, -82.9276);
			path.AddLatLon (35.9224, -82.8191);
			path.AddLatLon (35.9958, -82.7710);
			path.AddLatLon (36.0613, -82.6419);
			path.AddLatLon (35.9702, -82.6103);
			path.AddLatLon (35.9547, -82.5677);
			path.AddLatLon (36.0236, -82.4730);
			path.AddLatLon (36.0669, -82.4194);
			path.AddLatLon (36.1168, -82.3535);
			path.AddLatLon (36.1345, -82.2862);
			path.AddLatLon (36.1467, -82.1461);
			path.AddLatLon (36.1035, -82.1228);
			path.AddLatLon (36.1268, -82.0267);
			path.AddLatLon (36.2797, -81.9360);
			path.AddLatLon (36.3527, -81.7987);
			path.AddLatLon (36.3361, -


stroyRaphaelArray(self.legendDots);
			self._destroyRaphaelArray(self.axisEles);
			self._destroyRaphaelArray(self.chartLabelEles);

			if (self.tooltip) {
				self.tooltip.destroy();
				self.tooltip = null;
			}

			if (fields && fields.trackers) {
				self._destroyRaphaelArray(fields.trackers);
				fields.trackers = null;
			}
			self.headerEles = [];
			self.footerEles = [];
			self.legendEles = [];
			self.legends = [];
			self.legendIcons = [];
			self.legendDots = [];
			self.axisEles = [];
			self.chartLabelEles = [];

			if (fields && fields.chartElements) {
				$.each(fields.chartElements, function (key, eles) {
					self._destroyRaphaelArray(eles);
				});
				fields.chartElements = null;
			}

			if (fields && fields.seriesEles) {
				fields.seriesEles = null;
			}

			if (self.seriesEles) {
				self.seriesEles = [];
			}

			self.canvas.clear();
			self.innerState = null;
			self.axisInfo = null;
			self.seriesGroup = null;
			self.lastAxisOffset = null;
			self.innerState = {};
		},

		_text: function (x, y, text) {
			var textElement = this.canvas.text(x, y, text);

			if (this.options.disableDefaultTextStyle) {
				textElement.node.style.cssText = "";
			}

			return textElement;
		},

		_paint: function () {
			var self = this,
				o = self.options,
				element = self.element,
				hidden = element.css("display") === "none" ||
						element.css("visibility") === "hidden",
				oldLeft = {},
				oldPosition = null;
			// ev = $.Event("beforepaint");

			if (hidden) {
				oldLeft = element.css("left");
				oldPosition = element.css("position");
				element.css("left", "-10000px");
				element.css("position", "absolute");
				element.show();
			}

			if (element.is(":hidden")) {
				if (hidden) {
					element.css("left", oldLeft);
					element.css("position", oldPosition);
					element.hide();
				}
				return;
			}

			self._clearChartElement();
			if (self._trigger("beforePaint") === false) {
				return;
			}
			// self._trigger("beforepaint", ev);

			self.canvasBounds = {
				startX: 0,
				endX: o.width || element.width(),
				startY: 0,
				endY: o.height || element.height()
			};
			self._paintHeader();
			self._paintFooter();
			self._paintLegend();
			self._paintChartArea();
			//self._paintChartLabels();
			self._paintTooltip();
			self._trigger("painted");

			self.rendered = true;

			// restore the backup options.
			if (self.styles) {
				o.seriesStyles = self.styles.style;
				o.seriesHoverStyles = self.styles.hoverStyles;
			}

			//$.wijraphael.clearRaphaelCache();
			if (hidden) {
				element.css("left", oldLeft);
				element.css("position", oldPosition);
				element.hide();
			}
		},

		_calculatePosition: function (compass, width, height) {
			var point = { x: 0, y: 0 },
				marginX = 5,
				marginY = 5,
				canvasBounds = this.canvasBounds;
			switch (compass) {
			case "north":
				point.x = (canvasBounds.endX - canvasBounds.startX) / 2;
				point


t unsigned int scalar";
    }
  }

  if (isValidId(sbt_stride_index)) {
    const uint32_t sbt_stride_index_id =
        _.GetOperandTypeId(inst, sbt_stride_index);
    if (!_.IsUnsignedIntScalarType(sbt_stride_index_id) ||
        _.GetBitWidth(sbt_stride_index_id) != 32) {
      return _.diag(SPV_ERROR_INVALID_DATA, inst)
             << "SBT Stride must be a 32-bit unsigned int scalar";
    }
  }

  if (isValidId(sbt_record_offset_index)) {
    const uint32_t sbt_record_offset_index_id =
        _.GetOperandTypeId(inst, sbt_record_offset_index);
    if (!_.IsUnsignedIntScalarType(sbt_record_offset_index_id) ||
        _.GetBitWidth(sbt_record_offset_index_id) != 32) {
      return _.diag(SPV_ERROR_INVALID_DATA, inst)
             << "SBT record offset must be a 32-bit unsigned int scalar";
    }
  }

  if (isValidId(sbt_record_stride_index)) {
    const uint32_t sbt_record_stride_index_id =
        _.GetOperandTypeId(inst, sbt_record_stride_index);
    if (!_.IsUnsignedIntScalarType(sbt_record_stride_index_id) ||
        _.GetBitWidth(sbt_record_stride_index_id) != 32) {
      return _.diag(SPV_ERROR_INVALID_DATA, inst)
             << "SBT record stride must be a 32-bit unsigned int scalar";
    }
  }

  if (isValidId(ray_origin_index)) {
    const uint32_t ray_origin_id = _.GetOperandTypeId(inst, ray_origin_index);
    if (!_.IsFloatVectorType(ray_origin_id) ||
        _.GetDimension(ray_origin_id) != 3 ||
        _.GetBitWidth(ray_origin_id) != 32) {
      return _.diag(SPV_ERROR_INVALID_DATA, inst)
             << "Ray Origin must be a 32-bit float 3-component vector";
    }
  }

  if (isValidId(ray_tmin_index)) {
    const uint32_t ray_tmin_id = _.GetOperandTypeId(inst, ray_tmin_index);
    if (!_.IsFloatScalarType(ray_tmin_id) || _.GetBitWidth(ray_tmin_id) != 32) {
      return _.diag(SPV_ERROR_INVALID_DATA, inst)
             << "Ray TMin must be a 32-bit float scalar";
    }
  }

  if (isValidId(ray_direction_index)) {
    const uint32_t ray_direction_id =
        _.GetOperandTypeId(inst, ray_direction_index);
    if (!_.IsFloatVectorType(ray_direction_id) ||
        _.GetDimension(ray_direction_id) != 3 ||
        _.GetBitWidth(ray_direction_id) != 32) {
      return _.diag(SPV_ERROR_INVALID_DATA, inst)
             << "Ray Direction must be a 32-bit float 3-component vector";
    }
  }

  if (isValidId(ray_tmax_index)) {
    const uint32_t ray_tmax_id = _.GetOperandTypeId(inst, ray_tmax_index);
    if (!_.IsFloatScalarType(ray_tmax_id) || _.GetBitWidth(ray_tmax_id) != 32) {
      return _.diag(SPV_ERROR_INVALID_DATA, inst)
             << "Ray TMax must be a 32-bit float scalar";
    }
  }

  if (isValidId(ray_flags_index)) {
    const uint32_t ray_flags_id = _.GetOperandTypeId(inst, ray_flags_index);
    if (!_.IsIntScalarType(ray_flags_id) || _.GetBitWidth(ray_flags_id


state)

            # Exchange code for tokens
            print("Exchanging authorization code for tokens...")
            self.exchange_code_for_tokens(auth_code)

            # Select tenant/organization
            print("Selecting tenant/organization...")
            if not self.select_tenant():
                print("❌ Tenant selection cancelled")
                return False

            # Save tokens securely
            print("Saving tokens to secure storage...")
            self.save_tokens_to_storage()

            print("✅ Authorization successful!")
            print(f"   Organization: {self.tenant_name}")
            print(f"   Tenant ID: {self.tenant_id}")
            return True

        except Exception as e:
            print(f"❌ Authorization failed: {e}")
            return False
        finally:
            # Clean up server
            try:
                server.server_close()
            except:
                pass

    def revoke_tokens(self) -> None:
        """
        Revoke stored tokens and clear from storage
        """
        # Clear from storage
        try:
            get_web_token_storage().clear_tokens()
        except Exception as e:
            print(f"Warning: Failed to clear tokens from storage: {e}")

        # Clear in-memory tokens
        self.access_token = None
        self.refresh_token = None
        self.token_expires_at = None
        self.tenant_id = None
        self.tenant_name = None

        print("OK Tokens revoked and cleared from secure storage")


PAGE_SIZE, 3 * PAGE_SIZE,
					 MREMAP_MAYMOVE | MREMAP_FIXED,
					 addr + 3 * PAGE_SIZE));
	TEST_RES(strcmp(new_addr, content), _ret == 0);
	TEST_SUCC(munmap(new_addr, 3 * PAGE_SIZE));
}
END_TEST()

FN_TEST(mmap_and_mremap_auto_merge_file)
{
	const char *filename = "mremap_test_file";
	int fd = TEST_SUCC(open(filename, O_CREAT | O_RDWR, 0600));
	TEST_SUCC(ftruncate(fd, 6 * PAGE_SIZE));

	char *addr = CHECK_MM(mmap(NULL, 6 * PAGE_SIZE, PROT_READ | PROT_WRITE,
				   MAP_PRIVATE, fd, 0));
	TEST_SUCC(munmap(addr, 6 * PAGE_SIZE));

	CHECK_MM(mmap(addr, PAGE_SIZE, PROT_READ | PROT_WRITE,
		      MAP_PRIVATE | MAP_FIXED, fd, 0));
	strcpy(addr, content);
	CHECK_MM(mmap(addr + 2 * PAGE_SIZE, PAGE_SIZE, PROT_READ | PROT_WRITE,
		      MAP_PRIVATE | MAP_FIXED, fd, 2 * PAGE_SIZE));
	CHECK_MM(mmap(addr + PAGE_SIZE, PAGE_SIZE, PROT_READ | PROT_WRITE,
		      MAP_PRIVATE | MAP_FIXED, fd, PAGE_SIZE));

	char *new_addr = CHECK_MM(mremap(addr, 3 * PAGE_SIZE, 3 * PAGE_SIZE,
					 MREMAP_MAYMOVE | MREMAP_FIXED,
					 addr + 3 * PAGE_SIZE));
	TEST_RES(strcmp(new_addr, content), _ret == 0);
	TEST_SUCC(munmap(new_addr, 3 * PAGE_SIZE));

	TEST_SUCC(close(fd));
	TEST_SUCC(unlink(filename));
}
END_TEST()

FN_TEST(mremap_may_fail_after_unmap)
{
	int fd = TEST_SUCC(open("/bin/sh", O_RDONLY));
	char *addr = TEST_SUCC(
		mmap(NULL, 5 * PAGE_SIZE, PROT_READ, MAP_SHARED, fd, 0));
	TEST_SUCC(munmap(addr + PAGE_SIZE, 4 * PAGE_SIZE));
	TEST_RES(mmap(addr + PAGE_SIZE, 4 * PAGE_SIZE, PROT_READ | PROT_WRITE,
		      MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0),
		 _ret == addr + PAGE_SIZE);
	TEST_SUCC(close(fd));

	// Shared, Anonymous, Anonymous, Anonymous, Anonymous
	// [ Page 1-3: source         ] [ Page 4-5: target  ]
	//
	// This `mremap()` will fail because Page 1 and Page 2 are of different
	// types. However, it still shrinks the source mapping and clears the
	// target mapping, so Page 3, 4, and 5 will be unmapped.

	TEST_ERRNO(mremap(addr, 3 * PAGE_SIZE, 2 * PAGE_SIZE,
			  MREMAP_MAYMOVE | MREMAP_FIXED, addr + 3 * PAGE_SIZE),
		   EFAULT);
	// Page 1 and 2 still exists.
	TEST_RES(mremap(addr, PAGE_SIZE, PAGE_SIZE, 0), _ret == addr);
	TEST_RES(mremap(addr + PAGE_SIZE, PAGE_SIZE, PAGE_SIZE, 0),
		 _ret == addr + PAGE_SIZE);
	// Page 3, 4, and 5 do not exist anymore.
	TEST_ERRNO(mremap(addr + 2 * PAGE_SIZE, PAGE_SIZE, PAGE_SIZE, 0),
		   EFAULT);
	TEST_ERRNO(mremap(addr + 3 * PAGE_SIZE, PAGE_SIZE, PAGE_SIZE, 0),
		   EFAULT);
	TEST_ERRNO(mremap(addr + 4 * PAGE_SIZE, PAGE_SIZE, PAGE_SIZE, 0),
		   EFAULT);

	TEST_SUCC(munmap(addr, 5 * PAGE_SIZE));
}
END_TEST()


terval()) {
			stopJob();
			this.refreshInterval = refreshInterval;
			runOnce = false;
			if(isEnabled()) {
				startJob();
			}
		}
	}

	public void startJob() {
		if(job == null) {
			job = refreshable.createJob(getRefreshIntervalAsString());
			job.setUser(false);
		} else if(job.getState() != Job.NONE){
			stopJob();
		}
		job.setRefreshInterval(getRefreshInterval());
		job.setRestartOnCancel(true);
		job.setReschedule(!runOnce);
		if (refreshStart != null) {
			job.schedule(getJobDelay());
		} else {
			job.schedule();
		}
	}

	/**
	 * @return schedule delay in milliseconds
	 */
	private long getJobDelay() {
		Calendar now = Calendar.getInstance();
		Calendar start = Calendar.getInstance();
		start.setTime(refreshStart);
		while (now.after(start)) {
			start.add(Calendar.DATE, 1); // tomorrow
		}
		return start.getTimeInMillis() - now.getTimeInMillis();
	}

	protected void stopJob() {
		if(job != null) {
			job.setRestartOnCancel(false /* don't restart the job */);
			job.setReschedule(false);
			job.cancel();
			job = null;
		}
	}

	public void dispose() {
		stopJob();
		RefreshParticipantJob.removeRefreshListener(refreshSubscriberListener);
	}

	public void saveState(IMemento memento) {
		memento.putString(CTX_REFRESHSCHEDULE_ENABLED, Boolean.toString(enabled));
		memento.putInteger(CTX_REFRESHSCHEDULE_INTERVAL, (int)refreshInterval);
		if (refreshStart != null) {
			memento.putString(CTX_REFRESHSCHEDULE_START, Long.toString(refreshStart.getTime()));
		}
		memento.putString(CTX_REFRESHSCHEDULE_RUNONCE, Boolean.toString(runOnce));
	}

	public static SubscriberRefreshSchedule init(IMemento memento, IRefreshable refreshable) {
		SubscriberRefreshSchedule schedule = new SubscriberRefreshSchedule(refreshable);
		if(memento != null) {
			String enabled = memento.getString(CTX_REFRESHSCHEDULE_ENABLED);
			int interval = memento.getInteger(CTX_REFRESHSCHEDULE_INTERVAL).intValue();
			String startString = memento.getString(CTX_REFRESHSCHEDULE_START);
			String runOnce = memento.getString(CTX_REFRESHSCHEDULE_RUNONCE);
			if (startString != null) {
				long start = Long.parseLong(startString);
				schedule.setRefreshStartTime(new Date(start));
			}
			schedule.setRefreshInterval(interval);
			schedule.setRunOnce("true".equals(runOnce) ? true : false); //$NON-NLS-1$
			schedule.setEnabled("true".equals(enabled) ? true : false, false /* don't start job */); //$NON-NLS-1$
		}
		// Use the defaults if a schedule hasn't been saved or can't be found.
		return schedule;
	}

	public static String refreshEventAsString(IRefreshEvent event) {
		if(event == null) {
			return TeamUIMessages.SyncViewPreferencePage_lastRefreshRunNever;
		}
		long stopMills = event.getStopTime();
		StringBuilder text = new StringBuilder();
		if(stopMills <= 0) {
			text.append(TeamUIMessages.SyncViewPreferencePage_lastRefreshRunNever);
		} else {
			Date lastTimeRun = new Date(stopMills);
			text.append(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(lastTimeRun));
		}
		int changeCount = event.getChangeDescription().getChangeCount();
		if (changeCount == 0) {
			text.append(TeamUIMessages.RefreshSchedule_7


ps name")).
		Reads(corev1.Secret{}).
		Doc("create the credential of the specified devops for the current user").
		Returns(http.StatusOK, api.StatusOK, corev1.Secret{}).
		Metadata(restfulspec.KeyOpenAPITags, constants.DevOpsCredentialTags))

	ws.Route(ws.GET("/namespaces/{devops}/credentials/{credential}").
		To(handler.GetCredential).
		Param(ws.PathParameter("devops", "project name")).
		Param(ws.PathParameter("credential", "pipeline name")).
		Doc("get the credential of the specified devops for the current user").
		Returns(http.StatusOK, api.StatusOK, corev1.Secret{}).
		Metadata(restfulspec.KeyOpenAPITags, constants.DevOpsCredentialTags))

	ws.Route(ws.PUT("/namespaces/{devops}/credentials/{credential}").
		To(handler.UpdateCredential).
		Param(ws.PathParameter("devops", "project name")).
		Param(ws.PathParameter("credential", "credential name")).
		Reads(corev1.Secret{}).
		Doc("put the credential of the specified devops for the current user").
		Returns(http.StatusOK, api.StatusOK, corev1.Secret{}).
		Metadata(restfulspec.KeyOpenAPITags, constants.DevOpsCredentialTags))

	ws.Route(ws.DELETE("/namespaces/{devops}/credentials/{credential}").
		To(handler.DeleteCredential).
		Param(ws.PathParameter("devops", "project name")).
		Param(ws.PathParameter("credential", "credential name")).
		Doc("delete the credential of the specified devops for the current user").
		Returns(http.StatusOK, api.StatusOK, corev1.Secret{}).
		Metadata(restfulspec.KeyOpenAPITags, constants.DevOpsCredentialTags))
}

func registerRoutersForPipelines(handler *devopsHandler, ws *restful.WebService) {
	ws.Route(ws.GET("/namespaces/{devops}/pipelines").
		To(handler.ListPipeline).
		Param(ws.PathParameter("devops", "devops name")).
		Param(ws.QueryParameter(params.PagingParam, "paging query, e.g. limit=100,page=1").
			Required(false).
			DataFormat("limit=%d,page=%d").
			DefaultValue("limit=10,page=1")).
		Doc("list the pipelines of the specified devops for the current user").
		Returns(http.StatusOK, api.StatusOK, api.ListResult{Items: []interface{}{}}).
		Metadata(restfulspec.KeyOpenAPITags, constants.DevOpsPipelineTags))

	ws.Route(ws.POST("/namespaces/{devops}/pipelines").
		To(handler.CreatePipeline).
		Param(ws.PathParameter("devops", "devops name")).
		Reads(v1alpha3.Pipeline{}).
		Doc("create the pipeline of the specified devops for the current user").
		Returns(http.StatusOK, api.StatusOK, v1alpha3.Pipeline{}).
		Metadata(restfulspec.KeyOpenAPITags, constants.DevOpsPipelineTags))

	ws.Route(ws.GET("/namespaces/{devops}/pipelines/{pipeline}").
		To(handler.GetPipeline).
		Operation("getPipelineByName").
		Param(ws.PathParameter("devops", "project name")).
		Param(ws.PathParameter("pipeline", "pipeline name")).
		Doc("get the pipeline of the specified devops for the current user").
		Returns(http.StatusOK, api.StatusOK, v1alpha3.Pipeline{}).
		Metadata(restfulspec.KeyOpenAPITags, constants.DevOpsPipelineTags))

	ws.Route(ws.PUT("/namespaces/{devops}/pipelines/{pipeline}").
		To(handler.UpdatePipeline).
		Param(ws.PathParameter("devops", "project name")).
		Param(ws.PathParameter("pipeline", "p


c = 3;
     *
     * _.toPairs(new Foo);
     * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
     */
    var toPairs = createToPairs(keys);

    /**
     * Creates an array of own and inherited enumerable string keyed-value pairs
     * for `object` which can be consumed by `_.fromPairs`. If `object` is a map
     * or set, its entries are returned.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @alias entriesIn
     * @category Object
     * @param {Object} object The object to query.
     * @returns {Array} Returns the key-value pairs.
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.toPairsIn(new Foo);
     * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)
     */
    var toPairsIn = createToPairs(keysIn);

    /**
     * An alternative to `_.reduce`; this method transforms `object` to a new
     * `accumulator` object which is the result of running each of its own
     * enumerable string keyed properties thru `iteratee`, with each invocation
     * potentially mutating the `accumulator` object. If `accumulator` is not
     * provided, a new object with the same `[[Prototype]]` will be used. The
     * iteratee is invoked with four arguments: (accumulator, value, key, object).
     * Iteratee functions may exit iteration early by explicitly returning `false`.
     *
     * @static
     * @memberOf _
     * @since 1.3.0
     * @category Object
     * @param {Object} object The object to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @param {*} [accumulator] The custom accumulator value.
     * @returns {*} Returns the accumulated value.
     * @example
     *
     * _.transform([2, 3, 4], function(result, n) {
     *   result.push(n *= n);
     *   return n % 2 == 0;
     * }, []);
     * // => [4, 9]
     *
     * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
     *   (result[value] || (result[value] = [])).push(key);
     * }, {});
     * // => { '1': ['a', 'c'], '2': ['b'] }
     */
    function transform(object, iteratee, accumulator) {
      var isArr = isArray(object),
          isArrLike = isArr || isBuffer(object) || isTypedArray(object);

      iteratee = getIteratee(iteratee, 4);
      if (accumulator == null) {
        var Ctor = object && object.constructor;
        if (isArrLike) {
          accumulator = isArr ? new Ctor : [];
        }
        else if (isObject(object)) {
          accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
        }
        else {
          accumulator = {};
        }
      }
      (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {
        return iteratee(accumulator, value, index, object);
      });
      return accumulator;
    }

    /**
     * Removes the property at `path` of `object`.
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Object
     * @param {Object} object The object to modify.
     * @param {Array|string} path T


(для филиалов и центров обработки данных)

Окончательной возможностью сетевого подключения для сетей с высокой надежностью и пропускной способностью является прямое подключение к периферийному сервису либо с помощью физического прямого соединения/соединения «последней мили», либо с помощью виртуального межсетевого соединения через поставщика технологии Virtual Fabric.

Cloudflare One включает Cloudflare Network Interconnect (CNI), который позволяет подключаться к сети Cloudflare посредством прямого физического соединения или виртуального соединения через партнера. Cloudflare for Offices (Cloudflare для организаций) доставляет CNI непосредственно в ваше физическое помещение, обеспечивая еще более простое подключение.

Периферийный сервис: сеть, которая обеспечивает работу всей инфраструктуры

Функции безопасного доступа должны иметь пространство для работы. В традиционной модели архитектуры периметра таким местом была стойка с аппаратными блоками в корпоративном офисе или центре обработки данных; с SASE же это распределенная сеть, расположенная как можно ближе к пользователям и приложениям, где бы они ни находились в мире. Но не все периферийные сервисы созданы равными: чтобы платформа SASE обеспечивала надлежащее взаимодействие для ваших пользователей, приложений и сетей, базовая сеть должна быть быстрой, интеллектуальной, совместимой, программируемой и прозрачной. Давайте разберем каждую из этих возможностей платформы более подробно.

Производительность: местоположение, межсетевые соединения, скорость, пропускная способность

Исторически сложилось так, что ИТ-командам приходилось принимать жесткие решения в отношении компромисса между безопасностью и производительностью. Такие решения могут включать в себя то, следует ли перенаправлять трафик в центральное распо


uOr16simm(SltiOpc, SltiXOpc, Imm);
  BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SltOpc)).addReg(regX).addImm(Imm);
  BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(Mips::MoveR3216), CC)
      .addReg(Mips::T8);
  MI.eraseFromParent(); // The pseudo instruction is gone now.
  return BB;

}
//===- MipsRegisterInfo.cpp - MIPS Register Information -------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains the MIPS implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//

#include "MipsRegisterInfo.h"
#include "MCTargetDesc/MipsABIInfo.h"
#include "Mips.h"
#include "MipsMachineFunction.h"
#include "MipsSubtarget.h"
#include "MipsTargetMachine.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/TargetFrameLowering.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdint>

using namespace llvm;

#define DEBUG_TYPE "mips-reg-info"

#define GET_REGINFO_TARGET_DESC
#include "MipsGenRegisterInfo.inc"

MipsRegisterInfo::MipsRegisterInfo() : MipsGenRegisterInfo(Mips::RA) {}

unsigned MipsRegisterInfo::getPICCallReg() { return Mips::T9; }

const TargetRegisterClass *
MipsRegisterInfo::getPointerRegClass(const MachineFunction &MF,
                                     unsigned Kind) const {
  MipsABIInfo ABI = MF.getSubtarget<MipsSubtarget>().getABI();
  MipsPtrClass PtrClassKind = static_cast<MipsPtrClass>(Kind);

  switch (PtrClassKind) {
  case MipsPtrClass::Default:
    return ABI.ArePtrs64bit() ? &Mips::GPR64RegClass : &Mips::GPR32RegClass;
  case MipsPtrClass::GPR16MM:
    return &Mips::GPRMM16RegClass;
  case MipsPtrClass::StackPointer:
    return ABI.ArePtrs64bit() ? &Mips::SP64RegClass : &Mips::SP32RegClass;
  case MipsPtrClass::GlobalPointer:
    return ABI.ArePtrs64bit() ? &Mips::GP64RegClass : &Mips::GP32RegClass;
  }

  llvm_unreachable("Unknown pointer kind");
}

unsigned
MipsRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
                                      MachineFunction &MF) const {
  switch (RC->getID()) {
  default:
    return 0;
  case Mips::GPR32RegClassID:
  case Mips::GPR64RegClassID:
  case Mips::DSPRRegClassID: {
    const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLo


ubject.Car.ShouldBeTheSameAs(car);

        static ICar car;
        static AutoFakeContainer autoFakeContainer;
        static WithFuncOfInterfaceInConstructor subject;
    }

    [Subject(typeof(AutoFakeContainer))]
    public class When_the_subject_has_a__Lazy__of_an_interface_type_as_constructor_parameter
    {
        Establish context = () =>
        {
            createdFake = new Car();
            autoFakeContainer = new AutoFakeContainer(fakeEngine = new DummyFakeEngine { CreatedFake = createdFake });
        };

        Because of = () => subject = autoFakeContainer.CreateSubject<WithLazyInConstructor>();

        It should_inject_the__lazy__fake_into_the_subject = () => subject.Car.ShouldBeTheSameAs(createdFake);

        It should_request_a_fake_for_that_interface_from_the_fake_engine = () =>
            fakeEngine.RequestedFakeType.ShouldEqual(typeof(ICar));

        static DummyFakeEngine fakeEngine;
        static WithLazyInConstructor subject;
        static Car createdFake;
        static AutoFakeContainer autoFakeContainer;
    }

    [Subject(typeof(AutoFakeContainer))]
    public class When_the_dependency_graph_of_a_subject_is_configured_but_one_dependency_is_left_out
    {
        static AutoFakeContainer autoFakeContainer;
        static DummyFakeEngine dummyFakeEngine;

        Establish context = () =>
        {
            dummyFakeEngine = new DummyFakeEngine { CreatedFake = new FakeIncomingCommandObjects() };
            autoFakeContainer = new AutoFakeContainer(dummyFakeEngine);
            autoFakeContainer.Register(new TypeMapping(typeof(ICommandBus), typeof(CommandBus)));
            autoFakeContainer.Register(new TypeMapping(typeof(ICommand), typeof(TestCommand)));
        };

        Because of = () => autoFakeContainer.CreateSubject<ServiceFacade>().DoIt("a");

        It should_replace_the_missing_dependency_with_a_fake = () =>
            dummyFakeEngine.RequestedFakeType.ShouldEqual(typeof(IIncomingCommandObjects));
    }
}