Example #1
0
        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();
        }
        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);
        }
        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");
            }
        }
        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);
        }
Example #5
0
        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);
        }
Example #6
0
        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");
            }
        }
 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;
 }
Example #8
0
 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);
     }
 }
        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();
        }
Example #10
0
        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);
        }
Example #11
0
 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 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;
 }
Example #13
0
		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;
					}
				}
			}
Example #14
0
		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;
		}
Example #15
0
        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);

        }
Example #16
0
        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();
        }
Example #17
0
        /// <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;
        }
Example #18
0
        /// <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);
            }
        }
Example #19
0
        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;
        }
Example #20
0
        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();
        }
Example #21
0
File: getopt.cs Project: dyama/fwfw
   /// <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");
        }
    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
    }
        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);
            }
        }
Example #26
0
        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);
         }
     }
 }
Example #29
0
        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
                {                  
                }

            }
        }
Example #30
0
        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));
        }