Example #1
1
    static void ParseInput()
    {
        n = int.Parse(Console.ReadLine());

        stationsInfo = Regex.Matches(
                ("0 --> " + Console.ReadLine()).Replace(" --> ", "►"),
                "([^►]+)►([^►]+)"
            ).Cast<Match>()
            .Select(match =>
                new KeyValuePair<string, int>(
                    match.Groups[2].Value,
                    int.Parse(match.Groups[1].Value)
                )
            ).ToArray();

        int id = 0;
        stationsByName = stationsInfo.ToDictionary(
            info => info.Key,
            info => id++
        );

        stationsByIndex = stationsByName.ToDictionary(
            kvp => kvp.Value,
            kvp => kvp.Key
        );

        var separator = new string[] { " | " };

        camerasInfo = Enumerable.Range(0, int.Parse(Console.ReadLine()))
            .Select(_ => Console.ReadLine())
            .Select(line => line.Split(separator, StringSplitOptions.None))
            .Select(match =>
                new Tuple<DateTime, int, int, int, char>(
                    DateTime.ParseExact(match[0], DateFormat, CultureInfo.InvariantCulture),
                    stationsByName[match[1]],
                    int.Parse(match[2]),
                    int.Parse(match[3]),
                    match[4][0]
                )
            ).ToArray();

        trainCapacity = int.Parse(Console.ReadLine());

#if DEBUG
        //Console.WriteLine("# INPUT");

        //Console.WriteLine(string.Join(Environment.NewLine, stationsInfo));
        //Console.WriteLine();

        //Console.WriteLine(string.Join(Environment.NewLine, camerasInfo));
        //Console.WriteLine();

        //Console.WriteLine(trainCapacity);
        //Console.WriteLine();
#endif
    }
 public static void SomeFunction()
 {
     Dictionary<int, int> dict = new Dictionary<int, int>();
     dict.Add(4, 3);
     Console.WriteLine(dict[4]);
     Console.WriteLine(dict.ContainsKey(8));
     dict.Remove(4);
     foreach(int key in dict.Keys)
         Console.WriteLine(key);
     foreach(int val in dict.Values)
         Console.WriteLine(val);
     foreach(var kv in dict)
         Console.WriteLine(kv.Key + " " + kv.Value);
     var dict2 = dict.ToDictionary(o => o.Key, o => o.Value);
     var vals = dict.Values;
     
     HashSet<int> hash = new HashSet<int>();
     hash.Add(999);
     Console.WriteLine(hash.Contains(999));
     hash.Remove(999);
     Console.WriteLine(hash.Contains(999));
     foreach(int hashItem in hash)
         Console.WriteLine(hashItem);
     var z = hash.Select(o => 3).ToArray();
     var g = hash.GroupBy(o => o).Select(o => o.Count()).Min();
 }
 public HistoryTickerStream(Dictionary<string, List<CandleDataBidAsk>> quotes)
 {
     this.quotes = quotes;
     if (quotes.Count == 0) return;
     currentIndex = quotes.ToDictionary(q => q.Key, q => 0);
     timeNow = quotes.Select(q => q.Value.Count == 0 ? DateTime.MaxValue : q.Value[0].timeClose).Min();
 }
    public static Dictionary<string, List<SmallRNASequence>> ConvertFrom(List<ChromosomeCountSlimItem> items)
    {
      var result = new Dictionary<string, Dictionary<string, SmallRNASequence>>();
      foreach (var c in items)
      {
        foreach (var q in c.Queries)
        {
          Dictionary<string, SmallRNASequence> seqList;
          if (!result.TryGetValue(q.Sample, out seqList))
          {
            seqList = new Dictionary<string, SmallRNASequence>();
            result[q.Sample] = seqList;
          }

          if (!seqList.ContainsKey(q.Sequence))
          {
            seqList[q.Sequence] = new SmallRNASequence()
            {
              Sample = q.Sample,
              Sequence = q.Sequence,
              Count = q.QueryCount
            };
          }
        }
      }

      return result.ToDictionary(l => l.Key, l => l.Value.Values.ToList());
    }
        public async Task<Dictionary<string, string>> GenerateTextWithKey(CancellationToken cancellationToken)
        {
            var generatedTaskObjects = new Dictionary<string, Task<string>>();

            foreach (ExpressionWithSource expressionWithSource in _expressionsWithSources)
            {
                Expression expression = expressionWithSource.Expression;
                ExpressionSourceType source = expressionWithSource.Source;

                Task<string> generatedTextTask = GenerateTextAsync(expression, source, cancellationToken);

                string expressionNameResolvedDuplicates;
                if (generatedTaskObjects.Keys.Contains(expression.Name))
                {
                    int count = generatedTaskObjects.Keys.Count(x => x.StartsWith(expression.Name + " (")) + 1;
                    expressionNameResolvedDuplicates = expression.Name + " (" + count + ")";
                }
                else
                {
                    expressionNameResolvedDuplicates = expression.Name;
                }

                generatedTaskObjects.Add(expressionNameResolvedDuplicates, generatedTextTask);
            }

            await Task.WhenAll(generatedTaskObjects.Values);
            Dictionary<string, string> generatedObjects = generatedTaskObjects.ToDictionary(x => x.Key, y => y.Value.Result);

            return generatedObjects;
        }
Example #6
0
        public SimpleAppClient(IRequester requester, Dictionary<Type, object> services)
            : base(requester)
        {
            foreach (var pair in services)
            {
                Type iface = pair.Key;

                if (iface == null)
                {
                    throw new ApplicationException(); // todo2[ak]
                }

                if (!iface.IsInterface)
                {
                    throw new ApplicationException(); // todo2[ak]
                }

                object instance = pair.Value;
                if (instance == null)
                {
                    throw new ApplicationException(); // todo2[ak]
                }

                if (!iface.IsAssignableFrom(instance.GetType()))
                {
                    throw new ApplicationException(); // todo2[ak]
                }
            }

            _proxies = services.ToDictionary(
                pair => pair.Key.FullName,
                pair => new Tuple<Type, object>(pair.Key, pair.Value));
        }
        public BookPurchaseInfo BookPurchaseInfo(string totalBudget, Dictionary<string, string> purchaseBook)
        {
            BookPurchaseInfo thisPurchaseInfo = new BookPurchaseInfo();

            if (String.IsNullOrWhiteSpace(totalBudget))
            {
                throw new NullReferenceException("Input field(s) is empty.");
            }
            else
            {
                try
                {
                    thisPurchaseInfo.budget = float.Parse(totalBudget);
                    thisPurchaseInfo.items = purchaseBook.ToDictionary(
                        x => int.Parse(x.Key),
                        x => int.Parse(x.Value)
                        );
                }
                catch (Exception Ex)
                {
                    throw new Exception(Ex.Message);
                }
            }

            return thisPurchaseInfo;
        }
        public void IndependentMovements()
        {
            /* take a grid and populate with organisms: |___|_A_|___|_B_|___|___|___|___|___|___|
             * make A choose rightmost stimulus & make B choose leftmost stimulus
             * no conflict, both organisms should move where they chose to go
             * result of test:                          |_A_|___|___|___|_B_|___|___|___|___|___| */

            var organismHabitats = new Dictionary<Organism, Habitat>
                                        {
                                            { this.organisms["A"], this.habitats[1, 0] },
                                            { this.organisms["B"], this.habitats[3, 0] }
                                        };

            var organismIntendedDestinations = new Dictionary<Organism, Habitat>
                                        {
                                            { this.organisms["A"], this.habitats[0, 0] },
                                            { this.organisms["B"], this.habitats[4, 0] }
                                        };

            var expectedOrganismDestinations = organismIntendedDestinations.ToDictionary(
                    intendedDestination => intendedDestination.Key,
                    intendedDestination => intendedDestination.Value);

            var updateSummary = this.CreateAndUpdateEcosystem(organismHabitats, organismIntendedDestinations);

            var expectedCoordinates = expectedOrganismDestinations.Values.Select(expectedDestination => this.habitatCoordinates[expectedDestination]).ToList();
            var actualCoordinates = updateSummary.PostUpdateOrganismLocations.Values.ToList();
            Assert.That(actualCoordinates, Is.EqualTo(expectedCoordinates));
        }
Example #9
0
		private InputState(SAMViewportAdapter adapter, KeyboardState ks, MouseState ms, TouchCollection ts, GamePadState gs, InputState prev)
		{
			Mouse = ms;
			Keyboard = ks;
			TouchPanel = ts;
			GamePad = gs;

			if (Mouse.LeftButton == ButtonState.Pressed)
			{
				IsDown = true;
				PointerPosition = adapter.PointToScreen(Mouse.Position);
			}
			else if (TouchPanel.Count > 0)
			{
				IsDown = true;
				PointerPosition = adapter.PointToScreen(TouchPanel[0].Position.ToPoint());
			}
			else
			{
				IsDown = false;
				PointerPosition = prev.PointerPosition;
			}

			IsJustDown = IsDown && !prev.IsDown;
			IsJustUp = !IsDown && prev.IsDown;

			lastKeyState = prev.currentKeyState;
			currentKeyState = lastKeyState.ToDictionary(p => p.Key, p => ks.IsKeyDown(p.Key));
		}
Example #10
0
 private Font(int height, Dictionary<char, byte[]> characters)
 {
     Height = height;
     this.characters = characters.ToDictionary(
         keyValue => keyValue.Key,
         keyValue => new Character(keyValue.Value, height));
 }
Example #11
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="Lexer" /> class.
        /// </summary>
        public Lexer()
        {
            // regex special characters (should be escaped if needed): .$^{[(|)*+?\
            var patterns = new Dictionary<TokenType, string>
            {
                {TokenType.AND, @"&&"},
                {TokenType.OR, @"\|\|"},
                {TokenType.LEFT_BRACKET, @"\("},
                {TokenType.RIGHT_BRACKET, @"\)"},
                {TokenType.GE, @">="},
                {TokenType.LE, @"<="},
                {TokenType.GT, @">"},
                {TokenType.LT, @"<"},
                {TokenType.EQ, @"=="},
                {TokenType.NEQ, @"!="},
                {TokenType.NOT, @"!"},
                {TokenType.NULL, @"null"},
                {TokenType.COMMA, @","},
                {TokenType.INC, @"\+{2}"}, // Despite the fact our language does not support ++ and -- prefix/postfix operations yet, these unary tokens are explicitly designated as illegal. We're detecting them to prevent unification which is done for consecutive plus or minus operators (e.g. + + - - +-+- => +).
                {TokenType.DEC, @"\-{2}"}, // Unification of such unary operators breaks compatibility - such mixed 1++ + 2 operations are illegal in both C# and JavaScript (since we control C# side there is not pain here, but JavaScript would fail since we're sending raw expressions to client-side).
                {TokenType.ADD, @"\+"},
                {TokenType.SUB, @"-"},
                {TokenType.MUL, @"\*"},
                {TokenType.DIV, @"/"},
                {TokenType.FLOAT, @"[0-9]*\.[0-9]+(?:[eE][\+-]?[0-9]+)?"}, // 1.0, 0.3e-2
                {TokenType.INT, @"[0-9]+"},
                {TokenType.BOOL, @"(?:true|false)"},
                {TokenType.STRING, @"(['])(?:\\\1|.)*?\1"}, // '1234', 'John\'s cat'
                {TokenType.FUNC, @"[a-zA-Z_]+(?:(?:(?:\[[0-9]+\])?\.[a-zA-Z_])?[a-zA-Z0-9_]*)*(?:\[[0-9]+\])?"} // field, field.field, arr[0], func(...)
            };

            RegexMap = patterns.ToDictionary(
                kvp => kvp.Key,
                kvp => new Regex(string.Format("^{0}", kvp.Value))); // in general, for compiled version of regular expressions their construction and initialization time is amortized out over many runs
        }
        public async Task<bool> IdentifyCustomer(string customerId, string email, DateTime? dateCreatedUtc = null, Dictionary<string, string> extraData = null)
        {
            if (string.IsNullOrWhiteSpace(customerId))
                throw new ArgumentNullException("customerId may not be null or empty");

            if (string.IsNullOrWhiteSpace(email))
                throw new ArgumentNullException("email may not be null or empty");


            var request = new HttpRequestMessage(HttpMethod.Put, new Uri(ApiUrl + customerId));
            request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", SiteId, ApiKey))));

            var dict = extraData == null ? new Dictionary<string, string>() : extraData.ToDictionary(d => d.Key, d => d.Value);

            if (dict.ContainsKey("email"))
            {
                throw new ArgumentOutOfRangeException("extraData may not contain a key called 'email'");
            }

            dict.Add("email", email);

            dict.Add("created_at",
                dateCreatedUtc != null
                    ? DateTimeToUnixTimestamp(dateCreatedUtc.Value).ToString("####")
                    : DateTimeToUnixTimestamp(DateTime.UtcNow).ToString("####"));

            request.Content = new FormUrlEncodedContent(dict);

            var response = await Client.SendAsync(request).ConfigureAwait(false);
            return ProcessResponseAsync(response);
        }
Example #13
0
        public Dictionary<SportType, Dictionary<GameInfo, List<Game>>> GroupGamesByGameInfo(
           Dictionary<SportType, List<Game>> games)
        {
            return games.ToDictionary(
               gamesOfSport => gamesOfSport.Key,
                gamesOfSport =>
                    {
                        var resultDict = new Dictionary<GameInfo, List<Game>>();
                        for (var i = 0; i < gamesOfSport.Value.Count; i++)
                        {
                            if (resultDict.Keys.All(info => info != gamesOfSport.Value[i].Info))
                            {
                                var tempList = new List<Game> { gamesOfSport.Value[i] };
                                for (var j = i + 1; j < gamesOfSport.Value.Count; j++)
                                {
                                    if (gamesOfSport.Value[i].BetsName != gamesOfSport.Value[j].BetsName
                                        & gamesOfSport.Value[i].Info == gamesOfSport.Value[j].Info)
                                    {
                                        tempList.Add(gamesOfSport.Value[j]);
                                    }
                                }

                                resultDict.Add(gamesOfSport.Value[i].Info, tempList);
                            }
                        }

                        return resultDict.Where(x => x.Value.Count > 1).ToDictionary(t => t.Key, t => t.Value);
                    });
        }
        public async Task<IDictionary<string, Result>> GetBatchSentimentAsync(Dictionary<string, string> textBatch)
        {
            ValidateBatchRequest(textBatch);

            if (!textBatch.Any())
            {
                return new Dictionary<string, Result>();
            }

            string content;
            using (var response = await _requestor.PostAsync(Constants.SentimentBatchRequest, BuildInputString(textBatch)))
            {
                content = await response.Content.ReadAsStringAsync();
                if (!response.IsSuccessStatusCode)
                {
                    return textBatch.ToDictionary(r => r.Key, r => AzureMachineLearningResult.Build(_errorMessageGenerator.GenerateError(response.StatusCode, content)));
                }
            }

            var result = JsonConvert.DeserializeObject<SentimentBatchResult>(content);
            var parsedResults = result.SentimentBatch.ToDictionary(sr => sr.Id, sr => AzureMachineLearningResult.Build(sr.Score, ScoreToSentiment(sr.Score)));

            foreach (var error in result.Errors)
            {
                parsedResults.Add(error.Id, AzureMachineLearningResult.Build(error.Message));
            }

            return parsedResults;
        }
Example #15
0
        internal override void Prepare()
        {
            Contract.Requires(!String.IsNullOrWhiteSpace(Database));
            Contract.Requires(!String.IsNullOrWhiteSpace(Username));

            var parameters = new Dictionary<String, String> {
                { "database",           Database },
                { "user",               Username },
                { "client_encoding",    "UTF8"   },
            };

            if (ApplicationName != null)
            {
                parameters.Add("application_name", ApplicationName);
            }

            if (SearchPath != null)
            {
                parameters.Add("search_path", SearchPath);
            }

            // TODO: Is this really UTF8 or can be ASCII?
            _parameters = parameters.ToDictionary(kv => PGUtil.UTF8Encoding.GetBytes(kv.Key),
                                                  kv => PGUtil.UTF8Encoding.GetBytes(kv.Value));
            _length = 4 + // len
                      4 + // protocol version
                      _parameters.Select(kv => kv.Key.Length + kv.Value.Length + 2).Sum() +
                      1; // trailing zero byte
        }
Example #16
0
        public Translation Translate(Expression expression)
        {
            var queryVisitor = new QueryParser();

            // parameters are indexed by value to ease reusing params by value
            var parameters = new Dictionary<object, string>();

            queryVisitor.Visit(expression);

            var selectSql = new StringBuilder();
            if (queryVisitor.Select != null)
                new SqlCodeGenerator(selectSql, parameters).Visit(queryVisitor.Select);

            var whereSql = new StringBuilder();
            if (queryVisitor.Where != null)
                new SqlCodeGenerator(whereSql, parameters).Visit(queryVisitor.Where);

            var orderBySql = new StringBuilder();
            if (queryVisitor.OrderBy != null)
                new SqlCodeGenerator(orderBySql, parameters).Visit(queryVisitor.OrderBy);

            return new Translation
            {
                Select = selectSql.ToString(),
                Where = whereSql.ToString(),
                OrderBy = orderBySql.ToString(),
                Skip = queryVisitor.Skip,
                Take = queryVisitor.Take,
                ProjectAs = queryVisitor.ProjectAs,
                Parameters = parameters.ToDictionary(x => x.Value, x => x.Key),
                ExecutionMethod = queryVisitor.Execution
            };
        }
Example #17
0
        private static IDictionary<string, QiMethod> GetMethods(QiObject qiObj)
        {
            //観察事実としてmObjは4要素タプルであり、第0要素にメソッド一覧が入ってる
            var mObj = qiObj.MetaObject;
            if (mObj.Count == 0)
            {
                throw new InvalidOperationException("meta object does not contains info");
            }

            var qKeys = mObj[0].GetKeys();
            var methodInfos = Enumerable
                .Range(0, qKeys.Count)
                .Select(i => qKeys[i])
                .Select(k => new QiMethodInfo(mObj[0][k]));

            var methodOverloads = new Dictionary<string, List<QiMethodInfo>>();
            foreach (var mi in methodInfos)
            {
                if (methodOverloads.ContainsKey(mi.Name))
                {
                    methodOverloads[mi.Name].Add(mi);
                }
                else
                {
                    methodOverloads[mi.Name] = new List<QiMethodInfo>() { mi };
                }
            }

            return methodOverloads.ToDictionary(
                p => p.Key,
                p => new QiMethod(qiObj, p.Value)
                );
        }
Example #18
0
        public void Execute()
        {
            TypeModel model = RuntimeTypeModel.Default;
            using (var ms = new MemoryStream())
            {
                var tagToType = new Dictionary<int, Type>
                {
                    {1, typeof(B)}, {2, typeof(C)}
                };
                var typeToTag = tagToType.ToDictionary(pair => pair.Value, pair => pair.Key);
                
                object b = new B { Y = 2 };
                object c = new C { Y = 4 };
                // in v1, comparable to Serializer.NonGeneric.SerializeWithLengthPrefix(ms, b, PrefixStyle.Base128, typeToTag[b.GetType()]);
                model.SerializeWithLengthPrefix(ms, b, null, PrefixStyle.Base128, typeToTag[b.GetType()]);
                model.SerializeWithLengthPrefix(ms, c, null, PrefixStyle.Base128, typeToTag[c.GetType()]);
                ms.Position = 0;

                // in v1, comparable to Serializer.NonGeneric.TryDeserializeWithLengthPrefix(ms, PrefixStyle.Base128, key => tagToType[key], out b2);
                object b2 = model.DeserializeWithLengthPrefix(ms, null, null, PrefixStyle.Base128, 0, key => tagToType[key]);
                object c2 = model.DeserializeWithLengthPrefix(ms, null, null, PrefixStyle.Base128, 0, key => tagToType[key]);
                
                Assert.AreEqual(((B)b).Y, ((B)b2).Y);
                Assert.AreEqual(((C)c).Y, ((C)c2).Y);
            }
        }
Example #19
0
        /// <summary>
        /// A method for loading humans annotations from textual annotation files
        /// </summary>
        /// <param name="annotationsPath">Path to the file containing annotations</param>
        /// <param name="codingsPath">Path to the file in which it is coded which annotation corresponds to a simplification of which system</param>
        /// <param name="meaningPreservation">Flag that indicates if the annotations are for simplicity/grammaticality or meaning preservation (different format)</param>
        /// <returns>A dictionary containin annotations for simplifications of all systems being evaluated. Key is the identifier of the system (Biran et al.'s 2011 system, our system, human simplifications)</returns>
        public static Dictionary<string, double> EvaluateHuman(string annotationsPath, string codingsPath, bool meaningPreservation = false)
        {
            AllAnnotatorScores = new List<double>();

            var codings = TakeLab.Utilities.IO.StringLoader.LoadDictionaryStrings(codingsPath);
            var annotationLines = (new StreamReader(annotationsPath)).ReadToEnd().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();

            var index = 0;
            if (meaningPreservation)
            {
                annotationLines = annotationLines.Where(x => x.StartsWith("Simplified")).ToList();
                index++;
            }

            Dictionary<string, List<double>> systemScores = new Dictionary<string, List<double>>();
            annotationLines.ForEach(l => {
                var spl = l.Split();
                var system = codings[spl[index]];
                if (!systemScores.ContainsKey(system)) systemScores.Add(system, new List<double>());
                var score = Double.Parse(spl[index + 1]);
                systemScores[system].Add(score);
                AllAnnotatorScores.Add(score);
            });

            return systemScores.ToDictionary(x => x.Key, x => x.Value.Average());
        }
Example #20
0
 public void FiltrateFighters()
 {
     var pretendents = new Dictionary<string, int>();
     foreach (var e in Fighters)
         if (!pretendents.ContainsKey(e.Item1))
             pretendents[e.Item1] = 0;
     var temp = pretendents.ToDictionary(x => x.Key, y => y.Value);
     foreach (var e in temp)
     {
         try
         {
             var process = new Process();
             process.StartInfo.FileName = "Checkers.Tournament.exe";
             process.StartInfo.Arguments = e.Key + " " + "testPlayer.dll";
             process.StartInfo.UseShellExecute = false;
             process.StartInfo.RedirectStandardInput = true;
             process.StartInfo.RedirectStandardOutput = true;
             process.StartInfo.CreateNoWindow = true;
             process.Start();
             var winner = process.StandardOutput.ReadLine()[0];
             if (winner == 'W')
                 pretendents[e.Key]++;
         }
         catch
         {
             pretendents[e.Key] = -10;
         }
     }
     Fighters = Fighters.Where(x => pretendents.ContainsKey(x.Item1) && pretendents.ContainsKey(x.Item2))
                        .ToList();
     //добавить ограничение по победам
     // фильтруем некорректные дллс
 }
Example #21
0
 public EmbeddedResourceManager(IEmbeddedResourceBuilder builder, IWebContext webContext)
 {
     _assemblyPathPrefixes = builder.ResourceSettings.AssemblyPathPrefixes;
     _reverseAssemblyPathPrefixes = _assemblyPathPrefixes.ToDictionary(kvp => kvp.Value, kvp => kvp.Key);
     _clientResourcePrefixes = builder.ResourceSettings.ClientResourcePrefixes;
     _files = new Dictionary<string, EmbeddedResourceVirtualFile>();
     _webContext = webContext;
 }
Example #22
0
        static AsmHelper()
        {
            _registersIds = REGISTERS.ToDictionary(
                s => s.Split(':')[1].Trim(),
                s => (RegisterName)Enum.Parse(typeof(RegisterName), s.Split(':')[0].Trim()));

            _registerCaptions = _registersIds.ToDictionary(p => p.Value, p => p.Key);
        }
        public HttpRemoteResponse(HttpStatusCode statusCode, Dictionary<string, string> headers, string content)
        {
            if (headers == null)
                throw new ArgumentNullException("headers");

            StatusCode = statusCode;
            Headers = headers.ToDictionary(p => p.Key, p => p.Value, StringComparer.OrdinalIgnoreCase); // make a copy for better comparisons
            Content = content;
        }
		private ProfilerStatistics(Dictionary<ProfilerTarget, string> data)
		{
			_data = data.ToDictionary(x => x.Key, x => new TpProfilerStatisticRecord
			{
				Target = x.Key,
				Name = x.Key.GetMetadata<ProfilerTarget, HttpHeaderAttribute>(),
				Data = x.Value
			});
		}
 public string Encrypt(string text, Dictionary<string, string> publicKeyIdAndPublicKeyMap, out Dictionary<string, string> publicKeyIdAndEncryptedKeyMap)
 {
     Dictionary<string, byte[]> publicKeyIdAndEncryptedKeyMapByted;
     var result = Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(text), 
         publicKeyIdAndPublicKeyMap.ToDictionary(i => i.Key, i => Convert.FromBase64String(i.Value)),
         out publicKeyIdAndEncryptedKeyMapByted));
     publicKeyIdAndEncryptedKeyMap = publicKeyIdAndEncryptedKeyMapByted.ToDictionary(i => i.Key, i => Convert.ToBase64String(i.Value));
     return result;
 }
Example #26
0
 /// <param name="confidences"></param>
 /// <returns>message.ID -> (Topic.ID, Topic.Confidence)</returns>
 public static Dictionary<long, TopicIdAndConfidenceInItTuple[]> CleanConfidences(Dictionary<long, double[]> confidences)
 {
     var q = confidences.ToDictionary(k => k.Key, k => k.Value
         .Select((a,i) => Tuple.Create(i,a))
         .OrderByDescending(d => d.Item2)
         .Take(3)
         .ToArray());
     return q;
 }
		private TpProfilerStatistics(Dictionary<ProfilerTarget, string> data)
		{
			_data = data.ToDictionary(x => x.Key, x => new TpProfilerStatisticRecord
			{
				Target = x.Key,
				Name = x.Key.GetDescription(),
				Data = x.Value
			});
		}
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			var dict = new Dictionary<string, Dictionary<string, Dictionary<string, IndexSettings>>>();
			serializer.Populate(reader, dict);
			var response = new IndexSettingsResponse();
			if (!dict.HasAny() || !dict.First().Value.HasAny() || !dict.First().Value.First().Value.HasAny())
				return response;
			response.Nodes = dict.ToDictionary(k => k.Key, v => v.Value.First().Value.First().Value);
			return response;
		}
Example #29
0
 public Dictionary<string, decimal> GetPromoted(
     Dictionary<string, int> boughtDictionary)
 {
     return
         boughtDictionary.ToDictionary(bd => bd.Key,
             bd => promotionBarcodes.Contains(bd.Key)
                 ? bd.Value/3*
                   productRepository.GetByBarcodes(bd.Key).First().Price
                 : 0);
 }
Example #30
0
 static ScriptEngineFactory()
 {
     languageType = Assembly.GetExecutingAssembly()
         .GetTypes()
         .Where(x => x.IsClass && !x.IsAbstract && typeof(ScriptEngineBase).IsAssignableFrom(x))
         .ToDictionary(x => ((LanguageAttribute)x.GetCustomAttributes(typeof(LanguageAttribute), true).First()).Language);
     languageExtensions = languageType.ToDictionary(
         x => ((AllowedExtensionAttribute)x.Value
                 .GetCustomAttributes(typeof(AllowedExtensionAttribute), true)
                 .Single())
             .Extension,
         x => x.Key);
     languageSyntaxHighlighting = languageType.ToDictionary(
         x => x.Key,
         x => GetSyntaxHighlighting(x.Key));
     languageExampleScript = languageType.ToDictionary(
         x => x.Key,
         x => GetExampleScript(x.Key));
 }