// Creates a Pool of Prefabs public Pool<GameObject> CreatePool(string key, GameObject prefab) { if (this._prefabs.ContainsKey(key)) return this._pools[key] as Pool<GameObject>; this._prefabs.Add(key, prefab); // Create a new pool // - We call the Instantiate method to deal with the prefab-edness Pool<GameObject> pool = new Pool<GameObject>( DEFAULT_CAPACITY, () => { GameObject tmp = Instantiate( prefab, Vector3.zero, Quaternion.identity ) as GameObject; tmp.SetActive(false); return tmp; } ); this._pools.Add(key, pool); return pool; }
public ProducerTopicStats(string clientId) { this.ClientId = clientId; this.valueFactory = k => new ProducerTopicMetrics(k); this.stats = new Pool<ClientIdAndTopic, ProducerTopicMetrics>(this.valueFactory); this.allTopicsStats = new ProducerTopicMetrics(new ClientIdAndTopic(this.ClientId, "AllTopics")); }
public EjectHostFromPoolAction(Pool pool,Host hostToEject) : base(pool.Connection, string.Format(Messages.REMOVING_SERVER_FROM_POOL, hostToEject.Name, pool.Name)) { this.Pool = pool; this.Host = hostToEject; this.Description = Messages.WAITING; }
void Awake(){ gene = geneIni; biomatter = biomatterIni; newSpawnCostGene = newSpawnGene; newSpawnCostBio = newSpawnBio; pool = GameObject.Find ("Pool").GetComponent<Pool> (); }
public void SetPool(Pool pool) { _pool = pool; _pool.GetGroup(Matcher.SettingsModel).OnEntityUpdated += update; _group = pool.GetGroup(Matcher.DifficultyController); _models = pool.GetGroup(Matcher.DifficultyModel); }
static public void ShootCircleBullets(Pool pool, Entity e) { for(int i = 0; i < 12; ++i) { ShootCircleBullet(pool, e, i, 12); } }
void Awake() { if (GameObject.FindWithTag("PoolHolder")) { masterPoolHolder = GameObject.FindWithTag("PoolHolder"); } else { masterPoolHolder = new GameObject("Pool Holder"); masterPoolHolder.tag = "PoolHolder"; } if (masterPool == null) { masterPool = new List<Pool>(); } Pool existingPool = null; foreach (var p in masterPool) { if (p.prefab == prefab) existingPool = p; } if (existingPool == null) { pool = new Pool(); pool.prefab = prefab; if (parentGO == null) { pool.holder = new GameObject(string.Format("{0} Holder", prefab.name)); pool.holder.transform.parent = masterPoolHolder.transform; } else { pool.holder = parentGO; } if (instantiateOnAwake) { for (int i = 0; i < poolAmount; i++) { AddPoolObject(); } } masterPool.Add(pool); } else { pool = existingPool; } }
public DataBuffer CreateIndexBuffer(int length, Usage usage, Format format, Pool pool) { IntPtr pOut = IntPtr.Zero; int res = Interop.Calli(comPointer, length, (int)usage, (int)format, (int)pool, (IntPtr)(void*)&pOut, IntPtr.Zero,(*(IntPtr**)comPointer)[27]); if( res < 0 ) { throw new SharpDXException( res ); } return new DataBuffer( pOut ); }
void Start() { _pool = new Pool(ComponentIds.TotalComponents); _systems = createSystems(); _systems.Start(); _pool.CreateEntity().AddMyString(""); }
public void SetPool(Pool pool) { group = pool.GetGroup(Matcher.AllOf(Matcher.PlayerScore, Matcher.GameObject)); killInfo = pool.GetGroup(Matcher.AllOf(Matcher.KillInfo, Matcher.GameObject)); score = pool.GetGroup(Matcher.Score); translation = pool.GetGroup(Matcher.TranslationService); }
public void SetPool(Pool pool) { _pool = pool; _camera = _pool.GetGroup(Matcher.Camera); _time = _pool.GetGroup(Matcher.Time); _group = pool.GetGroup(Matcher.AllOf(Matcher.Path, Matcher.GameObject, Matcher.Velocity, Matcher.VelocityLimit, Matcher.Position)); }
/// <summary> /// Initializes a new instance of the <see cref="SelectedItem"/> class. /// </summary> /// <param name="xenObject">The xen object that is selected.</param> /// <param name="connection">The connection of the xen object.</param> /// <param name="hostAncestor">The host ancestor of the xen object in the tree.</param> /// <param name="poolAncestor">The pool ancestor of the xen object in the tree.</param> public SelectedItem(IXenObject xenObject, IXenConnection connection, Host hostAncestor, Pool poolAncestor) { _xenObject = xenObject; _hostAncestor = hostAncestor; _poolAncestor = poolAncestor; _connection = connection; }
public void OnEnable() { m_Pool = PoolManager.CreatePool(PrefabPaths.CAPSULE, poolSize: 0, parent: transform); StartCoroutine(TestQueueInit()); }
public WlbOptimizePoolAction(Pool pool, Dictionary<VM, WlbOptimizationRecommendation> vmOptLst, string optId) : base(pool.Connection, string.Format(Messages.WLB_OPTIMIZING_POOL, Helpers.GetName(pool).Ellipsise(50))) { if (pool == null) throw new ArgumentNullException("pool"); if (vmOptLst == null) throw new ArgumentNullException("vmOptLst"); this.Pool = pool; this.vmOptList = vmOptLst; this.optId = optId; #region RBAC Dependencies // HA adjustments ApiMethodsToRoleCheck.Add("pool.sync_database"); ApiMethodsToRoleCheck.Add("pool.set_ha_host_failures_to_tolerate"); ApiMethodsToRoleCheck.Add("vm.set_ha_restart_priority"); ApiMethodsToRoleCheck.Add("vm.set_ha_always_run"); ApiMethodsToRoleCheck.Add("vm.assert_can_boot_here"); ApiMethodsToRoleCheck.Add("vm.assert_agile"); ApiMethodsToRoleCheck.AddRange(Role.CommonTaskApiList); ApiMethodsToRoleCheck.AddRange(Role.CommonSessionApiList); #endregion }
void Start () { //Inicializamos el path para evitar errores; initPos = new Vector3(0,0,100000); //Buscamos la pool para solicitar los creeps; pool = GameObject.Find ("Pool").GetComponent<Pool> (); //Iniciamos la solicitud de creeps basicos; invokeGene [0] = true; invokeGene [1] = false; Invoke("Create",1f/spawnRate); //Iniciamos la solicitud de creeps de tier; //Invoke("CreateTier",spawnRateTier); //Texto para ver el numero de creeps; textNumberCreeps = GameObject.Find ("CreepsText/Number").GetComponent<UITest> (); numberCreeps = 0; pathfinder = GameObject.Find("GameManager/PathFinder").GetComponent<PathFinding>(); geneSpeed = 0; /*************************** * SOLO PARA LAS PRUEBAS DE LA BARRA DE GENERACION*/ spritesGene [0] = transform.FindChild ("ProductionBar/Prod_0").GetComponent<SpriteRenderer> (); spritesGene [1] = transform.FindChild ("ProductionBar/Prod_1").GetComponent<SpriteRenderer> (); spritesGene [2] = transform.FindChild ("ProductionBar/Prod_2").GetComponent<SpriteRenderer> (); spritesGene [3] = transform.FindChild ("ProductionBar/Prod_3").GetComponent<SpriteRenderer> (); spritesGene [4] = transform.FindChild ("ProductionBar/Prod_4").GetComponent<SpriteRenderer> (); /*****************************/ touchManager = GameObject.Find ("GameManager/TouchManager").GetComponent<TouchManager> (); tier = 0; subType = -1; numBioPools = 0; }
public void SetPool(Pool pool) { this.pool = pool; group = pool.GetGroup(Matcher.FirstBoss); time = pool.GetGroup(Matcher.Time); createStages(); }
public BonusesView(Pool pool, IViewService viewService, IBonusService bonusService) : base("EditorView/Bonus/BonusesView") { this.pool = pool; this.viewService = viewService; this.bonusService = bonusService; }
protected static void FixAd(Pool pool, List<Host> hostsToAdConfigure, Func<Host, AdUserAndPassword> getAdCredentials) { if (hostsToAdConfigure.Count == 0) return; Host poolMaster = Helpers.GetMaster(pool); AsyncAction action; bool success = true; do { success = true; AdUserAndPassword adUserAndPassword = getAdCredentials(poolMaster); try { foreach (Host h in hostsToAdConfigure) { action = new EnableAdAction(Helpers.GetPoolOfOne(h.Connection), poolMaster.external_auth_service_name,adUserAndPassword.Username, adUserAndPassword.Password) {Host = h}; action.RunExternal(null); } } catch (EnableAdAction.CredentialsFailure) { success = false; } } while (!success); }
public PoolScope(Pool pool, GlobalScope globalScope) : base(globalScope) { if (pool == null) throw new ArgumentNullException("pool"); this.Pool = pool; }
public PoolRef(GameObject src) { cachedObj = src; cachedPool = Pool.Instance; if(src != null) ptr = cachedPool.GetPoolInstance(src); }
public MineralsFactory(Simulator simulator) { Simulator = simulator; Pool = new Pool<Mineral>(); Minerals = new Dictionary<MineralType, MineralDefinition>(MineralTypeComparer.Default); }
public static void InitializeTerrainNodeDelegates(GraphicsDevice graphicsDevice) { TerrainNodeDelegates.graphicsDevice = graphicsDevice; terrainNodeVertexBufferPool = new Pool<TerrainNodeVertexBuffer>(512, t => t.Active) { Initialize = t => { // TODO : don't hard code border usage t.Initialize(graphicsDevice, (Constants.PatchWidth + 2) * (Constants.PatchHeight + 2)); }, Deinitialize = t => { } }; // pre-allocate vertex buffers object[] items = new object[512]; for (int i = 0; i < 512; i++) items[i] = (object)terrainNodeVertexBufferPool.New(); // release items for (int i = 0; i < 50; i++) ((TerrainNodeVertexBuffer)items[i]).Finished(); }
public void Test_DisposeContainedResources() { var disposable = new Disposable(); var pool = new Pool<Disposable>(() => disposable, AccessStrategy.LIFO, LoadingStrategy.Eager, 1); pool.Dispose(); Assert.True(disposable.Disposed); }
static IEnumerable LeaderboardCoroutine(Pool pool, Entity e, float startTime) { var audioSource = GameObject.Find("MusicSource").GetComponent<AudioSource>(); for (int i = 3; i >= 0; --i) { audioSource.volume = 0.25f * (i / 3.0f); yield return WaitMs(e, 200); } audioSource.Stop(); if(pool.hasLowestScoreLeaderboard && pool.lowestScoreLeaderboard.value <= pool.score.value) { audioSource.clip = (AudioClip)Resources.Load("Music/GameOverHighScore"); } else { audioSource.clip = (AudioClip)Resources.Load("Music/GameOver"); } audioSource.volume = 0.25f; audioSource.loop = false; audioSource.Play(); yield return WaitMs(e, 1200); e.AddLeaderboard(""); e.AddResource("Leaderboard"); }
void Start() { _pool = new Pool(ComponentIds.TotalComponents); new PoolObserver(_pool, ComponentIds.componentNames, ComponentIds.componentTypes, "Systems Pool"); _systems = createSystems(); _systems.Initialize(); _pool.CreateEntity().AddMyString(""); }
public MissingSRProblem(Check check, Pool pool, SR sr, Dictionary<string, string> device_config) : base(check) { this.pool = pool; this.sr = sr; this.device_config = device_config; }
/// <summary> /// /// </summary> /// <param name="pool">May not be null. HA must be turned off on the pool.</param> public EditVmHaPrioritiesDialog(Pool pool) { if (pool == null) throw new ArgumentNullException("pool"); if (!pool.ha_enabled) throw new ArgumentException("You may only show the EditVmHaPrioritiesDialog for pools that already have HA turned on"); this.pool = pool; InitializeComponent(); Text += string.Format(" - '{0}'", pool.Name.Ellipsise(30)); assignPriorities.StatusChanged += assignPriorities_StatusChanged; pool.PropertyChanged += pool_PropertyChanged; originalNtol = pool.ha_host_failures_to_tolerate; if (pool.ha_statefiles.Length != 1) { log.ErrorFormat("Cannot show dialog: pool {0} has {1} statefiles, but this dialog can only handle exactly 1. Closing dialog.", pool.Name, pool.ha_statefiles.Length); this.Close(); return; } XenRef<VDI> vdiRef = new XenRef<VDI>(pool.ha_statefiles[0]); VDI vdi = pool.Connection.Resolve(vdiRef); if (vdi == null) { log.Error("Could not resolve HA statefile reference. Closing dialog."); this.Close(); return; } pictureBoxWarningIcon.Image = SystemIcons.Warning.ToBitmap(); Rebuild(); }
public void Test_Dispose_4() { Disposable disposable; PoolResourceHolder<Disposable> poolResourceHolder; var pool = new Pool<Disposable>(() => new Disposable(), AccessStrategy.LIFO, LoadingStrategy.Eager, 1); pool.Dispose(); Assert.Throws<ObjectDisposedException>(() => pool.Acquire()); Assert.Throws<ObjectDisposedException>(() => pool.AcquireHolder()); Assert.Throws<ObjectDisposedException>(() => pool.TryAcquire(TimeSpan.FromDays(1), out disposable)); Assert.Throws<ObjectDisposedException>(() => pool.TryAcquireHolder(TimeSpan.FromDays(1), out poolResourceHolder)); Assert.Throws<ObjectDisposedException>(() => pool.TryAcquireImmediately(out disposable)); Assert.Throws<ObjectDisposedException>(() => pool.TryAcquireHolderImmediately(out poolResourceHolder)); // Асинхронные методы. try { pool.AcquireAsync().Wait(); Assert.Fail("Must throw exception."); } catch (AggregateException error) { Assert.True(error.InnerExceptions.Single() is ObjectDisposedException); } try { pool.AcquireHolderAsync().Wait(); Assert.Fail("Must throw exception."); } catch (AggregateException error) { Assert.True(error.InnerExceptions.Single() is ObjectDisposedException); } }
public PerfmonOptionsDefinitionAction(IXenConnection connection, PerfmonOptionsDefinition perfmonOptions) : base(connection, Messages.ACTION_CHANGE_EMAIL_OPTIONS) { this.perfmonOptions = perfmonOptions; pool = Helpers.GetPoolOfOne(connection); this.Description = string.Format(Messages.ACTION_CHANGING_EMAIL_OPTIONS_FOR, pool); }
public CallHomeEnrollNowDialog(Pool pool) { this.pool = pool; InitializeComponent(); InitializeControls(); UpdateButtons(); }
Cell obtainCell() { var cell = Pool<Cell>.obtain(); cell.setLayout( this ); return cell; }
protected override void Run() { // PR-1102: hosts that have been updated, plus the previous edition information - this data will be sent to the licensing server Dictionary <Host, LicensingHelper.LicenseDataStruct> updatedHosts = new Dictionary <Host, LicensingHelper.LicenseDataStruct>(); this.Description = Messages.LICENSE_UPDATING_LICENSES; foreach (IXenObject xo in xos) { Connection = xo.Connection; if (!Connection.IsConnected) { continue; } Host host = null; Pool pool = null; if (xo is Host) { host = xo as Host; } if (xo is Pool) { pool = xo as Pool; host = xo.Connection.Resolve(pool.master); } string previousLicenseServerAddress = null; string previousLicenseServerPort = null; CollectionChangeEventHandler alertsChangeHandler = null; string alertText = null; object lck = new object(); if (host != null && host.license_server.ContainsKey("address")) { previousLicenseServerAddress = host.license_server["address"]; } if (host != null && host.license_server.ContainsKey("port")) { previousLicenseServerPort = host.license_server["port"]; } try { if (pool != null) { pool.Connection.Cache.Hosts.ToList().ForEach(h => SetLicenseServer(h, _licenseServerAddress, _licenseServerPort)); } else { SetLicenseServer(host, _licenseServerAddress, _licenseServerPort); } IXenObject xoClosure = xo; alertsChangeHandler = delegate(object sender, CollectionChangeEventArgs e) { if (e.Action == CollectionChangeAction.Add) { lock (lck) { Alert alert = (Alert)e.Element; Message.MessageType messageType; // if this is a message alert, its Name property will contain the MessageType if (host != null && host.uuid == alert.HostUuid && Enum.TryParse(alert.Name, out messageType)) { switch (messageType) { case Message.MessageType.LICENSE_NOT_AVAILABLE: case Message.MessageType.LICENSE_SERVER_UNREACHABLE: case Message.MessageType.LICENSE_SERVER_VERSION_OBSOLETE: alertText = string.Format(Message.FriendlyBody(alert.Name), xoClosure.Name); break; case Message.MessageType.GRACE_LICENSE: alertText = string.Empty; break; } } } } }; Alert.RegisterAlertCollectionChanged(alertsChangeHandler); // PR-1102: catch the host's license data, before applying the new one, so it can be sent later to the licensing server LicensingHelper.LicenseDataStruct previousLicenseData = new LicensingHelper.LicenseDataStruct(host); if (xo is Host && host != null) { Host.apply_edition(host.Connection.Session, host.opaque_ref, Host.GetEditionText(_edition), false); // PR-1102: populate the list of updated hosts updatedHosts.Add(host, previousLicenseData); } if (xo is Pool) { Pool.apply_edition(xo.Connection.Session, pool.opaque_ref, Host.GetEditionText(_edition)); xo.Connection.Cache.Hosts.ToList().ForEach(h => updatedHosts.Add(h, previousLicenseData)); } Description = Messages.APPLYLICENSE_UPDATED; } catch (Failure e) { for (int i = 0; i < 50; i++) { Thread.Sleep(100); lock (lck) { if (alertText != null) { break; } } } LicenseFailures.Add(new LicenseFailure(host, alertText ?? e.Message)); if (pool != null) { pool.Connection.Cache.Hosts.ToList().ForEach(h => SetLicenseServer(h, previousLicenseServerAddress, previousLicenseServerPort)); } else { SetLicenseServer(host, previousLicenseServerAddress, previousLicenseServerPort); } } finally { Alert.DeregisterAlertCollectionChanged(alertsChangeHandler); } } // PR-1102: Send licensing data to the activation server if (updatedHosts.Count > 0) { LicensingHelper.SendLicenseEditionData(updatedHosts, Host.GetEditionText(_edition)); } if (LicenseFailures.Count > 0) { string exceptionText = LicenseFailures.Count == 1 ? string.Format(Messages.LICENSE_ERROR_1, LicenseFailures[0].Host.Name) : string.Format(Messages.LICENSE_ERROR_MANY, LicenseFailures.Count, new List <IXenObject>(xos).Count); if (DoOnLicensingFailure != null) { DoOnLicensingFailure(LicenseFailures, exceptionText); } throw new InvalidOperationException(exceptionText); } }
public static async Task Execute() { var issuerWalletName = "issuerWallet"; var proverWalletName = "proverWallet"; try { //1. Create and Open Pool await PoolUtils.CreatePoolLedgerConfig(); //2. Issuer Create and Open Wallet await WalletUtils.CreateWalleatAsync(PoolUtils.DEFAULT_POOL_NAME, issuerWalletName, "default", null, null); //3. Prover Create and Open Wallet await WalletUtils.CreateWalleatAsync(PoolUtils.DEFAULT_POOL_NAME, proverWalletName, "default", null, null); //4. Open pool and wallets in using statements to ensure they are closed when finished. using (var pool = await Pool.OpenPoolLedgerAsync(PoolUtils.DEFAULT_POOL_NAME, "{}")) using (var issuerWallet = await Wallet.OpenWalletAsync(issuerWalletName, null, null)) using (var proverWallet = await Wallet.OpenWalletAsync(proverWalletName, null, null)) { //5. Issuer create ClaimDef var schemaJson = "{\n" + " \"seqNo\":1,\n" + " \"data\": {\n" + " \"name\":\"gvt\",\n" + " \"version\":\"1.0\",\n" + " \"keys\":[\"age\",\"sex\",\"height\",\"name\"]\n" + " }\n" + "}"; var issuerDid = "NcYxiDXkpYi6ov5FcYDi1e"; var claimDef = await AnonCreds.IssuerCreateAndStoreClaimDefAsync(issuerWallet, issuerDid, schemaJson, null, false); //6. Prover create Master Secret var masterSecret = "masterSecretName"; await AnonCreds.ProverCreateMasterSecretAsync(proverWallet, masterSecret); //7. Prover store Claim Offer var claimOffer = string.Format("{{\"issuer_did\":\"{0}\", \"schema_seq_no\":{1}}}", issuerDid, 1); await AnonCreds.ProverStoreClaimOfferAsync(proverWallet, claimOffer); //8. Prover get Claim Offers var claimOfferFilter = string.Format("{{\"issuer_did\":\"{0}\"}}", issuerDid); var claimOffersJson = await AnonCreds.ProverGetClaimOffersAsync(proverWallet, claimOfferFilter); var claimOffersObject = JArray.Parse(claimOffersJson); Debug.Assert(claimOffersObject.Count == 1); var claimOfferObject = (JObject)claimOffersObject[0]; var claimOfferJson = claimOfferObject.ToString(); //9. Prover create ClaimReq var proverDid = "BzfFCYk"; var claimReq = await AnonCreds.ProverCreateAndStoreClaimReqAsync(proverWallet, proverDid, claimOfferJson, claimDef, masterSecret); Debug.Assert(claimReq != null); //10. Issuer create Claim var claimAttributesJson = "{\n" + " \"sex\":[\"male\",\"5944657099558967239210949258394887428692050081607692519917050011144233115103\"],\n" + " \"name\":[\"Alex\",\"1139481716457488690172217916278103335\"],\n" + " \"height\":[\"175\",\"175\"],\n" + " \"age\":[\"28\",\"28\"]\n" + "}"; var createClaimResult = await AnonCreds.IssuerCreateClaimAsync(issuerWallet, claimReq, claimAttributesJson, -1); var claimJson = createClaimResult.ClaimJson; //11. Prover store Claim await AnonCreds.ProverStoreClaimAsync(proverWallet, claimJson); //12. Prover gets Claims for Proof Request var proofRequestJson = "{\n" + " \"nonce\":\"123432421212\",\n" + " \"name\":\"proof_req_1\",\n" + " \"version\":\"0.1\",\n" + " \"requested_attrs\":{\"attr1_uuid\":{\"schema_seq_no\":1,\"name\":\"name\"},\n" + " \"attr2_uuid\":{\"schema_seq_no\":1,\"name\":\"sex\"}},\n" + " \"requested_predicates\":{\"predicate1_uuid\":{\"attr_name\":\"age\",\"p_type\":\"GE\",\"value\":18}}\n" + " }"; var claimsForProofJson = await AnonCreds.ProverGetClaimsForProofReqAsync(proverWallet, proofRequestJson); var claimsForProof = JObject.Parse(claimsForProofJson); var claimsForAttribute1 = (JArray)claimsForProof["attrs"]["attr1_uuid"]; var claimsForAttribute2 = (JArray)claimsForProof["attrs"]["attr1_uuid"]; var claimsForPredicate = (JArray)claimsForProof["predicates"]["predicate1_uuid"]; Debug.Assert(claimsForAttribute1.Count == 1); Debug.Assert(claimsForAttribute2.Count == 1); Debug.Assert(claimsForPredicate.Count == 1); var claimUuid = claimsForAttribute1[0].Value <string>("claim_uuid"); //13. Prover create Proof var selfAttestedValue = "yes"; var requestedClaimsJson = string.Format("{{\n" + " \"self_attested_attributes\":{{\"self1\":\"{0}\"}},\n" + " \"requested_attrs\":{{\"attr1_uuid\":[\"{1}\", true],\n" + " \"attr2_uuid\":[\"{2}\", false]}},\n" + " \"requested_predicates\":{{\"predicate1_uuid\":\"{3}\"}}\n" + "}}", selfAttestedValue, claimUuid, claimUuid, claimUuid); var schemasJson = string.Format("{{\"{0}\":{1}}}", claimUuid, schemaJson); var claimDefsJson = string.Format("{{\"{0}\":{1}}}", claimUuid, claimDef); var revocRegsJson = "{}"; var proofJson = await AnonCreds.ProverCreateProofAsync(proverWallet, proofRequestJson, requestedClaimsJson, schemasJson, masterSecret, claimDefsJson, revocRegsJson); var proof = JObject.Parse(proofJson); //14. Verifier verify Proof Debug.Assert(string.Equals("Alex", proof["requested_proof"]["revealed_attrs"]["attr1_uuid"][1].ToString())); Debug.Assert(proof["requested_proof"]["unrevealed_attrs"].Value <string>("attr2_uuid") != null); Debug.Assert(string.Equals(selfAttestedValue, proof["requested_proof"]["self_attested_attrs"].Value <string>("self1"))); var valid = await AnonCreds.VerifierVerifyProofAsync(proofRequestJson, proofJson, schemasJson, claimDefsJson, revocRegsJson); Debug.Assert(valid == true); //15. Close wallets and pool await issuerWallet.CloseAsync(); await proverWallet.CloseAsync(); await pool.CloseAsync(); } } finally { //16. Delete wallets and Pool ledger config await WalletUtils.DeleteWalletAsync(issuerWalletName, null); await WalletUtils.DeleteWalletAsync(proverWalletName, null); await PoolUtils.DeletePoolLedgerConfigAsync(PoolUtils.DEFAULT_POOL_NAME); } Console.WriteLine("Anoncreds sample -> completed"); }
public MixedPoolServerSelectionWarning(Check check, Pool pool) : base(check) { this.pool = pool; }
public ServerSelectionProblem(Check check, Pool pool) : base(check, pool) { }
private void Start() { GunChange(_gunType); pool = new Pool <PoolObject>(new PrefabFactory <PoolObject>(_bulletPrefab)); }
protected sealed override void ExecuteCore(SelectedItemCollection selection) { //It only supports one item selected for now Trace.Assert(selection.Count == 1); XenAPI.Network network = (XenAPI.Network)selection.FirstAsXenObject; List <PIF> pifs = network.Connection.ResolveAll(network.PIFs); if (pifs.Count == 0) { // Should never happen as long as the caller is enabling the button correctly, but // it's possible in a tiny window across disconnecting. log.Error("Network has no PIFs"); return; } // We just want one, so that we can name it. PIF pif = pifs[0]; string msg = string.Format(Messages.DELETE_BOND_MESSAGE, pif.Name); bool will_disturb_primary = NetworkingHelper.ContainsPrimaryManagement(pifs); bool will_disturb_secondary = NetworkingHelper.ContainsSecondaryManagement(pifs); if (will_disturb_primary) { Pool pool = Helpers.GetPool(network.Connection); if (pool != null && pool.ha_enabled) { new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Error, string.Format(Messages.BOND_DELETE_HA_ENABLED, pif.Name, pool.Name), Messages.DELETE_BOND)).ShowDialog(Parent); return; } string message = string.Format(will_disturb_secondary ? Messages.BOND_DELETE_WILL_DISTURB_BOTH : Messages.BOND_DELETE_WILL_DISTURB_PRIMARY, msg); if (DialogResult.OK != new ThreeButtonDialog( new ThreeButtonDialog.Details(SystemIcons.Warning, message, Messages.DELETE_BOND), "NetworkingConfigWarning", new ThreeButtonDialog.TBDButton(Messages.BOND_DELETE_CONTINUE, DialogResult.OK), ThreeButtonDialog.ButtonCancel).ShowDialog(Parent)) { return; } } else if (will_disturb_secondary) { if (DialogResult.OK != new ThreeButtonDialog( new ThreeButtonDialog.Details(SystemIcons.Warning, string.Format(Messages.BOND_DELETE_WILL_DISTURB_SECONDARY, msg), Messages.XENCENTER), ThreeButtonDialog.ButtonOK, ThreeButtonDialog.ButtonCancel).ShowDialog(Parent)) { return; } } else { if (DialogResult.OK != new ThreeButtonDialog( new ThreeButtonDialog.Details(SystemIcons.Warning, msg, Messages.XENCENTER), new ThreeButtonDialog.TBDButton(Messages.OK, DialogResult.OK, ThreeButtonDialog.ButtonType.ACCEPT, true), ThreeButtonDialog.ButtonCancel).ShowDialog(Program.MainWindow)) { return; } } // The UI shouldn't offer deleting a bond in this case, but let's make sure we've // done the right thing and that the bond hasn't been deleted in the meantime. (CA-27436). Bond bond = pif.BondMasterOf; if (bond != null) { new Actions.DestroyBondAction(bond).RunAsync(); } }
public void TearDown() { _healthMonitor?.Dispose(); Pool?.Dispose(); Pool = null; }
public void RegenTargetPoolValueCalculatesCorrectly(Pool targetPool, double expected) { var statFactory = new StatFactory(); var targetPoolStat = statFactory.RegenTargetPool(default, Pool.Life);
public static Group GetGroup(this Pool pool, IComp compData) { return(pool.GetGroup(compData.EntitasData.Match)); }
public void Dispose() { Pool?.Return(this); }
public void GetNextHost_LocalhostFallbackOff_AfterRefreshNoEndpoints_Throws() { CreatePool("host1, host2, host3"); ChangeConfig(""); Should.Throw <EnvironmentException>(() => Pool.GetNextHost()); }
public static void FillPolyMesh(this IPositionSpline spline, PolyMesh polyMesh, Matrix4x4? applyTransform = null, float? startT = null, float? endT = null, int? numSegments = null, float[] radii = null, float? radius = null, bool drawDebug = false) { float minT, maxT; int effNumSegments; //bool useRadiusArr = false; //float[] effRadii; float effRadius; bool useTransform; Matrix4x4 transform; RuntimeGizmos.RuntimeGizmoDrawer drawer = null; if (drawDebug) { RuntimeGizmos.RuntimeGizmoManager.TryGetGizmoDrawer(out drawer); } // Assign parameters based on optional inputs { minT = spline.minT; if (startT.HasValue) { minT = startT.Value; } maxT = spline.maxT; if (endT.HasValue) { maxT = endT.Value; } effNumSegments = 32; if (numSegments.HasValue) { effNumSegments = numSegments.Value; effNumSegments = Mathf.Max(1, effNumSegments); } //useRadiusArr = false; effRadius = 0.02f; if (radius.HasValue) { effRadius = radius.Value; } //effRadii = null; //if (radii != null) { // useRadiusArr = true; // effRadii = radii; //} useTransform = false; transform = Matrix4x4.identity; if (applyTransform.HasValue) { useTransform = true; transform = applyTransform.Value; } } // Multiple passes through the spline data will construct all the positions and // orientations we need to build the mesh. polyMesh.Clear(); var crossSection = new CircularCrossSection(effRadius, 16); float tStep = (maxT - minT) / effNumSegments; Vector3 position = Vector3.zero; Vector3 dPosition = Vector3.zero; Vector3? tangent = null; var positions = Pool<List<Vector3>>.Spawn(); positions.Clear(); var normals = Pool<List<Vector3>>.Spawn(); // to start, normals contain velocities, normals.Clear(); // but zero velocities are filtered out. var binormals = Pool<List<Vector3>>.Spawn(); binormals.Clear(); var crossSection0Positions = Pool<List<Vector3>>.Spawn(); crossSection0Positions.Clear(); var crossSection1Positions = Pool<List<Vector3>>.Spawn(); crossSection1Positions.Clear(); try { // Construct a rough list of positions and normals for each cross section. Some // of the normals may be zero, so we'll have to fix those. for (int i = 0; i <= effNumSegments; i++) { var t = minT + i * tStep; spline.ValueAndDerivativeAt(t, out position, out dPosition); if (useTransform) { positions.Add(transform.MultiplyPoint3x4(position)); normals.Add(transform.MultiplyVector(dPosition).normalized); } else { positions.Add(position); normals.Add(dPosition.normalized); } if (!tangent.HasValue && dPosition.sqrMagnitude > 0.001f * 0.001f) { tangent = (transform * dPosition.WithW(1)).ToVector3().normalized.Perpendicular(); } } // In case we never got a non-zero velocity, try to construct a tangent based on // delta positions. if (!tangent.HasValue) { if (positions[0] == positions[1]) { // No spline mesh possible; there's no non-zero length segment. return; } else { var delta = positions[1] - positions[0]; // Very specific case: Two points, each with zero velocity, use delta for // normals if (positions.Count == 2) { normals[0] = delta; normals[1] = delta; } tangent = delta.Perpendicular(); } } // Try to propagate non-zero normals into any "zero" normals. for (int i = 0; i <= effNumSegments; i++) { if (normals[i].sqrMagnitude < 0.00001f) { if (i == 0) { normals[i] = normals[i + 1]; } else if (i == effNumSegments) { normals[i] = normals[i - 1]; } else { normals[i] = Vector3.Slerp(normals[i - 1], normals[i + 1], 0.5f); } } if (normals[i].sqrMagnitude < 0.00001f) { // OK, we tried, but we still have zero normals. Error and fail. throw new System.InvalidOperationException( "Unable to build non-zero normals for this spline during PolyMesh " + "construction"); } } // With a set of normals and a starting tangent vector, we can construct all the // binormals we need to have an orientation and position for every cross-section. Vector3? lastNormal = null; Vector3? lastBinormal = null; for (int i = 0; i <= effNumSegments; i++) { var normal = normals[i]; Vector3 binormal; if (!lastBinormal.HasValue) { binormal = Vector3.Cross(normal, tangent.Value); } else { var rotFromLastNormal = Quaternion.FromToRotation(lastNormal.Value, normal); binormal = rotFromLastNormal * lastBinormal.Value; } binormals.Add(binormal); lastNormal = normal; lastBinormal = binormal; } // With positions, normals, and binormals for every cross section, add positions // and polygons for each cross section and their connections to the PolyMesh. int cs0Idx = -1, cs1Idx = -1; for (int i = 0; i + 1 <= effNumSegments; i++) { var pose0 = new Pose(positions[i], Quaternion.LookRotation(normals[i], binormals[i])); var pose1 = new Pose(positions[i + 1], Quaternion.LookRotation(normals[i + 1], binormals[i + 1])); if (drawDebug) { drawer.PushMatrix(); drawer.matrix = transform.inverse; drawer.color = LeapColor.blue; drawer.DrawRay(pose0.position, normals[i] * 0.2f); drawer.color = LeapColor.red; drawer.DrawRay(pose0.position, binormals[i] * 0.2f); drawer.PopMatrix(); } bool addFirstPositions = i == 0; // Add positions from Cross Section definition to reused buffers. if (addFirstPositions) { crossSection.FillPositions(crossSection0Positions, pose0); } crossSection.FillPositions(crossSection1Positions, pose1); // Add positions from buffers into the PolyMesh. if (addFirstPositions) { cs0Idx = polyMesh.positions.Count; polyMesh.AddPositions(crossSection0Positions); } cs1Idx = polyMesh.positions.Count; polyMesh.AddPositions(crossSection1Positions); // Add polygons to connect one cross section in the PolyMesh to the other. crossSection.AddConnectingPolygons(polyMesh, cs0Idx, cs1Idx); Utils.Swap(ref crossSection0Positions, ref crossSection1Positions); cs0Idx = cs1Idx; } } finally { positions.Clear(); Pool<List<Vector3>>.Recycle(positions); normals.Clear(); Pool<List<Vector3>>.Recycle(normals); binormals.Clear(); Pool<List<Vector3>>.Recycle(binormals); crossSection0Positions.Clear(); Pool<List<Vector3>>.Recycle(crossSection0Positions); crossSection1Positions.Clear(); Pool<List<Vector3>>.Recycle(crossSection1Positions); } }
internal DialogResult ShowCreationWarning() { List <PIF> pifs = BondedPIFs; bool will_disturb_primary = NetworkingHelper.ContainsPrimaryManagement(pifs); bool will_disturb_secondary = NetworkingHelper.ContainsSecondaryManagement(pifs); if (will_disturb_primary && will_disturb_secondary) { using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Error, Messages.BOND_CREATE_WILL_DISTURB_BOTH, Messages.BOND_CREATE))) { dlg.ShowDialog(this); } return(DialogResult.Cancel); } if (will_disturb_primary) { Pool pool = Helpers.GetPool(Connection); if (pool != null && pool.ha_enabled) { using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Error, string.Format(Messages.BOND_CREATE_HA_ENABLED, pool.Name), Messages.BOND_CREATE))) { dlg.ShowDialog(this); } return(DialogResult.Cancel); } DialogResult dialogResult; using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details(SystemIcons.Warning, Messages.BOND_CREATE_WILL_DISTURB_PRIMARY, Messages.BOND_CREATE), "BondConfigError", new ThreeButtonDialog.TBDButton(Messages.BOND_CREATE_CONTINUE, DialogResult.OK), ThreeButtonDialog.ButtonCancel)) { dialogResult = dlg.ShowDialog(this); } return(dialogResult); } if (will_disturb_secondary) { DialogResult dialogResult; using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Warning, Messages.BOND_CREATE_WILL_DISTURB_SECONDARY, Messages.BOND_CREATE), ThreeButtonDialog.ButtonOK, ThreeButtonDialog.ButtonCancel)) { dialogResult = dlg.ShowDialog(this); } return(dialogResult); } return(DialogResult.OK); }
void when_created() { Pool pool = null; Group groupA = null; GroupObserver observerA = null; IMatcher mactherA = Matcher.AllOf(new[] { CID.ComponentA }); before = () => { pool = new Pool(CID.NumComponents); groupA = pool.GetGroup(mactherA); }; context["when observing with eventType OnEntityAdded"] = () => { before = () => { observerA = new GroupObserver(groupA, GroupEventType.OnEntityAdded); }; it["is empty when nothing happend"] = () => { observerA.collectedEntities.should_be_empty(); }; context["when entity collected"] = () => { Entity e = null; before = () => { e = pool.CreateEntity(); e.AddComponentA(); }; it["returns collected entities"] = () => { var entities = observerA.collectedEntities; entities.Count.should_be(1); entities.should_contain(e); }; it["only collects matching entities"] = () => { var e2 = pool.CreateEntity(); e2.AddComponentB(); var entities = observerA.collectedEntities; entities.Count.should_be(1); entities.should_contain(e); }; it["collects entities only once"] = () => { e.RemoveComponentA(); e.AddComponentA(); var entities = observerA.collectedEntities; entities.Count.should_be(1); entities.should_contain(e); }; it["clears collected entities on deactivation"] = () => { observerA.Deactivate(); observerA.collectedEntities.should_be_empty(); }; it["doesn't collect entities when deactivated"] = () => { observerA.Deactivate(); var e2 = pool.CreateEntity(); e2.AddComponentA(); observerA.collectedEntities.should_be_empty(); }; it["continues collecting when activated"] = () => { observerA.Deactivate(); var e1 = pool.CreateEntity(); e1.AddComponentA(); observerA.Activate(); var e2 = pool.CreateEntity(); e2.AddComponentA(); var entities = observerA.collectedEntities; entities.Count.should_be(1); entities.should_contain(e2); }; it["clears collected entities"] = () => { observerA.ClearCollectedEntities(); observerA.collectedEntities.should_be_empty(); }; it["can ToString"] = () => { observerA.ToString().should_be("GroupObserver(Group(AllOf(1)))"); }; }; context["reference counting"] = () => { it["retains entity even after destroy"] = () => { var e = pool.CreateEntity(); e.AddComponentA(); e.OnEntityReleased += entity => this.Fail(); pool.DestroyEntity(e); e.retainCount.should_be(1); }; it["releases entity when clearing collected entities"] = () => { var e = pool.CreateEntity(); e.AddComponentA(); pool.DestroyEntity(e); observerA.ClearCollectedEntities(); e.retainCount.should_be(0); }; it["retains entities only once"] = () => { var e = pool.CreateEntity(); e.AddComponentA(); e.ReplaceComponentA(new ComponentA()); pool.DestroyEntity(e); e.retainCount.should_be(1); }; }; }; context["when observing with eventType OnEntityRemoved"] = () => { before = () => { observerA = new GroupObserver(groupA, GroupEventType.OnEntityRemoved); }; it["returns collected entities"] = () => { var e = pool.CreateEntity(); e.AddComponentA(); observerA.collectedEntities.should_be_empty(); e.RemoveComponentA(); var entities = observerA.collectedEntities; entities.Count.should_be(1); entities.should_contain(e); }; }; context["when observing with eventType OnEntityAddedOrRemoved"] = () => { before = () => { observerA = new GroupObserver(groupA, GroupEventType.OnEntityAddedOrRemoved); }; it["returns collected entities"] = () => { var e = pool.CreateEntity(); e.AddComponentA(); var entities = observerA.collectedEntities; entities.Count.should_be(1); entities.should_contain(e); observerA.ClearCollectedEntities(); e.RemoveComponentA(); entities = observerA.collectedEntities; entities.Count.should_be(1); entities.should_contain(e); }; }; context["when observing multiple groups"] = () => { Group groupB = null; before = () => { groupB = pool.GetGroup(Matcher.AllOf(new[] { CID.ComponentB })); }; it["throws when group count != eventType count"] = expect <GroupObserverException>(() => { observerA = new GroupObserver( new [] { groupA }, new [] { GroupEventType.OnEntityAdded, GroupEventType.OnEntityAdded } ); }); context["when observing with eventType OnEntityAdded"] = () => { before = () => { observerA = new GroupObserver( new [] { groupA, groupB }, new [] { GroupEventType.OnEntityAdded, GroupEventType.OnEntityAdded } ); }; it["returns collected entities"] = () => { var eA = pool.CreateEntity(); eA.AddComponentA(); var eB = pool.CreateEntity(); eB.AddComponentB(); var entities = observerA.collectedEntities; entities.Count.should_be(2); entities.should_contain(eA); entities.should_contain(eB); }; it["can ToString"] = () => { observerA.ToString().should_be("GroupObserver(Group(AllOf(1)), Group(AllOf(2)))"); }; }; context["when observing with eventType OnEntityRemoved"] = () => { before = () => { observerA = new GroupObserver( new [] { groupA, groupB }, new [] { GroupEventType.OnEntityRemoved, GroupEventType.OnEntityRemoved } ); }; it["returns collected entities"] = () => { var eA = pool.CreateEntity(); eA.AddComponentA(); var eB = pool.CreateEntity(); eB.AddComponentB(); observerA.collectedEntities.should_be_empty(); eA.RemoveComponentA(); eB.RemoveComponentB(); var entities = observerA.collectedEntities; entities.Count.should_be(2); entities.should_contain(eA); entities.should_contain(eB); }; }; context["when observing with eventType OnEntityAddedOrRemoved"] = () => { before = () => { observerA = new GroupObserver( new [] { groupA, groupB }, new [] { GroupEventType.OnEntityAddedOrRemoved, GroupEventType.OnEntityAddedOrRemoved } ); }; it["returns collected entities"] = () => { var eA = pool.CreateEntity(); eA.AddComponentA(); var eB = pool.CreateEntity(); eB.AddComponentB(); var entities = observerA.collectedEntities; entities.Count.should_be(2); entities.should_contain(eA); entities.should_contain(eB); observerA.ClearCollectedEntities(); eA.RemoveComponentA(); eB.RemoveComponentB(); entities = observerA.collectedEntities; entities.Count.should_be(2); entities.should_contain(eA); entities.should_contain(eB); }; }; context["when observing with mixed eventTypes"] = () => { before = () => { observerA = new GroupObserver( new [] { groupA, groupB }, new [] { GroupEventType.OnEntityAdded, GroupEventType.OnEntityRemoved } ); }; it["returns collected entities"] = () => { var eA = pool.CreateEntity(); eA.AddComponentA(); var eB = pool.CreateEntity(); eB.AddComponentB(); var entities = observerA.collectedEntities; entities.Count.should_be(1); entities.should_contain(eA); observerA.ClearCollectedEntities(); eA.RemoveComponentA(); eB.RemoveComponentB(); entities = observerA.collectedEntities; entities.Count.should_be(1); entities.should_contain(eB); }; }; }; }
private VirtualTreeNode AddPoolNode(Pool pool) { return(AddNode(Helpers.GetName(pool), Images.GetIconFor(pool), false, pool)); }
public static bool Request(IXenConnection connection, Session session) { bool needRetry = false; Dictionary <string, string> config = Pool.get_health_check_config(session, connection.Cache.Pools[0].opaque_ref); if (BoolKey(config, HealthCheckSettings.STATUS) == false) { ServerListHelper.instance.removeServerCredential(connection.Hostname); log.InfoFormat("Will not report for XenServer {0} that was not Enroll", connection.Hostname); return(false); } //Check if there already some service doing the uploading already if (CanLock(Get(config, HealthCheckSettings.UPLOAD_LOCK), false) == false) { log.InfoFormat("Will not report for XenServer {0} that already locked", connection.Hostname); return(false); } //No Lock has been set before, Check upload is due int intervalInDays = IntKey(config, HealthCheckSettings.INTERVAL_IN_DAYS, HealthCheckSettings.DEFAULT_INTERVAL_IN_DAYS); DateTime lastSuccessfulUpload = DateTime.UtcNow; bool haveSuccessfulUpload = false; if (config.ContainsKey(HealthCheckSettings.LAST_SUCCESSFUL_UPLOAD)) { try { lastSuccessfulUpload = HealthCheckSettings.StringToDateTime(Get(config, HealthCheckSettings.LAST_SUCCESSFUL_UPLOAD)); haveSuccessfulUpload = true; } catch (Exception exn) { log.Error("Catch exception when Parse LAST_SUCCESSFUL_UPLOAD", exn); } } if (haveSuccessfulUpload) {//If last successful update not due. return if (DateTime.Compare(DateTime.UtcNow, lastSuccessfulUpload.AddDays(intervalInDays)) < 0) { log.InfoFormat("Will not report for XenServer {0} that was not due {1} days", connection.Hostname, intervalInDays); return(false); } } if (config.ContainsKey(HealthCheckSettings.LAST_FAILED_UPLOAD)) { try { DateTime LastFailedUpload = HealthCheckSettings.StringToDateTime(Get(config, HealthCheckSettings.LAST_FAILED_UPLOAD)); int retryInterval = IntKey(config, HealthCheckSettings.RETRY_INTERVAL, HealthCheckSettings.DEFAULT_RETRY_INTERVAL); if (DateTime.Compare(LastFailedUpload.AddDays(retryInterval), DateTime.UtcNow) <= 0) { if ((!haveSuccessfulUpload) || (DateTime.Compare(lastSuccessfulUpload, LastFailedUpload) < 0)) { log.InfoFormat("Retry since retryInterval{0} - {1} > {2} met", LastFailedUpload, DateTime.UtcNow, retryInterval); needRetry = true; } } } catch (Exception exn) { log.Error("Catch exception when check if retry was needed", exn); } } DateTime currentTime = DateTime.Now; if (!needRetry) {//Check if uploading schedule meet only for new upload DayOfWeek dayOfWeek; if (!Enum.TryParse(Get(config, HealthCheckSettings.DAY_OF_WEEK), out dayOfWeek)) { log.Error("DAY_OF_WEEK not existed"); return(false); } if (!config.ContainsKey(HealthCheckSettings.TIME_OF_DAY)) { log.Error("TIME_OF_DAY not existed"); return(false); } int TimeOfDay = IntKey(config, HealthCheckSettings.TIME_OF_DAY, HealthCheckSettings.GetDefaultTime()); if (currentTime.DayOfWeek != dayOfWeek || currentTime.Hour != TimeOfDay) { log.InfoFormat("Will not report for XenServer {0} for incorrect schedule", connection.Hostname); return(false); } log.InfoFormat("Upload schedule for {0} is {1}:{2}, meet current time {3}", connection.Hostname, dayOfWeek, TimeOfDay, currentTime.ToString()); } return(getLock(connection, session)); }
// ------------------ Methods // Implement ISetPool to get the pool used when calling // pool.CreateSystem<VelocitySystem>(); public void SetPool(Pool pool) { _pool = pool; }
private Problem GetProblem(IXenConnection connection, XenRef <VM> vmRef, string[] exception) { try { System.Diagnostics.Trace.Assert(exception.Length > 0); VM vm; switch (exception[0]) { case Failure.VM_REQUIRES_SR: vm = connection.Resolve <VM>(vmRef); if (vm == null) { throw new NullReferenceException(Failure.VM_REQUIRES_SR); } XenRef <SR> srRef = new XenRef <SR>(exception[2]); SR sr = connection.Resolve <SR>(srRef); if (sr == null) { throw new NullReferenceException(Failure.VM_REQUIRES_SR); } if (sr.content_type == SR.Content_Type_ISO) { return(new LocalCD(this, vm)); } else if (!sr.shared) { // Only show the problem if it is really local storage // As the pbd-plug checks will pick up broken storage. return(new LocalStorage(this, vm)); } return(null); case Failure.VM_MISSING_PV_DRIVERS: vm = connection.Resolve <VM>(vmRef); if (vm == null) { throw new NullReferenceException(Failure.VM_MISSING_PV_DRIVERS); } return(new NoPVDrivers(this, vm)); case "VM_OLD_PV_DRIVERS": vm = connection.Resolve <VM>(vmRef); if (vm == null) { throw new NullReferenceException("VM_OLD_PV_DRIVERS"); } return(new PVDriversOutOfDate(this, vm)); case Failure.NO_HOSTS_AVAILABLE: //CA-63531: Boston server will come here in case of single host pool or standalone host vm = connection.Resolve <VM>(vmRef); if (vm == null) { throw new NullReferenceException(Failure.NO_HOSTS_AVAILABLE); } return(new NoHosts(this, vm)); case Failure.HOST_NOT_ENOUGH_FREE_MEMORY: vm = connection.Resolve <VM>(vmRef); if (vm == null) { throw new NullReferenceException(Failure.HOST_NOT_ENOUGH_FREE_MEMORY); } Pool pool = Helpers.GetPool(vm.Connection); if (pool == null || pool.Connection.Cache.HostCount == 1) { //CA-63531: Cowley server will come here in case of single host pool or standalone host return(new NoHosts(this, vm)); } Host host = vm.Connection.Resolve(vm.resident_on); return(new NotEnoughMem(this, host)); case Failure.VM_REQUIRES_NETWORK: vm = connection.Resolve(vmRef); if (vm == null) { throw new NullReferenceException(Failure.VM_REQUIRES_NETWORK); } XenRef <XenAPI.Network> netRef = new XenRef <XenAPI.Network>(exception[2]); XenAPI.Network network = connection.Resolve(netRef); if (network == null) { throw new NullReferenceException(Failure.VM_REQUIRES_NETWORK); } return(new VMCannotSeeNetwork(this, vm, network)); case Failure.VM_HAS_VGPU: vm = connection.Resolve(vmRef); if (vm == null) { throw new NullReferenceException(Failure.VM_HAS_VGPU); } return(new VmHasVgpu(this, vm)); default: throw new NullReferenceException(exception[0]); } } catch (Exception e) { log.Debug("Exception parsing exception", e); log.Debug(e, e); throw new Failure(new List <String>(exception)); } }
public static bool CanActivate(Pool pool) { return(pool.Connection.Cache.Hosts.Any(CanActivate)); }
public static async Task Execute() { Console.WriteLine("Anoncreds sample -> started"); var issuerWalletName = "issuerWallet"; var proverWalletName = "proverWallet"; var issuerDid = "NcYxiDXkpYi6ov5FcYDi1e"; var proverDid = "VsKV7grR1BUE29mG2Fm2kX"; try { //1. Create and Open Pool await PoolUtils.CreatePoolLedgerConfig(); //2. Issuer Create and Open Wallet await WalletUtils.CreateWalletAsync(PoolUtils.DEFAULT_POOL_NAME, issuerWalletName, "default", null, null); //3. Prover Create and Open Wallet await WalletUtils.CreateWalletAsync(PoolUtils.DEFAULT_POOL_NAME, proverWalletName, "default", null, null); // Open pool and wallets in using statements to ensure they are closed when finished. using (var pool = await Pool.OpenPoolLedgerAsync(PoolUtils.DEFAULT_POOL_NAME, "{}")) using (var issuerWallet = await Wallet.OpenWalletAsync(issuerWalletName, null, null)) using (var proverWallet = await Wallet.OpenWalletAsync(proverWalletName, null, null)) { //4. Issuer Creates Credential Schema var schemaName = "gvt"; var schemaVersion = "1.0"; var schemaAttributes = "[\"name\", \"age\", \"sex\", \"height\"]"; var createSchemaResult = await AnonCreds.IssuerCreateSchemaAsync(issuerDid, schemaName, schemaVersion, schemaAttributes); var schemaId = createSchemaResult.SchemaId; var schemaJson = createSchemaResult.SchemaJson; //5. Issuer create Credential Definition var credDefTag = "Tag1"; var credDefConfigJson = "{\"support_revocation\":false}"; var createCredDefResult = await AnonCreds.IssuerCreateAndStoreCredentialDefAsync(issuerWallet, issuerDid, schemaJson, credDefTag, null, credDefConfigJson); var credDefId = createCredDefResult.CredDefId; var credDefJson = createCredDefResult.CredDefJson; //6. Prover create Master Secret var masterSecretId = await AnonCreds.ProverCreateMasterSecretAsync(proverWallet, null); //7. Issuer Creates Credential Offer var credOffer = await AnonCreds.IssuerCreateCredentialOfferAsync(issuerWallet, credDefId); //8. Prover Creates Credential Request var createCredReqResult = await AnonCreds.ProverCreateCredentialReqAsync(proverWallet, proverDid, credOffer, credDefJson, masterSecretId); var credReqJson = createCredReqResult.CredentialRequestJson; var credReqMetadataJson = createCredReqResult.CredentialRequestMetadataJson; //9. Issuer create Credential var credValuesJson = "{\n" + " \"sex\": {\"raw\": \"male\", \"encoded\": \"594465709955896723921094925839488742869205008160769251991705001\"},\n" + " \"name\": {\"raw\": \"Alex\", \"encoded\": \"1139481716457488690172217916278103335\"},\n" + " \"height\": {\"raw\": \"175\", \"encoded\": \"175\"},\n" + " \"age\": {\"raw\": \"28\", \"encoded\": \"28\"}\n" + " }"; var createCredentialResult = await AnonCreds.IssuerCreateCredentialAsync(issuerWallet, credOffer, credReqJson, credValuesJson, null, null); var credential = createCredentialResult.CredentialJson; //10. Prover Stores Credential await AnonCreds.ProverStoreCredentialAsync(proverWallet, null, credReqJson, credReqMetadataJson, credential, credDefJson, null); //11. Prover Gets Credentials for Proof Request var proofRequestJson = "{" + " \"nonce\":\"123432421212\",\n" + " \"name\":\"proof_req_1\",\n" + " \"version\":\"0.1\", " + " \"requested_attributes\": {" + " \"attr1_referent\":{\"name\":\"name\"}," + " \"attr2_referent\":{\"name\":\"sex\"}," + " \"attr3_referent\":{\"name\":\"phone\"}" + " }," + " \"requested_predicates\":{" + " \"predicate1_referent\":{\"name\":\"age\",\"p_type\":\">=\",\"p_value\":18}" + " }" + " }"; var credentialsForProofJson = await AnonCreds.ProverGetCredentialsForProofReqAsync(proverWallet, proofRequestJson); var credentialsForProof = JObject.Parse(credentialsForProofJson); var credentialsForAttribute1 = (JArray)credentialsForProof["attrs"]["attr1_referent"]; var credentialsForAttribute2 = (JArray)credentialsForProof["attrs"]["attr2_referent"]; var credentialsForAttribute3 = (JArray)credentialsForProof["attrs"]["attr3_referent"]; var credentialsForPredicate = (JArray)credentialsForProof["predicates"]["predicate1_referent"]; Debug.Assert(credentialsForAttribute1.Count == 1); Debug.Assert(credentialsForAttribute2.Count == 1); Debug.Assert(credentialsForAttribute3.Count == 0); Debug.Assert(credentialsForPredicate.Count == 1); var credentialId = credentialsForAttribute1[0]["cred_info"]["referent"].ToObject <string>(); //12. Prover Creates Proof var selfAttestedValue = "8-800-300"; var requestedCredentialsJson = string.Format( "{{\n" + " \"self_attested_attributes\":{{\"attr3_referent\":\"{0}\"}},\n" + " \"requested_attributes\":{{\"attr1_referent\":{{\"cred_id\":\"{1}\", \"revealed\":true}},\n" + " \"attr2_referent\":{{\"cred_id\":\"{2}\", \"revealed\":false}}}},\n" + " \"requested_predicates\":{{\"predicate1_referent\":{{\"cred_id\":\"{3}\"}}}}\n" + " }}", selfAttestedValue, credentialId, credentialId, credentialId); var schemas = string.Format("{{\"{0}\":{1}}}", schemaId, schemaJson); var credentialDefs = string.Format("{{\"{0}\":{1}}}", credDefId, credDefJson); var revocStates = "{}"; var proofJson = await AnonCreds.ProverCreateProofAsync(proverWallet, proofRequestJson, requestedCredentialsJson, masterSecretId, schemas, credentialDefs, revocStates); var proof = JObject.Parse(proofJson); //13. Verifier verify Proof var revealedAttr1 = proof["requested_proof"]["revealed_attrs"]["attr1_referent"]; Debug.Assert("Alex" == revealedAttr1["raw"].ToObject <string>()); Debug.Assert(null != proof["requested_proof"]["unrevealed_attrs"]["attr2_referent"]["sub_proof_index"]); Debug.Assert(selfAttestedValue == proof["requested_proof"]["self_attested_attrs"]["attr3_referent"].ToObject <string>()); var revocRegDefs = "{}"; var revocRegs = "{}"; var valid = await AnonCreds.VerifierVerifyProofAsync(proofRequestJson, proofJson, schemas, credentialDefs, revocRegDefs, revocRegs); Debug.Assert(valid); //14. Close wallets and pool await issuerWallet.CloseAsync(); await proverWallet.CloseAsync(); await pool.CloseAsync(); } } finally { //15. Delete wallets and Pool ledger config await WalletUtils.DeleteWalletAsync(issuerWalletName, null); await WalletUtils.DeleteWalletAsync(proverWalletName, null); await PoolUtils.DeletePoolLedgerConfigAsync(PoolUtils.DEFAULT_POOL_NAME); } Console.WriteLine("Anoncreds sample -> completed"); }
private void Awake() { _activeAudioSources = new List <AudioSource>(); _audioSourcePool = new Pool <AudioSource>(_audioSource, transform, _audioPoolCapacity); }
/// <summary> /// Fills the provided indicesBuffer with the _latest occurring_ events with a unique /// message argument that were scrubbed through, and prevIdxBuffer with Some(idx) if /// there exists an event prior to the event at the same position in the indicesBuffer /// with the same message. /// /// After calling this method, indicesBuffer and prevIdxBuffer are guaranteed to be /// the same length. /// </summary> private void getUniqueMessageScrubbedEvents(double time0, double time1, List <int> indicesBuffer, List <Maybe <int> > prevIdxBuffer) { if (indicesBuffer.Count != 0) { indicesBuffer.Clear(); } if (prevIdxBuffer.Count != 0) { prevIdxBuffer.Clear(); } if (time1 < time0) { Utils.Swap(ref time0, ref time1); } // mostRecentEvents will key an event message to the two latest events with that // event message. (index 0 latest, index 1 just-prior, or -1 if no prior event // exists). var mostRecentEvents = Pool <Dictionary <string, Pair <int> > > .Spawn(); try { for (int i = 0; i < _clips.Count; i++) { var timelineClip = _clips[i]; if (timelineClip.start > time1) { // We've hit a clip whose start time is after the latest scrub range time. // Since clips are sorted by start time, we've done all the work we have to. break; } var eventClip = timelineClip.asset as EventClip; var eventMessage = eventClip.message; Pair <int> indices; if (!mostRecentEvents.TryGetValue(eventMessage, out indices)) { mostRecentEvents[eventMessage] = new Pair <int>(i, -1); } else { mostRecentEvents[eventMessage] = new Pair <int>(i, indices[0]); } } // Convert mostRecentEvents to the output format. foreach (var messageIndicesPair in mostRecentEvents) { var indices = messageIndicesPair.Value; // We only need to fire previous events of events we _actually_ scrubbed through. if (!_clips[indices[0]].start.IsBetween(time0, time1)) { continue; } indicesBuffer.Add(indices[0]); prevIdxBuffer.Add((indices[1] == -1 ? Maybe <int> .None : Maybe <int> .Some(indices[1]))); } } finally { mostRecentEvents.Clear(); Pool <Dictionary <string, Pair <int> > > .Recycle(mostRecentEvents); } }
// ------------------ Methods // Implement ISetPool to get the pool used when calling // pool.CreateSystem<FooSystem>(); public void SetPool(Pool pool) { // Get the group of entities that have these component(s) _pool = pool; }
/// <summary> /// Build optimize pool list view properly /// </summary> private void BuildRecList() { Program.AssertOnEventThread(); if (_xenObject == null) { return; } if (Helpers.WlbEnabled(_xenObject.Connection)) { try { if (_xenObject is Pool) { _pool = (Pool)_xenObject; // get any active WLB action action = HelpersGUI.FindActiveWLBAction(_xenObject.Connection); // make sure we are not initializing, starting or stopping WLB if (action is DisableWLBAction || action is EnableWLBAction || action is InitializeWLBAction) { return; } optimizePoolListView.BeginUpdate(); // check whether optimize pool is running before load optimize pool listview if ((action != null && action is WlbOptimizePoolAction) || (action == null && _pool.other_config.ContainsKey(WlbOptimizationRecommendation.OPTIMIZINGPOOL) && _pool.other_config[WlbOptimizationRecommendation.OPTIMIZINGPOOL] == Messages.IN_PROGRESS)) { //statusLabel.Text = Messages.WLB_OPT_OPTIMIZING; this.applyButton.Text = Messages.WLB_OPT_OPTIMIZING; EnableControls(false, false); } else if (action == null || (action != null && action.GetType() != typeof(WlbRetrieveRecommendationAction))) { this.applyButton.Text = Messages.WLB_OPT_APPLY_RECOMMENDATIONS; // retrieve recommendations, and load optimize pool listview properly WlbRetrieveRecommendationAction optAction = new WlbRetrieveRecommendationAction(_pool); optAction.Completed += this.OptRecRetrieveAction_Completed; optAction.RunAsync(); } } } catch (Failure f) { statusLabel.Text = Messages.WLB_OPT_LOADING_ERROR; log.Error(f, f); } catch (Exception e) { statusLabel.Text = Messages.WLB_OPT_LOADING_ERROR; log.Error($"There was an error calling retrieve_wlb_recommendations on pool {_pool.name_label}.", e); } finally { optimizePoolListView.EndUpdate(); } } else { this.WLBOptDisable(true); } }
public RenderTexture Initialize(int _playerNumber, Song _song, Song.Difficulty _difficulty, Vector2 _output, Pool _pool, PoolIndex _poolIndex, uint _resolution, float _speed) { playerNumber = _playerNumber; layerMask = 1 << (10 + playerNumber); song = _song; switch (_difficulty) { case Song.Difficulty.Easy: notes = song.data.notes.easy; break; case Song.Difficulty.Medium: notes = song.data.notes.medium; break; case Song.Difficulty.Hard: notes = song.data.notes.hard; break; case Song.Difficulty.Expert: notes = song.data.notes.expert; break; } pool = _pool; index = new PoolIndex(); resolution = _resolution; nextBar = resolution; speed = _speed; index = _poolIndex; lastNoteHit = true; activeNotes = new List <NoteInstance>(); activeBars = new List <BarInstance>(); willRemove = new List <NoteInstance>(); willRemoveBars = new List <BarInstance>(); nextLine = new Line(); nextLine.note = new List <NoteInstance>(); nextLine.fred = new bool[5]; noteCounter.Initialize(); output = new RenderTexture(Mathf.CeilToInt(_output.x), Mathf.CeilToInt(_output.y), 16, RenderTextureFormat.ARGB32); cam.GetComponent <Camera>().targetTexture = output; cam.GetComponent <Camera>().cullingMask = layerMask; SetLayerRecursive(transform, 10 + playerNumber); playerInput = new KeyPlayerInput(); return(output); }
/// <summary> /// TBD /// </summary> /// <param name="local">TBD</param> /// <param name="settings">TBD</param> /// <returns>TBD</returns> internal RouterConfig Copy(Pool local = null, ClusterRouterPoolSettings settings = null) { return(new ClusterRouterPool(local ?? Local, settings ?? Settings)); }
CssSelectorConstructor CreateChild() { return(Pool.NewSelectorConstructor(_attributeSelector, _pseudoClassSelector, _pseudoElementSelector)); }
public void SetPool(Pool pool) { _cameraGroup = pool.GetGroup(Matcher.Camera); _group = pool.GetGroup(Matcher.AllOf(Matcher.Position, Matcher.GameObject)); }
public void Construct(Pool memoryPool) { _memoryPool = memoryPool; }