public ToolAction(CodeGenerator codeGenerator, CodeGeneratorEntry entry, Dictionary<string, string> props) { this.CodeGenerator = codeGenerator; _props = props; this.Entry = entry; this.Comment = _props.GetOrDefault("comment"); this.FileName = _props.GetOrDefault("file-name"); }
public void ShouldBeAbleToGetADefaultValueIfTheKeyDoesntExist() { DateTime theDate = DateTime.Parse("April 04, 2005"); DateTime defaultDate = DateTime.Parse("October 31, 2005"); var bag = new Dictionary<string, object>(); Assert.That(bag.GetOrDefault("some_date", defaultDate), Is.EqualTo(defaultDate)); bag.Add("some_date", theDate); Assert.That(bag.GetOrDefault("some_date", defaultDate), Is.EqualTo(theDate)); }
public override PropertyDescriptor GetOwnProperty(JsValue property) { EnsurePropertiesInitialized(); var propertyName = property.AsString(); return(valueProperties?.GetOrDefault(propertyName) ?? PropertyDescriptor.Undefined); }
PositionedNode MatchNode(PositionedNode oldNode, Dictionary<int, PositionedNode> newNodeMap) { PositionedNode newNodeFound = newNodeMap.GetOrDefault(oldNode.ObjectNode.HashCode); if ((newNodeFound != null) && IsSameAddress(oldNode, newNodeFound)) { return newNodeFound; } else { return null; } }
private static Func<Question, RichQuestion> QuestionCreateor(Dictionary<int, int> votes, Dictionary<int, int> answerCounts) { return q => new RichQuestion(q, votes.GetOrDefault(q.Id), null, null, answerCounts.GetOrDefault(q.Id)); }
public void Value_Not_Exists() { var key = "key"; Dictionary<string, object> target = new Dictionary<string, object>(); var actual = target.GetOrDefault(key); Assert.IsNull(actual); }
public void GetOrDefaultMissing() { Dictionary<string, int> dict = new Dictionary<string, int>(); int @default = 15; int value = dict.GetOrDefault("two", @default); Assert.Equal(15, @default); }
public void Value_Is_Null() { var key = "key"; Dictionary<string, object> target = new Dictionary<string, object>(); target.Add(key, null); var actual = target.GetOrDefault(key); Assert.IsNull(actual); }
public void Value_Exists() { var key = "key"; var expected = "hello world!"; Dictionary<string, object> target = new Dictionary<string, object>(); target.Add(key, expected); var actual = target.GetOrDefault(key); Assert.AreEqual(expected, actual); }
private void OnPropertyChanged(string?name) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); if (name is not null && _propertyCallbacks?.GetOrDefault(name) is { } callbackList) { foreach (var callback in callbackList) { callback?.Invoke(); } } }
/* 3 Write a program that finds a set of words (e.g. 1000 words) * in a large text (e.g. 100 MB text file). Print how many times * each word occurs in the text. * Hint: you may find a C# trie in Internet. * */ static void Main(string[] args) { var dict = new Dictionary<string, int>(); var knownCount = new Dictionary<string, int> { {"foo", 10*1000}, {"bar", 20*1000}, {"quux",30*1000}, {"frob",40*1000}, {"asdf",50*1000} }; var trie = new Trie<int>(); var sw = new Stopwatch(); sw.Start(); // obviously, I couldn't zip the 100 MB file // use "bin\debug\generator.cs" to generate it if you want using (var reader = new StreamReader("text.txt")) foreach (var word in Words(reader)) dict[word] = 1 + dict.GetOrDefault(word, 0); sw.Stop(); /* foreach (var kvp in knownCount) Debug.Assert(dict[kvp.Key] == kvp.Value); */ Console.WriteLine("Using hashtable: " + sw.Elapsed.TotalMilliseconds); sw.Reset(); sw.Start(); using (var reader = new StreamReader("text.txt")) foreach (var word in Words(reader)) trie.Add(word, 1 + trie.GetOrDefault(word, 0)); sw.Stop(); foreach (var kvp in dict) Debug.Assert(trie.Find(kvp.Key) == kvp.Value); // the trie would probably do much better compared to a hashtable when used on // natural text with large amount of repetition and low average word length // it is however extremely space inefficient // at any rate, I'd be surprised if this implementation could beat .NET's build-in // hashtable Console.WriteLine("Using trie: " + sw.Elapsed.TotalMilliseconds); }
public override PropertyDescriptor GetOwnProperty(JsValue property) { EnsurePropertiesInitialized(); var propertyName = property.AsString(); if (propertyName.Equals("toJSON", StringComparison.OrdinalIgnoreCase)) { return(PropertyDescriptor.Undefined); } return(valueProperties?.GetOrDefault(propertyName) ?? PropertyDescriptor.Undefined); }
public FactionRelationStatus GetRelation(string self, string target) { //a few simple rules: // -factions are always friendly with themselvs // -factions are always neutral toward factions they have no entry for // -factions are always neutral toward "None" // -factions are always hostile toward "Chaotic" // -otherwise, it's a lookup if (self == target) { return(FactionRelationStatus.Friendly); } if (self == "None" || target == "None") { return(FactionRelationStatus.Neutral); } if (self == "Chaotic" || target == "Chaotic") { return(FactionRelationStatus.Hostile); } var selfEntry = FactionTable?.GetOrDefault(self); if (selfEntry != null) { return(selfEntry.GetOrDefault(target, FactionRelationStatus.Neutral)); } else { //no entry in table for our faction return(FactionRelationStatus.Neutral); } }
public void DeleteMappedResultsForDocumentId(string documentId, string view, Dictionary<ReduceKeyAndBucket, int> removed) { foreach (var key in storage.MappedResults["ByViewAndDocumentId"].SkipTo(new RavenJObject { {"view", view}, {"docId", documentId} }).TakeWhile(x => StringComparer.OrdinalIgnoreCase.Equals(x.Value<string>("view"), view) && StringComparer.OrdinalIgnoreCase.Equals(x.Value<string>("docId"), documentId))) { storage.MappedResults.Remove(key); var reduceKey = key.Value<string>("reduceKey"); var bucket = new ReduceKeyAndBucket(key.Value<int>("bucket"), reduceKey); removed[bucket] = removed.GetOrDefault(bucket) + 1; } }
public static string Build(IEnumerable<AssemblyDefinition> assemblys, string outDirectory, string bridgeDllPath, string libWhite, string libBlack) { TypeDefinitionBuilder builder = new TypeDefinitionBuilder(libWhite, libBlack); List<CodeCompileUnit> units = new List<CodeCompileUnit>(); foreach(var assemblyDefinition in assemblys) { CodeCompileUnit unit = new CodeCompileUnit(); Dictionary<string, CodeNamespace> namespaces = new Dictionary<string, CodeNamespace>(); foreach(var module in assemblyDefinition.Modules) { foreach(var type in module.Types) { if(builder.IsEnableType(type)) { CodeTypeDeclaration codeTypeDeclaration = builder.Build(type); CodeNamespace codeNamespace = namespaces.GetOrDefault(type.Namespace); if(codeNamespace == null) { codeNamespace = new CodeNamespace(type.Namespace); namespaces.Add(codeNamespace.Name, codeNamespace); } codeNamespace.Types.Add(codeTypeDeclaration); } } } unit.Namespaces.AddRange(namespaces.Values.ToArray()); units.Add(unit); } CompilerParameters cp = new CompilerParameters(); cp.CoreAssemblyFileName = bridgeDllPath; cp.GenerateExecutable = false; cp.GenerateInMemory = false; cp.TreatWarningsAsErrors = false; cp.TempFiles.KeepFiles = true; cp.OutputAssembly = Path.Combine(outDirectory, kWrapDllName); cp.ReferencedAssemblies.Add(bridgeDllPath); CSharpCodeProvider provider = new CSharpCodeProvider(); CompilerResults cr = provider.CompileAssemblyFromSource(cp, units.Select(i => i.Compile()).ToArray()); if(cr.Errors.Count > 0) { StringBuilder sb = new StringBuilder(); foreach(CompilerError ce in cr.Errors) { sb.AppendFormat(" {0}", ce.ToString()); sb.AppendLine(); } throw new System.Exception(sb.ToString()); } return cr.PathToAssembly; }
public Core.Entity Generate(Core.EntitySet set, Resources.ResourceCache cache, string entityName, Dictionary<string, object> parameters) { var e = set.Create(entityName); var sprite = e.AddComponent<Sprite>(); if (r == null) r = new Random((int)(DateTime.Now.Ticks % (long)int.MaxValue)); var path = "Data/Texture/house" + r.Next(500) % (MaxIndex + 1) + ".png"; sprite.Load(cache, path); sprite.Origin = new SharpDX.Vector2(160f / 2f); var rot = parameters.GetOrDefault("Rotation", 0f); e.Transform.LocalRotation = rot; var area = e.AddComponent<ClickArea>(); area.BaseWidth = 160; area.BaseHeight = 160; area.OriginX = sprite.Origin.X; area.OriginY = sprite.Origin.Y; return e; }
public void DeleteMappedResultsForView(string view) { var statsByKey = new Dictionary<string, int>(); foreach (var key in storage.MappedResults["ByViewAndReduceKey"].SkipTo(new RavenJObject { { "view", view } }) .TakeWhile(x => StringComparer.OrdinalIgnoreCase.Equals(x.Value<string>("view"), view))) { storage.MappedResults.Remove(key); var reduceKey = key.Value<string>("reduceKey"); statsByKey[reduceKey] = statsByKey.GetOrDefault(reduceKey) - 1; } foreach (var reduceKeyStat in statsByKey) { IncrementReduceKeyCounter(view, reduceKeyStat.Key, reduceKeyStat.Value); } }
private void CheckLocalSymbolName(ISymbol symbol, ref LuaIdentifierNameSyntax name) { var newName = localReservedNames_.GetOrDefault(symbol); if (newName != null) { name = newName; } }
public IDatabaseApi FindDatabaseApi(string key) { return(_databaseApis.GetOrDefault(key)); }
public override PropertyDescriptor GetOwnProperty(string propertyName) { EnsurePropertiesInitialized(); return(valueProperties?.GetOrDefault(propertyName) ?? PropertyDescriptor.Undefined); }
/// <summary> /// Performs an "index" "get" operation. This tries to resolve minor variations of member names. /// </summary> /// <param name="ecToken">The execution control token of the script processing thread</param> /// <param name="script">The script originating the request</param> /// <param name="obj">The object (null if a static request is done)</param> /// <param name="index">The index.</param> /// <param name="isDirectIndexing">If set to true, it's indexed with a name, if false it's indexed through brackets.</param> public virtual DynValue Index(ExecutionControlToken ecToken, Script script, object obj, DynValue index, bool isDirectIndexing) { if (!isDirectIndexing) { var mdesc = m_Members .GetOrDefault(SPECIALNAME_INDEXER_GET) .WithAccessOrNull(MemberDescriptorAccess.CanExecute); if (mdesc != null) { return(this.ExecuteIndexer(ecToken, mdesc, script, obj, index, null)); } } index = index.ToScalar(); if (index.Type != DataType.String) { return(null); } var v = this.TryIndex(script, obj, index.String); if (v == null) { v = this.TryIndex(script, obj, UpperFirstLetter(index.String)); } if (v == null) { v = this.TryIndex(script, obj, Camelify(index.String)); } if (v == null) { v = this.TryIndex(script, obj, UpperFirstLetter(Camelify(index.String))); } if (v == null && m_ExtMethodsVersion < UserData.GetExtensionMethodsChangeVersion()) { m_ExtMethodsVersion = UserData.GetExtensionMethodsChangeVersion(); v = this.TryIndexOnExtMethod(script, obj, index.String); if (v == null) { v = this.TryIndexOnExtMethod(script, obj, UpperFirstLetter(index.String)); } if (v == null) { v = this.TryIndexOnExtMethod(script, obj, Camelify(index.String)); } if (v == null) { v = this.TryIndexOnExtMethod(script, obj, UpperFirstLetter(Camelify(index.String))); } } return(v); }
/*In this method we will get all the files for the lead adapter and we will download the file to our machine * in to the local folder of the lead adapter and we will get all the data that is embeded in the file * and we will validate each record and also checking the duplicate status and adding the particular recrod * and finally we will upload all the contacts and the joblogs and then we will move the file from local folder * to archive folder and we will delete the file from the ftp location. */ public virtual void Process() { try { leadAdapterAndAccountMap = repository.GetLeadAdapterByID(LeadAdapterAccountMapID); ServiceProvider ServiceProviders = serviceProviderRepository .GetServiceProviders(1, CommunicationType.Mail, MailType.TransactionalEmail); #region Read FTP var ftpManager = new FtpService(); ftpManager.OnServiceFailure += ftpManager_OnServiceFailure; var filesList = ftpManager.GetFiles(leadAdapterAndAccountMap.RequestGuid, string.Empty, ServiceProviders.LoginToken, leadAdapterAndAccountMap.LeadAdapterTypeID.ToString(), leadAdapterAndAccountMap.AccountName); foreach (var fileName in filesList) { /* * Read XML file from local path for Builder Number * Get accounts related to builder number * Copy file to all those accounts * **/ try { var localFilePath = Path.Combine(leadAdapterAndAccountMap.LocalFilePath, fileName); ftpManager.Download(leadAdapterAndAccountMap.RequestGuid, string.Empty, fileName, localFilePath); List <LeadAdapterAndAccountMap> leadData = new List <LeadAdapterAndAccountMap>(); leadData.Add(leadAdapterAndAccountMap); var nodes = GetNodes(localFilePath); foreach (var node in nodes) { var attributes = node.GetAllAttributesAndElements(); var builderNumber = attributes[_fieldMappings.GetOrDefault("BuilderNumber")].Value; IEnumerable <Guid> matchedGuids = ftpManager.FindMatchGuids(leadAdapterAndAccountMap.RequestGuid); leadData.AddRange(repository.GetEmptyCommunities(builderNumber, leadAdapterAndAccountMap.LeadAdapterTypeID, matchedGuids)); } if (File.Exists(localFilePath)) { File.Delete(localFilePath); } foreach (LeadAdapterAndAccountMap leadAdapter in leadData.GroupBy(g => g.Id).Select(s => s.First())) { Logger.Current.Informational("Inserting joblog for account id : " + leadAdapter.AccountID); var jobLog = new LeadAdapterJobLogs(); jobLog.LeadAdapterAndAccountMapID = leadAdapter.Id; jobLog.LeadAdapterJobStatusID = LeadAdapterJobStatus.Undefined; jobLog.Remarks = string.Empty; jobLog.FileName = fileName; List <LeadAdapterJobLogDetails> details = new List <LeadAdapterJobLogDetails>(); jobLog.LeadAdapterJobLogDetails = details; var leadAdapterJobLogID = importDataRepository.InsertLeadAdapterjob(jobLog, new Guid(), false, false, leadAdapter.AccountID, leadAdapter.CreatedBy, 1, leadAdapter.CreatedBy, true); var filePath = Path.Combine(leadAdapter.LocalFilePath, fileName); var fileName_rename = Path.GetFileNameWithoutExtension(filePath) + "~" + leadAdapterJobLogID + Path.GetExtension(filePath); localFilePath = Path.Combine(leadAdapter.LocalFilePath, fileName_rename); ftpManager.Download(leadAdapter.RequestGuid, string.Empty, fileName, localFilePath); } } catch (Exception ex) { Logger.Current.Error("An error occured while accessing file downloading it to matched accounts, filename : " + fileName, ex); continue; } } ; #endregion #region Read Local Files readLocalFiles(ftpManager); #endregion } catch (IndexOutOfRangeException indexEx) { Logger.Current.Error("Index out of range exception, account name : " + leadAdapterAndAccountMap.AccountName, indexEx); } catch (Exception ex) { Logger.Current.Error("An error occured when uploading the contacts in the lead adapter, account name : " + leadAdapterAndAccountMap.AccountName, ex); SendEmail("Exception details" + ex, "Exception while processing data from " + leadAdapterAndAccountMap.LeadAdapterTypeID.ToString() + " LeadAdapter"); } finally { repository.UpdateProcessedDate(LeadAdapterAccountMapID); } }
public static ControlFlowGraph DoCreateCarcass(IMethodBody cil, out ReadOnlyDictionary<ControlFlowBlock, ReadOnlyCollection<IILOp>> blocks2parts) { // create the control flow graph var cfg = new ControlFlowGraph(); // partition the code into blocks with continuous control flow // todo. support switches and protected regions var targets = new HashSet<IILOp>(cil.OfType<Branch>().Select(br => br.Target)); var l_partitions = new List<ReadOnlyCollection<IILOp>>(); var l_partition = new List<IILOp>(); Action qualifyPartition = () => { if (l_partition.IsNotEmpty()) { l_partitions.Add(l_partition.ToReadOnly()); l_partition = new List<IILOp>(); } }; foreach (var op in cil) { if (op is Branch || op is Ret) qualifyPartition(); else { if (targets.Contains(op)) qualifyPartition(); l_partition.Add(op); if (op is Throw) qualifyPartition(); } } qualifyPartition(); var partitions = l_partitions.ToReadOnly(); // create blocks and map those to ops and partitions blocks2parts = partitions.ToDictionary(p => new ControlFlowBlock(), p => p).ToReadOnly(); blocks2parts.ForEach(kvp => cfg.AddVertex(kvp.Key)); var op2blocks = new Dictionary<IILOp, ControlFlowBlock>(); blocks2parts.ForEach(kvp => kvp.Value.ForEach(op => op2blocks.Add(op, kvp.Key))); cil.ForEach(op => { if (!op2blocks.ContainsKey(op)) op2blocks.Add(op, null); }); // prepare to link the blocks Action<IILOp, IILOp, CilPredicateType?> link = (op1, op2, cil_pred) => { var source = op1 == null ? cfg.Start : op2blocks[op1]; var target = op2 == null ? cfg.Finish : op2blocks[op2]; var hir_pred = cil_pred == null ? (HirPredicateType?)null : (HirPredicateType)Enum.Parse(typeof(HirPredicateType), cil_pred.Value.ToString()); cfg.AddEdge(new ControlFlowEdge(source, target, hir_pred)); }; // link the blocks (down from 300+ LOC to this simple loop =)) if (cil.IsEmpty()) link(null, null, null); foreach (var op in cil) { // todo. support switches here if (op is Switch) throw AssertionHelper.Fail(); // todo. support general case of control flow // n0te. throw needs something on stack, so br > throw is impossible Func<IILOp, bool> isJmp = op1 => op1 is Ret || op1 is Branch; if (isJmp(op) && isJmp(op.Prev)) continue; if (isJmp(op)) { Func<IILOp, CilPredicateType?> pred = op1 => op1 is Ret ? null : op1 is Branch ? ((Branch)op1).PredicateType : ((Func<CilPredicateType?>)(() => { throw AssertionHelper.Fail(); }))(); Func<IILOp, bool> uncond = op1 => isJmp(op1) && pred(op1) == null; Func<IILOp, bool> cond = op1 => isJmp(op1) && pred(op1) != null; Func<IILOp, IILOp> target = null; target = op1 => op1 is Ret ? null : op1 is Branch ? target(((Branch)op1).Target) : op1; (target(op) is Branch).AssertFalse(); if (target(op) is Ret) link(op.Prev, null, pred(op)); else link(op.Prev, target(op), pred(op)); isJmp(op.Next).AssertImplies(uncond(op.Next)); if (cond(op)) link(op.Prev, target(op.Next), pred(op).Negate()); } else if (op is Throw) { // do nothing - throw doesn't create links } else { if (op.Prev == null) link(null, op, null); if (isJmp(op.Next)) continue; var blk = op2blocks.GetOrDefault(op); var blk_next = op2blocks.GetOrDefault(op.Next); if (blk != blk_next) link(op, op.Next, null); } } // yield control to the next step of the pipeline return cfg; }
private void ProcessTCPPacket(TCPPacket pTCPPacket, ref uint pSequence, Dictionary<uint, byte[]> pBuffer, FiestaStream pStream) { if (pTCPPacket.SequenceNumber > pSequence) { byte[] data; while ((data = pBuffer.GetOrDefault(pSequence, null)) != null) { pBuffer.Remove(pSequence); pStream.Append(data); pSequence += (uint)data.Length; } if (pTCPPacket.SequenceNumber > pSequence) pBuffer[(uint)pTCPPacket.SequenceNumber] = pTCPPacket.TCPData; } if (pTCPPacket.SequenceNumber < pSequence) { int difference = (int)(pSequence - pTCPPacket.SequenceNumber); if (difference > 0) { byte[] data = pTCPPacket.TCPData; if (data.Length > difference) { pStream.Append(data, difference, data.Length - difference); pSequence += (uint)(data.Length - difference); } } } else if (pTCPPacket.SequenceNumber == pSequence) { byte[] data = pTCPPacket.TCPData; pStream.Append(data); pSequence += (uint)data.Length; } FiestaPacket packet; try { while ((packet = pStream.Read(pTCPPacket.Timeval.Date)) != null) { mPackets.Add(packet); Definition definition = Config.Instance.Definitions.Find(d => d.Build == 1 && d.Outbound == packet.Outbound && d.Opcode == packet.Opcode); if (!mOpcodes.Exists(kv => kv.Item1 == packet.Outbound && kv.Item2 == packet.Opcode)) { mOpcodes.Add(new Tuple<bool, ushort>(packet.Outbound, packet.Opcode)); } if (definition != null && definition.Ignore) continue; if (!FilterOut(packet)) { mPacketList.Items.Add(packet); } if (mPacketList.SelectedItems.Count == 0) packet.EnsureVisible(); } } catch (Exception exc) { OutputForm output = new OutputForm("Packet Error"); output.Append(exc.ToString()); output.Show(DockPanel, new Rectangle(MainForm.Location, new Size(400, 400))); mTerminated = true; Text += " (Terminated)"; } }
public string Translate(string text) { return(Translates.GetOrDefault(text)); }
/// <summary> /// Will find a Service Registered to process the item. /// </summary> public static IIntegrationQueueItem Process(IIntegrationQueueItem item) { if (item.ResponseDate != null) { // Already processed: return(item); } #region Pick the item Type serviceType; lock (PickLock) { if (item.DatePicked != null) { // Already picked, let the other thread finish its job: return(null); } if (!item.IsNew) { item = (IIntegrationQueueItem)item.Clone(); } serviceType = IntegrationServices.GetOrDefault(item.IntegrationService); if (serviceType == null) { return(null); } item.DatePicked = LocalTime.Now; Database.Save(item); } // TOOD: This is not thread safe in multi-server (web farm) scenarios. // To make it completely safe, we need a single StoredProc or SQL command that will do both at the same time, with a lock at the DB level. #endregion var service = serviceType.CreateInstance(); var serviceInterface = serviceType.GetInterfaces().Single(x => x.Name.Contains("IServiceImplementor")); var typeOfRequest = serviceInterface.GetGenericArguments().First(); var request = JsonConvert.DeserializeObject(item.Request, typeOfRequest); //var request = new JavaScriptSerializer().Deserialize(item.Request, typeOfRequest); var method = serviceType.GetMethod("GetResponse", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); try { var response = method.Invoke(service, new[] { request }); item.Response = JsonConvert.SerializeObject(response); } catch (Exception ex) { item.ErrorResponse = ex.ToString(); } item.ResponseDate = LocalTime.Now; Database.Save(item); return(item); }
internal SymbolRef Find(string name) { return(m_DefinedNames.GetOrDefault(name)); }
/// <summary> /// Removes redundatant Br, Nop, Dup, Pop /// </summary> /// <param name="method"></param> void RemoveRedundantCode(ILBlock method) { Dictionary <ILLabel, int> labelRefCount = new Dictionary <ILLabel, int>(); foreach (ILLabel target in method.GetSelfAndChildrenRecursive <ILExpression>(e => e.IsBranch()).SelectMany(e => e.GetBranchTargets())) { labelRefCount[target] = labelRefCount.GetOrDefault(target) + 1; } foreach (ILBlock block in method.GetSelfAndChildrenRecursive <ILBlock>()) { List <ILNode> body = block.Body; List <ILNode> newBody = new List <ILNode>(body.Count); for (int i = 0; i < body.Count; i++) { ILLabel target; ILExpression popExpr; if (body[i].Match(ILCode.Br, out target) && i + 1 < body.Count && body[i + 1] == target) { // Ignore the branch if (labelRefCount[target] == 1) { i++; // Ignore the label as well } } else if (body[i].Match(ILCode.Nop)) { // Ignore nop } else if (body[i].Match(ILCode.Pop, out popExpr)) { ILVariable v; if (!popExpr.Match(ILCode.Ldloc, out v)) { throw new Exception("Pop should have just ldloc at this stage"); } // Best effort to move the ILRange to previous statement ILVariable prevVar; ILExpression prevExpr; if (i - 1 >= 0 && body[i - 1].Match(ILCode.Stloc, out prevVar, out prevExpr) && prevVar == v) { prevExpr.ILRanges.AddRange(((ILExpression)body[i]).ILRanges); } // Ignore pop } else { newBody.Add(body[i]); } } block.Body = newBody; } // 'dup' removal foreach (ILExpression expr in method.GetSelfAndChildrenRecursive <ILExpression>()) { for (int i = 0; i < expr.Arguments.Count; i++) { ILExpression child; if (expr.Arguments[i].Match(ILCode.Dup, out child)) { child.ILRanges.AddRange(expr.Arguments[i].ILRanges); expr.Arguments[i] = child; } } } }
public void GetOrDefault_should_return_value_if_key_exists() { valueDictionary[12] = 34; Assert.Equal(34, valueDictionary.GetOrDefault(12)); }
/// <inheritdoc/> public async Task <IReadOnlyList <ISettingValue> > GetAllSettingValuesAsync(SettingScopes scopes) { var settingDefinitions = new Dictionary <string, SettingDefinition>(); var settingValues = new Dictionary <string, ISettingValue>(); //Fill all setting with default values. foreach (var setting in _settingDefinitionManager.GetAllSettingDefinitions()) { settingDefinitions[setting.Name] = setting; settingValues[setting.Name] = new SettingValueObject(setting.Name, setting.DefaultValue); } //Overwrite application settings if (scopes.HasFlag(SettingScopes.Application)) { foreach (var settingValue in await GetAllSettingValuesForApplicationAsync()) { var setting = settingDefinitions.GetOrDefault(settingValue.Name); //TODO: Conditions get complicated, try to simplify it if (setting == null || !setting.Scopes.HasFlag(SettingScopes.Application)) { continue; } if (!setting.IsInherited && ((setting.Scopes.HasFlag(SettingScopes.Tenant) && Session.TenantId.HasValue) || (setting.Scopes.HasFlag(SettingScopes.User) && Session.UserId.HasValue))) { continue; } settingValues[settingValue.Name] = new SettingValueObject(settingValue.Name, settingValue.Value); } } //Overwrite tenant settings if (scopes.HasFlag(SettingScopes.Tenant) && Session.TenantId.HasValue) { foreach (var settingValue in await GetAllSettingValuesForTenantAsync(Session.TenantId.Value)) { var setting = settingDefinitions.GetOrDefault(settingValue.Name); //TODO: Conditions get complicated, try to simplify it if (setting == null || !setting.Scopes.HasFlag(SettingScopes.Tenant)) { continue; } if (!setting.IsInherited && (setting.Scopes.HasFlag(SettingScopes.User) && Session.UserId.HasValue)) { continue; } settingValues[settingValue.Name] = new SettingValueObject(settingValue.Name, settingValue.Value); } } //Overwrite user settings if (scopes.HasFlag(SettingScopes.User) && Session.UserId.HasValue) { foreach (var settingValue in await GetAllSettingValuesForUserAsync(Session.ToUserIdentifier())) { var setting = settingDefinitions.GetOrDefault(settingValue.Name); if (setting != null && setting.Scopes.HasFlag(SettingScopes.User)) { settingValues[settingValue.Name] = new SettingValueObject(settingValue.Name, settingValue.Value); } } } return(settingValues.Values.ToImmutableList()); }
public void UpdateRemovedMapReduceStats(string view, Dictionary<ReduceKeyAndBucket, int> removed) { var statsByKey = new Dictionary<string, int>(); foreach (var reduceKeyAndBucket in removed) { statsByKey[reduceKeyAndBucket.Key.ReduceKey] = statsByKey.GetOrDefault(reduceKeyAndBucket.Key.ReduceKey) - reduceKeyAndBucket.Value; } foreach (var reduceKeyStat in statsByKey) { IncrementReduceKeyCounter(view, reduceKeyStat.Key, reduceKeyStat.Value); } }
public static string[] SelectComboBox(string name) { return(comboBox.GetOrDefault(name, nullSelection)); }
public void GetOrDefault() { Dictionary<int, string> dict = new Dictionary<int, string>(); dict.Add(1, "one"); Assert.AreEqual("one", dict.GetOrDefault(1)); Assert.IsNull(dict.GetOrDefault(4)); dict.Add(2, "two"); dict.Add(3, "three"); dict.Add(4, "four"); Assert.AreEqual("three", dict.GetOrDefault((k, v) => !v.Contains('o'))); }
/// <summary> /// Get value from parsed connection string. Returns null if not found /// </summary> public string this[string key] => _values.GetOrDefault(key);
public void DeleteMappedResultsForDocumentId(string documentId, int view, Dictionary<ReduceKeyAndBucket, int> removed) { var viewAndDocumentId = CreateKey(view, documentId); var mappedResultsByViewAndDocumentId = tableStorage.MappedResults.GetIndex(Tables.MappedResults.Indices.ByViewAndDocumentId); using (var iterator = mappedResultsByViewAndDocumentId.MultiRead(Snapshot, viewAndDocumentId)) { if (!iterator.Seek(Slice.BeforeAllKeys)) return; do { var id = iterator.CurrentKey.Clone(); ushort version; var value = LoadJson(tableStorage.MappedResults, id, writeBatch.Value, out version); var reduceKey = value.Value<string>("reduceKey"); var bucket = value.Value<int>("bucket"); DeleteMappedResult(id, view, documentId, reduceKey, bucket.ToString(CultureInfo.InvariantCulture)); var reduceKeyAndBucket = new ReduceKeyAndBucket(bucket, reduceKey); removed[reduceKeyAndBucket] = removed.GetOrDefault(reduceKeyAndBucket) + 1; } while (iterator.MoveNext()); } }
/* * 0 no race * 1 usa_great_corp * 2 eu_great_corp * 3 asia_great_corp */ public static long GetAllianceEidByRace(int raceId) { return(_raceIdToAlliance.GetOrDefault(raceId)); }
public ITransactionApi FindTransactionApi(string key) { Check.NotNull(key, nameof(key)); return(_transactionApis.GetOrDefault(key)); }
private void ProcessTCPPacket(TcpPacket pTCPPacket, ref uint pSequence, Dictionary<uint, byte[]> pBuffer, MapleStream pStream, DateTime pArrivalDate) { if (pTCPPacket.SequenceNumber > pSequence) { byte[] data; while ((data = pBuffer.GetOrDefault(pSequence, null)) != null) { pBuffer.Remove(pSequence); pStream.Append(data); pSequence += (uint)data.Length; } if (pTCPPacket.SequenceNumber > pSequence) pBuffer[(uint)pTCPPacket.SequenceNumber] = pTCPPacket.PayloadData; } if (pTCPPacket.SequenceNumber < pSequence) { int difference = (int)(pSequence - pTCPPacket.SequenceNumber); if (difference > 0) { byte[] data = pTCPPacket.PayloadData; if (data.Length > difference) { pStream.Append(data, difference, data.Length - difference); pSequence += (uint)(data.Length - difference); } } } else if (pTCPPacket.SequenceNumber == pSequence) { byte[] data = pTCPPacket.PayloadData; pStream.Append(data); pSequence += (uint)data.Length; } MaplePacket packet; bool refreshOpcodes = false; try { while ((packet = pStream.Read(pArrivalDate, mBuild, mLocale)) != null) { mPackets.Add(packet); Definition definition = Config.Instance.GetDefinition(mBuild, mLocale, packet.Outbound, packet.Opcode); if (!mOpcodes.Exists(kv => kv.First == packet.Outbound && kv.Second == packet.Opcode)) { mOpcodes.Add(new Pair<bool, ushort>(packet.Outbound, packet.Opcode)); refreshOpcodes = true; } if (definition != null && !mViewIgnoredMenu.Checked && definition.Ignore) continue; mPacketList.Items.Add(packet); if (mPacketList.SelectedItems.Count == 0) packet.EnsureVisible(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); mTerminated = true; Text += " (Terminated)"; //MainForm.CloseSession(this); return; } if (DockPanel.ActiveDocument == this && refreshOpcodes) MainForm.SearchForm.RefreshOpcodes(true); }
public AbpWorkflowStepBody GetStepBodyOrNull(string name) { return(AbpStepBodys.GetOrDefault(name)); }
private void ProcessTCPPacket(TcpPacket pTCPPacket, ref uint pSequence, Dictionary<uint, byte[]> pBuffer, PacketStream pStream, bool pInbound) { if (pTCPPacket.SequenceNumber > pSequence) { byte[] data; while ((data = pBuffer.GetOrDefault(pSequence, null)) != null) { pBuffer.Remove(pSequence); pStream.Append(data); pSequence += (uint)data.Length; } if (pTCPPacket.SequenceNumber > pSequence) { pBuffer[(uint)pTCPPacket.SequenceNumber] = pTCPPacket.PayloadData; } } if (pTCPPacket.SequenceNumber < pSequence) { int difference = (int)(pSequence - pTCPPacket.SequenceNumber); if (difference > 0) { byte[] data = pTCPPacket.PayloadData; if (data.Length > difference) { pStream.Append(data, difference, data.Length - difference); pSequence += (uint)(data.Length - difference); } } } else if (pTCPPacket.SequenceNumber == pSequence) { byte[] data = pTCPPacket.PayloadData; pStream.Append(data); pSequence += (uint)data.Length; } CheckForPackets(pStream, pInbound); }
private void UpdateFacetResults(Dictionary <string, Dictionary <string, FacetValue> > facetsByName) { foreach (var facet in Facets.Values) { if (facet.Mode == FacetMode.Ranges) { continue; } var values = new List <FacetValue>(); List <string> allTerms; int maxResults = Math.Min(PageSize ?? facet.MaxResults ?? Database.Configuration.MaxPageSize, Database.Configuration.MaxPageSize); var groups = facetsByName.GetOrDefault(facet.DisplayName); if (groups == null) { continue; } switch (facet.TermSortMode) { case FacetTermSortMode.ValueAsc: allTerms = new List <string>(groups.OrderBy(x => x.Key).ThenBy(x => x.Value.Hits).Select(x => x.Key)); break; case FacetTermSortMode.ValueDesc: allTerms = new List <string>(groups.OrderByDescending(x => x.Key).ThenBy(x => x.Value.Hits).Select(x => x.Key)); break; case FacetTermSortMode.HitsAsc: allTerms = new List <string>(groups.OrderBy(x => x.Value.Hits).ThenBy(x => x.Key).Select(x => x.Key)); break; case FacetTermSortMode.HitsDesc: allTerms = new List <string>(groups.OrderByDescending(x => x.Value.Hits).ThenBy(x => x.Key).Select(x => x.Key)); break; default: throw new ArgumentException(string.Format("Could not understand '{0}'", facet.TermSortMode)); } foreach (var term in allTerms.Skip(Start).TakeWhile(term => values.Count < maxResults)) { var facetValue = groups.GetOrDefault(term); values.Add(facetValue ?? new FacetValue { Range = term }); } var previousHits = allTerms.Take(Start).Sum(allTerm => { var facetValue = groups.GetOrDefault(allTerm); return(facetValue == null ? 0 : facetValue.Hits); }); var key = string.IsNullOrWhiteSpace(facet.DisplayName) ? facet.Name : facet.DisplayName; Results.Results[key] = new FacetResult { Values = values, RemainingTermsCount = allTerms.Count - (Start + values.Count), RemainingHits = groups.Values.Sum(x => x.Hits) - (previousHits + values.Sum(x => x.Hits)), }; if (facet.IncludeRemainingTerms) { Results.Results[key].RemainingTerms = allTerms.Skip(Start + values.Count).ToList(); } } }
private static Dictionary<char, int> getCharactersCount(string s) { Dictionary<char, int> res = new Dictionary<char, int>(); foreach (char c in s) { res[c] = res.GetOrDefault(c, 0) + 1; } return res; }
internal object GetConstraint(string key) => where?.GetOrDefault(key, null);
public async Task <IReadOnlyList <IWebhookEntity> > QueryByAppAsync(Guid appId) { await EnsureWebooksLoadedAsync(); return(inMemoryWebhooks.GetOrDefault(appId) ?? EmptyWebhooks); }
/// <summary> /// Get a page in my cache, first check if is in my dirty list. If not, check in my cache list. Returns null if not /// found /// </summary> public BasePage GetPage(uint pageID) { // check for in dirty list - if not found, check in cache list return(_dirty.GetOrDefault(pageID, null) ?? _cache.GetOrDefault(pageID, null)); }
public AssStyleOptions GetStyleOptions(string name) { return(_styleOptions?.GetOrDefault(name)); }
private CardWithExtraInfo GenerateCard(string text) { IDictionary <string, string> infos = new Dictionary <string, string>(); //Parsing using (XmlTextReader xmlReader = new XmlTextReader(new StringReader(SpecialXMLCorrection(text)))) { while (xmlReader.Read()) { if (xmlReader.NodeType != XmlNodeType.Element) { continue; } IAwareXmlTextReader reader = new AwareXmlTextReader(xmlReader); ICardInfoParserWorker worker = CardInfoParserWorkerFactory.Instance.CreateParserWorker(reader); if (worker == null) { continue; } infos.AddRange(ParseElement(reader, worker)); } } //Check parsing result CheckInfos(infos); //Generate result class CardWithExtraInfo cardWithExtraInfo = new CardWithExtraInfo { Name = RemoveParentheses(infos.GetOrDefault(NameKey)), CastingCost = infos.GetOrDefault(ManaCostKey), Text = infos.GetOrDefault(TextKey), Type = infos.GetOrDefault(TypeKey), PictureUrl = infos.GetOrDefault(ImageKey), Rarity = infos.GetOrDefault(RarityKey) }; if (MagicRules.IsCreature(cardWithExtraInfo.Type) || MagicRules.IsVehicle(cardWithExtraInfo.Type)) { string htmlTrim = infos.GetOrDefault(PTKey).HtmlTrim(); cardWithExtraInfo.Power = GetPower(htmlTrim); cardWithExtraInfo.Toughness = GetToughness(htmlTrim); } if (MagicRules.IsPlaneswalker(cardWithExtraInfo.Type)) { string htmlTrim = infos.GetOrDefault(PTKey).HtmlTrim(); //Possible see CheckInfos for more info if (!string.IsNullOrWhiteSpace(htmlTrim)) { htmlTrim = htmlTrim.ToUpper(); //Special case for: // Nissa, Steward of Elements with loyalty to X // B.O.B. (Bevy of Beebles) with loyalty to * if (htmlTrim == "X" || htmlTrim == "*") { cardWithExtraInfo.Loyalty = htmlTrim; } else { cardWithExtraInfo.Loyalty = int.Parse(htmlTrim).ToString(); } } } string variations = infos.GetOrDefault(VariationsKey); if (!string.IsNullOrWhiteSpace(variations)) { foreach (string variation in variations.Split(new[] { VariationsWorker.Separator }, System.StringSplitOptions.RemoveEmptyEntries)) { if (int.TryParse(variation, out int gatherid)) { cardWithExtraInfo.Add(gatherid); } } } cardWithExtraInfo.Type = infos.GetOrDefault(TypeKey); return(cardWithExtraInfo); }
public IEntityDefinition GetByCode(string code) { return(_entityDefinitions.GetOrDefault(code)); }
internal async Task PublishDiagnosticsAsync(CodeAnalysis.Document document) { // Retrieve all diagnostics for the current document grouped by their actual file uri. var fileUriToDiagnostics = await GetDiagnosticsAsync(document, CancellationToken.None).ConfigureAwait(false); // Get the list of file uris with diagnostics (for the document). // We need to join the uris from current diagnostics with those previously published // so that we clear out any diagnostics in mapped files that are no longer a part // of the current diagnostics set (because the diagnostics were fixed). // Use sorted set to have consistent publish ordering for tests and debugging. var urisForCurrentDocument = _documentsToPublishedUris.GetOrValue(document.Id, ImmutableSortedSet.Create <Uri>(s_uriComparer)).Union(fileUriToDiagnostics.Keys); // Update the mapping for this document to be the uris we're about to publish diagnostics for. _documentsToPublishedUris[document.Id] = urisForCurrentDocument; // Go through each uri and publish the updated set of diagnostics per uri. foreach (var fileUri in urisForCurrentDocument) { // Get the updated diagnostics for a single uri that were contributed by the current document. var diagnostics = fileUriToDiagnostics.GetOrValue(fileUri, ImmutableArray <LanguageServer.Protocol.Diagnostic> .Empty); if (_publishedFileToDiagnostics.ContainsKey(fileUri)) { // Get all previously published diagnostics for this uri excluding those that were contributed from the current document. // We don't need those since we just computed the updated values above. var diagnosticsFromOtherDocuments = _publishedFileToDiagnostics[fileUri].Where(kvp => kvp.Key != document.Id).SelectMany(kvp => kvp.Value); // Since diagnostics are replaced per uri, we must publish both contributions from this document and any other document // that has diagnostic contributions to this uri, so union the two sets. diagnostics = diagnostics.AddRange(diagnosticsFromOtherDocuments); } await SendDiagnosticsNotificationAsync(fileUri, diagnostics).ConfigureAwait(false); // There are three cases here -> // 1. There are no diagnostics to publish for this fileUri. We no longer need to track the fileUri at all. // 2. There are diagnostics from the current document. Store the diagnostics for the fileUri and document // so they can be published along with contributions to the fileUri from other documents. // 3. There are no diagnostics contributed by this document to the fileUri (could be some from other documents). // We should clear out the diagnostics for this document for the fileUri. if (diagnostics.IsEmpty) { // We published an empty set of diagnostics for this uri. We no longer need to keep track of this mapping // since there will be no previous diagnostics that we need to clear out. _documentsToPublishedUris.MultiRemove(document.Id, fileUri); // There are not any diagnostics to keep track of for this file, so we can stop. _publishedFileToDiagnostics.Remove(fileUri); } else if (fileUriToDiagnostics.ContainsKey(fileUri)) { // We do have diagnostics from the current document - update the published diagnostics map // to contain the new diagnostics contributed by this document for this uri. var documentsToPublishedDiagnostics = _publishedFileToDiagnostics.GetOrAdd(fileUri, (_) => new Dictionary <DocumentId, ImmutableArray <LanguageServer.Protocol.Diagnostic> >()); documentsToPublishedDiagnostics[document.Id] = fileUriToDiagnostics[fileUri]; } else { // There were diagnostics from other documents, but none from the current document. // If we're tracking the current document, we can stop. _publishedFileToDiagnostics.GetOrDefault(fileUri)?.Remove(document.Id); _documentsToPublishedUris.MultiRemove(document.Id, fileUri); } } }
public void DeleteMappedResultsForDocumentId(string documentId, string view, Dictionary<ReduceKeyAndBucket, int> removed) { Api.JetSetCurrentIndex(session, MappedResults, "by_view_and_doc_key"); Api.MakeKey(session, MappedResults, view, Encoding.Unicode, MakeKeyGrbit.NewKey); Api.MakeKey(session, MappedResults, documentId, Encoding.Unicode, MakeKeyGrbit.None); if (Api.TrySeek(session, MappedResults, SeekGrbit.SeekEQ) == false) return; Api.MakeKey(session, MappedResults, view, Encoding.Unicode, MakeKeyGrbit.NewKey); Api.MakeKey(session, MappedResults, documentId, Encoding.Unicode, MakeKeyGrbit.None); Api.JetSetIndexRange(session, MappedResults, SetIndexRangeGrbit.RangeUpperLimit | SetIndexRangeGrbit.RangeInclusive); do { // esent index ranges are approximate, and we need to check them ourselves as well var viewFromDb = Api.RetrieveColumnAsString(session, MappedResults, tableColumnsCache.MappedResultsColumns["view"]); if (StringComparer.OrdinalIgnoreCase.Equals(viewFromDb, view) == false) continue; var documentIdFromDb = Api.RetrieveColumnAsString(session, MappedResults, tableColumnsCache.MappedResultsColumns["document_key"]); if (StringComparer.OrdinalIgnoreCase.Equals(documentIdFromDb, documentId) == false) continue; var reduceKey = Api.RetrieveColumnAsString(session, MappedResults, tableColumnsCache.MappedResultsColumns["reduce_key"], Encoding.Unicode); var bucket = Api.RetrieveColumnAsInt32(session, MappedResults, tableColumnsCache.MappedResultsColumns["bucket"]).Value; var key = new ReduceKeyAndBucket(bucket, reduceKey); removed[key] = removed.GetOrDefault(key) + 1; Api.JetDelete(session, MappedResults); } while (Api.TryMoveNext(session, MappedResults)); }
private void UpdateFacetResults(Dictionary<string, Dictionary<string, FacetValue>> facetsByName) { foreach (var facet in Facets.Values) { if (facet.Mode == FacetMode.Ranges) continue; var values = new List<FacetValue>(); List<string> allTerms; int maxResults = Math.Min(PageSize ?? facet.MaxResults ?? Database.Configuration.MaxPageSize, Database.Configuration.MaxPageSize); var groups = facetsByName.GetOrDefault(facet.DisplayName); if (groups == null) continue; switch (facet.TermSortMode) { case FacetTermSortMode.ValueAsc: allTerms = new List<string>(groups.OrderBy(x => x.Key).ThenBy(x => x.Value.Hits).Select(x => x.Key)); break; case FacetTermSortMode.ValueDesc: allTerms = new List<string>(groups.OrderByDescending(x => x.Key).ThenBy(x => x.Value.Hits).Select(x => x.Key)); break; case FacetTermSortMode.HitsAsc: allTerms = new List<string>(groups.OrderBy(x => x.Value.Hits).ThenBy(x => x.Key).Select(x => x.Key)); break; case FacetTermSortMode.HitsDesc: allTerms = new List<string>(groups.OrderByDescending(x => x.Value.Hits).ThenBy(x => x.Key).Select(x => x.Key)); break; default: throw new ArgumentException(string.Format("Could not understand '{0}'", facet.TermSortMode)); } foreach (var term in allTerms.Skip(Start).TakeWhile(term => values.Count < maxResults)) { var facetValue = groups.GetOrDefault(term); values.Add(facetValue ?? new FacetValue { Range = term }); } var previousHits = allTerms.Take(Start).Sum(allTerm => { var facetValue = groups.GetOrDefault(allTerm); return facetValue == null ? 0 : facetValue.Hits; }); var key = string.IsNullOrWhiteSpace(facet.DisplayName) ? facet.Name : facet.DisplayName; Results.Results[key] = new FacetResult { Values = values, RemainingTermsCount = allTerms.Count - (Start + values.Count), RemainingHits = groups.Values.Sum(x => x.Hits) - (previousHits + values.Sum(x => x.Hits)), }; if (facet.IncludeRemainingTerms) Results.Results[key].RemainingTerms = allTerms.Skip(Start + values.Count).ToList(); } }
/// <summary> /// 建立 SubCategoryUser 個體。 /// </summary> /// <param name="catSub">CatSub 個體</param> /// <param name="userMap">User 快查表。</param> /// <returns>子站維護人員資訊</returns> private CategoryContactModel CreateCategoryContact(CatSub catSub, Dictionary<string, PriUser> userMap) { var categoryContact = new CategoryContactModel { Id = catSub.Id, }; categoryContact.Pm = userMap.GetOrDefault(catSub.User.UsrName); categoryContact.Manager = userMap.GetOrDefault(catSub.MdyPm); categoryContact.Purchaser = userMap.GetOrDefault(catSub.MdyPurher); categoryContact.Staff = userMap.GetOrDefault(catSub.MdyStaff); return categoryContact; }
public static ActionColumnViewModel GetActionValues(string header, GenericActionViewModel action, Dictionary <int, string> wbsValues = null) { var model = new ActionColumnViewModel { Values = new List <ActionValueViewModel>() }; switch (header) { case nameof(PublishedAction.WBS): model.Values.Add(new ActionValueViewModel { Type = "Text", Value = wbsValues?.GetOrDefault(action.ActionId) ?? action.WBS }); break; case nameof(PublishedAction.Label): model.Values.Add(new ActionValueViewModel { Type = "Text", Value = action.Label ?? string.Empty }); break; case nameof(PublishedAction.Thumbnail): model.Values.Add(new ActionValueViewModel { Type = "Image", Value = action.ImageHash, FileHash = action.ImageHash, FileExt = action.Extension }); break; case nameof(PublishedAction.Duration): model.Values.Add(new ActionValueViewModel { Type = "Text", Value = TicksUtil.TicksToString(action.Duration, action.TimeScale) }); break; case nameof(PublishedAction.Refs1): model.Values = BuildMultiValueRefs(action, ProcessReferentialIdentifier.Ref1); break; case nameof(PublishedAction.Refs2): model.Values = BuildMultiValueRefs(action, ProcessReferentialIdentifier.Ref2); break; case nameof(PublishedAction.Refs3): model.Values = BuildMultiValueRefs(action, ProcessReferentialIdentifier.Ref3); break; case nameof(PublishedAction.Refs4): model.Values = BuildMultiValueRefs(action, ProcessReferentialIdentifier.Ref4); break; case nameof(PublishedAction.Refs5): model.Values = BuildMultiValueRefs(action, ProcessReferentialIdentifier.Ref5); break; case nameof(PublishedAction.Refs6): model.Values = BuildMultiValueRefs(action, ProcessReferentialIdentifier.Ref6); break; case nameof(PublishedAction.Refs7): model.Values = BuildMultiValueRefs(action, ProcessReferentialIdentifier.Ref7); break; case nameof(PublishedAction.CustomTextValue): model.Values.Add(new ActionValueViewModel { Type = "Text", Value = action.CustomTextValues != null ? action.CustomTextValues .Where(t => t.Key == ProcessReferentialIdentifier.CustomTextLabel) .Select(t => t.Value) .DefaultIfEmpty(string.Empty) .FirstOrDefault() : string.Empty }); break; case nameof(PublishedAction.CustomTextValue2): model.Values.Add(new ActionValueViewModel { Type = "Text", Value = action.CustomTextValues != null ? action.CustomTextValues .Where(t => t.Key == ProcessReferentialIdentifier.CustomTextLabel2) .Select(t => t.Value) .DefaultIfEmpty(string.Empty) .FirstOrDefault() : string.Empty }); break; case nameof(PublishedAction.CustomTextValue3): model.Values.Add(new ActionValueViewModel { Type = "Text", Value = action.CustomTextValues != null ? action.CustomTextValues .Where(t => t.Key == ProcessReferentialIdentifier.CustomTextLabel3) .Select(t => t.Value) .DefaultIfEmpty(string.Empty) .FirstOrDefault() : string.Empty }); break; case nameof(PublishedAction.CustomTextValue4): model.Values.Add(new ActionValueViewModel { Type = "Text", Value = action.CustomTextValues != null ? action.CustomTextValues .Where(t => t.Key == ProcessReferentialIdentifier.CustomTextLabel4) .Select(t => t.Value) .DefaultIfEmpty(string.Empty) .FirstOrDefault() : string.Empty }); break; case nameof(PublishedAction.CustomNumericValue): model.Values.Add(new ActionValueViewModel { Type = "Text", Value = action.CustomNumericFields != null ? action.CustomNumericValues .Where(t => t.Key == ProcessReferentialIdentifier.CustomNumericLabel) .Select(t => $"{t.Value}") .DefaultIfEmpty(string.Empty) .FirstOrDefault() : string.Empty }); break; case nameof(PublishedAction.CustomNumericValue2): model.Values.Add(new ActionValueViewModel { Type = "Text", Value = action.CustomNumericFields != null ? action.CustomNumericValues .Where(t => t.Key == ProcessReferentialIdentifier.CustomNumericLabel2) .Select(t => $"{t.Value}") .DefaultIfEmpty(string.Empty) .FirstOrDefault() : string.Empty }); break; case nameof(PublishedAction.CustomNumericValue3): model.Values.Add(new ActionValueViewModel { Type = "Text", Value = action.CustomNumericFields != null ? action.CustomNumericValues .Where(t => t.Key == ProcessReferentialIdentifier.CustomNumericLabel3) .Select(t => $"{t.Value}") .DefaultIfEmpty(string.Empty) .FirstOrDefault() : string.Empty }); break; case nameof(PublishedAction.CustomNumericValue4): model.Values.Add(new ActionValueViewModel { Type = "Text", Value = action.CustomNumericFields != null ? action.CustomNumericValues .Where(t => t.Key == ProcessReferentialIdentifier.CustomNumericLabel4) .Select(t => $"{t.Value}") .DefaultIfEmpty(string.Empty) .FirstOrDefault() : string.Empty }); break; default: var attribute = ReflectionHelper.GetPropertyValue(action, header); model.Values.Add(new ActionValueViewModel { Type = "Text", Value = attribute != null ? attribute.ToString() : string.Empty }); break; } return(model); }
public static ActionColumnViewModel GetActionValues( string header, KAction action, IEnumerable <ProjectReferential> usedReferentials, Dictionary <int, string> wbsValues = null) { var model = new ActionColumnViewModel { Values = new List <ActionValueViewModel>() }; switch (header) { case nameof(PublishedAction.WBS): model.Values.Add(new ActionValueViewModel { Type = "Text", Value = wbsValues?.GetOrDefault(action.ActionId) ?? action.WBS }); break; case nameof(PublishedAction.Label): model.Values.Add(new ActionValueViewModel { Type = "Text", Value = action.Label ?? string.Empty }); break; case nameof(PublishedAction.Thumbnail): model.Values.Add(new ActionValueViewModel { Type = "Image", Value = action.Thumbnail?.Hash, FileHash = action.Thumbnail?.Hash, FileExt = action.Thumbnail?.Extension }); break; case nameof(PublishedAction.Duration): model.Values.Add(new ActionValueViewModel { Type = "Text", Value = TicksUtil.TicksToString(action.Duration, action.Scenario.Project.TimeScale) }); break; case nameof(PublishedAction.PublishedResource): model.Values.Add(BuildFile(action.Operator?.CloudFile ?? action.Equipment?.CloudFile, action.Operator?.Label ?? action.Equipment?.Label, 1)); break; case nameof(PublishedAction.Refs1): model.Values = BuildReferentialFile(action.Refs(ProcessReferentialIdentifier.Ref1), usedReferentials); break; case nameof(PublishedAction.Refs2): model.Values = BuildReferentialFile(action.Refs(ProcessReferentialIdentifier.Ref2), usedReferentials); break; case nameof(PublishedAction.Refs3): model.Values = BuildReferentialFile(action.Refs(ProcessReferentialIdentifier.Ref3), usedReferentials); break; case nameof(PublishedAction.Refs4): model.Values = BuildReferentialFile(action.Refs(ProcessReferentialIdentifier.Ref4), usedReferentials); break; case nameof(PublishedAction.Refs5): model.Values = BuildReferentialFile(action.Refs(ProcessReferentialIdentifier.Ref5), usedReferentials); break; case nameof(PublishedAction.Refs6): model.Values = BuildReferentialFile(action.Refs(ProcessReferentialIdentifier.Ref6), usedReferentials); break; case nameof(PublishedAction.Refs7): model.Values = BuildReferentialFile(action.Refs(ProcessReferentialIdentifier.Ref7), usedReferentials); break; default: var attribute = ReflectionHelper.GetPropertyValue(action, header); model.Values.Add(new ActionValueViewModel { Type = "Text", Value = attribute != null ? attribute.ToString() : "" }); break; } return(model); }
public void DeleteMappedResultsForDocumentId(string documentId, int view, Dictionary<ReduceKeyAndBucket, int> removed) { var viewKey = CreateKey(view); var viewKeySlice = new Slice(viewKey); var viewAndDocumentId = new Slice(AppendToKey(viewKey, documentId)); var mappedResultsByViewAndDocumentId = tableStorage.MappedResults.GetIndex(Tables.MappedResults.Indices.ByViewAndDocumentId); var mappedResultsByView = tableStorage.MappedResults.GetIndex(Tables.MappedResults.Indices.ByView); var mappedResultsByViewAndReduceKey = tableStorage.MappedResults.GetIndex(Tables.MappedResults.Indices.ByViewAndReduceKey); var mappedResultsByViewAndReduceKeyAndSourceBucket = tableStorage.MappedResults.GetIndex(Tables.MappedResults.Indices.ByViewAndReduceKeyAndSourceBucket); var mappedResultsData = tableStorage.MappedResults.GetIndex(Tables.MappedResults.Indices.Data); using (var iterator = mappedResultsByViewAndDocumentId.MultiRead(Snapshot, viewAndDocumentId)) { if (!iterator.Seek(Slice.BeforeAllKeys)) return; do { // TODO: Check if we can relax the clone. var id = iterator.CurrentKey.Clone(); ushort version; var value = LoadStruct(tableStorage.MappedResults, id, writeBatch.Value, out version); var reduceKey = value.ReadString(MappedResultFields.ReduceKey); var bucket = value.ReadInt(MappedResultFields.Bucket); var reduceKeyHash = HashKey(reduceKey); var viewAndReduceKey = AppendToKey(viewKey, ReduceKeySizeLimited(reduceKey), reduceKeyHash); var viewAndReduceKeyAndSourceBucket = AppendToKey(viewAndReduceKey, bucket); tableStorage.MappedResults.Delete(writeBatch.Value, id); mappedResultsByViewAndDocumentId.MultiDelete(writeBatch.Value, viewAndDocumentId, id); mappedResultsByView.MultiDelete(writeBatch.Value, viewKeySlice, id); mappedResultsByViewAndReduceKey.MultiDelete(writeBatch.Value, (Slice)viewAndReduceKey, id); mappedResultsByViewAndReduceKeyAndSourceBucket.MultiDelete(writeBatch.Value, (Slice)viewAndReduceKeyAndSourceBucket, id); mappedResultsData.Delete(writeBatch.Value, id); var reduceKeyAndBucket = new ReduceKeyAndBucket(bucket, reduceKey); removed[reduceKeyAndBucket] = removed.GetOrDefault(reduceKeyAndBucket) + 1; } while (iterator.MoveNext()); } }
/// <inheritdoc/> public async Task<IReadOnlyList<ISettingValue>> GetAllSettingValuesAsync(SettingScopes scopes) { var settingDefinitions = new Dictionary<string, SettingDefinition>(); var settingValues = new Dictionary<string, ISettingValue>(); //Fill all setting with default values. foreach (var setting in _settingDefinitionManager.GetAllSettingDefinitions()) { settingDefinitions[setting.Name] = setting; settingValues[setting.Name] = new SettingValueObject(setting.Name, setting.DefaultValue); } //Overwrite application settings if (scopes.HasFlag(SettingScopes.Application)) { foreach (var settingValue in await GetAllSettingValuesForApplicationAsync()) { var setting = settingDefinitions.GetOrDefault(settingValue.Name); //TODO: Conditions get complicated, try to simplify it if (setting == null || !setting.Scopes.HasFlag(SettingScopes.Application)) { continue; } if (!setting.IsInherited && (setting.Scopes.HasFlag(SettingScopes.User) && AbpSession.UserId.HasValue)) { continue; } settingValues[settingValue.Name] = new SettingValueObject(settingValue.Name, settingValue.Value); } } //Overwrite user settings if (scopes.HasFlag(SettingScopes.User) && AbpSession.UserId.HasValue) { foreach (var settingValue in await GetAllSettingValuesForUserAsync(AbpSession.UserId.Value)) { var setting = settingDefinitions.GetOrDefault(settingValue.Name); if (setting != null && setting.Scopes.HasFlag(SettingScopes.User)) { settingValues[settingValue.Name] = new SettingValueObject(settingValue.Name, settingValue.Value); } } } return settingValues.Values.ToImmutableList(); }
public void GetOrDefaultPresent() { Dictionary<string, int> dict = new Dictionary<string, int>() { { "one", 1 } }; int value = dict.GetOrDefault("one", -999); Assert.Equal(1, 1); }