private ConcurrentChatStatistics CalculateStatisticsFromMinuteDistribution(Dictionary<int, int> minuteDistribution)
        {
            var seed = new
            {
                Maximum = int.MinValue,
                ChatMinutes = 0.0,
                TotalMinutes = 0,
            };

            var result = minuteDistribution.Aggregate(seed,
                (current, chats) => new
                {
                    Maximum = Math.Max(current.Maximum, chats.Key),
                    ChatMinutes = current.ChatMinutes + chats.Key * chats.Value,
                    TotalMinutes = current.TotalMinutes + chats.Value
                });

            var mean = result.ChatMinutes / result.TotalMinutes;

            var variance = minuteDistribution.Aggregate
                (0.0, (current, chats) => current + (chats.Key - mean) * (chats.Key - mean) * chats.Value) / result.TotalMinutes;

            return new ConcurrentChatStatistics
            {
                Maximum = result.Maximum,
                Mean = mean,
                StandardDeviation = Math.Sqrt(variance),
                PercentageByConcurrentChatCount = minuteDistribution
                    .Select(kvp => new KeyValuePair<int, double>(kvp.Key, (double)kvp.Value / result.TotalMinutes))
                    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
            };
        }
        public override void GenerateScripts(AgentSettings settings)
        {
            Trace.Entering();

            CalculateServiceName(settings, _svcNamePattern, _svcDisplayPattern);
            try
            {
                string svcShPath = Path.Combine(IOUtil.GetRootPath(), _svcShName);

                // TODO: encoding?
                // TODO: Loc strings formatted into MSG_xxx vars in shellscript
                string svcShContent = File.ReadAllText(Path.Combine(IOUtil.GetBinPath(), _shTemplate));
                var tokensToReplace = new Dictionary<string, string>
                                          {
                                              { "{{SvcDescription}}", ServiceDisplayName },
                                              { "{{SvcNameVar}}", ServiceName }
                                          };

                svcShContent = tokensToReplace.Aggregate(
                    svcShContent,
                    (current, item) => current.Replace(item.Key, item.Value));

                //TODO: encoding?
                File.WriteAllText(svcShPath, svcShContent);

                var unixUtil = HostContext.CreateService<IUnixUtil>();
                unixUtil.ChmodAsync("755", svcShPath).GetAwaiter().GetResult();
            }
            catch (Exception e)
            {
                Trace.Error(e);
                throw;
            }
        }
    static void Main()
    {
        Console.Write("Enter a number N (size of array): ");
        int n = int.Parse(Console.ReadLine());

        int[] numbers = new int[n];
        Console.WriteLine("\nEnter a {0} number(s) to array: ", n);
        for (int i = 0; i < numbers.Length; i++)
        {
            Console.Write("   {0}: ", i + 1);
            numbers[i] = int.Parse(Console.ReadLine());
        }
        
        // Adds numbers to dictionary
        Dictionary<int, int> frequents = new Dictionary<int, int>();
        for (int i = 0; i < numbers.Length; i++)
        {
            if (!frequents.ContainsKey(numbers[i])) frequents.Add(numbers[i], 1);
            else frequents[numbers[i]]++;
        }

        // Get the key of the highest value
        var max = frequents.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;

        // Print all array elements
        Console.WriteLine("\nArray's elements: {0}", string.Join(" ", numbers));

        // Print all keys (numbers) with the highest value
        Console.WriteLine("\nMost frequent numbers: ");
        foreach (KeyValuePair<int, int> item in frequents)
            if (item.Value == frequents[max])
                Console.WriteLine("{0} -> {1} times", item.Key, frequents[item.Key]);

        Console.WriteLine();
    }
Example #4
0
 protected static string ProcessVocabulary(string template, Dictionary<string, string> vocabulary)
 {
     return vocabulary.Aggregate(template,
                                 (current, vocabularyPair) =>
                                 current.Replace(String.Format("{{{0}}}", vocabularyPair.Key),
                                                 vocabularyPair.Value));
 }
Example #5
0
        public static string CarregarMensagemHtml(string templateEmail, Dictionary<string, string> parametros)
        {
            var streamReaderHtml = File.OpenText(templateEmail);
            var textoHtml = new StringBuilder();

            try
            {
                string linha = streamReaderHtml.ReadLine();

                while (linha != null)
                {
                    textoHtml.Append(linha);

                    linha = streamReaderHtml.ReadLine();
                }

                textoHtml = parametros.Aggregate(textoHtml, (current, parametro) => current.Replace(parametro.Key, parametro.Value));
            }
            finally
            {
                streamReaderHtml.Close();
            }

            return textoHtml.ToString();
        }
        protected override object FindParameterValue(Match match, ICmsRenderer cmsRenderer, ICmsContext context, ITheme theme, Func<string, string> recurse)
        {
            var localizationNamespace = _findCurrentLocalizationNamespace.Find();

            var key = !string.IsNullOrEmpty(localizationNamespace) ? string.Format("{0}:{1}", localizationNamespace, match.Groups["resource"].Value) : match.Groups["resource"].Value;

            var replacements = new Dictionary<string, string>();

            var replacementsGroup = match.Groups["replacements"];

            if (replacementsGroup != null && !string.IsNullOrEmpty(replacementsGroup.Value))
            {
                var replacementsData = replacementsGroup
                    .Value
                    .Split(',')
                    .Where(x => !string.IsNullOrEmpty(x))
                    .Select(x => x.Split(':'))
                    .Where(x => x.Length > 1 && !string.IsNullOrEmpty(x[0]) && !string.IsNullOrEmpty(x[1]))
                    .ToList();

                foreach (var item in replacementsData)
                    replacements[item[0]] = item[1];
            }

            var localized = _localizeText.Localize(key, _findCultureForRequest.FindUiCulture());

            localized = replacements.Aggregate(localized, (current, replacement) => current.Replace(string.Concat("{{", replacement.Key, "}}"), replacement.Value));

            return recurse(localized);
        }
        private string GetProcessArguments(ServiceInstance instance)
        {
            var configParameters = new Dictionary<string, string>();
            configParameters.Add("log", instance.LogPath);
            configParameters.Add("db", instance.DbPath);
            configParameters.Add("run-projections", instance.RunProjections);

            if (!string.IsNullOrWhiteSpace(instance.InternalAddresses))
            {
                configParameters.Add("int-http-prefixes", instance.InternalAddresses);
            }

            if (!string.IsNullOrWhiteSpace(instance.ExternalAddresses))
            {
                configParameters.Add("ext-http-prefixes", instance.ExternalAddresses);
            }

            var externalIp = GetIp(instance.ExternalIP);
            configParameters.Add("ext-ip", externalIp);
            var internalIp = GetIp(instance.InternalIP);
            configParameters.Add("int-ip", internalIp);

            return configParameters.Aggregate("",
                (acc, next) => string.Format("{0} --{1} \"{2}\"", acc, next.Key, next.Value));
        }
Example #8
0
        public string GenerateToken(string sessionId, Dictionary<string, object> options)
        {
            var appSettings = ConfigurationManager.AppSettings;

            options.Add("session_id", sessionId);
            options.Add("create_time", (int) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds);
            options.Add("nonce", RandomNumber(0, 999999));
            if (!options.ContainsKey(TokenPropertyConstants.Role)) {
                options.Add(TokenPropertyConstants.Role, "publisher");
            }
            // Convert expire time to Unix Timestamp
            if (options.ContainsKey(TokenPropertyConstants.ExpireTime)) {
                var origin = new DateTime(1970, 1, 1, 0, 0, 0);
                var expireTime = (DateTime) options[TokenPropertyConstants.ExpireTime];
                var diff = expireTime - origin;
                options[TokenPropertyConstants.ExpireTime] = Math.Floor(diff.TotalSeconds);
            }

            string dataString = options.Aggregate(string.Empty, (current, pair) => current + (pair.Key + "=" + HttpUtility.UrlEncode((pair.Value == null) ? "" : pair.Value.ToString()) + "&"));
            dataString = dataString.TrimEnd('&');

            string sig = SignString(dataString, appSettings["opentok_secret"].Trim());
            string token = string.Format("{0}{1}", appSettings["opentok_token_sentinel"], EncodeTo64(string.Format("partner_id={0}&sdk_version={1}&sig={2}:{3}", appSettings["opentok_key"], appSettings["opentok_sdk_version"], sig, dataString)));

            return token;
        }
        public static string FixTrx(XDocument doc)
        {
            var replaceList = new Dictionary<Guid, Guid>();
            var storageReplace = new Dictionary<string, string>();

            FixEndDateBeforeStartDate(doc);
            var trx = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + doc;
            var unitTests =
                doc.Descendants(XName.Get("TestRun", Ns))
                    .Descendants(XName.Get("TestDefinitions", Ns))
                    .Single()
                    .Descendants(XName.Get("UnitTest", Ns));
            foreach (var unitTest in unitTests)
            {
                //Storage attribute from VSTest.Console is fully qualified, i.e c:\foo\bar.dll, but tcm requires just bar.dll
                var testMethod = unitTest.Descendants(XName.Get("TestMethod", Ns)).Single();
                var storage = unitTest.Attribute("storage").Value;
                if (!storageReplace.ContainsKey(storage))
                    storageReplace.Add(storage, Path.GetFileName(storage));

                //VSTest.Console.exe generates random Guids for test Ids, we need to generate a guid based on the test name using the same
                // algorithm as MSTest
                var className = testMethod.Attribute("className");
                var name = testMethod.Attribute("name");
                var id = new Guid(unitTest.Attribute("id").Value);
                if (!replaceList.ContainsKey(id))
                    replaceList.Add(id, CalcProperGuid(className.Value + "." + name.Value));
            }

            trx = replaceList.Aggregate(trx,
                (current, replacement) => current.Replace(replacement.Key.ToString(), replacement.Value.ToString()));
            trx = storageReplace.Aggregate(trx,
                (current, replacement) => current.Replace(replacement.Key.ToString(), replacement.Value.ToString()));
            return trx;
        }
        private void DisplayAvgLoanBase()
        {
            var calcUtil = new LoanCalcUtil(
                    10000 * decimal.Parse(txtTotalLoanBase.Text.Trim()),
                    int.Parse(cbxYears.Text),
                    0.01M * decimal.Parse(txtYearInterestRate.Text.Trim()),
                    PayLoanType.AvgLoanBase,
                    rbtnQuarterly.Checked ? PayCycleType.PerQuarter : PayCycleType.PerMonth);

            Dictionary<int, decimal> interestsDic = new Dictionary<int, decimal>();
            List<string> cyclePayList = new List<string>();

            decimal cycleInterest = 0.0M;
            decimal cycleLoanBase = calcUtil.TotalLoanBase / calcUtil.Cycles;
            for (int cycle = 0; cycle < calcUtil.Cycles; cycle++)
            {
                cycleInterest = calcUtil.CalcInterestForAvgLoanBase(cycle);
                interestsDic.Add(cycle, cycleInterest);

                string cyclePay = string.Format("第 {0} {1}: 本金({2:F2}),利息({3:F2}),共({4:F2})元;{5}",
                                    cycle + 1,
                                    calcUtil.PayCycle == PayCycleType.PerMonth ? "月" : "季",
                                    cycleLoanBase,
                                    cycleInterest,
                                    cycleLoanBase + cycleInterest,
                                    Environment.NewLine);
                cyclePayList.Add(cyclePay);
            }

            var totalInterests = interestsDic.Aggregate(0.0M, (seed, kvp) => { return seed + kvp.Value; });
            txtInterestsForLoanBase.Text = totalInterests.ToString("F2");

            string showText = cyclePayList.Aggregate(string.Empty, (seed, cyclePay) => { return seed + cyclePay; });
            rtxtCyclePays.Text = showText;
        }
Example #11
0
    private static void Main(string[] args)
    {
        string[] strings = new string[int.Parse(Console.ReadLine())];
        for (int i = 0; i < strings.Length; i++)
        {
            strings[i] = Console.ReadLine();
        }

        Dictionary<string, int> Areas = new Dictionary<string, int>();

        foreach (var item in strings)
        {
            if (Areas.ContainsKey(item))
            {
                Areas[item]++;
            }
            else
            {
                Areas.Add(item, 1);
            }
        }

        for (int i = 0; i < Areas.Max(x => x.Value); i++)
        {
            Console.WriteLine(Areas.Aggregate((x, y) => y.Value > x.Value ? y : x).Key);
        }
    }
        /// <summary>
        ///     Sends the specified message to an SMTP server for delivery.
        /// </summary>
        /// <param name="recepientMails">
        ///     The mail addresses of the recepients. If multiple addresses are specified,
        ///     they must be separated by the comma character
        /// </param>
        /// <param name="subject">The subject of the email</param>
        /// <param name="fileName">The name of the file that has the mail text</param>
        /// <param name="parameters">Parameters to pass in the mail text</param>
        public async Task<bool> SendMailAsync(string recepientMails, string subject, string fileName, Dictionary<string, string> parameters)
        {
            var filePath = HostingEnvironment.MapPath("~/Content/email_templates/");

            try
            {
                string mailText;

                using (var streamReader = new StreamReader(filePath + fileName))
                {
                    mailText = streamReader.ReadToEnd();
                }

                mailText = parameters.Aggregate(mailText, (current, item) => current.Replace(item.Key, item.Value));
                _mail.To.Add(recepientMails);
                _mail.Subject = subject;
                _mail.Body = mailText;
                _mail.IsBodyHtml = true;

                await _smtpClient.SendMailAsync(_mail);

                return true;
            }
            catch
            {
                return false;
            }
        }
Example #13
0
        private void Track(Dictionary<string, string> values)
        {
            var request = (HttpWebRequest)WebRequest.Create(endpoint);
            request.Method = "POST";
            request.KeepAlive = false;

            var postDataString = values
                .Aggregate("", (data, next) => string.Format("{0}&{1}={2}", data, next.Key,
                                                             HttpUtility.UrlEncode(next.Value)))
                .TrimEnd('&');

            // set the Content-Length header to the correct value
            request.ContentLength = Encoding.UTF8.GetByteCount(postDataString);

            // write the request body to the request
            using (var writer = new StreamWriter(request.GetRequestStream()))
            {
                writer.Write(postDataString);
            }

            // Send the response to the server
            var webResponse = (HttpWebResponse)request.GetResponse();

            if (webResponse.StatusCode != HttpStatusCode.OK)
            {
                throw new HttpException((int)webResponse.StatusCode, "Google Analytics tracking did not return OK 200");
            }

            webResponse.Close();
        }
        public static string LoadHTMLMensage(string templateEmail, Dictionary<string, string> parameters)
        {
            var streamReaderHtml = File.OpenText(templateEmail);
            var htmlText = new StringBuilder();

            try
            {
                var line = streamReaderHtml.ReadLine();

                while (line != null)
                {
                    htmlText.Append(line);

                    line = streamReaderHtml.ReadLine();
                }

                htmlText = parameters.Aggregate(htmlText, (current, parameter) => current.Replace(parameter.Key, parameter.Value));
            }
            finally
            {
                streamReaderHtml.Close();
            }

            return htmlText.ToString();
        }
Example #15
0
        static void Main(string[] args)
        {
            Dictionary<int, int> triangles = new Dictionary<int, int>();

            for (int p = 3; p < 1000; p++)
            {
                triangles.Add(p, 0);
                for (int a = 1; a < p; a++)
                    for (int b = 1; b < p; b++)
                    {
                        if (a + b > 1000)
                            break;

                        int c = p - a - b;

                        if ((a * a + b * b) == c * c)
                        {
                            triangles[p]++;
                        }
                    }
            }

            Console.WriteLine(triangles.Aggregate((l, r) => l.Value > r.Value ? l : r).Key);
            Console.Read();
        }
 // REVIEW: Is there a standard and safe query parser and joiner?
 static string QueryJoin(Dictionary<string, string> queryParts) {
     return String.Join(
         "&",
         queryParts.Aggregate(
             new List<string>(),
             (list, kvp) => { list.Add(kvp.Key + "=" + kvp.Value); return list; }
         ).ToArray());
 }
Example #17
0
 private string Replace(Dictionary<string, string> tokens, string value)
 {
     string val = tokens.Aggregate(value, (current, token) => Regex.Replace(current, token.Key, match => token.Value));
     if ( this.functionTokenizers != null ) {
         val = this.functionTokenizers.Aggregate(val, (current, tokenizer) => tokenizer.TokenizeContent(current));
     }
     return val;
 }
Example #18
0
 protected override Uri GetServiceLoginUrl(Uri returnUrl)
 {
     var dict = new Dictionary<string, string>();
     dict["client_id"] = this.appId;
     dict["redirect_uri"] = returnUrl.AbsoluteUri;
     dict["response_type"] = "code";
     var url = dict.Aggregate(AuthorizationEndpoint, (current, param) => current.AddQueryParam(param.Key, param.Value));
     return new Uri(url);
 }
        private static void Track(HitType type, string category, string action, string label,
                                  int? value = null)
        {
            if (string.IsNullOrEmpty(category)) throw new ArgumentNullException("category");
            if (string.IsNullOrEmpty(action)) throw new ArgumentNullException("action");

            var request = (HttpWebRequest)WebRequest.Create("http://www.google-analytics.com/collect");
            request.Method = "POST";
            request.KeepAlive = false;

            var postData = new Dictionary<string, string>
                           {
                               { "v", "1" },
                               { "tid", trackingId },
                               { "cid", "555" },
                               { "t", type.ToString() },
                               { "ec", category },
                               { "ea", action },
                           };
            if (!string.IsNullOrEmpty(label))
            {
                postData.Add("el", label);
            }
            if (value.HasValue)
            {
                postData.Add("ev", value.ToString());
            }

            var postDataString = postData
                .Aggregate("", (data, next) => string.Format("{0}&{1}={2}", data, next.Key,
                                                             HttpUtility.UrlEncode(next.Value)))
                .TrimEnd('&');

            request.ContentLength = Encoding.UTF8.GetByteCount(postDataString);
            using (var writer = new StreamWriter(request.GetRequestStream()))
            {
                writer.Write(postDataString);
            }

            try
            {
                var webResponse = (HttpWebResponse)request.GetResponse();
                if (webResponse.StatusCode != HttpStatusCode.OK)
                {
                    throw new HttpException((int)webResponse.StatusCode,
                                            "Google Analytics tracking did not return OK 200");
                }
                webResponse.Close();
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
            }
        }
Example #20
0
 public string Clean(string content)
 {
     var itemsToBeCleaned = new Dictionary<string,string>
                                {
                                    {"\t", "\\t"},
                                    {"\r", "\\r"},
                                    {"\n", "\\n"},
                                    {"\"", "\\\""},
                                };
     return itemsToBeCleaned.Aggregate(content, (current, item) => current.Replace(item.Key, item.Value));
 }
Example #21
0
        protected VkWebCommand GetVkXmlCommand(string methodName, Dictionary<string, object> parameters, bool includeToken)
        {
            if (includeToken)
            {
                parameters.Add("access_token", AccessToken);
            }
            var uri = String.Format("https://api.vk.com/method/{0}.xml?app=1", methodName);
            uri = parameters.Aggregate(uri, (current, pair) => current + String.Format("&{0}={1}", pair.Key, pair.Value));

            Logger.DebugFormat("XML Command: '{0}'", uri);
            return new VkWebCommand(methodName, uri);
        }
    static void Main(string[] args)
    {
        int[] arrayToCheck = { 4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3 };
        Dictionary<int, int> occurences = new Dictionary<int, int>();
        for (int i = 0; i < arrayToCheck.Length; i++)
        {
            if (occurences.ContainsKey(arrayToCheck[i]))
            {
                occurences[arrayToCheck[i]]++;
            }
            else
            {
                occurences.Add(arrayToCheck[i], 1);
            }
        }

        int maxKey = occurences.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;
        int maxValue = occurences.Aggregate((l,r) => l.Value > r.Value ? l : r).Value;

        Console.WriteLine("Number with maximum occurences: {0} and number of occurences: {1}", maxKey, maxValue);
    }
        public async Task TestPostRequestWithCustomeHeadersAndBody()
        {
            using (var server = new HttpHost(TestPort))
            {
                const string path = "/test/path?query=value";
                var headers = new Dictionary<string, string>
                    { { "custom-header-1", "custom-value-1" }, { "content-custom", "content-value" } };
                const string contentType = "suave/test";
                const string content = "string content";
                var responseContent = new byte[] { 1, 2, 3 };

                await server.OpenAsync(async request =>
                {
                    Assert.Equal(path, request.RequestUri.PathAndQuery);

                    Assert.Equal(HttpMethod.Post, request.Method);

                    Assert.True(headers.All(pair => request.Headers.First(s => s.Key == pair.Key).Value.First() == pair.Value));

                    Assert.Equal(contentType, request.Content.Headers.ContentType.ToString());

                    Assert.Equal(content, await request.Content.ReadAsStringAsync());

                    var response =  new HttpResponseMessage
                    {
                        StatusCode = HttpStatusCode.Accepted,
                        Content = new ByteArrayContent(responseContent)
                    };
                    response.Headers.Add("server-custom", "server-value");
                    return response;
                });

                using (var client = new HttpClient())
                {
                    var request = new HttpRequestMessage(HttpMethod.Post, LocalHost + path);
                    headers.Aggregate(request.Headers, (a, b) =>
                    {
                        a.Add(b.Key, b.Value);
                        return a;
                    });
                    request.Content = new StringContent(content);
                    request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);

                    var response = await client.SendAsync(request);
                    
                    Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);

                    Assert.Equal(responseContent, await response.Content.ReadAsByteArrayAsync());

                    Assert.Equal("server-value", response.Headers.First(s => s.Key == "server-custom").Value.First());
                }
            }
        }
Example #24
0
        static void Main(string[] args)
        {
            int numberOfrows= int.Parse(Console.ReadLine());
            List<Employee> employeesList= new List<Employee>();
            for (int i = 0; i < numberOfrows; i++)
            {
                string[] input = Console.ReadLine().Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);

                var emp = new Employee(input[0], decimal.Parse(input[1]), input[2], input[3]);
                if (input.Length > 4)
                {
                    if (input.Length > 5)
                    {
                        emp.mail = input[4];
                        emp.age = int.Parse(input[5]);
                    }
                    else
                    {
                        if (input[4].Contains("@"))
                        {
                            emp.mail = input[4];
                        }
                        else
                        {
                            emp.age = int.Parse(input[4]);
                        }
                    }
                }
                employeesList.Add(emp);
            }
            Dictionary<string, decimal> result=new Dictionary<string, decimal>();

            for (int i = 0; i < employeesList.Count; i++)
            {
                if (result.ContainsKey(employeesList[i].department))
                {
                    result[employeesList[i].department] += employeesList[i].salary;
                    result[employeesList[i].department] /= 2.0m;
                }
                else
                {
                    result.Add(employeesList[i].department, employeesList[i].salary);
                }
            }

            var max = result.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;

            Console.WriteLine($"Highest Average Salary: {max}");
            foreach (var r in employeesList.Where(x=>x.department.Equals(max)).OrderByDescending(x=>x.salary))
            {
                Console.WriteLine("{0} {1:F2} {2} {3}",r.name,r.salary, r.mail, r.age);
            }
        }
 protected override string CreateClassWithOverridingParams(string className, string baseClassName, IEnumerable<string> nsImports, Dictionary<string, string> overidenParams)
 {
     return
         CreateCsharpConfigClassCode(
             overidenParams.Aggregate("",
                 (acc, p) => acc + GetPublicOverrideStringPropertySnippet(p.Key, p.Value))
             , className,
             baseClassName,
             false,
             nsImports
             );
 }
Example #26
0
        public static bool EspeakTTS(Word w, string lang, bool _generate_wav)
        {
            string espeak_binary_location = PamyaSettings.Instance.GetSetting("espeakbin");
            Dictionary<string, string> eo_string_replace_dict = new Dictionary<string, string>();
            eo_string_replace_dict.Add("Ĝ", "Gx"); //FIXME
            eo_string_replace_dict.Add("ĝ", "gx");
            eo_string_replace_dict.Add("Ĥ", "Hx");
            eo_string_replace_dict.Add("ĥ", "hx");
            eo_string_replace_dict.Add("Ĵ", "Jx");
            eo_string_replace_dict.Add("ĵ", "jx");
            eo_string_replace_dict.Add("Ŝ", "Sx");
            eo_string_replace_dict.Add("ŝ", "sx");
            eo_string_replace_dict.Add("Ĉ", "Cx");
            eo_string_replace_dict.Add("ĉ", "cx");
            eo_string_replace_dict.Add("Ŭ", "Ux");
            eo_string_replace_dict.Add("ŭ", "ux");
            eo_string_replace_dict.Add("-", "_");
            eo_string_replace_dict.Add(" ", "_");
            eo_string_replace_dict.Add("!", "_");
            eo_string_replace_dict.Add(",", "_");
            var text = eo_string_replace_dict.Aggregate(w.Target, (current, value) =>
                current.Replace(value.Key, value.Value));
            if (File.Exists(espeak_binary_location) && (! _generate_wav))
            {
                //ugly stuff for now

                System.Diagnostics.Process process = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                startInfo.FileName = espeak_binary_location;
                startInfo.Arguments = "-v " + lang + " \"" + text + "\"";
                process.StartInfo = startInfo;
                process.Start();
                return true;
            }
            else if (File.Exists(espeak_binary_location) && _generate_wav)
            {
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                startInfo.FileName = espeak_binary_location;
                startInfo.Arguments = "-w " + text + ".wav " + "-v " + lang + " \"" + text + "\"";
                startInfo.WorkingDirectory = PamyaDeck.Instance.CurrentDeckFolder;
                process.StartInfo = startInfo;
                process.Start();
                w.SoundFileLocation = text + ".wav ";
                return true;
            }
            else
            {
                return false;
            }
        }
Example #27
0
        public Builder EnterDiv(string id = null, string htmlClass = null, Dictionary<string, object> attributes = null)
        {
            var tag = "<div";

            if (id != null) tag += String.Format(" id=\"{0}\"", id);
            if (htmlClass != null) tag += String.Format(" class=\"{0}\"", htmlClass);
            if (attributes != null) tag = attributes.Aggregate(tag, (current, attribute) => current + String.Format(" {0}=\"{1}\"", attribute.Key, attribute.Value));

            tag += ">";
            Html += tag;

            return this;
        }
Example #28
0
 public void MakeReplacements(Dictionary<string, string> replacements)
 {
     if(replacements == null)
     {
         return;
     }
     var stream = File.OpenText(WorkingDirectory + _testName + "\\script.txt" );
     var script = stream.ReadToEnd();
     stream.Close();
     script = replacements.Aggregate(script, (current, replacement) => current.Replace("<!--" + replacement.Key + "-->", replacement.Value));
     script = script.Replace("<!--SERVER-->", _server);
     File.WriteAllText(WorkingDirectory + _testName + "\\script.txt", script);
 }
Example #29
0
        public string LoadTemplate(string templateName, Dictionary<string, string> replacements = null)
        {
            var projectTemplateStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(GetType(), templateName);
            Debug.Assert(projectTemplateStream != null);
            string fileContent = new StreamReader(projectTemplateStream).ReadToEnd();

            if (replacements != null)
            {
                fileContent = replacements.Aggregate(fileContent, (current, replacement) => current.Replace("{" + replacement.Key + "}", replacement.Value));
            }

            return fileContent;
        }
Example #30
0
        public IReadOnlyDictionary<Vertex, Location> Plan([NotNull] Graph graph)
        {
            // create initial random locations for each vertex
            var currentLocations = CreateRandomLocations(graph);

            // loop until the number of iterations exceeds the hard limit
            const double terminationThreshold = TerminationThreshold * TerminationThreshold;
            for (var i = 0; i < MaximumIterations; ++i)
            {
                // the total displacement, used as a stop condition
                var totalDisplacement = 0.0D;

                // prepare the new positions
                var newLocations = new Dictionary<Vertex, Location>(currentLocations);

                // iterate over all vertices ...
                foreach (var vertex in graph.Vertices)
                {
                    // obtain the vertex location
                    var locationOf = currentLocations[vertex];

                    // and process against all other vertices
                    var netForce = Vector.Zero;
                    netForce += CalculateTotalRepulsion(graph, vertex, locationOf, currentLocations);
                    netForce += CalculateTotalAttraction(graph, vertex, locationOf, currentLocations); // TODO: make use of force symmetry along edges here

                    // finally, update the vertex' position
                    locationOf += netForce;
                    newLocations[vertex] = locationOf;

                    // update the total displacement
                    totalDisplacement += netForce.SquaredNorm();
                }

                // calculate the center
                var center = newLocations.Aggregate(Vector.Zero, (vector, location) => vector + (Vector)location.Value) * (1D / currentLocations.Count);

                // adjust each node to prevent creep
                foreach (var location in newLocations)
                {
                    currentLocations[location.Key] = location.Value - center;
                }

                // early exit if nodes don't move much anymore
                if (totalDisplacement < terminationThreshold) break;
            }

            return currentLocations;
        }