public Dictionary<SystemMetricTypes, object> UpdateValues(Dictionary<SystemMetricTypes, object> values) { lock (_milliSeconds) { long cnt = _milliSeconds.Count; double high = 0; double tot = 0; while (_milliSeconds.Count > 0) { double tmp = _milliSeconds.Dequeue(); tot += tmp; high = (tmp > high ? tmp : high); } values.Remove(SystemMetricTypes.Average_Inbound_Connection_Duration); values.Add(SystemMetricTypes.Average_Inbound_Connection_Duration, new sSystemMetric(SystemMetricTypes.Average_Inbound_Connection_Duration, MetricUnits.MILLISECONDS, (tot == 0 ? (decimal)0 : (decimal)Math.Round(tot / (double)cnt, 2)))); if (values.ContainsKey(SystemMetricTypes.Max_Inbound_Connection_Duration)) { if (high>_high){ values.Remove(SystemMetricTypes.Max_Inbound_Connection_Duration); values.Add(SystemMetricTypes.Max_Inbound_Connection_Duration, new sSystemMetric(SystemMetricTypes.Max_Inbound_Connection_Duration, MetricUnits.MILLISECONDS, (decimal)high)); _high = high; } } else values.Add(SystemMetricTypes.Max_Inbound_Connection_Duration, new sSystemMetric(SystemMetricTypes.Max_Inbound_Connection_Duration, MetricUnits.MILLISECONDS, (decimal)high)); } return values; }
public void AddThreeItems_RemoveMiddleItem_CheckConsistency() { string path = AppDomain.CurrentDomain.BaseDirectory; BackingUnknownSize<Customer, string> backingFile = new BackingUnknownSize<Customer, string>(path, 100); Dictionary<Customer, string> dict = new Dictionary<Customer, string>(backingFile); Customer c1 = new Customer {Name = "Mikael"}; Customer c2 = new Customer {Name = "Svenson"}; Customer c3 = new Customer {Name = "Boss"}; dict.Add(c1, "test"); dict.Add(c2, "test2"); dict.Add(c3, "test3"); var result = dict.Remove(c2); Assert.IsTrue(result); result = dict.Remove(c2); Assert.IsFalse(result); dict.Add(c2, "test2"); result = dict.Remove(c2); Assert.IsTrue(result); var res2 = dict[c3]; Assert.AreEqual("test3", res2); }
public Uri GetAuthorizationUri(object parameters) { string queryString = String.Empty; if (parameters != null) { Dictionary<string, string> queryParameters = new Dictionary<string, string>(); #if WINMD foreach (var parameter in parameters.GetType().GetTypeInfo().DeclaredProperties) { if (queryParameters.ContainsKey(parameter.Name)) queryParameters.Remove(parameter.Name); queryParameters.Add(parameter.Name, parameter.GetValue(parameters).ToString()); } #else foreach (var parameter in parameters.GetType().GetProperties()) { if (queryParameters.ContainsKey(parameter.Name)) queryParameters.Remove(parameter.Name); queryParameters.Add(parameter.Name, parameter.GetValue(parameters, null).ToString()); } #endif foreach (var parameter in queryParameters) { queryString = String.Format("{0}&{1}={2}", queryString, parameter.Key, Uri.EscapeDataString(parameter.Value)); } } return new Uri(Context.AuthorizationUri.ToString() + "?oauth_token=" + RequestToken.Token + queryString); }
public static IScheduler Get_Scheduler(string schedule_file) { // load the schedule file Dictionary<string, object> schedule_dict = new Dictionary<string,object>(); if (File.Exists(schedule_file)) Inputs_to_Dictionary.Add_Input_Parameters_to_Dictionary(ref schedule_dict, schedule_file); else schedule_dict.Add("type", "none"); // get the type of scheduler required and return the scheduler switch (((string)schedule_dict["type"]).ToLower()) { case "none": // these are the default values for the mixing scheduler schedule_dict.Add("alpha", 0.01); schedule_dict.Add("zeta", 3.0); schedule_dict.Remove("type"); schedule_dict.Add("type", Scheduler_Type.None); return new Constant_Scheduler(schedule_dict); case "constant": schedule_dict.Remove("type"); schedule_dict.Add("type", Scheduler_Type.Constant); return new Constant_Scheduler(schedule_dict); case "file_defined": schedule_dict.Add("filename", schedule_file); schedule_dict.Remove("type"); schedule_dict.Add("type", Scheduler_Type.File_Defined); return new File_Defined_Scheduler(schedule_dict); default: throw new NotImplementedException("Error - the scheduler type requested is not implemented"); } }
private List<TaskSync> MergeTasks(List<TaskSync> tasksFromDb, List<TaskSync> tasksFromUser) { Dictionary<string, TaskSync> result = new Dictionary<string, TaskSync>(); foreach(TaskSync task in tasksFromDb) { task.Id = 0; result.Remove(task.SourceId); result.Add(task.SourceId, task); } foreach(TaskSync task in tasksFromUser) { task.Id = 0; TaskSync tempTask = null; result.TryGetValue(task.SourceId, out tempTask); if(tempTask != null) { DateTime tempTaskDate = tempTask.LastModifyDate; DateTime taskDate = task.LastModifyDate; if(DateTime.Compare(tempTaskDate, taskDate) <= 0) { result.Remove(task.SourceId); result.Add(task.SourceId, task); } } else result.Add(task.SourceId, task); } return new List<TaskSync>(result.Values); }
static void MapContentType(Dictionary<string, string> headers) { string contentType; if (!headers.TryGetValue("rebus-content-type", out contentType)) return; if (contentType == "text/json") { string contentEncoding; if (headers.TryGetValue("rebus-encoding", out contentEncoding)) { headers.Remove("rebus-content-type"); headers.Remove("rebus-encoding"); headers[Headers.ContentType] = $"{JsonSerializer.JsonContentType};charset={contentEncoding}"; } else { throw new FormatException( "Content type was 'text/json', but the 'rebus-encoding' header was not present!"); } } else { throw new FormatException( $"Sorry, but the '{contentType}' content type is currently not supported by the legacy header mapper"); } }
/// <summary> /// v3 serialization /// </summary> /// <param name="e"></param> public TranscriptionPhrase(XElement e) { Elements = e.Attributes().ToDictionary(a => a.Name.ToString(), a => a.Value); Elements.Remove("b"); Elements.Remove("e"); Elements.Remove("f"); this._phonetics = (e.Attribute("f") ?? EmptyAttribute).Value; this._text = e.Value.Trim('\r', '\n'); if (e.Attribute("b") != null) { string val = e.Attribute("b").Value; int ms; if (int.TryParse(val, out ms)) { Begin = TimeSpan.FromMilliseconds(ms); } else Begin = XmlConvert.ToTimeSpan(val); } if (e.Attribute("e") != null) { string val = e.Attribute("e").Value; int ms; if (int.TryParse(val, out ms)) { End = TimeSpan.FromMilliseconds(ms); } else End = XmlConvert.ToTimeSpan(val); } }
void SplitIntoSpeciallyNamedPictures (Dictionary<String, String> Source) { BeforeProjekteMaterialien = new Dictionary<string, string> (); IntermediateProjekteMaterialien = new Dictionary<string, string> (); AfterProjekteMaterialien = new Dictionary<string, string> (); int Index = Source.Keys.Count; while (Index > 0) { Index--; if (Source.Keys.ElementAt (Index).IndexOf (WordUp23.Basics.BeforeIndicator, StringComparison.CurrentCultureIgnoreCase) != -1) { BeforeProjekteMaterialien [Source.Keys.ElementAt (Index)] = Source [Source.Keys.ElementAt (Index)]; Source.Remove (Source.Keys.ElementAt (Index)); continue; } if (Source.Keys.ElementAt (Index).IndexOf (WordUp23.Basics.IntermediateIndicator, StringComparison.CurrentCultureIgnoreCase) != -1) { IntermediateProjekteMaterialien [Source.Keys.ElementAt (Index)] = Source [Source.Keys.ElementAt (Index)]; Source.Remove (Source.Keys.ElementAt (Index)); continue; } if (Source.Keys.ElementAt (Index).IndexOf (WordUp23.Basics.AfterIndicator, StringComparison.CurrentCultureIgnoreCase) != -1) { AfterProjekteMaterialien [Source.Keys.ElementAt (Index)] = Source [Source.Keys.ElementAt (Index)]; Source.Remove (Source.Keys.ElementAt (Index)); continue; } } }
public void Dictionary_kvp_Remove_checks_key_and_value() { IDictionary<int, string> dictionary = new Dictionary<int, string>(); dictionary[1] = "foo"; Assert.IsFalse(dictionary.Remove(new KeyValuePair<int, string>(1, "bar"))); Assert.IsTrue(dictionary.Remove(new KeyValuePair<int, string>(1, "foo"))); }
public static bool FindEndFromDict(string[] values, Dictionary<string, string[]> chainDictionary, int length) { if (values[1] == "END" && chainDictionary.Count == 0) return true; if (chainDictionary.Count == 0 || length <= 0) return false; string[] foundItem; if(chainDictionary.ContainsKey(values[1])) foundItem = chainDictionary[values[1]]; else return false; var searchItem = foundItem; // itme to look for again in dict // remove begin from Dictionary if (chainDictionary.ContainsKey("BEGIN")) chainDictionary.Remove("BEGIN"); chainDictionary.Remove(foundItem[0]); length = length - 1; return FindEndFromDict(searchItem, chainDictionary, length); }
public static Dictionary<string, int> GetShortestLevenshtein(string givenWord, List<string> words) { Dictionary<string, int> dists = new Dictionary<string, int>(); foreach (string word in words) { dists.Add(word, LevenshteinDistance(givenWord, word)); } dists = dists.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value); var shortestElement = dists.ElementAt(1); int shortestDist = shortestElement.Value; for (int i = dists.Count - 1; i > 0; i--) { var item = dists.ElementAt(i); if (item.Value != shortestDist) { dists.Remove(item.Key); } } /* Remove givenWord from the output */ dists.Remove(dists.ElementAt(0).Key); return dists; }
public static string CreateForRequest(string callbackURL, string consumerKey, string consumerSecret, string url) { parameters = new Dictionary<string, string>() { {"oauth_callback",""}, {"oauth_consumer_key",""}, {"oauth_nonce",""}, {"oauth_signature",""}, {"oauth_signature_method","HMAC-SHA1"}, {"oauth_timestamp",""}, {"oauth_token",""}, {"oauth_verifier",""}, {"oauth_version","1.0"}, }; OauthConsumerSecret = consumerSecret; parameters.Remove("oauth_token"); parameters.Remove("oauth_verifier"); parameters["oauth_callback"] = callbackURL; parameters["oauth_consumer_key"] = consumerKey; parameters["oauth_nonce"] = GenerateNonce(); parameters["oauth_timestamp"] = GenerateTimeStamp(); parameters["oauth_signature"] = GenerateSignature(url, "GET"); return "OAuth " + EncodeRequestParameters(); }
/// <summary> /// Compute rated usage per meter /// </summary> /// <param name="rates">rate</param> /// <param name="usage">usage</param> /// <returns>total cost for meter</returns> public static double computeRatedUsagePerMeter(Dictionary<double, double> rates, double usage) { double total = 0.0; if (rates.Count == 0) return 0.0; else if (rates.Count == 1) return (usage * rates.Values.FirstOrDefault()); var remainingUsage = usage; while (rates.Count > 0) { //double currentValue=rates.GetEnumerator().Current.Key; double LastKey = rates.Keys.Last(); if (remainingUsage > LastKey) { double LastKeyValue = 0.0; if (rates.TryGetValue(LastKey, out LastKeyValue)) { total = total + ((remainingUsage - LastKey + 1) * LastKeyValue); // remainingUsage - LastKey +1 because tiered pricing is exclusive remainingUsage = LastKey - 1; } rates.Remove(LastKey); } else if (remainingUsage <= LastKey) { rates.Remove(LastKey); } } return total; }
private async static Task<FlickrResult<string>> GetDataResponseOAuthAsync(Twitter flickr, string method, string baseUrl, Dictionary<string, string> parameters) { if (parameters.ContainsKey("api_key")) parameters.Remove("api_key"); if (parameters.ContainsKey("api_sig")) parameters.Remove("api_sig"); if (!String.IsNullOrEmpty(flickr.OAuthAccessToken) && !parameters.ContainsKey("oauth_token")) { parameters.Add("oauth_token", flickr.OAuthAccessToken); } if (!String.IsNullOrEmpty(flickr.OAuthAccessTokenSecret) && !parameters.ContainsKey("oauth_signature")) { string sig = flickr.OAuthCalculateSignatureForCalls(method, baseUrl, parameters, flickr.OAuthAccessTokenSecret); parameters.Add("oauth_signature", sig); } string data = OAuthCalculatePostData(parameters); string authHeader = OAuthCalculateAuthHeader(parameters); baseUrl = baseUrl.Split("?".ToCharArray())[0]; if (method == "GET") return await DownloadDataAsync(method, baseUrl, data, GetContentType, authHeader); else return await DownloadDataAsync(method, baseUrl, data, PostContentType, authHeader); }
public static void Rename(Dictionary<string, string> file_to_new_file) { var file_to_new_file_copy = new Dictionary<string, string>(file_to_new_file); while (file_to_new_file_copy.Count > 0) { var kvp = file_to_new_file_copy.ElementAt(0); Action<string> recursive_rename_delegate = null; recursive_rename_delegate = file => { if (File.Exists(file_to_new_file_copy[file])) { if (file_to_new_file_copy[file] == kvp.Key) { string temp_file = Path.Combine(Path.GetDirectoryName(file) ?? string.Empty, Path.GetRandomFileName()); File.Move(file, temp_file); file_to_new_file_copy[temp_file] = file_to_new_file_copy[file]; file_to_new_file_copy.Remove(file); return; } else { recursive_rename_delegate(file_to_new_file_copy[file]); } } File.Move(file, file_to_new_file_copy[file]); file_to_new_file_copy.Remove(file); }; recursive_rename_delegate(kvp.Key); } }
static void Main(string[] args) { //StreamReader myReader = new StreamReader() var myReader = File.ReadAllText("C:\\CoderCAMP_projects\\Hamlet\\Hamlet\\hamlet.txt").ToLower(); myReader = myReader.Remove(',', ' '); myReader = myReader.Remove('?', ' '); var words = myReader.Split(' '); var hamlet = new Dictionary<string, int>(); int value = 0; foreach (var word in words) { hamlet[word] = hamlet.TryGetValue(word, out value) ? ++value : 1; } hamlet.Remove(""); hamlet.Remove(" "); foreach (KeyValuePair<string, int> item in hamlet.OrderBy(key => key.Value)) { Console.WriteLine("{0} {1} ", item.Key, item.Value); } Console.WriteLine(hamlet.Values); Console.ReadLine(); }
static void Main(string[] args) { string hamlet = File.ReadAllText(@"C:\Projects\ConsoleApplication1\hamlet.txt").ToLower(); //Console.WriteLine(hamlet); hamlet = hamlet.Replace(",", ""); hamlet = hamlet.Replace("?", ""); hamlet = hamlet.Replace(".", ""); hamlet = hamlet.Replace(Environment.NewLine, ""); var contents = hamlet.Split(' '); var hamletDictionary = new Dictionary<string, int>(); int value = 0; foreach (var word in contents) { hamletDictionary[word] = hamletDictionary.TryGetValue(word, out value) ? ++value : 1; } hamletDictionary.Remove(""); hamletDictionary.Remove(" "); foreach (KeyValuePair<string, int> item in hamletDictionary.Where(a => a.Key.Length > 3).OrderBy(key => key.Value)) { Console.WriteLine("{0}, {1}", item.Key, item.Value); } Console.ReadLine(); }
private static ServerContext CreateContext(Dictionary<string, Route> scanResult, Http404Behavior http404Behavior, string rootRequestPath) { var context = new ServerContext { Http404Behavior = http404Behavior, RootRequestPath = rootRequestPath }; var http404 = scanResult.Keys.FirstOrDefault(x => x.EndsWith("/_error/404")); if (http404 != null) { context.Custom404Page = scanResult[http404].Resource; scanResult.Remove(http404); } var http500 = scanResult.Keys.FirstOrDefault(x => x.EndsWith("/_error/500")); if (http500 != null) { context.Custom500Page = scanResult[http500].Resource; scanResult.Remove(http500); } context.Routes = scanResult; return context; }
public static Storyboard CreateAnimation(this DependencyObject target, Dictionary<string, StoryboardInfo> storyboards, DependencyProperty animatingDependencyProperty, string propertyPath, string propertyKey, object initialValue, object targetValue, TimeSpan timeSpan, IEasingFunction easingFunction, Action releaseAction) { StoryboardInfo storyboardInfo; storyboards.TryGetValue(DependencyPropertyAnimationHelper.GetStoryboardKey(propertyKey), out storyboardInfo); if (storyboardInfo != null) { DependencyObject storyboardTarget = storyboardInfo.StoryboardTarget; storyboardInfo.Storyboard.Stop(); storyboards.Remove(DependencyPropertyAnimationHelper.GetStoryboardKey(propertyKey)); if (storyboardInfo.ReleaseAction != null) { storyboardInfo.ReleaseAction(); storyboardInfo.ReleaseAction = (Action)null; } } storyboardInfo = new StoryboardInfo(); storyboardInfo.Storyboard = DependencyPropertyAnimationHelper.CreateStoryboard(target, animatingDependencyProperty, propertyPath, propertyKey, ref targetValue, timeSpan, easingFunction); storyboardInfo.ReleaseAction = releaseAction; storyboardInfo.StoryboardTarget = target; storyboardInfo.AnimateFrom = initialValue; storyboardInfo.Storyboard.Completed += (EventHandler)((source, args) => { storyboards.Remove(DependencyPropertyAnimationHelper.GetStoryboardKey(propertyKey)); if (storyboardInfo.ReleaseAction == null) return; storyboardInfo.ReleaseAction(); storyboardInfo.ReleaseAction = (Action)null; }); storyboards.Add(DependencyPropertyAnimationHelper.GetStoryboardKey(propertyKey), storyboardInfo); return storyboardInfo.Storyboard; }
private static void FilterValidStackLocals(Dictionary<LocalSymbol, LocalDefUseInfo> info) { // remove fake dummies and variable that cannot be scheduled var dummies = ArrayBuilder<LocalDefUseInfo>.GetInstance(); foreach (var local in info.Keys.ToArray()) { var locInfo = info[local]; if (local.SynthesizedKind == SynthesizedLocalKind.OptimizerTemp) { dummies.Add(locInfo); info.Remove(local); } else if (locInfo.CannotSchedule) { locInfo.LocalDefs.Free(); info.Remove(local); } } if (info.Count != 0) { RemoveIntersectingLocals(info, dummies); } foreach (var dummy in dummies) { dummy.LocalDefs.Free(); } dummies.Free(); }
/// <summary> /// Do parse /// </summary> /// <param name="args">Command line argument</param> /// <param name="options">Result of options</param> /// <param name="arguments">Result of another args</param> public static void parse(string[] args, out Dictionary<string, string> options, out List<string> arguments) { options = new Dictionary<string, string>(); arguments = new List<string>(); if (args.Length > 0 && Regex.IsMatch(args[0], @"\.exe$", RegexOptions.IgnoreCase)) { var tmp = new List<string>(args); tmp.RemoveAt(0); args = tmp.ToArray(); } foreach (string arg in args) { var maa = new Regex(@"^-(?<key>[a-zA-Z0-9])=(?<val>.*$)").Match(arg); if (maa.Success) { // Ex: -d=C:/Windows/Temp string key = maa.Groups["key"].Value; if (options.ContainsKey(key)) { options.Remove(key); } options.Add(key, maa.Groups["val"].Value); } else if (Regex.IsMatch(arg, @"^-[a-zA-Z0-9]+$")) { // Ex: -RIi, -R -I -i foreach (char c in arg.ToCharArray()) { string key = c.ToString(); if (key != "-") { if (options.ContainsKey(key)) { options.Remove(key); } options.Add(key, null); } } } else if (Regex.IsMatch(arg, @"^--[a-zA-Z0-9\-]+$")) { // Ex: --no-retry string key = Regex.Replace(arg, @"^--", ""); if (options.ContainsKey(key)) { options.Remove(key); } options.Add(key, null); } else { // Ex: --temp-directory=C:/Windows/Temp var ma = new Regex(@"^--(?<key>[a-zA-Z0-9\-]+)=(?<val>.*)$").Match(arg); if (ma.Success) { string key = ma.Groups["key"].Value; if (options.ContainsKey(key)) { options.Remove(key); } options.Add(key, ma.Groups["val"].Value); } else { // other arguments.Add(arg); } } } return; }
public void dictionary_remove_doesnt_fail_for_non_existant_key() { var dict = new Dictionary<string, int>(); dict.Add("foo", 33); dict.Remove("foo"); dict.Remove("foo"); }
public TranscriptionParagraph(XElement e) { if (!e.CheckRequiredAtributes("b", "e", "s")) throw new ArgumentException("required attribute missing on paragraph (b,e,s)"); Phrases = new VirtualTypeList<TranscriptionPhrase>(this, this._children); _internalID = int.Parse(e.Attribute( "s").Value); AttributeString = (e.Attribute( "a") ?? EmptyAttribute).Value; Elements = e.Attributes().ToDictionary(a => a.Name.ToString(), a => a.Value); foreach (var p in e.Elements("p").Select(p => (TranscriptionElement)new TranscriptionPhrase(p))) Add(p); string bfr; if (Elements.TryGetValue("a", out bfr)) this.AttributeString = bfr; if (Elements.TryGetValue("b", out bfr)) { int ms; if (int.TryParse(bfr, out ms)) Begin = TimeSpan.FromMilliseconds(ms); else Begin = XmlConvert.ToTimeSpan(bfr); } else { var ch = _children.FirstOrDefault(); Begin = ch == null ? TimeSpan.Zero : ch.Begin; } if (Elements.TryGetValue("e", out bfr)) { int ms; if (int.TryParse(bfr, out ms)) End = TimeSpan.FromMilliseconds(ms); else End = XmlConvert.ToTimeSpan(bfr); } else { var ch = _children.LastOrDefault(); End = ch == null ? TimeSpan.Zero : ch.Begin; } if (Elements.TryGetValue("l", out bfr)) { if(!string.IsNullOrWhiteSpace(bfr)) Language = bfr.ToUpper(); } Elements.Remove("b"); Elements.Remove("e"); Elements.Remove("s"); Elements.Remove("a"); Elements.Remove("l"); }
private static string GetDataResponseOAuth(Flickr flickr, string baseUrl, Dictionary<string, string> parameters) { string method = "POST"; // Remove api key if it exists. if (parameters.ContainsKey("api_key")) parameters.Remove("api_key"); if (parameters.ContainsKey("api_sig")) parameters.Remove("api_sig"); // If OAuth Access Token is set then add token and generate signature. if (!String.IsNullOrEmpty(flickr.OAuthAccessToken) && !parameters.ContainsKey("oauth_token")) { parameters.Add("oauth_token", flickr.OAuthAccessToken); } if (!String.IsNullOrEmpty(flickr.OAuthAccessTokenSecret) && !parameters.ContainsKey("oauth_signature")) { string sig = flickr.OAuthCalculateSignature(method, baseUrl, parameters, flickr.OAuthAccessTokenSecret); parameters.Add("oauth_signature", sig); } // Calculate post data, content header and auth header string data = OAuthCalculatePostData(parameters); string authHeader = OAuthCalculateAuthHeader(parameters); // Download data. try { return DownloadData(method, baseUrl, data, PostContentType, authHeader); } catch (WebException ex) { if (ex.Status != WebExceptionStatus.ProtocolError) throw; var response = ex.Response as HttpWebResponse; if (response == null) throw; string responseData = null; using (var stream = response.GetResponseStream()) { if( stream != null) using (var responseReader = new StreamReader(stream)) { responseData = responseReader.ReadToEnd(); responseReader.Close(); } } if (response.StatusCode == HttpStatusCode.BadRequest || response.StatusCode == HttpStatusCode.Unauthorized) { throw new OAuthException(responseData, ex); } if (String.IsNullOrEmpty(responseData)) throw; throw new WebException("WebException occurred with the following body content: " + responseData, ex, ex.Status, ex.Response); } }
static void Main() { Dictionary<string, int> d = new Dictionary<string, int>(); d.Add("cat", 1); d.Add("dog", 2); d.Remove("cat"); // Removes cat d.Remove("nothing"); // Doesn't Remove Anything }
public void Subscribe_HighThroughPut() { var handle = new ManualResetEvent(false); var pn = new Pubnub("demo", "demo", string.Empty); var list = new Dictionary<int, object>(); int count = 10; var sync = new object(); pn.MessageRecieved += (s, e) => { Task.Factory.StartNew(() => { if (e.Channel == "csharp_throughput_test") { var o = JObject.Parse(e.Message); System.Diagnostics.Debug.WriteLine(o["ID"].ToString()); lock (sync) list.Remove(Convert.ToInt32(o["ID"].ToString())); if (Interlocked.Decrement(ref count) == 0) { System.Threading.Thread.Sleep(1000); handle.Set(); } } }); }; pn.Subscribe("csharp_throughput_test"); System.Threading.Thread.Sleep(10000); Parallel.For(0, 10, (i) => { lock (sync) list.Add(i, null); // System.Diagnostics.Debug.WriteLine(i); var test = (pn.Publish("csharp_throughput_test", new { ID = i })); if (!test) { lock (sync) list.Remove(i); System.Diagnostics.Debug.WriteLine("Failed: " + i); } }); handle.WaitOne(Convert.ToInt32(new TimeSpan(0, 1, 0).TotalMilliseconds)); Assert.IsTrue(count == 0); }
public Dictionary<SystemMetricTypes, object> UpdateValues(Dictionary<SystemMetricTypes, object> values) { values.Remove(SystemMetricTypes.Freeswitch_Events); values.Remove(SystemMetricTypes.System_Events); values.Add(SystemMetricTypes.Freeswitch_Events, new sSystemMetric(SystemMetricTypes.Freeswitch_Events, MetricUnits.GENERIC, _freeswitchEvents)); values.Add(SystemMetricTypes.System_Events, new sSystemMetric(SystemMetricTypes.System_Events, MetricUnits.GENERIC, _systemEvents)); _systemEvents = 0; _freeswitchEvents = 0; return values; }
private void RemoveDeviceSpecificWithCorrespondingDesktop(ProjectFile file, Dictionary<string, ProjectFile> views) { string path = file.RelativePath; if (path.EndsWith(DeviceSpecificExtension, StringComparison.OrdinalIgnoreCase)) { int preSuffixIndex = path.Length - DeviceSpecificExtension.Length; string desktopPath = path.Substring(0, preSuffixIndex) + ".cshtml"; if (views.ContainsKey(desktopPath)) { views.Remove(desktopPath); views.Remove(path); } } }
public void serviceThread() { //Dictionary<string, string> tagList = new Dictionary<string, string>(); Dictionary<string,string> newTagList=new Dictionary<string,string>(); //Random rng = new Random(); rfidUtils.openSerialPort(); while (true) { if (serviceStatus == true) { uiStatusCallback.Invoke("扫描rfid数据!"); } //playSoundAtOneMinute(); Thread.Sleep(200); if (serviceStatus == false) //如果线程状态为位设置为false ,停止该线程 { break; } //当前该线程什么也不做,只定期发出声音 try { newTagList= rfidUtils.readTags(); //后台线程会在此阻塞,知道读到条码 foreach (KeyValuePair<string,string> item in newTagList) //读取新的rfid标签 { //只要有新数据的信息,就一直更新 if(item.Value.Equals("shelf")) { uiShelfCallback(item.Key); newTagList.Remove(item.Key); } //不能添加Key相同的字典值,在此做个检查。也就免得再去处理异常了 if(item.Value.Equals("book")) { uiBookCallback(item.Key); newTagList.Remove(item.Key); } } newTagList.Clear(); } catch (Exception ) { System.Media.SystemSounds.Beep.Play(); Thread.Sleep(200); //throw e; } finally { } } }
private static void InitializeInventory(Inventory inventory) { Dictionary<string, string> properties = new Dictionary<string, string>(); properties["instrumentType"] = InstrumentType.Guitar.ToString(); properties["builder"] = Builder.COLLINGS.ToString(); properties["model"] = "CJ"; properties["type"] = Type.ACOUSTIC.ToString(); properties["numStrings"] = "6"; properties["topWood"] = Wood.INDIAN_ROSEWOOD.ToString(); properties["backWood"] = Wood.SITKA.ToString(); inventory.AddInstrument("11277", 3999.95, new InstrumentSpec(properties)); properties["builder"] = Builder.MARTIN.ToString(); properties["model"] = "D-18"; properties["topWood"] = Wood.MAHOGANY.ToString(); properties["backWood"] = Wood.ALDER.ToString(); inventory.AddInstrument("122784", 5495.95, new InstrumentSpec(properties)); properties["builder"] = Builder.FENDER.ToString(); properties["model"] = "Stratocastor"; properties["type"] = Type.ELECTRIC.ToString(); properties["topWood"] = Wood.ALDER.ToString(); properties["backWood"] = Wood.ALDER.ToString(); inventory.AddInstrument("V95693", 1499.95, new InstrumentSpec(properties)); inventory.AddInstrument("V9512", 1549.95, new InstrumentSpec(properties)); properties["builder"] = Builder.GIBSON.ToString(); properties["model"] = "Les Paul"; properties["topWood"] = Wood.MAPLE.ToString(); properties["backWood"] = Wood.MAPLE.ToString(); inventory.AddInstrument("70108276", 2295.95, new InstrumentSpec(properties)); properties["model"] = "SG '61 Reissue"; properties["topWood"] = Wood.MAHOGANY.ToString(); properties["backWood"] = Wood.MAHOGANY.ToString(); inventory.AddInstrument("82765501", 1890.95, new InstrumentSpec(properties)); properties["instrumentType"] = InstrumentType.Mandolin.ToString(); properties["type"] = Type.ACOUSTIC.ToString(); properties["model"] = "F-5G"; properties["backWood"] = Wood.MAPLE.ToString(); properties["topWood"] = Wood.MAPLE.ToString(); properties.Remove("numStrings"); inventory.AddInstrument("9019920", 5495.99, new InstrumentSpec(properties)); properties["instrumentType"] = InstrumentType.Banjo.ToString(); properties["model"] = "RB-3 Wreath"; properties.Remove("topWood"); properties["numStrings"] = "5"; inventory.AddInstrument("8900231", 2945.95, new InstrumentSpec(properties)); }
protected internal void RemoveRootComponent(int componentId) { Dispatcher.AssertAccess(); // Asserts it's a root component _ = GetRequiredRootComponentState(componentId); // This assumes there isn't currently a batch in progress, and will throw if there is. // Currently there's no known scenario where we need to support calling RemoveRootComponentAsync // during a batch, but if a scenario emerges we can add support. _batchBuilder.ComponentDisposalQueue.Enqueue(componentId); if (HotReloadManager.MetadataUpdateSupported) { _rootComponentsLatestParameters?.Remove(componentId); } ProcessRenderQueue(); }
/// <inheritdoc /> public void SetComponent <TComponent>(TComponent instance) { if (this is TComponent) { throw new ArgumentException("Cannot override a component which is implemented by this grain"); } if (instance == null) { _components?.Remove(typeof(TComponent)); return; } if (_components is null) { _components = new Dictionary <Type, object>(); } _components[typeof(TComponent)] = instance; }
private void HandleDeleteInternal(BlittableJsonReaderObject batchResult, CommandType type) { var id = GetLazyStringField(batchResult, type, nameof(ICommandData.Id)); _modifications?.Remove(id); if (_session.DocumentsById.TryGetValue(id, out var documentInfo) == false) { return; } _session.DocumentsById.Remove(id); if (documentInfo.Entity != null) { _session.DocumentsByEntity.Remove(documentInfo.Entity); _session.DeletedEntities.Remove(documentInfo.Entity); } }
public static void WaitForMethod(float waitTime, Action action, TimeType timeType = TimeType.Scaled) { Action <TimerContainer, float, float> superAction = null; superAction += (_, _, _) => _timers?.Remove(action); superAction += (_, _, _) => action.Invoke(); bool isTimer = TimerContainer.CreateTimer(out var timer, waitTime, true, true, superAction, timeType); if (isTimer) { UpdateTimers(action, timer); } }
private void OnDestroyPlayer(NetworkConnection conn) { NetworkPlayerObject playerObject = PlayerObjects?.Find(x => x.ConnectionID == conn.ConnectionID); if (playerObject != null) { if (SpawnedObjects?.Contains(playerObject.GameObject) ?? false) { SpawnedObjects.Remove(playerObject.GameObject); } DestroyedGameObject?.Invoke(playerObject.NetworkIdentity); Object.Destroy(playerObject.GameObject); PlayerObjects.Remove(playerObject); m_PlayerObjectCache?.Remove(conn.ConnectionID); } if (m_BufferedPlayersCreations?.ContainsKey(conn.ConnectionID) ?? false) { m_BufferedPlayersCreations.Remove(conn.ConnectionID); } if (m_BufferedOwnerCreations?.ContainsKey(conn.ConnectionID) ?? false) { m_BufferedOwnerCreations.Remove(conn.ConnectionID); } if (m_AuthroityObjects?.ContainsKey(conn) ?? false) { foreach (NetworkIdentity identity in m_AuthroityObjects[conn]) { if (identity != null) { Destroy(identity.gameObject); } } m_AuthroityObjects.Remove(conn); } m_BufferedPlayerConnections?.Remove(conn); }
/// <summary> /// Creates the instance. /// </summary> /// <returns>The instance.</returns> /// <param name="name">Name.</param> /// <param name="logFilePath">Log file path.</param> public static Logger CreateInstance(string name, string logFilePath) { if (instances?.ContainsKey(name) == true) { Logger logger = null; instances?.TryGetValue(name, out logger); logger.LogFilePath = logFilePath; TotalIndicies = TotalIndicies + 1; logger.CurrentInstanceIndex = TotalIndicies; instances?.Remove(name); instances?.Add(name, logger); return(logger); } else { var logger = new Logger(name, logFilePath); instances?.Add(name, logger); return(logger); } }
public void Release(FComponent uiObj) { if (uiObj == null) { return; } if (AvailableCount >= MaxCount) { onDispose?.Invoke(uiObj); m_recordObjs?.Remove(uiObj); } else { var poolList = GetObjectList(); var newPoolObj = CreatePoolObj(uiObj); onRelease?.Invoke(uiObj); poolList.AddLast(newPoolObj); } }
public bool update(Location[] src) { foreach (var loc in src) { var obj = loc.MapObject; if (null != obj) { Place(obj, loc); } else { _knownMapObjects?.Remove(loc); } } if (null != _knownMapObjects && 0 >= _knownMapObjects.Count) { _knownMapObjects = null; } return(false); }
/// <summary> /// Removes the given URL from the cache. /// Returns true if any work was done, false otherwise. /// This method is filesystem transaction aware. /// </summary> public bool Remove(Uri url) { TxFileManager tx_file = new TxFileManager(); string file = GetCachedFilename(url); if (file != null) { tx_file.Delete(file); // We've changed our cache, so signal that immediately. cachedFiles?.Remove(CreateURLHash(url)); sha1Cache.Remove(file); sha256Cache.Remove(file); return(true); } return(false); }
private void SaveFormSettings(Form form) { var grids = GetAllControlsByType(form, typeof(DataGridView)); Size formSize; Point formLocation; if (form.WindowState == FormWindowState.Maximized) { formSize = form.RestoreBounds.Size; formLocation = form.RestoreBounds.Location; } else { formSize = form.Size; formLocation = form.Location; } var gridsInfo = GetGridsWidthInfo(grids); var info = new FormInfo { Key = form.GetType().Namespace + '.' + form.Name, FormWidth = formSize.Width, FormHeight = formSize.Height, LocationX = formLocation.X, LocationY = formLocation.Y, GridsInfos = gridsInfo, Maximized = (form.WindowState == FormWindowState.Maximized) }; _formData?.Remove(info.Key); if (_formData != null) { _formData.Add(info.Key, info); } else { _formData = new Dictionary <string, FormInfo>(); _formData.Add(info.Key, info); } }
/// <summary> /// Deletes the files. /// </summary> /// <param name="filesToDelete">The files.</param> /// <param name="files">The files dictionary.</param> private void DeleteFiles(IEnumerable <FileInfo> filesToDelete, Dictionary <string, FileInfo> files) { if (filesToDelete == null) { return; } foreach (FileInfo file in filesToDelete) { try { file.Delete(); files?.Remove(file.Name); } catch (Exception exception) { Trace.TraceError("Unable to delete the log file. {0}", exception); } } }
/// <summary> /// Get or sets the associated value from the collection as a single string. /// </summary> /// <param name="key">The header name.</param> /// <returns>the associated value from the collection as a StringValues or StringValues.Empty if the key is not present.</returns> public StringValues this[string key] { get { if (Store == null) { return(StringValues.Empty); } StringValues value; if (TryGetValue(key, out value)) { return(value); } return(StringValues.Empty); } set { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (StringValues.IsNullOrEmpty(value)) { Store?.Remove(key); } else { if (Store == null) { Store = new Dictionary <string, StringValues>(1, StringComparer.OrdinalIgnoreCase); } Store[key] = value; } } }
private async void DisposeDisplayedThumbnails(object sender, EventArgs e) { if (isLoadingThumbnails || displayedThumbnails == null || displayedThumbnails.Count == 0) { return; } isDisposingThumbnails = true; isDisposingThumbnails = await Task.Run(() => { var filePaths = new List <string>(displayedThumbnails.Keys); foreach (var path in filePaths) { if (isLoadingThumbnails) { break; } displayedThumbnails[path]?.Dispose(); displayedThumbnails?.Remove(path); } filePaths.Clear(); return(false); }); }
/// <summary> /// Needs either a delegate or a property name to get the key from the child item. /// Using a delegate should be faster than the property name which will use reflection. /// If TItem implements both INotifyCollectionChanged and INotifyCollectionChanging, the name of the key property is also needed for key updating to work. /// <para>Be aware that this is not thread-safe.</para> /// </summary> public ObservableKeyedCollection(Func <TItem, TKey> getKeyFunc = null, string keyPropName = null, IEnumerable <TItem> collection = null) { if (getKeyFunc == null && keyPropName == null) { throw new ArgumentException(@"GetKeyForItemDelegate and KeyPropertyName cannot both be null."); } keyPropertyName = keyPropName; GetKeyForItemDelegate = getKeyFunc; if (keyPropertyName != null && typeof(TItem).GetInterface(nameof(INotifyPropertyChanged)) != null && typeof(TItem).GetInterface(nameof(INotifyPropertyChanging)) != null) { ChildPropertyChanging = (o, e) => { if (e.PropertyName != keyPropertyName) { return; } var item = (TItem)o; Dictionary?.Remove(GetKeyForItem(item)); }; ChildPropertyChanged = (o, e) => { if (e.PropertyName != keyPropertyName) { return; } var item = (TItem)o; Dictionary?.Add(GetKeyForItem(item), item); }; } if (collection != null) { AddRange(collection); } }
private void Remove( object entity, IEntityType entityType, EntityState oldState) { if (_sharedTypeReferenceMap != null && entityType.HasSharedClrType) { _sharedTypeReferenceMap[entityType].Remove(entity, entityType, oldState); } else { switch (oldState) { case EntityState.Detached: _detachedReferenceMap?.Remove(entity); break; case EntityState.Unchanged: _unchangedReferenceMap?.Remove(entity); break; case EntityState.Deleted: _deletedReferenceMap?.Remove(entity); break; case EntityState.Modified: _modifiedReferenceMap?.Remove(entity); break; case EntityState.Added: _addedReferenceMap?.Remove(entity); break; } } }
private void Remove( object entity, IEntityType entityType, EntityState oldState) { if (_dependentTypeReferenceMap != null && entityType.HasDefiningNavigation()) { _dependentTypeReferenceMap[entityType].Remove(entity, entityType, oldState); } else { switch (oldState) { case EntityState.Detached: _detachedReferenceMap?.Remove(entity); break; case EntityState.Unchanged: _unchangedReferenceMap.Remove(entity); break; case EntityState.Deleted: _deletedReferenceMap.Remove(entity); break; case EntityState.Modified: _modifiedReferenceMap.Remove(entity); break; case EntityState.Added: _addedReferenceMap.Remove(entity); break; } } }
protected bool RemoveUnknown(string key) => MaybeUnknown?.Remove(key) ?? false;
public void DeleteIndex(string name) { Indexes?.Remove(name); AutoIndexes?.Remove(name); }
public void put(LuaValue key, LuaValue val) { if (key == null) { throw new Exception("table index is nil!"); } if (key.isFloat() && double.IsNaN(key.toFloat())) { throw new Exception("table index is NaN!"); } key = _floatToInteger(key); if (key.isInteger()) { var idx = key.toInteger(); if (idx >= 1) { var arrLen = arr?.Length ?? 0; if (idx <= arrLen) { arr[idx - 1] = val; if (idx == arrLen && val.value == null) { _shrinkArray(); } return; } if (idx == arrLen + 1) { _map?.Remove(idx); if (val != null) { if (arr == null) { var b = new List <LuaValue> { val }; arr = b.ToArray(); _expandArray(); } else { var b = arr.ToList(); b.Add(val); arr = b.ToArray(); _expandArray(); } } return; } } } if (val != null) { if (_map == null) { _map = new Dictionary <object, LuaValue>(8); } _map.Add(key.value, val); } else { _map.Remove(key.value); } }
private void RemoveLineDeltas(MethodId methodId) { _lazyMethodLineDeltas?.Remove(methodId); }
public void RemoveEngine(int id) { engines?.Remove(id); }
internal void RemoveMaid(Maid maid) { maidLockList?.Remove(maid.status.guid); }
private void RemoveKey(string key) { _dictionary?.Remove(key); }
public static Dictionary <TKey, TValue> RemoveKey <TKey, TValue>(this Dictionary <TKey, TValue> map, TKey key) { map?.Remove(key); return(map); }
private IEnumerator RemoveCache(string url, float delay) { yield return(WaitForSecondsCache.Get(delay)); cache?.Remove(url); }
public void DeleteSorter(string sorterName) { Sorters?.Remove(sorterName); }
public void Delete(object @object) { if (@object == null) { throw new ArgumentNullException(nameof(@object)); } var indirect = @object as IIndirect; if (indirect != null) { if (indirect.Oid != 0) { Delete(indirect.Oid); return; } Delete(indirect.ValueAsObject); return; } var tableInfo = AutoRegisterType(@object.GetType()); DBObjectMetadata metadata; if (_objSmallMetadata != null) { if (!_objSmallMetadata.TryGetValue(@object, out metadata)) { _objSmallMetadata.Add(@object, new DBObjectMetadata(0, DBObjectState.Deleted)); return; } } else if (_objBigMetadata != null) { if (!_objBigMetadata.TryGetValue(@object, out metadata)) { _objBigMetadata.Add(@object, new DBObjectMetadata(0, DBObjectState.Deleted)); return; } } else { return; } if (metadata.Id == 0 || metadata.State == DBObjectState.Deleted) { return; } metadata.State = DBObjectState.Deleted; _keyValueTrProtector.Start(); _keyValueTr.SetKeyPrefix(ObjectDB.AllObjectsPrefix); if (_keyValueTr.FindExactKey(BuildKeyFromOid(metadata.Id))) { _keyValueTr.EraseCurrent(); } tableInfo.CacheSingletonContent(_transactionNumber + 1, null); if (_objSmallCache != null) { _objSmallCache.Remove(metadata.Id); } else { _objBigCache?.Remove(metadata.Id); } _dirtyObjSet?.Remove(metadata.Id); }
public void Remove(Guid key) { _values?.Remove(key); }
public override string this[int index] { get { if (index < 0) { throw new IndexOutOfRangeException(nameof(index)); } CacheItem <string> item = _cache; if (item?.RowIndex == index) { return(item.Value); } if (_savedValues != null && _savedValues.TryGetValue(index, out string result)) { return(result); } if (IsNull == null || IsNull[index]) { return(null); } ArraySlice <byte> bytes = Values[index]; item = new CacheItem <string>(index, (bytes.Count == 0 ? string.Empty : Encoding.UTF8.GetString(bytes.Array, bytes.Index, bytes.Count))); _cache = item; return(item.Value); } set { _cache = default; // Always set IsNull; IsNull tracks Count cheaply Init(); IsNull[index] = (value == null); int length = value?.Length ?? 0; if (length == 0 || length > ArraySliceChapter <byte> .MaximumSmallValueLength) { // Directly set null, empty, and long values _savedValues?.Remove(index); Values[index] = (string.IsNullOrEmpty(value) ? ArraySlice <byte> .Empty : new ArraySlice <byte>(Encoding.UTF8.GetBytes(value))); } else { // Cache other values to convert together if (_savedValues == null) { _savedValues = new Dictionary <int, string>(); } _savedValues[index] = value; if (_savedValues.Count >= SavedValueCountLimit) { PushSavedValues(); } } } }
private void RemoveClient(int clientId) { _clients?.Remove(clientId); _hosts?.Remove(clientId); }