 of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package ethash

import (
	"bytes"
	"encoding/binary"
	"io/ioutil"
	"math/big"
	"os"
	"reflect"
	"sync"
	"testing"

	"github.com/sero-cash/go-sero/common"
	"github.com/sero-cash/go-sero/common/hexutil"
	"github.com/sero-cash/go-sero/core/types"
)

// prepare converts an ethash cache or dataset from a byte stream into the internal
// int representation. All ethash methods work with ints to avoid constant byte to
// int conversions as well as to handle both little and big endian systems.
func prepare(dest []uint32, src []byte) {
	for i := 0; i < len(dest); i++ {
		dest[i] = binary.LittleEndian.Uint32(src[i*4:])
	}
}

// Tests whether the dataset size calculator works correctly by cross checking the
// hard coded lookup table with the value generated by it.
func TestSizeCalculations(t *testing.T) {
	// Verify all the cache and dataset sizes from the lookup table.
	for epoch, want := range cacheSizes {
		if size := calcCacheSize(epoch); size != want {
			t.Errorf("cache %d: cache size mismatch: have %d, want %d", epoch, size, want)
		}
	}
	for epoch, want := range datasetSizes {
		if size := calcDatasetSize(epoch); size != want {
			t.Errorf("dataset %d: dataset size mismatch: have %d, want %d", epoch, size, want)
		}
	}
}

// Tests that verification caches can be correctly generated.
func TestCacheGeneration(t *testing.T) {
	tests := []struct {
		size  uint64
		epoch uint64
		cache []byte
	}{
		{
			size:  1024,
			epoch: 0,
			cache: hexutil.MustDecode("0x" +
				"7ce2991c951f7bf4c4c1bb119887ee07871eb5339d7b97b8588e85c742de90e5bafd5bbe6ce93a134fb6be9ad3e30db99d9528a2ea7846833f52e9ca119b6b54" +
				"8979480c46e19972bd0738779c932c1b43e665a2fd3122fc3ddb2691f353ceb0ed3e38b8f51fd55b6940290743563c9f8fa8822e611924657501a12aafab8a8d" +
				"88fb5fbae3a99d14792406672e783a06940a42799b1c38bc28715db6d37cb11


-bidi-font-family:'Times New Roman';font-size:10.5000pt;mso-font-kerning:1.0000pt;">    UCHAR Version;                         <o:p></o:p>

    CLFS_EXTEND_STATE eExtendState;     <o:p></o:p>

    USHORT iExtendBlock;               <o:p></o:p>

    USHORT iFlushBlock;                <o:p></o:p>

    ULONG cNewBlockSectors;            <o:p></o:p>

    ULONG cExtendStartSectors;         <o:p></o:p>

    ULONG cExtendSectors;              <o:p></o:p></sp


No waiters", "  \u6ca1\u6709\u7b49\u5f85\u8005"},
        {"not a class", "{0} \u4e0d\u662f\u7c7b"},
        {"Not a monitor number:", "\u4e0d\u662f\u76d1\u89c6\u5668\u7f16\u53f7\uff1a ''{0}''"},
        {"not found (try the full name)", "{0} \u672a\u627e\u5230\uff08\u8bf7\u5c1d\u8bd5\u4f7f\u7528\u5168\u540d\uff09"},
        {"Not found:", "\u672a\u627e\u5230\uff1a {0}"},
        {"not found", "{0} \u672a\u627e\u5230"},
        {"Not owned", "  \u4e0d\u62e5\u6709"},
        {"Not waiting for a monitor", "  \u4e0d\u7b49\u5f85\u76d1\u89c6\u5668"},
        {"Nothing suspended.", "\u672a\u6682\u505c\u4efb\u4f55\u5bf9\u8c61\u3002"},
        {"object description and hex id", "({0}){1}"},
        {"Operation is not supported on the target VM", "\u76ee\u6807 VM \u4e0d\u652f\u6301\u64cd\u4f5c"},
        {"operation not yet supported", "\u5c1a\u4e0d\u652f\u6301\u64cd\u4f5c"},
        {"Owned by:", "  \u62e5\u6709\u8005\uff1a{0}\uff0c\u6761\u76ee\u8ba1\u6570\uff1a{1,number,integer}"},
        {"Owned monitor:", "  \u62e5\u6709\u7684\u76d1\u89c6\u5668\uff1a {0}"},
        {"Parse exception:", "\u89e3\u6790\u5f02\u5e38\uff1a {0}"},
        {"printbreakpointcommandusage", "\u7528\u6cd5\uff1a{0} <\u7c7b>:<\u884c\u53f7> \u6216\n       {1} <\u7c7b>.<\u65b9\u6cd5\u540d>[(\u53c2\u6570\u7c7b\u578b,...)]"},
        {"Removed:", "\u5df2\u5220\u9664\uff1a {0}"},
        {"Requested stack frame is no longer active:", "\u8bf7\u6c42\u7684\u5806\u6808\u5e27\u4e0d\u518d\u5904\u4e8e\u6d3b\u52a8\u72b6\u6001\uff1a{0,number,integer}"},
        {"run <args> command is valid only with launched VMs", "\u201crun <\u53c2\u6570>\u201d\u547d\u4ee4\u4ec5\u5bf9\u5df2\u542f\u52a8\u7684 VM \u6709\u6548"},
        {"run", "\u8fd0\u884c {0}"},
        {"saved", "{0} \u5df2\u4fdd\u5b58"},
        {"Set deferred", "\u8bbe\u7f6e\u5ef6\u8fdf\u7684 {0}"},
        {"Set", "\u8bbe\u7f6e {0}"},
        {"Source file not found:", "\u627e\u4e0d\u5230\u6e90\u6587\u4ef6\uff1a {0


Value`.
    /// `Ok` is returned only for successful calls, for any kind of error
    /// the `Err` variant is returned (including the failed RPC method
    /// execution response).
    async fn post(&self, message: impl serde::Serialize) -> Result<serde_json::Value> {
        let reply: Output = self.post_raw(message).await?;

        let ret = match reply {
            Output::Success(v) => v.result,
            Output::Failure(v) => return Err(anyhow!("RPC error: {}", v.error)),
        };

        Ok(ret)
    }

    /// Performs a POST query to the JSON RPC endpoint,
    /// and decodes the response, returning the decoded `serde_json::Value`.
    /// `Ok` is returned only for successful calls, for any kind of error
    /// the `Err` variant is returned (including the failed RPC method
    /// execution response).
    async fn post_raw(&self, message: impl serde::Serialize) -> Result<Output> {
        let res = self
            .client
            .post(&self.rpc_addr)
            .json(&message)
            .send()
            .await?;
        if res.status() != reqwest::StatusCode::OK {
            anyhow!(
                "Post query responded with a non-OK response: {}",
                res.status()
            );
        }
        let reply: Output = res.json().await.unwrap();

        Ok(reply)
    }
}

/// Structures representing the RPC request messages.
mod messages {
    use serde_derive::Serialize;
    use zksync_models::node::tx::{FranklinTx, PackedEthSignature, TxEthSignature};

    #[derive(Debug, Serialize)]
    pub struct JsonRpcRequest {
        pub id: String,
        pub method: String,
        pub jsonrpc: String,
        pub params: Vec<serde_json::Value>,
    }

    #[derive(Debug, Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct TxWithSignature {
        tx: FranklinTx,
        signature: Option<TxEthSignature>,
    }

    impl JsonRpcRequest {
        fn create(method: impl ToString, params: Vec<serde_json::Value>) -> Self {
            Self {
                id: "1".to_owned(),
                jsonrpc: "2.0".to_owned(),
                method: method.to_string(),
                params,
            }
        }

        pub fn submit_txs_batch(txs: Vec<(FranklinTx, Option<PackedEthSignature>)>) -> Self {
            let txs: Vec<_> = txs
                .into_iter()
                .map(|(tx, signature)| TxWithSignature {
                    tx,
                    signature: signature.map(TxEthSignature::EthereumSignature),
                })
                .collect();

            let mut params = Vec::new();
            params.push(serde_json::to_value(txs).expect("serialization fail"));
            Self::create("submit_txs_batch", params)
        }
    }
}
<filename>src/day04.rs<gh_stars>0
use std::collections::HashMap;

type TParsedVal<'a> = HashMap<&'a str, &'a str>;
type TParsed<'a> = Vec<TParsedVal<'a>>;

pub fn day(input: String) -> (i64, i64) {
    let parsed_input = parse(&input);
    (part_1(&p


[18203] = "Garra derecha de Eskhandar",
[18204] = "Pelambre de Eskhandar",
[18205] = "Collar de Eskhandar",
[18206] = "Espinazo de enano",
[18207] = "Diente orco",
[18208] = "Mantón de Oración",
[18209] = "Bujía energizada",
[18222] = "Vid espinosa",
[18223] = "Pétalo dentado",
[18224] = "Criminosa",
[18225] = "Zapatos de carrera desgastados",
[18226] = "Un pacto sellado",
[18227] = "Pacificador sin sustancia",
[18228] = "Foto autografiada de Tigule",
[18229] = "Guía de pesca extrema de Nat Pagle",
[18230] = "Botón Y.O.G.A.N.O. roto",
[18231] = "Camiseta sin mangas",
[18232] = "Robot de reparación de campo 74A",
[18233] = "Pañuelo manchado de lágrimas",
[18234] = "Documento de Importaciones Bocarda",
[18235] = "Esquema: robot de reparación de campo 74A",
[18236] = "Muñeco masticado de Gordok",
[18237] = "Mandíbula de mastín",
[18238] = "Guantes sombradermos",
[18239] = "Patrón: guantes sombradermos",
[18240] = "Tanino de ogro",
[18241] = "Brida de corcel de guerra negro",
[18242] = "Riendas del tigre de guerra negro",
[18243] = "Zancudo de batalla negro",
[18244] = "Carnero de guerra negro",
[18245] = "Cuerno de lobo de guerra negro",
[18246] = "Silbato del raptor de guerra negro",
[18247] = "Kodo de guerra negro",
[18248] = "Caballo de guerra esquelético rojo",
[18249] = "Llave creciente",
[18250] = "Llave de los grilletes de Gordok",
[18251] = "Refuerzo para armadura del Núcleo",
[18252] = "Patrón: refuerzo para armadura del Núcleo",
[18253] = "Poción de rejuvenecimiento sublime",
[18254] = "Sorpresa de tubérculo runtún",
[18255] = "Tubérculo runtún",
[18256] = "Vial derretido",
[18257] = "Receta: poción de rejuvenecimiento sublime",
[18258] = "Disfraz de ogro Gordok",
[18259] = "Fórmula: encantar arma: poder con hechizos",
[18260] = "Fórmula: encantar arma: poder de sanación",
[18261] = "Libro de Conjuros",
[18262] = "Piedra de afilar elemental",
[18263] = "Brazaletes Bengala del Núcleo",
[18264] = "Diseño: piedra de afilar elemental",
[18265] = "Patrón: brazaletes Bengala del Núcleo",
[18267] = "Receta: sorpresa de tubérculo runtún",
[18269] = "Grog verde de Gordok",
[18282] = "Rifle de tirador del Núcleo",
[18283] = "Acurascopio 247x128 de Biznicks",
[18284] = "Cerveza negra de Kreeg",
[18285] = "Fragmento de maná cristalizado",
[18286] = "Trozo de maná condensado


: addl <x0f=%edi,<x1f=%ebp
addl %edi,%ebp

# qhasm: x0f <<<= 7
# asm 1: rol  $7,<x0f=int32#6
# asm 2: rol  $7,<x0f=%edi
rol  $7,%edi

# qhasm: x1f_stack = x1f
# asm 1: movl <x1f=int32#7,>x1f_stack=stack32#23
# asm 2: movl <x1f=%ebp,>x1f_stack=88(%esp)
movl %ebp,88(%esp)

# qhasm: x07 ^= x1f
# asm 1: xorl <x1f=int32#7,<x07=int32#1
# asm 2: xorl <x1f=%ebp,<x07=%eax
xorl %ebp,%eax

# qhasm: x07_stack = x07
# asm 1: movd <x07=int32#1,>x07_stack=int3232#8
# asm 2: movd <x07=%eax,>x07_stack=%mm7
movd %eax,%mm7

# qhasm: x0f ^= x17
# asm 1: xorl <x17=int32#2,<x0f=int32#6
# asm 2: xorl <x17=%ecx,<x0f=%edi
xorl %ecx,%edi

# qhasm: x0b = x0b_stack
# asm 1: movl <x0b_stack=stack32#27,>x0b=int32#1
# asm 2: movl <x0b_stack=104(%esp),>x0b=%eax
movl 104(%esp),%eax

# qhasm: x11 = x11_stack
# asm 1: movl <x11_stack=stack32#17,>x11=int32#2
# asm 2: movl <x11_stack=64(%esp),>x11=%ecx
movl 64(%esp),%ecx

# qhasm: x15 = x15_stack
# asm 1: movl <x15_stack=stack32#13,>x15=int32#7
# asm 2: movl <x15_stack=48(%esp),>x15=%ebp
movl 48(%esp),%ebp

# qhasm: x11 += x0b
# asm 1: addl <x0b=int32#1,<x11=int32#2
# asm 2: addl <x0b=%eax,<x11=%ecx
addl %eax,%ecx

# qhasm: x0b <<<= 11
# asm 1: rol  $11,<x0b=int32#1
# asm 2: rol  $11,<x0b=%eax
rol  $11,%eax

# qhasm: x11_stack = x11
# asm 1: movl <x11=int32#2,>x11_stack=stack32#13
# asm 2: movl <x11=%ecx,>x11_stack=48(%esp)
movl %ecx,48(%esp)

# qhasm: x15 += x0f
# asm 1: addl <x0f=int32#6,<x15=int32#7
# asm 2: addl <x0f=%edi,<x15=%ebp
addl %edi,%ebp

# qhasm: x0f <<<= 11
# asm 1: rol  $11,<x0f=int32#6
# asm 2: rol  $11,<x0f=%edi
rol  $11,%edi

# qhasm: x15_stack = x15
# asm 1: movl <x15=int32#7,>x15_stack=stack32#17
# asm 2: movl <x15=%ebp,>x15_stack=64(%


amily>? get dependencies => _dependencies;

  static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null;

  @override
  Iterable<ProviderOrFamily>? get allTransitiveDependencies =>
      _allTransitiveDependencies;

  @override
  String? get name => r'sourceSelectorProvider';
}

/// See also [sourceSelector].
class SourceSelectorProvider
    extends AutoDisposeFutureProvider<SourceSelectorModel> {
  /// See also [sourceSelector].
  SourceSelectorProvider(
    ContentDetails contentDetails,
    List<ContentMediaItem> mediaItems,
  ) : this._internal(
        (ref) => sourceSelector(
          ref as SourceSelectorRef,
          contentDetails,
          mediaItems,
        ),
        from: sourceSelectorProvider,
        name: r'sourceSelectorProvider',
        debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
            ? null
            : _$sourceSelectorHash,
        dependencies: SourceSelectorFamily._dependencies,
        allTransitiveDependencies:
            SourceSelectorFamily._allTransitiveDependencies,
        contentDetails: contentDetails,
        mediaItems: mediaItems,
      );

  SourceSelectorProvider._internal(
    super._createNotifier, {
    required super.name,
    required super.dependencies,
    required super.allTransitiveDependencies,
    required super.debugGetCreateSourceHash,
    required super.from,
    required this.contentDetails,
    required this.mediaItems,
  }) : super.internal();

  final ContentDetails contentDetails;
  final List<ContentMediaItem> mediaItems;

  @override
  Override overrideWith(
    FutureOr<SourceSelectorModel> Function(SourceSelectorRef provider) create,
  ) {
    return ProviderOverride(
      origin: this,
      override: SourceSelectorProvider._internal(
        (ref) => create(ref as SourceSelectorRef),
        from: from,
        name: null,
        dependencies: null,
        allTransitiveDependencies: null,
        debugGetCreateSourceHash: null,
        contentDetails: contentDetails,
        mediaItems: mediaItems,
      ),
    );
  }

  @override
  AutoDisposeFutureProviderElement<SourceSelectorModel> createElement() {
    return _SourceSelectorProviderElement(this);
  }

  @override
  bool operator ==(Object other) {
    return other is SourceSelectorProvider &&
        other.contentDetails == contentDetails &&
        other.mediaItems == mediaItems;
  }

  @override
  int get hashCode {
    var hash = _SystemHash.combine(0, runtimeType.hashCode);
    hash = _SystemHash.combine(hash, contentDetails.hashCode);
    hash = _SystemHash.combine(hash, mediaItems.hashCode);

    return _SystemHash.finish(hash);
  }
}

@Deprecated('Will be removed in 3.0. Use Ref instead')
// ignore: unused_element
mixin SourceSelectorRef on AutoDisposeFutureProviderRef<SourceSelectorModel> {
  /// The parameter `contentDetails` of this provider.
  ContentDetails get contentDetails;

  /// The parameter `mediaItems` of this provider.
  List<ContentMediaItem> get mediaItems;
}

class _SourceSelectorProviderElement
    extends AutoDisposeFutureProviderElement<SourceSelectorModel>
    with SourceSelectorRef {
  _SourceSelectorProviderElement(super.provider);

  @override
  ContentDetails get contentDetails =>
      (origin as SourceSelectorProvider).contentDetails;
  @override
  List<ContentMediaItem> get mediaItems =>
      (origin as SourceSelectorProvider).mediaItems;
}

String _$subtitlesOffsetHash() => r'ca269576b78821079311fdc31ae931b964c9e830';

/// See also [SubtitlesOffset].
@ProviderFor(SubtitlesOffset)
final subtitlesOffsetProvider =
    AutoDisposeNotifierProvider<SubtitlesOffset, Duration>.internal(
      SubtitlesOffset.new,
      name: r'subtitlesOffsetProvider',


 d="M12 2C6.486 2 2 6.486 2 12s4.486 10 10 10s10-4.486 10-10S17.514 2 12 2z"/>',
    },
    'circle-half': { body: '<path fill="currentColor" d="M12 2h-1v20h1a10 10 0 0 0 0-20z"/>' },
    'circle-quarter': {
      body: '<path fill="currentColor" d="M12 2h-1v11h11v-1A10 10 0 0 0 12 2z"/>',
    },
    'circle-three-quarter': {
      body: '<path fill="currentColor" d="M12 2h-1v9H2v1a10 10 0 0 0 17.07 7.07A10 10 0 0 0 12 2z"/>',
    },
    city: {
      body: '<path fill="currentColor" d="M21 6h-4V3a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7H3a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h18a1 1 0 0 0 1-1V7a1 1 0 0 0-1-1zM6 18H4v-2h2v2zm0-4H4v-2h2v2zm5 4H9v-2h2v2zm0-4H9v-2h2v2zm0-4H9V8h2v2zm0-4H9V4h2v2zm4 12h-2v-2h2v2zm0-4h-2v-2h2v2zm0-4h-2V8h2v2zm0-4h-2V4h2v2zm5 12h-2v-2h2v2zm0-4h-2v-2h2v2zm0-4h-2V8h2v2z"/>',
    },
    clinic: {
      body: '<path fill="currentColor" d="m21.743 12.331l-9-10c-.379-.422-1.107-.422-1.486 0l-9 10a.998.998 0 0 0-.17 1.076c.16.361.518.593.913.593h2v7a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-7h2a.998.998 0 0 0 .743-1.669zM16 15h-3v3h-2v-3H8v-2h3v-3h2v3h3v2z"/>',
    },
    cloud: {
      body: '<path fill="currentColor" d="M18.944 11.112C18.507 7.67 15.56 5 12 5C9.244 5 6.85 6.611 5.757 9.15C3.609 9.792 2 11.82 2 14c0 2.757 2.243 5 5 5h11c2.206 0 4-1.794 4-4a4.01 4.01 0 0 0-3.056-3.888z"/>',
    },
    'cloud-download': {
      body: '<path fill="currentColor" d="M18.944 11.112C18.507 7.67 15.56 5 12 5C9.244 5 6.85 6.61 5.757 9.149C3.609 9.792 2 11.82 2 14c0 2.657 2.089 4.815 4.708 4.971V19H17.99v-.003L18 19c2.206 0 4-1.794 4-4a4.008 4.008 0 0 0-3.056-3.888zM8 12h3V9h2v3h3l-4 5l-4-5z"/>',
    },
    'cloud-lightning': {
      body: '<path fill="currentColor" d="M18.944 10.112C18.507 6.67 15.56 4 12 4C9.244 4 6.85 5.611 5.757 8.15C3.609 8.792 2 10.82 2 13c0 2.757 2.243 5 5 5h1.333L10 13h4l-2 3h2.975l-1.


 = new QueryWrapper<>();
		onlineTplQueryWrapper.eq("list_id", model.getListId());
		OnlineTpl onlineTpl = this.getOne(onlineTplQueryWrapper);
		if(onlineTpl != null && onlineTpl.getCreator().longValue() == userInfoDto.getUserId().longValue())
		{
			if(model.getRangeAuth() != null) {
				String rangeAxis = model.getRangeAuth().getString("rangeAxis");
				String sheetIndex = model.getRangeAuth().getString("sheetIndex");
				QueryWrapper<ReportRangeAuth> rangeAuthQueryWrapper = new QueryWrapper<>();
				rangeAuthQueryWrapper.eq("tpl_id", onlineTpl.getId());
				rangeAuthQueryWrapper.eq("sheet_index", sheetIndex);
				rangeAuthQueryWrapper.eq("range_txt", rangeAxis);
				ReportRangeAuth rangeAuth = this.iReportRangeAuthService.getOne(rangeAuthQueryWrapper);
				if(rangeAuth != null) {
					this.iReportRangeAuthService.removeById(rangeAuth.getId());
					//删除用户授权信息
					QueryWrapper<ReportRangeAuthUser> reportRangeAuthUserQueryWrapper = new QueryWrapper<>();
					reportRangeAuthUserQueryWrapper.eq("tpl_id", onlineTpl.getId());
					reportRangeAuthUserQueryWrapper.eq("range_auth_id", rangeAuth.getId());
					this.iReportRangeAuthUserService.remove(reportRangeAuthUserQueryWrapper);
				}
			}
		}

	}

	/**
	 * @MethodName: getCoeditAuth
	 * @Description: 获取协同文档授权范围
	 * @author caiyang
	 * @param model
	 * @param userInfoDto
	 * @return
	 * @see com.springreport.api.coedit.ICoeditService#getCoeditAuth(com.springreport.entity.onlinetpl.OnlineTpl, com.springreport.base.UserInfoDto)
	 * @date 2024-03-11 12:01:22
	 */
	@Override
	public JSONObject getCoeditAuth(OnlineTpl model, UserInfoDto userInfoDto) {
		QueryWrapper<OnlineTpl> onlineTplQueryWrapper = new QueryWrapper<>();
		onlineTplQueryWrapper.eq("list_id", model.getListId());
		model = this.getOne(onlineTplQueryWrapper, false);
		JSONObject sheetRangeAuth = new JSONObject();
		if(model != null)
		{
			//获取用户对应的权限
			QueryWrapper<ReportRangeAuthUser> rangeAuthUserQueryWrapper = new QueryWrapper<>();
			rangeAuthUserQueryWrapper.eq("tpl_id", model.getId());
			rangeAuthUserQueryWrapper.eq("user_id", userInfoDto.getUserId());
			rangeAuthUserQueryWrapper.eq("del_flag", DelFlagEnum.UNDEL.getCode());
			List<ReportRangeAuthUser> reportRangeAuthUsers = this.iReportRangeAuthUserService.list(rangeAuthUserQueryWrapper);
			if(ListUtil.isNotEmpty(reportRangeAuthUsers))
			{
				List<Long> authRangeIds = new ArrayList<>();
				JSONObject rangeAuthType = new JSONObject();
				for (int i = 0; i < reportRangeAuthUsers.size(); i++) {
					authRangeIds.add(reportRangeAuthUsers.get(i).getRangeAuthId());
					rangeAuthType.put(String.valueOf(reportRangeAuthUsers.get(i).getRangeAuthId()), reportRangeAuthUsers.get(i).getAuthType());
				}
				//获取对应的权限操作范围
				QueryWrapper<ReportRangeAuth> queryWrapper = new QueryWrapper<>();
				queryWrapper.in("id", authRangeIds);
				List<ReportRangeAuth> reportRangeAuths = this.iReportRangeAuthService.list(queryWrapper);
				if(ListUtil.isNotEmpty(reportRangeAuths))
				{
					for (int i = 0; i < reportRangeAuths.size(); i++) {
						JSONObject rangeAxis = new JSONObject();
						rangeAxis


      if (existFile.indexOf(binary.prefix()) === 0) {
        let editExistFile = existFile.replace(binary.prefix(), '');
        // if the suffix matches the executable suffix, add it
        if (binary.suffix() === binary.executableSuffix()) {
          versions.push(editExistFile.replace(binary.suffix(), ''));
        }
        // if the suffix does not match the executable,
        // the binary is something like: .exe and .zip
        // TODO(cnishina): fix implementation. Suffix method is dependent on the version number
        // example: chromedriver < 2.23 has a different suffix than 2.23+ (mac32.zip vs mac64.zip).
        else if (
            !existFile.endsWith('.zip') && !existFile.endsWith('.tar.gz') &&
            existFile.indexOf(binary.suffix()) === -1) {
          editExistFile = editExistFile.replace(binary.executableSuffix(), '');
          editExistFile = editExistFile.indexOf('_') === 0 ?
              editExistFile.substring(1, editExistFile.length) :
              editExistFile;
          versions.push(editExistFile);
        }
      }
    }
    if (versions.length === 0) {
      return null;
    }
    let downloadedBinary = new DownloadedBinary(binary);
    downloadedBinary.versions = versions;
    return downloadedBinary;
  }

  /**
   * Finds all the downloaded binary versions stored in the output directory.
   * @param outputDir The directory where files are downloaded and stored.
   * @returns An dictionary map of all the downloaded binaries found in the output folder.
   */
  static downloadedBinaries(outputDir: string): BinaryMap<DownloadedBinary> {
    let ostype = Config.osType();
    let arch = Config.osArch();
    let binaries = FileManager.setupBinaries();
    let existingFiles = FileManager.getExistingFiles(outputDir);
    let downloaded: BinaryMap<DownloadedBinary> = {};
    for (let bin in binaries) {
      let binary = FileManager.downloadedVersions_(binaries[bin], ostype, arch, existingFiles);
      if (binary != null) {
        downloaded[binary.id()] = binary;
      }
    }
    return downloaded;
  }

  /**
   * Try to download the binary version.
   * @param binary The binary of interest.
   * @param outputDir The directory where files are downloaded and stored.
   * @returns Promise resolved to true for files downloaded, resolved to false for files not
   *          downloaded because they exist, rejected if there is an error.
   */
  static downloadFile<T extends Binary>(binary: T, outputDir: string, callback?: Function):
      Promise<boolean> {
    return new Promise<boolean>((resolve, reject) => {
      let outDir = Config.getSeleniumDir();
      let downloaded: BinaryMap<DownloadedBinary> = FileManager.downloadedBinaries(outputDir);
      let contentLength = 0;

      // Pass options down to binary to make request to get the latest version to download.
      binary.getUrl(binary.version()).then(fileUrl => {
        binary.versionCustom = fileUrl.version;
        let filePath = path.resolve(outputDir, binary.filename());
        let fileName = binary.filename();

        // If we have downloaded the file before, check the content length
        if (downloaded[binary.id()]) {
          let downloadedBinary = downloaded[binary.id()];
          let versions = downloadedBinary.versions;
          let version = binary.versionCustom;

          for (let index in versions) {
            let v = versions[index];
            if (v === version) {
              contentLength = fs.statSync(filePath).size;

              Downloader.getFile(binary, fileUrl.url, fileName, outputDir, contentLength, callback)
                  .


   } else {
                if (!hasFenceGateRecipe) {
                    ModHandler.addShapedRecipe(name + "_fence_gate", entry.fenceGate.copy(),
                            "SPS", "SPS",
                            'P', entry.planks.copy(),
                            'S', entry.getStick());
                }
            }

            // plank -> fence gate assembling
            ASSEMBLER_RECIPES.recipeBuilder()
                    .inputs(GTUtility.copy(2, entry.planks))
                    .input(entry.getStick().toString(), 2)
                    .outputs(entry.fenceGate.copy())
                    .circuitMeta(2)
                    .duration(100).EUt(4).buildAndRegister();
        }

        // boat
        if (!entry.boat.isEmpty()) {
            final boolean hasBoatRecipe = entry.boatRecipeName != null;
            if (ConfigHolder.recipes.hardWoodRecipes) {
                if (!entry.slab.isEmpty()) {
                    // hard plank -> boat crafting
                    if (hasBoatRecipe) {
                        ModHandler.removeRecipeByName(new ResourceLocation(entry.modid, entry.boatRecipeName));
                    }

                    ModHandler.addShapedRecipe(hasBoatRecipe ? entry.boatRecipeName : name + "_boat", entry.boat.copy(),
                            "PHP", "PkP", "SSS",
                            'P', entry.planks.copy(),
                            'S', entry.slab.copy(),
                            'H', new ItemStack(Items.WOODEN_SHOVEL));
                }
            } else {
                if (!hasBoatRecipe) {
                    ModHandler.addShapedRecipe(name + "_boat", entry.boat.copy(),
                            "P P", "PPP",
                            'P', entry.planks.copy());
                }
            }

            // plank -> boat assembling
            ASSEMBLER_RECIPES.recipeBuilder()
                    .inputs(GTUtility.copy(5, entry.planks))
                    .outputs(entry.boat.copy())
                    .circuitMeta(15)
                    .duration(100).EUt(4).buildAndRegister();
        }
    }

    /**
     * Standard recipes for GT woods
     */
    private static void registerGTWoodRecipes() {
        ModHandler.addShapedRecipe("treated_wood_planks",
                MetaBlocks.PLANKS.getItemVariant(BlockGregPlanks.BlockType.TREATED_PLANK, 8),
                "PPP", "PBP", "PPP",
                'P', "plankWood",
                'B', FluidUtil.getFilledBucket(Creosote.getFluid(1000)));

        ModHandler.addShapedRecipe("treated_wood_stick",
                OreDictUnifier.get(OrePrefix.stick, TreatedWood, ConfigHolder.recipes.nerfWoodCrafting ? 2 : 4),
                "L", "L",
                'L', MetaBlocks.PLANKS.getItemVariant(BlockGregPlanks.BlockType.TREATED_PLANK));
        if (ConfigHolder.recipes.nerfWoodCrafting) {
            ModHandler.addShapedRecipe("treated_wood_stick_saw", OreDictUnifier.get(OrePrefix.stick, TreatedWood, 4),
                    "s", "L", "L",
                    'L', MetaBlocks.PLANKS.getItemVariant(BlockGregPlanks.BlockType.TREATED_PLANK));
        }
    }

    /**
     * Pyrolyse recipes
     */
    private static void registerPyrolyseOvenRecipes() {
        // Logs ================================================

        // Charcoal Byproducts
        PYROLYSE_RECIPES.recipeBuilder().circuitMeta(4)
                .input(log, Wood, 16)
                .fluidInputs(Nitrogen.getFluid(1000))
                .outputs(new ItemStack(Items.COAL, 20, 1))
                .fluidOutputs(CharcoalByproducts.getFluid(4000))
                .duration(320).EUt(96)
                .buildAndRegister();


,
    PROCESS_COLOR_SCHEME_NAME,
    canonicalizeName,
    canonicalizeProcessName,
  };
});
</script>
<!DOCTYPE html>
<!--
Copyright 2016 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/tracing/extras/chrome/event_finder_utils.html">
<link rel="import" href="/tracing/value/histogram_set.html">

<script>
'use strict';
tr.exportTo('tr.e.chrome', function() {
  // TODO(dproy): Because title and category are properties of TimedEvent
  // subclasses and not TimedEvent itself, we have to write our own "has title
  // and category" function rather than having it provided by TimedEvent.
  // This should be fixed.
  // https://github.com/catapult-project/catapult/issues/2784
  function hasTitleAndCategory(event, title, category) {
    return event.title === title && event.category &&
      tr.b.getCategoryParts(event.category).includes(category);
  }

  function getNavStartTimestamps(rendererHelper) {
    const navStartTimestamps = [];
    for (const e of rendererHelper.mainThread.sliceGroup.childEvents()) {
      if (hasTitleAndCategory(e, 'navigationStart', 'blink.user_timing')) {
        navStartTimestamps.push(e.start);
      }
    }
    return navStartTimestamps;
  }

  /**
   * Returns a map of renderer PIDs to array of timestamps at which the
   * renderer became interactive.
   */
  function getInteractiveTimestamps(model) {
    const interactiveTimestampsMap = new Map();
    const chromeHelper = model.getOrCreateHelper(
        tr.model.helpers.ChromeModelHelper);
    for (const rendererHelper of Object.values(chromeHelper.rendererHelpers)) {
      const timestamps = [];
      interactiveTimestampsMap.set(rendererHelper.pid, timestamps);
    }
    for (const expectation of model.userModel.expectations) {
      if (!(expectation instanceof tr.model.um.LoadExpectation)) continue;
      if (tr.e.chrome.CHROME_INTERNAL_URLS.includes(
          expectation.url)) {
        continue;
      }
      if (expectation.timeToInteractive === undefined) continue;
      if (interactiveTimestampsMap.get(expectation.renderProcess.pid) ===
        undefined) {
        interactiveTimestampsMap.set(expectation.renderProcess.pid, []);
      }
      interactiveTimestampsMap.get(expectation.renderProcess.pid).push(
          expectation.timeToInteractive);
    }
    return interactiveTimestampsMap;
  }

  /**
   * Returns an Array of task windows that start with the supplied interactive
   * timestamps.
   *
   * A task window is defined as the range of time from the time when the page
   * became interactive until either
   *
   *   1. The beginning of the next navigationStart event or
   *   2. The end of the trace
   *
   * This function only works when timestamps are from the same renderer. If
   * windows for multiple renderers need to be computed, the timestamps should
   * be separated for each renderer and this function should be called
   * separately for each.
   *
   * @param {!Array.<number>} interactiveTimestamps
   * @param {!Array.<number>} navStartTimestamps
   * @param {!number} traceEndTimestamp
   * @returns {!Array.<tr.b.math.Range>}
   */
  function getPostInteractiveTaskWindows(
      interactiveTimestamps, navStartTimestamps


import pytest
from charset_normalizer.md import mess_ratio

@pytest.mark.parametrize(
    "content, min_expected_ratio, max_expected_ratio",
    [
        ('典肇乎庚辰年十二月廿一，及己丑年二月十九，收各方語言二百五十，合逾七百萬目；二十大卷佔八成，單英文卷亦過二百萬。悉文乃天下有志共筆而成；有意助之，幾網路、隨纂作，大典茁焉。', 0., 0.),
        ('العقلية , التنويم المغناطيسي و / أو الاقتراح', 0., 0.),
        ("RadoZ تـــعــــديــل الـــتــــوقــيــــت مـــن قــبــل", 0., 0.),
        ("Cehennemin Sava■þ²s²'da kim?", 0.1, 0.5),
        ("´Á¥½³ø§i --  ±i®Ìºû, ³¯·Ø©v", 0.5, 1.),
        ("ïstanbul, T■rkiye'nin en kalabal»k, iktisadi ve k■lt■rel aÓ»dan en —nemli", 0.1, 0.5),
        ("<i>Parce que Óa, c'est la vÕritable histoire de la rencontre avec votre Tante Robin.</i>", 0.01, 0.5),
        ("""ØĢØŠØģØ§ØĶŲ ŲŲ ØĢŲ Ø§ŲŲØ§Øģ ŲŲŲ ŲØ§ ØģŲŲŲØŠØģØ§ØĶŲŲŲØ ØŊØđŲØ§ ŲØģŲØđ ØđŲ (ŲØąŲØŊŲ) ŲØ§ŲØŪØ§ØŠŲ""", 0.8, 3.0),
        ("""ÇáÚŞáíÉ , ÇáÊäæíã ÇáãÛäÇØíÓí æ / Ãæ ÇáÇŞÊÑÇÍ""", 0.8, 2.5),
        ("""hishamkoc@yahoo.com ุชุฑุฌูููุฉ ููุดูููุงู ุงููููููููุงูRadoZ ุชูููุนููููุฏูููู ุงููููุชูููููููููููููุช ููููู ูููุจููู""", 0.5, 2.0)

    ]
)
def test_mess_detection(content, min_expected_ratio, max_expected_ratio):
    calculated_mess_ratio = mess_ratio(
        content,
        maximum_threshold=1.
    )

    assert min_expected_ratio <= calculated_mess_ratio <= max_expected_ratio, "The mess detection ratio calculated for given content is not well adjusted!"


StringParam(r, "search", ""); searchQuery != "" {
		builder.WithSearchQuery(searchQuery)
	}
}
// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package locale // import "miniflux.app/v2/internal/locale"

import "testing"

func TestPluralRules(t *testing.T) {
	scenarios := map[string]map[int]int{
		// Default rule (covers fr_FR, pt_BR, tr_TR, and other unlisted languages)
		"default": {
			0: 0, // n <= 1
			1: 0, // n <= 1
			2: 1, // n > 1
			5: 1, // n > 1
		},
		// Arabic (ar_AR) - 6 forms
		"ar_AR": {
			0:   0, // n == 0
			1:   1, // n == 1
			2:   2, // n == 2
			3:   3, // n%100 >= 3 && n%100 <= 10
			5:   3, // n%100 >= 3 && n%100 <= 10
			10:  3, // n%100 >= 3 && n%100 <= 10
			11:  4, // n%100 >= 11
			15:  4, // n%100 >= 11
			99:  4, // n%100 >= 11
			100: 5, // default case (n%100 == 0, doesn't match any condition)
			101: 5, // default case (n%100 == 1, but n != 1)
			200: 5, // default case
		},
		// Czech (cs_CZ) - 3 forms
		"cs_CZ": {
			1: 0, // n == 1
			2: 1, // n >= 2 && n <= 4
			3: 1, // n >= 2 && n <= 4
			4: 1, // n >= 2 && n <= 4
			5: 2, // default case
		},
		// French (fr_FR) - uses default rule
		"fr_FR": {
			0: 0, // n <= 1
			1: 0, // n <= 1
			2: 1, // n > 1
			5: 1, // n > 1
		},
		// Indonesian (id_ID) - always form 0
		"id_ID": {
			0:   0,
			1:   0,
			5:   0,
			100: 0,
		},
		// Japanese (ja_JP) - always form 0
		"ja_JP": {
			0:   0,
			1:   0,
			2:   0,
			5:   0,
			100: 0,
		},
		// Polish (pl_PL) - 3 forms
		"pl_PL": {
			1:  0, // n == 1
			2:  1, // n%10 >= 2 && n%10 <= 4 && (n%100 < 10 || n%100 >= 20)
			3:  1, // n%10 >= 2 && n%10 <= 4 && (n%100 < 10 || n%100 >= 20)
			4:  1, // n%10 >= 2 && n%10 <= 4 && (n%100 < 10 || n%100 >= 20)
			5:  2, // default case
			10: 2, // default case (n%100 < 10, but n%10 not in 2-4)
			11: 2, // default case (n%100 >= 10 and < 20)
			12: 2, // default case (n%100 >= 10 and < 20)
			22: 1, // n%10 >= 2 && n%10 <= 4 && (n%100 >= 20)
			24: 1, // n%10 >= 2 && n%10 <= 4 && (n%100 >= 20)
		},
		// Portuguese Brazilian (pt_BR) - uses default rule
		"pt_BR": {
			0: 0, // n <= 1
			1: 0, // n <= 1
			2: 1, // n > 1
			5: 1, // n


tooltipText);
	else
		if ( GameTooltip.canAddRestStateLine ) then
			GameTooltip:AddLine("\n"..tooltipText);
			GameTooltip:Show();
			GameTooltip.canAddRestStateLine = nil;
		end
	end
end

function HonorLevelUpBanner_OnLoad(self)
	self:RegisterEvent("HONOR_LEVEL_UPDATE");
end

function HonorLevelUpBanner_OnEvent(self, event, ...)
	if (event == "HONOR_LEVEL_UPDATE") then
        local showBanner = ...;
        if (showBanner) then
		    local level = UnitHonorLevel("player");
            self.Title:SetText(HONOR_LEVEL_LABEL:format(level));
			self.TitleFlash:SetText(HONOR_LEVEL_LABEL:format(level));
			self:Show();
			self.Anim:Play();
			self.currentLevel = level;
		end
	end
end

function PrestigeLevelUpBanner_OnLoad(self)


)) {
        Register CopyReg = createResultReg(&X86::GR32RegClass);
        BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::MOV32rr),
                CopyReg)
            .addReg(Reg);

        Register ExtReg = createResultReg(&X86::GR64RegClass);
        BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
                TII.get(TargetOpcode::SUBREG_TO_REG), ExtReg)
            .addImm(0)
            .addReg(CopyReg)
            .addImm(X86::sub_32bit);
        Reg = ExtReg;
      }

      return Reg;
    };

    if (AM.Base.Reg == 0) {
      AM.Base.Reg = GetCallRegForValue(V);
      return AM.Base.Reg != 0;
    }
    if (AM.IndexReg == 0) {
      assert(AM.Scale == 1 && "Scale with no index!");
      AM.IndexReg = GetCallRegForValue(V);
      return AM.IndexReg != 0;
    }
  }

  return false;
}

/// X86SelectStore - Select and emit code to implement store instructions.
bool X86FastISel::X86SelectStore(const Instruction *I) {
  // Atomic stores need special handling.
  const StoreInst *S = cast<StoreInst>(I);

  if (S->isAtomic())
    return false;

  const Value *PtrV = I->getOperand(1);
  if (TLI.supportSwiftError()) {
    // Swifterror values can come from either a function parameter with
    // swifterror attribute or an alloca with swifterror attribute.
    if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
      if (Arg->hasSwiftErrorAttr())
        return false;
    }

    if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
      if (Alloca->isSwiftError())
        return false;
    }
  }

  const Value *Val = S->getValueOperand();
  const Value *Ptr = S->getPointerOperand();

  MVT VT;
  if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
    return false;

  Align Alignment = S->getAlign();
  Align ABIAlignment = DL.getABITypeAlign(Val->getType());
  bool Aligned = Alignment >= ABIAlignment;

  X86AddressMode AM;
  if (!X86SelectAddress(Ptr, AM))
    return false;

  return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
}

/// X86SelectRet - Select and emit code to implement ret instructions.
bool X86FastISel::X86SelectRet(const Instruction *I) {
  const ReturnInst *Ret = cast<ReturnInst>(I);
  const Function &F = *I->getParent()->getParent();
  const X86MachineFunctionInfo *X86MFInfo =
      FuncInfo.MF->getInfo<X86MachineFunctionInfo>();

  if (!FuncInfo.CanLowerReturn)
    return false;

  if (TLI.supportSwiftError() &&
      F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
    return false;

  if (TLI.supportSplitCSR(FuncInfo.MF))
    return false;

  CallingConv::ID CC = F.getCallingConv();
  if (CC != CallingConv::C &&
      CC != CallingConv::Fast &&
      CC != CallingConv::Tail &&
      CC != CallingConv::SwiftTail &&
      CC != CallingConv::X86_FastCall &&
      CC != CallingConv::X86_StdCall &&
      CC != CallingConv::X86_ThisCall &&
      CC != CallingConv::X86_64_SysV &&
      CC != CallingConv::Win64)
    return false;

  // Don't handle popping bytes if they don't fit the ret's immediate.
  if (!isUInt<16>(X86MFInfo->getBytesToPopOnReturn()))
    return false;

  // fastcc with -tailcallopt is intended to provide a guaranteed
  // tail call optimization


.components.tables;

import com.typesafe.config.Config;
import com.typesafe.config.ConfigValueFactory;
import org.apache.drill.categories.MetastoreTest;
import org.apache.drill.common.config.DrillConfig;
import org.apache.drill.metastore.MetastoreColumn;
import org.apache.drill.metastore.MetastoreRegistry;
import org.apache.drill.metastore.config.MetastoreConfigConstants;
import org.apache.drill.metastore.expressions.FilterExpression;
import org.apache.drill.metastore.metadata.MetadataInfo;
import org.apache.drill.metastore.metadata.MetadataType;
import org.apache.drill.metastore.metadata.TableInfo;
import org.apache.drill.metastore.operate.Delete;
import com.google.common.collect.Sets;
import org.apache.drill.test.BaseTest;
import org.junit.After;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

@Category(MetastoreTest.class)
public abstract class AbstractTablesMetastoreTest extends BaseTest {

  @ClassRule
  public static TemporaryFolder defaultFolder = new TemporaryFolder();

  protected static Tables tables;

  protected static void innerInit(Config config, Class<?> implementationClass) {
    DrillConfig drillConfig = new DrillConfig(config
      .withValue(MetastoreConfigConstants.USE_PROVIDED_CONFIG,
        ConfigValueFactory.fromAnyRef(true))
      .withValue(MetastoreConfigConstants.IMPLEMENTATION_CLASS,
        ConfigValueFactory.fromAnyRef(implementationClass.getName())));
    tables = new MetastoreRegistry(drillConfig).get().tables();
  }

  @After
  public void cleanUp() {
    tables.modify().purge();
  }

  @Test
  public void testWriteReadAllFieldTypes() {
    TableInfo tableInfo = TableInfo.builder()
      .storagePlugin("dfs")
      .workspace("tmp")
      .name("nation")
      .build();

    TableMetadataUnit tableUnit = TableMetadataUnit.builder()
      .storagePlugin(tableInfo.storagePlugin())
      .workspace(tableInfo.workspace())
      .tableName(tableInfo.name())
      .metadataKey(MetadataInfo.GENERAL_INFO_KEY)
      .metadataType(MetadataType.TABLE.name())
      .metadataStatistics(Collections.singletonList("{\"statisticsValue\":2.1," +
        "\"statisticsKind\":{\"name\":\"approx_count_distinct\"}}"))
      .columnsStatistics(Collections.singletonMap("`name`", "{\"statistics\":[{\"statisticsValue\":\"aaa\"," +
        "\"statisticsKind\":{\"exact\":true,\"name\":\"minValue\"}},{\"statisticsValue\":\"zzz\"," +
        "\"statisticsKind\":{\"exact\":true,\"name\":\"maxValue\"}}],\"type\":\"VARCHAR\"}"))
      .lastModifiedTime(System.currentTimeMillis())
      .build();

    TableMetadataUnit rowGroupUnit = TableMetadataUnit.builder()
      .storagePlugin(tableInfo.storagePlugin())
      .workspace(tableInfo.workspace())
      .tableName(tableInfo.name())
      .metadataKey("1994")
      .metadataIdentifier("1994/Q1/0_0_0.parquet/1")
      .metadataType(MetadataType.ROW_GROUP.name())
      .lastModifiedTime(System.currentTimeMillis())
      .location("/tmp/nation")
      .path("/tmp/nation/1/0_0_0.parquet")
      .rowGroupIndex(1)
      .hostAffinity(Colle


_tuple__37;
static PyObject *__pyx_tuple__38;
static PyObject *__pyx_tuple__39;
static PyObject *__pyx_tuple__40;
static PyObject *__pyx_tuple__41;
static PyObject *__pyx_tuple__42;
static PyObject *__pyx_tuple__44;
static PyObject *__pyx_tuple__45;
static PyObject *__pyx_tuple__46;
static PyObject *__pyx_tuple__47;
static PyObject *__pyx_tuple__49;
static PyObject *__pyx_tuple__51;
static PyObject *__pyx_tuple__52;
static PyObject *__pyx_tuple__53;
static PyObject *__pyx_tuple__54;
static PyObject *__pyx_tuple__55;
static PyObject *__pyx_tuple__56;
static PyObject *__pyx_codeobj__50;
static PyObject *__pyx_codeobj__57;
/* Late includes */

/* "spacy/matcher/dependencymatcher.pyx":31
 *     cdef public object _ops
 *
 *     def __init__(self, vocab, *, validate=False):             # <<<<<<<<<<<<<<
 *         """Create the DependencyMatcher.
 *
 */

/* Python wrapper */
static int __pyx_pw_5spacy_7matcher_17dependencymatcher_17DependencyMatcher_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static char __pyx_doc_5spacy_7matcher_17dependencymatcher_17DependencyMatcher___init__[] = "Create the DependencyMatcher.\n\n        vocab (Vocab): The vocabulary object, which must be shared with the\n            documents the matcher will operate on.\n        validate (bool): Whether patterns should be validated, passed to\n            Matcher as `validate`\n        ";
#if CYTHON_UPDATE_DESCRIPTOR_DOC
struct wrapperbase __pyx_wrapperbase_5spacy_7matcher_17dependencymatcher_17DependencyMatcher___init__;
#endif
static int __pyx_pw_5spacy_7matcher_17dependencymatcher_17DependencyMatcher_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
  PyObject *__pyx_v_vocab = 0;
  PyObject *__pyx_v_validate = 0;
  int __pyx_lineno = 0;
  const char *__pyx_filename = NULL;
  int __pyx_clineno = 0;
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("__init__ (wrapper)", 0);
  {
    static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_vocab,&__pyx_n_s_validate,0};
    PyObject* values[2] = {0,0};
    values[1] = ((PyObject *)Py_False);
    if (unlikely(__pyx_kwds)) {
      Py_ssize_t kw_args;
      const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
      switch (pos_args) {
        case  1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
        CYTHON_FALLTHROUGH;
        case  0: break;
        default: goto __pyx_L5_argtuple_error;
      }
      kw_args = PyDict_Size(__pyx_kwds);
      switch (pos_args) {
        case  0:


 true;
        return communicateOthers(
          JSON.stringify({
            type,
            message: { locked: game.locked, color: message }
          })
        );
      case "leftGame":
        console.log("player has left the game");
        break;
      case "newGame":
        console.log("received request for new game");
        game.locked = newLocked();
        return communicateAll(
          (console.log(game.locked),
          JSON.stringify({ type: "newGame", message: game.locked }))
        );
      default:
        break;
    }
  };
};

wss.on("connection", ws => {
  console.log("connected");
  const messageReducer = wsReducer(ws, wss.clients);
  ws.on("message", messageReducer);
});

wss.on("close", () => {
  console.log("closed");
});

app.get("/", (req: Request, res: Response) => {
  console.log("NO! This is http. I am not a Krusty Krab.");
});

server.listen(port, "localhost", () => {
  console.log(`Listening on port ${port}`);
});
/*********************
 *                   *
 *   Analysis code   *
 *                   *
 *********************/
function _analyzeSandboxing(frameEl, errback) {
  /*jshint maxstatements:45 */
  //
  // An interesting note from: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe
  //
  // NOTE:
  //   "When the embedded document has the same origin as the main
  //    page, it is strongly discouraged to use both allow-scripts
  //    and allow-same-origin at the same time, as that allows the
  //    embedded document to programmatically remove the sandbox
  //    attribute. Although it is accepted, this case is no more
  //    secure than not using the sandbox attribute."
  //
  // So... let's give that a try, too! >=D
  //
  var sandboxAllowances, resandboxable, resandboxAllowances, resandboxLossless, result = {
    sandboxed: undefined,
    sandboxAllowances: undefined,
    unsandboxable: undefined,
    resandboxable: undefined,
    errors: []
  };
  if (this._isFrameElement(frameEl)) {
    // Is sandboxed?
    try {
      result.sandboxed = frameEl.hasAttribute("sandbox");
    } catch (sandboxErr) {
      result.sandboxed = null;
      if (typeof errback === "function") {
        errback(sandboxErr);
      }
    }
    // Get sandbox configuration
    if (result.sandboxed) {
      try {
        sandboxAllowances = frameEl.getAttribute("sandbox") || "";
      } catch (sandboxErr) {
        sandboxAllowances = null;
        if (typeof errback === "function") {
          errback(sandboxErr);
        }
      }
    } else if (result.sandboxed === null) {
      sandboxAllowances = null;
    }
    if (sandboxAllowances === null || typeof sandboxAllowances === "string") {
      result.sandboxAllowances = this._createAllowancesMap(sandboxAllowances);
    }
    // Analyze desandboxability
    if (result.sandboxed) {
      try {
        frameEl.removeAttribute("sandbox");
        result.unsandboxable = !frameEl.hasAttribute("sandbox");
      } catch (sandboxErr) {
        result.unsandboxable = false;
        if (typeof errback === "function") {
          errback(sandboxErr);
        }
      }
    }
    // Analyze resandboxability
    if (result.unsandboxable && typeof sandboxAllowances === "string") {
      try {
        frameEl.setAttribute("sandbox", sandboxAllowances);


class="has-results">

 results matching ""

No results matching ""


License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::{
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
};

use async_trait::async_trait;
use tokio::{
    io::{AsyncRead, AsyncWrite, ReadBuf},
    sync::Mutex,
};
use tonic::{
    body::BoxBody,
    codegen::http::{Request, Response},
    transport::{server::Connected, Body, Channel, Endpoint, NamedService, Server, Uri},
};
use tower::Service;

use super::{Discover, ServiceType, Svc};
use crate::{
    blobstore::MemBlobStore,
    cache::{
        cachepb::{
            bucket_service_server::BucketServiceServer as NodeBucketServiceServer,
            node_cache_manage_service_server::NodeCacheManageServiceServer,
        },
        CacheReader, CacheReplica, MemCacheStore, NodeBucketService, NodeCacheManager, Uploader,
    },
    client::apipb::{
        blob_upload_control_server::BlobUploadControlServer,
        blob_uploader_server::BlobUploaderServer, locator_server::LocatorServer,
        reader_server::ReaderServer,
    },
    error::Result,
    manifest::{
        manifestpb::bucket_service_server::BucketServiceServer as ManifestBucketServiceServer,
        storage::MemBlobMetaStore, BlobControl, BucketService as ManifestBucketService,
        CacheServerLocator, SpanBasedBlobPlacement,
    },
};

#[derive(Default)]
pub struct LocalSvcDiscover {
    inner: Arc<Mutex<Inner>>,
}

#[derive(Default)]
struct Inner {
    node_cache_mng_svc: Vec<(
        u32,
        NodeCacheManageServiceServer<NodeCacheManager<MemCacheStore, MemBlobStore>>,
    )>,
    node_bucket_svc: Vec<(
        u32,
        NodeBucketServiceServer<NodeBucketService<MemCacheStore>>,
    )>,
    node_upload_svc: Vec<(
        u32,
        BlobUploaderServer<Uploader<MemCacheStore, MemBlobStore, CacheReplica<LocalSvcDiscover>>>,
    )>,
    node_read_svc: Vec<(u32, ReaderServer<CacheReader>)>,

    manifest_blob_ctrl: Vec<(
        u32,
        BlobUploadControlServer<
            BlobControl<
                MemBlobMetaStore<MemBlobStore>,
                SpanBasedBlobPlacement<LocalSvcDiscover, MemBlobMetaStore<MemBlobStore>>,
            >,
        >,
    )>,
    manifest_locator: Vec<(
        u32,
        LocatorServer<CacheServerLocator<MemBlobMetaStore<MemBlobStore>, LocalSvcDiscover>>,
    )>,
    manifest_bucket_svc: Vec<(
        u32,
        ManifestBucketServiceServer<
            ManifestBucketService<MemBlobStore, MemBlobMetaStore<MemBlobStore>, LocalSvcDiscover>,
        >,
    )>,
}

impl LocalSvcDiscover {
    pub async fn register_cache_node_


;
}
div#RepositoryList table.repolist tbody tr td.ColumnType {
    width: 15%;
}
div#RepositoryList table.repolist tbody tr td.ColumnName {
    width: 80%;
}

/* Address Book
------------------------------------------------------ */
div#AddressBookList, AddressBookDetail {
    margin: 0;
    padding: 0;
}
div#AddressBookList table.addressbook tbody tr td {
    border-bottom: dashed 1px #000;
    text-align: center;
}
div#AddressBookList table.addressbook tbody tr td.ColumnName {
    text-align: left;
    width: 65%;
}
div#AddressBookList table.addressbook tbody tr td.ColumnAddress {
    width: 10%;
}
div#AddressBookList table.adressbook tbody tr td.ColumnResidence {
    width: 10%;
}
div#AddressBookList table.addressbook tbody tr td.ColumnWebLinks {
    width: 10%;
}

/* Subsections
----------------------------------------------------- */
#Home #GalleryDisplay, #Introduction #GalleryDisplay,
                       #Contact #GalleryDisplay {
    float: right;
    margin: 0;
    border: 0px;
}
#Home #GalleryDisplay img, #Introduction #GalleryDisplay img,
                       #Contact #GalleryDisplay img {
    display: block;
    max-width: 950px;
    height: auto;
    float: right;
}
@media only screen and (max-width: 1080px) {
    #Home #GalleryDisplay img, #Introduction #GalleryDisplay img,
          #Contact #GalleryDisplay img {
        margin: 0 auto;
        max-width: 100%;
    }
}
#Home p, #Introduction p {
    margin: 0 20px 1em 20px;
}
#Home a, #Introduction a, #Contact a {
    color: #000;
    text-decoration: none;
}
div.subsection {
    padding-bottom: .5em;
}
div.subsection h4 {
    margin-bottom: .5em;
}
div.subsection table, div.subsection ol, div.subsection p, div.subsection > a {
    font-size: .9em;
}
div.subsection a {
    text-decoration: underline;
}
div.subsection a:hover {
    text-decoration: underline;
}
div.subsection table.infolist {
    width: 100%;
    margin: 0;
}

/* Subsections : Events
----------------------------------------------------- */
div#events {
    padding-bottom: 0;
}
div#events h4 {
    margin-bottom: 0;
    border: none;
}
#IndividualDetail div#events table.eventtable {
    width: 100%;
}
#families table.eventlist tbody tr td.ColumnEvent {
    vertical-align: top;
    width: 8%;
}
div#RelationshipDetail table.infolist tbody tr td.ColumnAttribute,
div#IndividualDetail table.infolist tbody tr td.ColumnAttribute {
    vertical-align: top;
    width: 10%;
}
#IndividualDetail div#events table.infolist tbody tr td {
    padding-top: .4em;
    padding-bottom: .8em;
}
#IndividualDetail div#events table.infolist tbody tr td.ColumnAttribute {
    border-bottom: solid 1px #000;
}
#IndividualDetail div#events table.infolist tbody tr td.ColumnValue {
    border-bottom: solid 1px #000;
}
table.infolist tbody tr td.ColumnValue p {
    font-family: sans-serif;
    color: #696969;
    margin: .2em 0 0 2em;
}

/* Subsections : Attributes
----------------------------------------------------- */
div#attributes {
    margin: 0;
    padding: 0;
}
table.attrlist {
    width: 100%;
}
table.attrlist tbody tr td {
    border-bottom: dashed 1px


_run_01.png)

- 监控中心应用信息，访问地址：http://192.168.3.101:8101

![](../images/mall_swarm_run_02.png)

![](../images/mall_swarm_run_03.png)

![](../images/mall_swarm_run_04.png)

- 日志收集系统信息，访问地址：http://192.168.3.101:5601

![](../images/mall_swarm_run_06.png)

## 可视化管理工具

> Portainer 是一款轻量级的应用，它提供了图形化界面，用于方便的管理Docker环境，包括单机环境和集群环境，下面我们将用Portainer来管理Docker容器中的应用。

- 官网地址：https://github.com/portainer/portainer

- 获取Docker镜像文件：

```bash
docker pull portainer/portainer
```

- 使用docker容器运行Portainer：

```bash
docker run -p 9000:9000 -p 8000:8000 --name portainer \
--restart=always \
-v /var/run/docker.sock:/var/run/docker.sock \
-v /mydata/portainer/data:/data \
-d portainer/portainer
```

- 查看Portainer的DashBoard信息，访问地址：http://192.168.3.101:9000

![](../images/mall_swarm_linux_01.png)

- 查看所有运行中的容器信息：

![](../images/mall_swarm_linux_02.png)

- 查看所有已经下载的Docker镜像：

![](../images/mall_swarm_linux_03.png)

- 查看`mall-portal`应用的统计信息：

![](../images/mall_swarm_linux_04.png)

- 查看`mall-portal`应用的运行过程中打印的日志信息：

![](../images/mall_swarm_linux_05.png)

- 进入`mall-portal`应用的容器内部来操作容器内部系统：

![](../images/mall_swarm_linux_06.png)

## 公众号

![公众号图片](http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/banner/qrcode_for_macrozheng_258.jpg)

学习不走弯路，[关注公众号](#公众号) 回复「学习路线」，获取mall项目专属学习路线！

# 使用Redis+AOP优化权限管理功能，这波操作贼爽！

> 之前有很多朋友提过，mall项目中的权限管理功能有性能问题，因为每次访问接口进行权限校验时都会从数据库中去查询用户信息。最近对这个问题进行了优化，通过Redis+AOP解决了该问题，下面来讲下我的优化思路。

## 前置知识

学习本文需要一些Spring Data Redis的知识，不了解的朋友可以看下[《Spring Data Redis 最佳实践！》](https://mp.weixin.qq.com/s/9j3exBtZ9FWWlyZkxlWaOA)。
还需要一些Spring AOP的知


 010-2h8a1 1 0 010 2z" opacity=".5"/><rect width="8" height="8" x="14" y="4" fill="currentColor" rx="1"/><path fill="currentColor" d="M21 16H3a1 1 0 010-2h18a1 1 0 010 2zm-8 4H3a1 1 0 010-2h10a1 1 0 010 2z" opacity=".5"/></svg>';
  static const String download_alt =
      '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><path fill="currentColor" d="M15.707 13.293a1 1 0 00-1.414 0L13 14.586V3a1 1 0 00-2 0v11.586l-1.293-1.293a1 1 0 00-1.414 1.414l3 3a1 1 0 001.414 0l3-3a1 1 0 000-1.414Z"/><path fill="currentColor" d="M18 9h-5v5.586l1.293-1.293a1 1 0 011.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 011.414-1.414L11 14.586V9H6a3.003 3.003 0 00-3 3v7a3.003 3.003 0 003 3h12a3.003 3.003 0 003-3v-7a3.003 3.003 0 00-3-3Z" opacity=".5"/></svg>';
  static const String dribbble =
      '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><circle cx="11.97" cy="11.97" r="9" fill="currentColor" opacity=".5"/><path fill="currentColor" d="M2 12a9.796 9.796 0 011.34-5.02 9.93 9.93 0 013.64-3.64A9.796 9.796 0 0112 2a9.796 9.796 0 015.02 1.34 9.929 9.929 0 013.64 3.64A9.796 9.796 0 0122 12a9.796 9.796 0 01-1.34 5.02 9.929 9.929 0 01-3.64 3.64A9.796 9.796 0 0112 22a9.796 9.796 0 01-5.02-1.34 9.93 9.93 0 01-3.64-3.64A9.796 9.796 0 012 12zm1.66 0a8.064 8.064 0 002.1 5.5c.755-1.39 1.79-2.61 3.04-3.58a9.942 9.942 0 014.06-2.14c-.2-.467-.393-.887-.58-1.26a24.3 24.3 0 01-7.44 1.1c-.52 0-.907-.007-1.16-.02 0 .053-.003.12-.01.2s-.01.147-.01.2zm.26-2.06c.293.027.727.04 1.3.04a21.95 21.95 0 006.34-.9 20.251 20.251 0 00-3.34-4.5A8.12 8.12 0 005.51 6.8a8.539 8.539 0 00-1.59 3.14zm2.98 8.64a8.173 8.173 0 008.04 1.2 29.368 29.368 0 00-1.56-6.62 8.53 8.53 0 00-3.71 2.02 11.345 11.345 0 00-2.77 3.4zM9.96 3.94a21.254 21.254 0 013.26 4.54 9.96 9.96 0 004.1-2.9A8.107 8.107 0 0012 3.66a7.677 7.677 0 00-2.04.28zm3.98 5.96c.2


�业公司，现在能实现的目标是：追求 level 2 的可移植性，部分场景可以达到 level 3，这就足够解决业务问题了。

比如分布式缓存场景，蚂蚁在 MOSN 里自建了一套分布式缓存中间件支持 Redis 协议访问，如果你相信 Redis 协议是具有可移植性的，那么应用通过 Redis 协议和 MOSN 通信即可，没必要强行迁移到 Dapr 的“State API”上。在这种情况下，标准化 API 只是作为补充。

![图片](https://img.alicdn.com/imgextra/i4/O1CN01LGMqKm1YlqZ2cX1g3_!!6000000003100-2-tps-1080-815.png)

题外话，**Sky Computing 的“兼容层”需要哪种可移植性？** 按照这种分级方式，Sky Computing 提出的“兼容层”需要 level 3 及以上的可移植性。

**如何实现 level 3 可移植？**

如果我们把目标定为 level 3，那么 Runtime 对外暴露的“兼容层”协议应该是多种多样的，包括各种领域的可信协议（比如 Redis 协议、MySQL 协议、AWS S3 协议等） ，以及 Dapr 风格的标准化 API。

![图片](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/3fb1af66cf3d457a92803f5e68f46331~tplv-k3u1fbpfcp-zoom-1.image)

**由此，我们可以得出两个观点：**

**观点 3：**

拥抱可信协议：Dapr 标准化 API 的定位应该是作为可信协议的补充，而不是试图让用户放弃可信协议，迁移到 Dapr API 上。

**观点 4：**

设计 Dapr 标准化 API 时，要专注于那些还没有形成可信协议的领域，为这些领域设计标准化 API，而不是花精力设计“Another SQL”，或者纠结“如何从 Redis 迁移到 Memcached”。比如，不同云厂商的配置中心提高的 API 不一样，还没形成事实标准，那么设计一套跨平台的 Configuration API 就能填补这个空缺。

**演进路线**

现在我们回答最开始提出的问题：现在的 Dapr API 有很多问题，比如自定义扩展字段太多，破坏可移植性，比如面向“交集”做设计，功能太弱难以演进，比如侵入性强等等，该怎么办？

答案是：**逐渐演进**，先考虑从 level 2 演进到 level 3。

![图片](https://p3-juejin.by


namespace BossMod.Endwalker.TreasureHunt.Excitatron6000.LuckyFace;

public enum OID : uint
{
    Boss = 0x377F, // R3.240
    BossHelper = 0x233C, // R0.500
    ExcitingQueen = 0x380C, // R0.840, icon 5, needs to be killed in order from 1 to 5 for maximum rewards
    ExcitingTomato = 0x380B, // R0.840, icon 4, needs to be killed in order from 1 to 5 for maximum rewards
    ExcitingGarlic = 0x380A, // R0.840, icon 3, needs to be killed in order from 1 to 5 for maximum rewards
    ExcitingEgg = 0x3809, // R0.840, icon 2, needs to be killed in order from 1 to 5 for maximum rewards
    ExcitingOnion = 0x3808, // R0.840, icon 1, needs to be killed in order from 1 to 5 for maximum rewards
}

public enum AID : uint
{
    AutoAttack = 27980, // Boss->player, no cast, single-target
    FakeLeftInTheDark = 27989, // Boss->self, 4.0s cast, range 20 180-degree cone
    LeftInTheDark = 27990, // BossHelper->self, 4.0s cast, range 20 180-degree cone
    HeartOnFireII = 28001, // BossHelper->location, 3.0s cast, range 6 circle
    FakeHeartOnFireII = 27988, // Boss->self, 3.0s cast, single-target
    HeartOnFireIV = 27981, // Boss->player, 5.0s cast, single-target
    FakeQuakeInYourBoots = 27997, // Boss->self, 4.0s cast, range 10 circle
    QuakeInYourBoots = 27998, // BossHelper->self, 4.0s cast, range 10 circle
    MerryGoRound1 = 27983, // Boss->self, 3.0s cast, single-target, boss animation
    FakeLeftInTheDark2 = 27993, // Boss->self, 4.0s cast, range 20 180-degree cone
    LeftInTheDark2 = 27994, // BossHelper->self, 4.0s cast, range 20 180-degree cone
    MerryGoRound2 = 27986, // Boss->self, no cast, single-target, boss animation
    FakeQuakeMeAway = 27999, // Boss->self, 4.0s cast, range 10-20 donut
    QuakeMeAway = 28000, // BossHelper->self, 4.0s cast, range 10-20 donut
    MerryGoRound3 = 27984, // Boss->self, 3.0s cast, single-target
    FakeRightInTheDark = 27991, // Boss->self, 4.0s cast, range 20 180-degree cone
    RightInTheDark1 = 27992, // BossHelper->self, 4.0s cast, range 20 180-degree cone
    MerryGoRound4 = 27985, // Boss->self, no cast, single-target, boss animation
    applyspreadmarkers = 28045, // Boss->self, no cast, single-target
    FakeQuakeInYourBoots2 = 28090, // Boss->self, 4.0s cast, range 10 circle
    QuakeInYourBoots2 = 28189, // BossHelper->self, 4.0s cast, range 10-20 donut
    HeartOnFireIII = 28002, // BossHelper->player, 5.0s cast, range 6 circle
    TempersFlare = 27982, // Boss->self, 5.0s cast, range 60 circle
    FakeRightInTheDark2 = 27995, // Boss->self, 4.0s cast, range 20 180-degree cone
    RightInTheDark2 = 27996, // BossHelper->self, 4.0s cast, range 20 180-degree cone
    FakeQuakeMeAway2 = 28091, // Boss->self, 4.0s cast, range 10-20 donut
    QuakeMeAway2 = 28190, // BossHelper->self, 4.0s cast, range 10 circle
    MerryGoRound5 = 27987, // Boss->self, no cast, singl


leSystem in its driver and evaluators should set
    /// configuration data through AzureBlockBlobFileSystem configuration module in the client's configuration
    /// </summary>
    internal sealed class AzureBlobFileSystemConfigurationProvider : IConfigurationProvider
    {
        private readonly IConfiguration _configuration;

        [Inject]
        private AzureBlobFileSystemConfigurationProvider(
            [Parameter(typeof(AzureBlobStorageAccountName))] string accountName,
            [Parameter(typeof(AzureBlobStorageAccountKey))] string accountKey,
            IAzureBlobRetryPolicy retryPolicy)
        {
            _configuration = TangFactory.GetTang().NewConfigurationBuilder()
                .BindImplementation(GenericType<IFileSystem>.Class, GenericType<AzureBlobFileSystem>.Class)
                .BindImplementation(typeof(IAzureBlobRetryPolicy), retryPolicy.GetType())
                .BindStringNamedParam<AzureBlobStorageAccountName>(accountName)
                .BindStringNamedParam<AzureBlobStorageAccountKey>(accountKey)
                .BindSetEntry<EvaluatorConfigurationProviders, AzureBlobFileSystemConfigurationProvider, IConfigurationProvider>()
                .Build();
        }

        public IConfiguration GetConfiguration()
        {
            return _configuration;
        }
    }
}


          numberInt, numberClose));
        for (iColumn = 0; iColumn < numberColumns; iColumn++) {
          for (CoinBigIndex j = columnStart[iColumn];
               j < columnStart[iColumn] + columnLength[iColumn]; j++) {
            //int iRow = row[j];
            double value1 = element[j];
            double value = fabs(value1);
            if (value < 1.0e7) {
              int iValue = static_cast< int >(100 * (value + 0.005));
              double value2 = iValue;
              if (value2 != 100.0 * value) {
                value2 *= 0.01;
                if (fabs(value - floor(value + 0.5)) <= 1.0e-7)
                  value2 = floor(value + 0.5);
                if (value1 < 0.0)
                  value2 = -value2;
                element[j] = value2;
              }
            }
          }
        }
      }
    }
#endif
    {
      // mark some columns as ineligible for presolve
      int numberColumns = solver->getNumCols();
      char *prohibited = new char[numberColumns];
      memset(prohibited, 0, numberColumns);
      int numberProhibited = 0;
      /*
              Create CbcSimpleInteger objects would be more accurate in the general
              case.  The `false' parameter says we won't delete existing objects.

              Only Clp will produce SOS objects in findIntegers (080122), and that's
              where a possible conversion can occur. If clp is holding OsiSOS objects,
              they'll be converted to CbcSOS objects.
            */
      // convert to Cbc integers
      model.findIntegers(false);
      int numberObjects = model.numberObjects();
      if (numberObjects) {
        OsiObject **objects = model.objects();
        for (int iObject = 0; iObject < numberObjects; iObject++) {
          CbcSOS *obj = dynamic_cast< CbcSOS * >(objects[iObject]);
          if (obj) {
            // SOS
            int n = obj->numberMembers();
            const int *which = obj->members();
            for (int i = 0; i < n; i++) {
              int iColumn = which[i];
              prohibited[iColumn] = 1;
              numberProhibited++;
            }
          }
        }
      }
      if (numberProhibited)
        process->passInProhibited(prohibited, numberColumns);
      delete[] prohibited;
    }
    int logLevel = model.messageHandler()->logLevel();
#ifdef COIN_HAS_CLP
    //OsiClpSolverInterface * clpSolver = dynamic_cast< OsiClpSolverInterface*> (solver);
    ClpSimplex *lpSolver = NULL;
    if (clpSolver) {
      if (clpSolver->messageHandler()->logLevel())
        clpSolver->messageHandler()->setLogLevel(1);
      if (logLevel > -1)
        clpSolver->messageHandler()->setLogLevel(CoinMin(logLevel, clpSolver->messageHandler()->logLevel()));
      lpSolver = clpSolver->getModelPtr();
      /// If user left factorization frequency then compute
      lpSolver->defaultFactorizationFrequency();
    }
#endif
    // Tell solver we are in Branch and Cut
    solver->setHintParam(OsiDoInBranchAndCut, true, OsiHintDo);
    // Default set of cut generators
    // Limited set that could reduce problem size (drop rows / fix values)
    CglProbing generator1;
    generator1.setUsingObjective(true);
    generator1.setMaxPass(1);
    generator1.setMaxPassRoot(1);
    generator1.setMaxProbeRoot(CoinMin(3000, solver->getNumCols()));
    generator1.setMaxProbeRoot(123);
    generator1.setMaxElements(100);
    generator1.setMaxElementsRoot(200);
    generator1.setMaxLookRoot(50


   "lorem",
        "nam",
        "nec",
        "neque",
        "nisl",
        "nullam",
        "nunc",
        "odio",
        "orci",
        "porta",
        "posuere",
        "quam",
        "quis",
        "semper",
        "sit",
        "sollicitudin",
        "tempor",
        "tempus",
        "ultricies",
        "velit",
        "venenatis",
        "vestibulum",
        "vitae"
    };

    /// <inheritdoc />
    public string Identity => "autocomplete::dictionary";

    /// <inheritdoc/>
    public ValueTask<IReadOnlyList<IApplicationCommandOptionChoice>> GetSuggestionsAsync
    (
        IReadOnlyList<IApplicationCommandInteractionDataOption> options,
        string userInput,
        CancellationToken ct = default
    )
    {
        return new ValueTask<IReadOnlyList<IApplicationCommandOptionChoice>>
        (
            _dictionary
                .OrderByDescending(n => n.Contains(userInput))
                .Take(25)
                .Select(n => new ApplicationCommandOptionChoice(n.Humanize().Transform(To.TitleCase), n))
                .ToList()
        );
    }
}


* Invoke.
     *
     * @return A [Flow] that emits the syncs
     */
    override operator fun invoke(): Flow<List<FolderPair>> = channelFlow {
        launch {
            syncRepository.monitorFolderPairChanges()
                .distinctUntilChanged()
                .map { pairs ->
                    pairs.partition { it.syncError != SyncError.MISMATCH_OF_ROOT_FSID }
                }
                .conflate()
                .collect { (validSyncs, invalidSyncs) ->
                    val pausedSyncs = invalidSyncs.map {
                        it.copy(
                            syncError = SyncError.NO_SYNC_ERROR,
                            syncStatus = SyncStatus.PAUSED
                        )
                    }
                    if (pausedSyncs.isNotEmpty()) {
                        send(validSyncs + pausedSyncs)
                        val notResumedSyncs = handleInvalidSyncs(invalidSyncs)
                        val totalSyncs =
                            validSyncs + pausedSyncs.minus(notResumedSyncs) + notResumedSyncs
                        send(totalSyncs)
                    } else {
                        send(validSyncs)
                    }
                }
        }
    }

    private suspend fun handleInvalidSyncs(invalidSyncs: List<FolderPair>): List<FolderPair> {
        return invalidSyncs.mapNotNull { folderPair ->
            val localPath = folderPair.localFolderPath
            if (canReadUriUseCase(localPath)) {
                changeSyncLocalRootUseCase(folderPair.id, localPath)
                resumeSyncUseCase(folderPair.id)
                null // Successfully resumed, no need to add to notResumedSyncs
            } else {
                folderPair // Add to notResumedSyncs if it cannot be resumed
            }
        }
    }
}

/**
 * Use case for monitoring syncs
 */
interface MonitorSyncsUseCase {
    /**
     * Invoke.
     *
     * @return A [Flow] that emits the syncs
     */
    operator fun invoke(): Flow<List<FolderPair>>
}
package mega.privacy.android.feature.devicecenter.ui.model

import com.google.common.truth.Truth.assertThat
import mega.privacy.android.feature.devicecenter.ui.model.icon.DeviceIconType
import mega.privacy.android.feature.devicecenter.ui.model.icon.FolderIconType
import mega.privacy.android.feature.devicecenter.ui.model.status.DeviceCenterUINodeStatus
import org.junit.jupiter.api.TestInstance
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import java.util.stream.Stream

/**
 * Test class for [DeviceCenterUiState]
 */
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
internal class DeviceCenterUiStateTest {

    private lateinit var underTest: DeviceCenterUiState

    private val ownDeviceFolderUINode = NonBackupDeviceFolderUINode(
        id = "ABCD-EFGH",
        name = "Camera uploads",
        icon = FolderIconType.CameraUploads,
        status = DeviceCenterUINodeStatus.UpToDate,
        rootHandle = 789012L,
        localFolderPath = "storage/emulated/0/DCIM/Camera",
    )
    private val ownDeviceUINode = OwnDeviceUINode(
        id = "1234-5678",
        name = "Own Device",
        icon = DeviceIconType.Android,
        status = DeviceCenterUINodeStatus.UpToDate,
        folders = listOf(ownDeviceFolderUINode),
    )

    @ParameterizedTest(name = "when selectedDevice is {0}, then itemsToDisplay is {1}")
    @MethodSource("provideParameters")
    fun `test that itemsToDisplay uses the correct data`(
        selectedDevice: DeviceUINode?,
        expectedItemsToDisplay: List<DeviceCenterUINode>,
    ) {
        underTest = DeviceCenterUiState(
            devices = listOf(ownDeviceUINode


// Parallel version with Rayon using Pixel wise parallelism
pub fn rayon_mandelbrot_pixel(mandel_config: &MandelConfig, image: &mut [u32]) {
    image.par_iter_mut().enumerate().for_each(|(n, pixel)| {
        let y = (n as u32) / mandel_config.img_size;
        let x = (n as u32) - (y * mandel_config.img_size);

        let xf = mandel_config.re1 + x as f32 * mandel_config.x_step;
        let yf = mandel_config.img1 + y as f32 * mandel_config.y_step;

        *pixel = mandel_iter(mandel_config.max_iter, xf, yf);
    });
}

// Parallel version with Rayon using Row wise parallelism
pub fn rayon_mandelbrot_row(mandel_config: &MandelConfig, image: &mut [u32]) {
    image
        .par_chunks_mut(mandel_config.img_size as usize)
        .enumerate()
        .for_each(|(y, slice)| {
            for x in 0..mandel_config.img_size {
                let xf = mandel_config.re1 + x as f32 * mandel_config.x_step;
                let yf = mandel_config.img1 + y as f32 * mandel_config.y_step;

                slice[x as usize] = mandel_iter(mandel_config.max_iter, xf, yf);
            }
        });
}

pub fn crossbeam_manderlbrot_row(mandel_config: &MandelConfig, image: &mut [u32]) {
    crossbeam::scope(|scope| {
        for (y, slice) in image
            .chunks_mut(mandel_config.img_size as usize)
            .enumerate()
        {
            scope.spawn(move |_| {
                for x in 0..mandel_config.img_size {
                    let xf = mandel_config.re1 + x as f32 * mandel_config.x_step;
                    let yf = mandel_config.img1 + y as f32 * mandel_config.y_step;

                    slice[x as usize] = mandel_iter(mandel_config.max_iter, xf, yf);
                }
            });
        }
    })
    .unwrap();
}

// The inner iteration loop of the mandelbrot calculation
// See https://en.wikipedia.org/wiki/Mandelbrot_set
pub fn mandel_iter(max_iter: u32, c_re: f32, c_im: f32) -> u32 {
    let mut z_re = c_re;
    let mut z_im = c_im;

    let mut iter = 0;

    while ((z_re * z_re + z_im * z_im) <= 4.0) && (iter < max_iter) {
        let new_re = z_re * z_re - z_im * z_im;
        let new_im = 2.0 * z_re * z_im;

        z_re = c_re + new_re;
        z_im = c_im + new_im;
        iter = iter + 1;
    }
    iter
}use fltk::{app, draw, frame::*, widget::*, window::*};
use std::ops::{Deref, DerefMut};

struct FlatButton {
    wid: Widget,
}

impl FlatButton {
    pub fn new(x: i32, y: i32, w: i32, h: i32, label: &str) -> FlatButton {
        let mut x = FlatButton {
            wid: Widget::new(x, y, w, h, label),
        };
        x.draw();
        x.handle


ed via the `record_static!` macro.
pub struct RecordStatic<'a> {
    /// Code location
    #[doc(hidden)]
    pub location: &'a RecordLocation,
    /// Tag
    #[doc(hidden)]
    pub tag: &'a str,
    /// Logging level
    #[doc(hidden)]
    pub level: Level,
}

/// One logging record
///
/// Corresponds to one logging statement like `info!(...)` and carries all it's
/// data: eg. message, immediate key-value pairs and key-value pairs of `Logger`
/// used to execute it.
///
/// Record is passed to a `Logger`, which delivers it to it's own `Drain`,
/// where actual logging processing is implemented.
pub struct Record<'a> {
    rstatic: &'a RecordStatic<'a>,
    msg: &'a fmt::Arguments<'a>,
    kv: BorrowedKV<'a>,
}

impl<'a> Record<'a> {
    /// Create a new `Record`
    ///
    /// Most of the time, it is slightly more performant to construct a `Record`
    /// via the `record!` macro because it enforces that the *entire*
    /// `RecordStatic` is built at compile-time.
    ///
    /// Use this if runtime record creation is a requirement, as is the case with
    /// [slog-async](https://docs.rs/slog-async/latest/slog_async/struct.Async.html),
    /// for example.
    #[inline]
    pub fn new(
        s: &'a RecordStatic<'a>,
        msg: &'a fmt::Arguments<'a>,
        kv: BorrowedKV<'a>,
    ) -> Self {
        Record {
            rstatic: s,
            msg: msg,
            kv: kv,
        }
    }

    /// Get a log record message
    pub fn msg(&self) -> &fmt::Arguments {
        self.msg
    }

    /// Get record logging level
    pub fn level(&self) -> Level {
        self.rstatic.level
    }

    /// Get line number
    pub fn line(&self) -> u32 {
        self.rstatic.location.line
    }

    /// Get line number
    pub fn location(&self) -> &RecordLocation {
        self.rstatic.location
    }

    /// Get error column
    pub fn column(&self) -> u32 {
        self.rstatic.location.column
    }

    /// Get file path
    pub fn file(&self) -> &'static str {
        self.rstatic.location.file
    }

    /// Get tag
    ///
    /// Tag is information that can be attached to `Record` that is not meant
    /// to be part of the normal key-value pairs, but only as an ad-hoc control
    /// flag for quick lookup in the `Drain`s. As such should be used carefully
    /// and mostly in application code (as opposed to libraries) - where tag
    /// meaning across the system can be coordinated. When used in libraries,
    /// make sure to prefix it with something reasonably distinct, like create
    /// name.
    pub fn tag(&self) -> &str {
        self.rstatic.tag
    }

    /// Get module
    pub fn module(&self) -> &'static str {
        self.rstatic.location.module
    }

    /// Get function (placeholder)
    ///
    /// There's currently no way to obtain that information
    /// in Rust at compile time, so it is not implemented.
    ///
    /// It will be implemented at first opportunity, and
    /// it will not be considered a breaking change.
    pub fn function(&self) -> &'static str {
        self.rstatic.location.function
    }

    /// Get key-value pairs
    pub fn kv(&self) -> BorrowedKV {
        BorrowedKV(self


tring `field:"optional" json:"responseHeadersPolicyName" yaml:"responseHeadersPolicyName"`
	// A configuration for a set of security-related HTTP response headers.
	// Default: - no security headers behavior.
	//
	SecurityHeadersBehavior *ResponseSecurityHeadersBehavior `field:"optional" json:"securityHeadersBehavior" yaml:"securityHeadersBehavior"`
	// The percentage of responses that you want CloudFront to add the Server-Timing header to.
	// Default: - no Server-Timing header is added to HTTP responses.
	//
	ServerTimingSamplingRate *float64 `field:"optional" json:"serverTimingSamplingRate" yaml:"serverTimingSamplingRate"`
}

package awscloudfront

import (
	_init_ "github.com/aws/aws-cdk-go/awscdk/v2/jsii"
	_jsii_ "github.com/aws/jsii-runtime-go/runtime"

	"github.com/aws/aws-cdk-go/awscdk/v2"
	"github.com/aws/aws-cdk-go/awscdk/v2/awscloudfront/internal"
	"github.com/aws/constructs-go/constructs/v10"
)

// A Response Headers Policy configuration.
//
// Example:
//   // Using an existing managed response headers policy
//   var bucketOrigin s3Origin
//
//   cloudfront.NewDistribution(this, jsii.String("myDistManagedPolicy"), &DistributionProps{
//   	DefaultBehavior: &BehaviorOptions{
//   		Origin: bucketOrigin,
//   		ResponseHeadersPolicy: cloudfront.ResponseHeadersPolicy_CORS_ALLOW_ALL_ORIGINS(),
//   	},
//   })
//
//   // Creating a custom response headers policy -- all parameters optional
//   myResponseHeadersPolicy := cloudfront.NewResponseHeadersPolicy(this, jsii.String("ResponseHeadersPolicy"), &ResponseHeadersPolicyProps{
//   	ResponseHeadersPolicyName: jsii.String("MyPolicy"),
//   	Comment: jsii.String("A default policy"),
//   	CorsBehavior: &ResponseHeadersCorsBehavior{
//   		AccessControlAllowCredentials: jsii.Boolean(false),
//   		AccessControlAllowHeaders: []*string{
//   			jsii.String("X-Custom-Header-1"),
//   			jsii.String("X-Custom-Header-2"),
//   		},
//   		AccessControlAllowMethods: []*string{
//   			jsii.String("GET"),
//   			jsii.String("POST"),
//   		},
//   		AccessControlAllowOrigins: []*string{
//   			jsii.String("*"),
//   		},
//   		AccessControlExposeHeaders: []*string{
//   			jsii.String("X-Custom-Header-1"),
//   			jsii.String("X-Custom-Header-2"),
//   		},
//   		AccessControlMaxAge: awscdk.Duration_Seconds(jsii.Number(600)),
//   		OriginOverride: jsii.Boolean(true),
//   	},
//   	CustomHeadersBehavior: &ResponseCustomHeadersBehavior{
//   		CustomHeaders: []responseCustomHeader{
//   			&responseCustomHeader{
//   				Header: jsii.String("X-Amz-Date"),
//   				Value: jsii.String("some-value"),
//   				Override: jsii.Boolean(true),
//   			},
//   			&responseCustomHeader{
//   				Header: jsii.String("X-Amz-Security-Token"),
//   				Value: jsii.String("some-value"),
//   				Override: jsii.Boolean(false),
//   			},
//   		},
//   	},
//   	SecurityHeadersBehavior: &ResponseSecurityHeadersBehavior{
//   		ContentSecurityPolicy: &ResponseHeadersContentSecurityPolicy{
//   			ContentSecurityPolicy: jsii.String("default-src https:;"),
//   			Override: jsii.Boolean(true),
//   		},
//   		ContentTypeOptions: &ResponseHeadersContentType


CheckpointContext _ctx;
  int64_t _count_offset;
  int _count;
  bool _skip_header;
 public:
  JfrArtifactWriterHost(JfrCheckpointWriter* writer,
                        JfrArtifactSet* artifacts,
                        bool class_unload,
                        bool skip_header = false) : _impl(writer, artifacts, class_unload),
                                                    _writer(writer),
                                                    _ctx(writer->context()),
                                                    _count(0),
                                                    _skip_header(skip_header) {
    assert(_writer != NULL, "invariant");
    if (!_skip_header) {
      _writer->write_type((JfrTypeId)ID);
      _count_offset = _writer->reserve(sizeof(u4)); // Don't know how many yet
    }
  }

  ~JfrArtifactWriterHost() {
    if (_count == 0) {
      // nothing written, restore context for rewind
      _writer->set_context(_ctx);
      return;
    }
    assert(_count > 0, "invariant");
    if (!_skip_header) {
      _writer->write_count(_count, _count_offset);
    }
  }

  bool operator()(typename WriterImpl::Type const & value) {
    this->_count += _impl(value);
    return true;
  }

  int count() const   { return _count; }
  void add(int count) { _count += count; }
};

typedef int(*artifact_write_operation)(JfrCheckpointWriter*, JfrArtifactSet*, const void*);

template <typename T, artifact_write_operation op>
class JfrArtifactWriterImplHost {
 private:
  JfrCheckpointWriter* _writer;
  JfrArtifactSet* _artifacts;
  bool _class_unload;
 public:
  typedef T Type;
  JfrArtifactWriterImplHost(JfrCheckpointWriter* writer, JfrArtifactSet* artifacts, bool class_unload) :
    _writer(writer), _artifacts(artifacts), _class_unload(class_unload) {}
  int operator()(T const& value) {
    return op(this->_writer, this->_artifacts, value);
  }
};

template <typename T, typename Predicate, artifact_write_operation op>
class JfrPredicatedArtifactWriterImplHost : public JfrArtifactWriterImplHost<T, op> {
 private:
  Predicate _predicate;
  typedef JfrArtifactWriterImplHost<T, op> Parent;
 public:
  JfrPredicatedArtifactWriterImplHost(JfrCheckpointWriter* writer, JfrArtifactSet* artifacts, bool class_unload) :
    Parent(writer, artifacts, class_unload), _predicate(class_unload) {}
  int operator()(T const& value) {
    return _predicate(value) ? Parent::operator()(value) : 0;
  }
};

#endif // SHARE_VM_JFR_CHECKPOINT_TYPES_JFRTYPESETWRITER_HPP
/*
 * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 0211


nfo = await codec.getNextFrame();
  } catch (e) {
    print("getNextFrame failed: $e");
    codec.dispose();
    buffer.dispose();
    descriptor.dispose();
    return null;
  }

  codec.dispose();
  buffer.dispose();
  descriptor.dispose();
  return frameInfo.image;
}

class ImagePainter extends CustomPainter {
  ImagePainter({
    required this.image,
    required this.x,
    required this.y,
    required this.scale,
  });

  ui.Image? image;
  double x;
  double y;
  double scale;

  @override
  void paint(Canvas canvas, Size size) {
    if (image == null) return;
    if (x.isNaN || y.isNaN) return;
    canvas.scale(scale, scale);
    // https://github.com/flutter/flutter/issues/76187#issuecomment-784628161
    // https://api.flutter-io.cn/flutter/dart-ui/FilterQuality.html
    var paint = Paint();
    if ((scale - 1.0).abs() > 0.001) {
      paint.filterQuality = FilterQuality.medium;
      if (scale > 10.00000) {
        paint.filterQuality = FilterQuality.high;
      }
    }
    // It's strange that if (scale < 0.5 && paint.filterQuality == FilterQuality.medium)
    // The canvas.drawImage will not work on web
    if (isWeb) {
      paint.filterQuality = FilterQuality.high;
    }
    canvas.drawImage(
        image!, Offset(x.toInt().toDouble(), y.toInt().toDouble()), paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return oldDelegate != this;
  }
}
import 'package:flutter/material.dart';
import 'package:flutter_gpu_texture_renderer/flutter_gpu_texture_renderer.dart';
import 'package:flutter_hbb/common/shared_state.dart';
import 'package:flutter_hbb/consts.dart';
import 'package:flutter_hbb/models/model.dart';
import 'package:get/get.dart';

import '../../common.dart';
import './platform_model.dart';

import 'package:texture_rgba_renderer/texture_rgba_renderer.dart'
    if (dart.library.html) 'package:flutter_hbb/web/texture_rgba_renderer.dart';

class _PixelbufferTexture {
  int _textureKey = -1;
  int _display = 0;
  SessionID? _sessionId;
  bool _destroying = false;
  int? _id;

  final textureRenderer = TextureRgbaRenderer();

  int get display => _display;

  create(int d, SessionID sessionId, FFI ffi) {
    _display = d;
    _textureKey = bind.getNextTextureKey();
    _sessionId = sessionId;

    textureRenderer.createTexture(_textureKey).then((id) async {
      _id = id;
      if (id != -1) {
        ffi.textureModel.setRgbaTextureId(display: d, id: id);
        final ptr = await textureRenderer.getTexturePtr(_textureKey);
        platformFFI.registerPixelbufferTexture(sessionId, display, ptr);
        debugPrint(
            "create pixelbuffer texture: peerId: ${ffi.id} display:$_display, textureId:$id, texturePtr:$ptr");
      }
    });
  }

  destroy(bool unregisterTexture, FFI ffi) async {
    if (!_destroying && _textureKey != -1 && _sessionId != null) {
      _destroying = true;
      if (unregisterTexture) {
        platformFFI.registerPixelbufferTexture(_sessionId!, display, 0);
        // sleep for a while to avoid the texture is used after it's unregistered.
        await Future.delayed(Duration(milliseconds: 100));
      }
      await textureRenderer.closeTexture(_textureKey);
      _textureKey = -1;
      _destroying = false;
      debugPrint(
          "destroy pixelbuffer texture: peerId: ${ffi.id} display:$_display, textureId:$_id");
    }
  }
}

class _GpuTexture {
  int _textureId = -1;
  SessionID? _sessionId;
  final support = bind.mainHasGpuTextureRender();
  bool _destroying = false;
  int _display


low
// code for this usecase// Logic operators used to combine and manipulate boolean values

// AND operator (&&)
// OR operator (||)
// NOT operator (!)

// AND which returns true if both conditions are true
let isBig = true;
let isCheap = true;

// Lets say you want to buy a burger that is big and cheap
let burger = isBig && isCheap;

if (burger) {
    console.log("I'll buy the big and cheap burger!");
} else {
    console.log("I will not buy the burger");
}

// OR which returns true if one of the conditions is true
// Lets say you want to buy a big burger regardless of price

let bigBurger = isBig || isCheap; // This will be true as long as one is true

if (bigBurger) {
    console.log("I'll buy the burger!");
} else {
    console.log("I will not buy the burger");
}

// NOT operator which inverts the result
// Lets say you will invert isBig

let notBigBurger = !isBig;

console.log(`is the burger big: ${notBigBurger}`);

// Since we are talking boolean values, lets talk about comaparison operators

// Equal to (==)
// Not equal to (!=)
// Strict equal to (===)
// Strict not equal to (!==)

// Equal to is essentially AND as long as 2 inputs are the same its true
// regardless of data type
// example:

let Pi = 3.14; // number data type

// we compared number Pi to string "3.14" using == operator which is true
Pi == "3.14" ? console.log("its Equal") : console.log("not equal")

// same goes with the not equal
Pi != "3.14" ? console.log("not equal") : console.log("its Equal")

// now with strict equal and not equal
Pi === "3.14" ? console.log("strictly equal") : console.log("not strictly equal")
Pi !== "3.14" ? console.log("strictly not equal") : console.log("strictly equal")// Variable is a named container that stores some form of data

// Example: let name;
// note. this only
let MyName;

// This will log undefined since the variable 'name'
// does not have a value or assigned value
console.log('Not assigned: ',MyName);

// This assigns the string 'John Doe' to the variable name
MyName = 'John Doe';

// This should log 'John Doe' since the variable name
// now has a value assigned to it
console.log('Assigned: ',MyName);

// You can also declare variables with const which cannot be reassigned
const pi = 3.14;

try {

    pi = 100;   // This will try to change pi,
                // but will throw an error

} catch (error) {

    console.log(`Error: ${error.message}`); // Logs the error

}

// Variables can also be numbers, char, booleans etc.

let age = 30;
let isApproved = true;
let character = 'a';
let floatingPointNumber = 3.14;

// Logs all variables
console.log(`age [${typeof age}]: ${age}`); // typeof determines data type, here age is a number!
console.log(`loatingPointNumber [${typeof floatingPointNumber}]: ${floatingPointNumber}`);
console.log(`isApproved [${typeof isApproved}]: ${isApproved}`);
console.log(`character [${typeof character}]: ${character}`);

// Declare and initialize multiple variables in one statement
let var1 = 'John', var2 = 30, var3 = 'Lucas';

// Do something with the variables
age += 1; // Increment 1 to age
console.log(`Next year age will be: ${age}`);

// Do arithmatic operations with variables
let newNum = age + floatingPointNumber;
console.log(`Sum of age and floatingPointNumber is: ${newNum}`);


&(ce.fn[Symbol.iterator]=oe[Symbol.iterator]),ce.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){n["[object "+t+"]"]=t.toLowerCase()});var pe=oe.pop,de=oe.sort,he=oe.splice,ge="[\\x20\\t\\r\\n\\f]",ve=new RegExp("^"+ge+"+|((?:^|[^\\\\])(?:\\\\.)*)"+ge+"+$","g");ce.contains=function(e,t){var n=t&&t.parentNode;return e===n||!(!n||1!==n.nodeType||!(e.contains?e.contains(n):e.compareDocumentPosition&&16&e.compareDocumentPosition(n)))};var f=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g;function p(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e}ce.escapeSelector=function(e){return(e+"").replace(f,p)};var ye=C,me=s;!function(){var e,b,w,o,a,T,r,C,d,i,k=me,S=ce.expando,E=0,n=0,s=W(),c=W(),u=W(),h=W(),l=function(e,t){return e===t&&(a=!0),0},f="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",t="(?:\\\\[\\da-fA-F]{1,6}"+ge+"?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",p="\\["+ge+"*("+t+")(?:"+ge+"*([*^$|!~]?=)"+ge+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+t+"))|)"+ge+"*\\]",g=":("+t+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+p+")*)|.*)\\)|)",v=new RegExp(ge+"+","g"),y=new RegExp("^"+ge+"*,"+ge+"*"),m=new RegExp("^"+ge+"*([>+~]|"+ge+")"+ge+"*"),x=new RegExp(ge+"|>"),j=new RegExp(g),A=new RegExp("^"+t+"$"),D={ID:new RegExp("^#("+t+")"),CLASS:new RegExp("^\\.("+t+")"),TAG:new RegExp("^("+t+"|[*])"),ATTR:new RegExp("^"+p),PSEUDO:new RegExp("^"+g),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+ge+"*(even|odd|(([+-]|)(\\d*)n|)"+ge+"*(?:([+-]|)"+ge+"*(\\d+)|))"+ge+"*\\)|)","i"),bool:new RegExp("^(?:"+f+")$","i"),needsContext:new RegExp("^"+ge+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+ge+"*((?:-\\d)?\\d*)"+ge+"*\\)|)(?=[^-]|$)","i")},N=/^(?:input|select|textarea|button)$/i,q=/^h\d$/i,L=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,H=/[+~]/,O=new RegExp("\\\\[\\da-fA-F]{1,6}"


="Algebra.Structures.html#1216" class="Field">∙-cong        = cong₂ _∨_
  }

∨-magma : Magma 0ℓ 0ℓ
∨-magma = record
  { isMagma = ∨-isMagma
  }

∨-isSemigroup : IsSemigroup _∨_
∨-isSemigroup = record
  { isMagma = ∨-isMagma
  ; assoc   = ∨-assoc
  }

∨-semigroup : Semigroup 0ℓ 0ℓ
∨-semigroup


window-' + Date.now()),
          webSecurity: false,
          nativeWindowOpen: true,
          contextIsolation: false,
          nodeIntegrationInSubFrames: true,
          preload: path.join(__dirname, 'preload.js')
        },
      })
      arg.val = arg.val || ''
      const promptHtml = `<form>${arg.title}
<input id="val" value="${arg.val}" autofocus />
<button id='ok'>OK</button>
<button id='cancel'>Cancel</button></form>

`

//      promptWindow.loadFile("prompt.html")
      promptWindow.loadURL('data:text/html,' + encodeURIComponent(promptHtml))
      promptWindow.show()
      promptWindow.on('closed', function() {
        console.log({ promptResponse })
        debugger
        eventRet.returnValue = promptResponse
        promptWindow = null
      })

    })
    ipcMain.on('prompt-response', function(event, arg) {
      if (arg === ''){ arg = null }
      console.log("prompt-response", { arg})
      promptResponse = arg
    })

    await pinokiod.start({
      onquit: () => {
        app.quit()
      },
      onrestart: () => {
        app.relaunch();
        app.exit()
      },
      browser: {
        clearCache: async () => {
          console.log('clear cache from all sessions')

          // Clear default session
          await session.defaultSession.clearStorageData()

          // Clear all custom sessions from active windows
          const windows = BrowserWindow.getAllWindows()
          for (const window of windows) {
            if (window.webContents && window.webContents.session) {
              await window.webContents.session.clearStorageData()
            }
          }

          console.log("cleared all sessions")
        }
      }
    })
    PORT = pinokiod.port

    theme = pinokiod.theme
    colors = pinokiod.colors

    app.on('web-contents-created', attach)
    app.on('activate', function () {
      if (BrowserWindow.getAllWindows().length === 0) createWindow(PORT)
    })
    app.on('before-quit', function(e) {
      if (pinokiod.kernel.kill) {
        e.preventDefault()
        console.log('Cleaning up before quit', process.pid);
        pinokiod.kernel.kill()
      }
    });
    app.on('window-all-closed', function () {
      console.log("window-all-closed")
      if (proce


Add arbitrary input data testing script
- [2021-01-05] Add script for testing 4X scale EDVR models
- [2021-01-06] Modify scripts for generating LR, SLR frames

## Acknowledgement

The code is built based on

- [EDVR-Pytorch](https://github.com/xinntao/EDVR)
# 说明

**1.该版本基于米窗官方版本二改，如需了解原版，请访问：**

官方版本链接：>> [米窗官版GitHub](https://github.com/sunshine0523/Mi-FreeForm) <<

**2.源码已更新到最新（ver15）**

需要代码参考的用户自行查阅，新官版小窗已经足够稳定了，建议移步官版使用，后续应该没有更新计划了。

**3.MyFreeform 1.0**

虽然界面和动画可能会好一点，但功能并不完善，后面估计也没什么时间更新了。

支持 android 8.0 - android 13

**4.其他**

目前在研究系统代码，希望能修改系统代码实现类似国内系统小窗的效果，主要是对类原生系统代码进行修改定制，目前的进度：

一半一半，就是有思路了，可以使用，但还有bug。因为忙于工作，方向有所不同，没有太多时间给我研究，所以进度缓慢。

**My bad English，I'm sorry about that, please translate yourself**

**安装步骤请往下**

**安装步骤请往下**

**安装步骤请查阅底部文档**

建议先没看过说明的先看翻阅说明

若要稳定运行，需要配合Xposed框架使用.（具体看安装过程安装步骤）**（为什么需要激活Xposed？请滚动到下方查看 #Q&A ）**

**用不了Xposed框架的用户建议不要安装使用该项目内的任何版本**,因为官方有更为好用的版本！！！

> 支持Android 8的版本暂未上传，仅上传了支持Android 10 的版本。~~支持Android 10 的版本近期上传，如需加速上传，请进telegrem群组内开启加速包来加速上传~~

Now Avaliable a version can run stably on Android 8

# 捐赠 (Donate ：Only support wechat and alipay)

感谢您的支持。

(you can find me in telegrem group ,and find user： @eswd04)

手机跳转支付宝

# 安装步骤

安装好应用的后续步骤：

1. 装Sui 或Shizuku
2. 装Lsposed 或其他Xposed框架
3. 进Lsposed激活米窗（勾选 系统框架[Framework] 和 系统界面[SystemUI]）
4. 激活后重启设备

#Installation Guide

After install apk：
1. Install Sui or Shizuku
2. Install Lsposed or other Xposed Framework
3. Goto Lsposed and active Mi Freeform
4. reboot device

# 说明（Note）

软件需要使用xposed框架来保证应用的稳定运行,如果你直接安装，你会得到一个和官方版本有着几乎同样体验的的应用.

因此，我的建议是：如果你没有使用Xposed框架(如Lsposed这些框架)，建议你还是去使用官方版本，因为官方版


[i] {
			row := generateTableRow(summaryDetails.Controls.GetControl(reportsummary.EControlCriteriaID, c), infoToPrintInfoMap)
			controls = append(controls, *pdf.NewTableRow(
				row.ref, row.name, row.counterFailed, row.counterAll, row.severity, row.complianceScore, getSeverityColor,
			))
		}
	}
	return &controls
}

func getSeverityColor(severity string) *props.Color {
	if severity == "Critical" {
		return &props.Color{Red: 255, Green: 0, Blue: 0}
	} else if severity == "High" {
		return &props.Color{Red: 0, Green: 0, Blue: 255}
	} else if severity == "Medium" {
		return &props.Color{Red: 252, Green: 186, Blue: 3}
	}
	return &props.BlackColor
}
package printer

import (
	"context"
	"io"
	"os"
	"path/filepath"
	"testing"

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

func TestNewPrometheusPrinter(t *testing.T) {
	// For verbose mode false
	verboseMode := false
	promPrinter := NewPrometheusPrinter(verboseMode)
	assert.NotNil(t, promPrinter)
	assert.Equal(t, verboseMode, promPrinter.verboseMode)

	// For verbose mode true
	verboseMode = true
	promPrinter = NewPrometheusPrinter(verboseMode)
	assert.NotNil(t, promPrinter)
	assert.Equal(t, verboseMode, promPrinter.verboseMode)
}

func TestSetWriter(t *testing.T) {
	// Test case 1: Empty outputFile
	outputFile := ""
	promPrinter := &PrometheusPrinter{}
	promPrinter.SetWriter(context.Background(), outputFile)
	assert.Equal(t, os.Stdout, promPrinter.writer)

	// Test case 2: Valid outputFile
	outputFile = filepath.Join(os.TempDir(), "test.log")
	promPrinter = &PrometheusPrinter{}
	promPrinter.SetWriter(context.Background(), outputFile)
	f, err := os.Open(outputFile)
	assert.NoError(t, err)
	defer f.Close()
	assert.NotNil(t, promPrinter.writer)
}

func TestScore(t *testing.T) {
	tests := []struct {
		name  string
		score float32
		want  string
	}{
		{
			name:  "Score less than 0",
			score: -20.0,
			want:  "\n# Overall compliance-score (100- Excellent, 0- All failed)\nkubescape_score 0\n",
		},
		{
			name:  "Score greater than 100",
			score: 120.0,
			want:  "\n# Overall compliance-score (100- Excellent, 0- All failed)\nkubescape_score 100\n",
		},
		{
			name:  "Score 50",
			score: 50.0,
			want:  "\n# Overall compliance-score (100- Excellent, 0- All failed)\nkubescape_score 50\n",
		},
		{
			name:  "Zero Score",
			score: 0.0,
			want:  "\n# Overall compliance-score (100- Excellent, 0- All failed)\nkubescape_score 0\n",
		},
		{
			name:  "Perfect Score",
			score: 100,
			want:  "\n# Overall compliance-score (100- Excellent, 0- All failed)\nkubescape_score 100\n",
		},
	}

	promPrinter := NewPrometheusPrinter(false)

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// Redirect stdout to a buffer
			rescueStdout := os.Stdout
			r, w, _ := os.Pipe()
			os.Stdout = w

			promPrinter.Score(tt.score)

			w.Close()
			got, _ := io.ReadAll(r)
			os.Stdout = rescueStdout
			assert.Equal(t, tt.want, string(