Example #1
0
 public ModuleCriteria CreateCriteria(int testId, Dictionary<string, string> scormData) {
   //Velka data, zaroven se vypocitaji properties, odvozene z Results
   if (scormData != null) { ScormDataKey = scormData.Select(kv => kv.Key).ToArray(); ScormDataValue = scormData.Select(kv => kv.Value).ToArray(); }
   byte[] encode = Encode();
   //Mala proxy data
   PageResult[] res = Results; Results = null; ScormDataValue = ScormDataKey = null;
   byte[] encodeProxy = Encode();
   Results = res;
   //Uloz do DB
   ModuleCriteria crit = new ModuleCriteria() {
     CourseId = testId,
     DataBin = new IdDataBin() { Id = Id, DataBin = encode },
     ProxyDataBin = new IdDataBin() { Id = Id, DataBin = encodeProxy },
     Status = (short)Status,
     Level = (short)Level
   };
   if (Status == ExerciseStatus.Evaluated) {
     crit.Skill = Skill;
     crit.ElapsedSeconds = (short)(ElapsedTime / 1000);
     crit.Score = (short)Score.ToPercent();
     TestProxy.LevelScore score = TestProxy.GetLevelScore(this);
     crit.AbsLevel = score.absLevel;
     crit.AbsScore = (short) score.absScore;
     crit.GlobalScore = (short)score.globalScore;
   }
   return crit;
 }
        public void Optimize(Dictionary<double, double> values)
        {
            var n = _f.Functions.Count();
              var xs = values.Select(v => v.Key).ToList();
              var ys = values.Select(v => v.Value).ToList();
              var fs = new List<List<double>>(n);

              for (var i = 0; i < n; i++)
              {
            fs[i] = _f.Functions[i].Evaluate(xs);
              }

              var matrix = new DenseMatrix(n, n);
              var vector = new DenseVector(n);
              for (var i = 0; i < n; i++)
              {
            for (var j = 0; j < n; j++)
            {
              matrix[i, j] = fs[i].ScalarProduct(fs[j]);
            }
            vector[i] = ys.ScalarProduct(fs[i]);
              }

              var matrixInverse = matrix.Inverse();

              var result = matrixInverse * vector;

              for (var i = 0; i < n; i++)
              {
            _f.LinearParameters[i].Value = result[i];
              }
        }
        public static void DataUserSelectorListView(BasePage page, String ObjId, Dictionary<Guid, String> SelectedUsers, List<GroupInfo> SelectedGroups, bool DisabledGroupSelector)
        {
            var ids = SelectedUsers != null && SelectedUsers.Count > 0 ? SelectedUsers.Select(i => i.Key).ToArray() : new List<Guid>().ToArray();
            var names = SelectedUsers != null && SelectedUsers.Count > 0 ? SelectedUsers.Select(i => i.Value).ToArray() : new List<string>().ToArray();

            page.RegisterInlineScript(String.Format(" SelectedUsers{0} = {1}; ",
                                                        ObjId,
                                                        JsonConvert.SerializeObject(
                                                            new
                                                            {
                                                                IDs = ids,
                                                                Names = names,
                                                                PeopleImgSrc = WebImageSupplier.GetAbsoluteWebPath("people_icon.png", ProductEntryPoint.ID),
                                                                DeleteImgSrc = WebImageSupplier.GetAbsoluteWebPath("trash_12.png"),
                                                                DeleteImgTitle = CRMCommonResource.DeleteUser,
                                                                CurrentUserID = SecurityContext.CurrentAccount.ID
                                                            })), onReady: false);
            if (!DisabledGroupSelector)
            {
                ids = SelectedGroups != null && SelectedGroups.Count > 0 ? SelectedGroups.Select(i => i.ID).ToArray() : new List<Guid>().ToArray();
                names = SelectedGroups != null && SelectedGroups.Count > 0 ? SelectedGroups.Select(i => i.Name.HtmlEncode()).ToArray() : new List<string>().ToArray();

                page.RegisterInlineScript(String.Format(" SelectedGroups{0} = {1}; ",
                                                            ObjId,
                                                            JsonConvert.SerializeObject(
                                                                    new
                                                                    {
                                                                        IDs = ids,
                                                                        Names = names,
                                                                        GroupImgSrc = WebImageSupplier.GetAbsoluteWebPath("group_12.png"),
                                                                        TrashImgSrc = WebImageSupplier.GetAbsoluteWebPath("trash_12.png"),
                                                                        TrashImgTitle = CRMCommonResource.Delete
                                                                    })), onReady: false);
            }
        }
        public StructureVoxelModel(MyObjectBuilder_EntityBase entityBase, string voxelPath)
            : base(entityBase)
        {
            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            if (voxelPath != null)
            {
                VoxelFilepath = Path.Combine(voxelPath, Name + MyVoxelMap.V2FileExtension);
                var previewFile = VoxelFilepath;

                if (!File.Exists(VoxelFilepath))
                {
                    var oldFilepath = Path.Combine(voxelPath, Name + MyVoxelMap.V1FileExtension);
                    if (File.Exists(oldFilepath))
                    {
                        SourceVoxelFilepath = oldFilepath;
                        previewFile = oldFilepath;
                        SpaceEngineersCore.ManageDeleteVoxelList.Add(oldFilepath);
                    }
                }

                ReadVoxelDetails(previewFile);
            }

            var materialList = new Dictionary<string, string>();
            foreach (MyVoxelMaterialDefinition item in SpaceEngineersCore.Resources.VoxelMaterialDefinitions.OrderBy(m => m.Id.SubtypeName))
            {
                string texture = item.GetVoxelDisplayTexture();
                materialList.Add(item.Id.SubtypeName, texture == null ? null : SpaceEngineersCore.GetDataPathOrDefault(texture, Path.Combine(contentPath, texture)));
            }

            GameMaterialList = new List<VoxelMaterialAssetModel>(materialList.Select(m => new VoxelMaterialAssetModel { MaterialName = m.Key, DisplayName = m.Key, TextureFile = m.Value }));
            EditMaterialList = new List<VoxelMaterialAssetModel> { new VoxelMaterialAssetModel { MaterialName = null, DisplayName = "Delete/Remove" } };
            EditMaterialList.AddRange(materialList.Select(m => new VoxelMaterialAssetModel { MaterialName = m.Key, DisplayName = m.Key, TextureFile = m.Value }));
        }
 public void Add_Random_Parameter_Test()
 {
     var dictionary = new Dictionary<string, object>();
     Enumerable.Range(1, 10).ToList().ForEach(x => dictionary.AddWithUniquelyNamedKey(x));
     dictionary.Select(x => x.Key).Distinct().Count().ShouldEqual(10);
     dictionary.Select(x => x.Value).ToList().ForEach(x => x.ShouldBeType(typeof(int)));
     dictionary.Select(x => x.Value).ToList().ForEach(x => x.ShouldBeGreaterThan(0));
 }
        /// <summary>
        /// Entraine le réseau
        /// </summary>
        /// <param name="maxIteration">Nombre d'itérations max</param>
        /// <param name="pas">Pas d'apprentissage</param>
        /// <param name="lettreCible">Lettre pour laquelle on entraîne le réseau</param>
        /// <param name="jeuEssai">Jeu d'essai pour entraîner le réseau</param>
        /// <param name="biais">Biais initial</param>
        /// <returns>L'erreur du réseau à la fin de son entraînement</returns>
        public double[] Entrainer(Dictionary<string, double[]> jeuEssai, string lettreCible, int maxIteration, double pas, double biais)
        {
            // on entraîne le réseau
            Neurone neurone = Couches[0].Neurones[0]; // un seul neurone dans le Perceptron

            double erreurCible = 0;
            double[] erreurCourante = new double[] { double.MaxValue };
            int iteration = 0;
            // valeurs initiales
            neurone.Poids = new double[neurone.NbEntrees];
            neurone.Biais = biais;

            while (iteration < maxIteration && erreurCourante[0] > erreurCible)
            {
                // pour chaque élément de test
                foreach (string lettre in jeuEssai.Keys)
                {
                    // récupère le jeu d'entraînement courant
                    double[] entraineur = jeuEssai[lettre];
                    // détermine si c'est la valeur cible (1) ou pas (-1)
                    int valeurCible = (lettre == lettreCible) ? 1 : 0; // la fonction de transfert doit donc produire des -1 ou des 1

                    double sortie = neurone.CalculerSortie(entraineur);
                    // de combien la sortie s'écarte de la cible
                    double ecart = valeurCible - sortie;

                    if (ecart != 0)
                    {
                        // réévalue le poids de chaque entrée (règle de RosenBlatt)
                        for (int p = 0; p < neurone.NbEntrees; p++)
                        {
                            neurone.Poids[p] = neurone.Poids[p] + (pas * ecart * entraineur[p]);
                        }
                        // réévalue le biais
                        // le biais est considéré comme une entrée supplémentaire avec un coefficient toujours égal à 1
                        neurone.Biais = neurone.Biais + (pas * ecart);
                    }
                }

                ++iteration;
                Debug.WriteLine("Itération: " + iteration.ToString());

                // on a un biais et un jeu de poids candidat
                // calcule l'erreur faite par le réseau dans l'estimation de notre jeu d'essai avec notre candidat
                double[][] tests = jeuEssai.Select(jeu => jeu.Value).ToArray();
                double[] cibles = jeuEssai.Select(jeu => (jeu.Key == lettreCible) ? 1.0 : 0.0).ToArray();
                double[][] c = jeuEssai.Select(jeu => cibles).ToArray();
                erreurCourante = CalculerErreur(tests, cibles);
            }

            return erreurCourante;
        }
Example #7
0
 public static bool Insert(string table, Dictionary<string,object> vars)
 {
     using (SqlConnection sqlc = new SqlConnection(ConnectionString))
     {
         var sqlcom = sqlc.CreateCommand();
         sqlcom.CommandText = "INSERT INTO " + table + " ";
         sqlcom.CommandText += "(" + String.Join(",", vars.Select(elem => elem.Key)) + ")";
         sqlcom.CommandText += " VALUES (";
         sqlcom.CommandText += String.Join(",", vars.Select(elem => "@" + elem.Key));
         sqlcom = SetValues(vars, sqlcom);
         sqlcom.CommandText += ")";
         return Exec(sqlcom);
     }
 }
        private void PublishSite(Dictionary<string, string> properties)
        {
            var arguments = "/p:" + string.Join(";", properties.Select(kvp => kvp.Key + "=" + kvp.Value)) + " \"" + ProjectPath + "\"";

            var msBuildProc = new Process();
            msBuildProc.StartInfo = new ProcessStartInfo
                {
                    FileName = Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(), "msbuild.exe"),
                    Arguments = arguments,
                    RedirectStandardError = true,
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                };
            msBuildProc.Start();

            var stdout = msBuildProc.StandardOutput.ReadToEnd();
            var stderr = msBuildProc.StandardError.ReadToEnd();
            msBuildProc.WaitForExit();

            var success = msBuildProc.ExitCode == 0;

            if (!success)
            {
                Console.WriteLine("The publish failed.");
                Console.WriteLine(stdout);
                Console.WriteLine(stderr);
                throw new ApplicationException("Build failed.");
            }
            else
            {
                Console.WriteLine("The publish succeeded.");
            }
        }
Example #9
0
        static void Main(string[] args)
        {
            var input = Console.In;

            var amount = int.Parse(input.ReadLine());
            var numberOfTypes = int.Parse(input.ReadLine());

            var faceValues = Enumerable.Range(0, numberOfTypes)
                .Select(i => input.ReadLine())
                .Select(int.Parse)
                .OrderByDescending(i => i)
                .ToList();

            var dictionary = new Dictionary<int, int>();

            while (amount > 0)
            {
                var toUse = faceValues.First(i => i <= amount);
                if (!dictionary.ContainsKey(toUse))
                {
                    dictionary.Add(toUse,0);
                }

                dictionary[toUse] = dictionary[toUse] + 1;
                amount -= toUse;
            }

            var result = string.Join(" ", dictionary.Select(pair => pair.Value + " " + pair.Key));

            Console.Write(result);
        }
Example #10
0
    static void Main()
    {
        Console.Write("Enter a string: ");
        string input = Console.ReadLine();
        MatchCollection words = Regex.Matches(input, @"\b\w+\b");

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

        foreach (var word in words)
        {
            if (word.ToString() != string.Empty)
            {
                if (!dict.ContainsKey(word.ToString()))
                {
                    dict.Add(word.ToString(), 1);
                }
                else
                {
                    dict[word.ToString()]++;
                }
            }
        }

        Console.WriteLine(string.Join("\n", dict.Select(x => string.Format(@"{0} - {1}", x.Key, x.Value)).ToArray()));
    }
Example #11
0
        public LoadMenu(String path, Dictionary<String, String> fileTypes, Window parentWindow)
            : base("Load Menu", Math.Min(6, Console.WindowHeight - 22), (Console.WindowWidth / 2) - 30, 60, 20, parentWindow)
        {
            BackgroundColour = ConsoleColor.White;
            FileTypes = fileTypes;

            fileSelect = new FileBrowser(PostionX + 2, PostionY + 2, 56, 13, path, "fileSelect", this, true, "txt");
            fileSelect.ChangeItem = delegate() { UpdateCurrentlySelectedFileName(); };
            fileSelect.SelectFile = delegate() { LoadFile(); };

            var openLabel = new Label("Open", PostionX + 16, PostionY + 2, "openLabel", this);
            openTxtBox = new TextBox(PostionX + 16, PostionY + 7, "openTxtBox", this, Width - 13) { Selectable = false };

            fileTypeDropdown = new Dropdown(PostionX + 18, PostionY + 40, FileTypes.Select(x => x.Value).ToList(), "fileTypeDropdown", this, 17);
            fileTypeDropdown.OnUnselect = delegate() { UpdateFileTypeFilter(); };

            loadBtn = new Button(PostionX + 18, PostionY + 2, "Load", "loadBtn", this);
            loadBtn.Action = delegate() { LoadFile(); };
            cancelBtn = new Button(PostionX + 18, PostionY + 9, "Cancel", "cancelBtn", this);
            cancelBtn.Action = delegate() { ExitWindow(); };

            Inputs.Add(fileSelect);
            Inputs.Add(loadBtn);
            Inputs.Add(cancelBtn);
            Inputs.Add(openLabel);
            Inputs.Add(openTxtBox);
            Inputs.Add(fileTypeDropdown);

            CurrentlySelected = fileSelect;

            Draw();
            MainLoop();
        }
Example #12
0
 void ReloadBuilds()
 {
     try
     {
         string res = Util.GetPageSource("http://d3up.com/ajax/builds?username=" + Properties.Settings.Default.D3UpUsername);
         JObject o = JObject.Parse(res);
         if (o["builds"] != null)
         {
             var builds = o["builds"];
             _builds = builds.ToObject<Dictionary<string, string>>();
             var buildNames = _builds.Select(b => b.Value).ToArray();
             this.UIThread(() =>
             {
                 cbDefaultBuild.Items.Clear();
                 cbDefaultBuild.Items.AddRange(buildNames);
             });
             GUI.Log(_builds.Count + " Builds loaded from D3Up.com");
         }
         else
         {
             throw new Exception("No builds");
         }
     }
     catch (Exception ex)
     {
         GUI.Log("Cannot fetch default build. Please check your d3up username.");
     }
 }
 private string ConvertToMessage(Dictionary<string, string> message, bool useJson)
 {
     if(useJson)
         return JsonSerializer.SerializeToString(message);
     else
         return string.Join(" ", message.Select(m => String.Format("{0}={1}", m.Key, m.Value)));
 }
Example #14
0
 private static string Compose(string apiPath, Dictionary<string,string> extra = null)
 {
     extra = extra ?? new Dictionary<string, string>();
     var list = extra.Select(x => x.Key + "=" + x.Value).ToList();
     list.Add(apikey);
     return baseUrl + apiPath + soSite + string.Join("&", list);
 }
Example #15
0
        public string PeopleGetPublicPhotos(string userId, 
            string safeSearch = null, string extras = null, 
            int? perPage = null, int? page = null)
        {
            string url = "http://api.flickr.com/services/rest?method=flickr.people.getPublicPhotos&";
            var parameters = new Dictionary<string, string>
                {
                    {"format", "json"},
                    {"nojsoncallback", "1"},
                    {"api_key", _apiKey},
                    {"user_id", userId}
                };
            if (safeSearch != null)
                parameters.Add("safe_search", safeSearch);
            if (extras != null)
                parameters.Add("extras", extras);
            if (perPage != null)
                parameters.Add("per_page", perPage.Value.ToString(CultureInfo.InvariantCulture));
            if (page != null)
                parameters.Add("page", page.Value.ToString(CultureInfo.InvariantCulture));

            var parameterArray = parameters.Select(item => item.Key + "=" + item.Value).ToArray();
            url += string.Join("&", parameterArray);

            using (var webClient = new WebClient())
            using (var stream = webClient.OpenRead(url))
            {
                if (stream == null)
                    return null;
                using (var streamReader = new StreamReader(stream))
                {
                    return streamReader.ReadToEnd();
                }
            }
        }
Example #16
0
        static void Main(string[] args)
        {
            var input = Console.ReadLine();

            if (input != null)
            {
                string[] words = input.Split();

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

                for (int i = 0; i < words.Length; i++)
                {
                    string word = words[i];
                    if (result.ContainsKey(word))
                    {
                        result[word]++;
                    }
                    result.Add(word, 1);
                }

                Console.WriteLine("\nWord occurence table:\n{0}\n",
                                      string.Join("\n", result.Select(x => string.Format(@"'{0}' -> {1} time(s)", x.Key, x.Value)).ToArray()));

            }

            throw new ArgumentNullException();
        }
Example #17
0
        /// <summary>
        /// Konstruktor okna warunków początkowych
        /// </summary>
        internal InitialCondition(int _mode=SPDAssets.MAX,InitialConditions condition=null)
        {
            _tooltip = -1;
            InitializeComponent();

            Mode = _mode;
            _selectedOperation = Operation.None;
            ComboBox.ItemsSource = SPDAssets.GetBrushRectangles(Mode,InitialConditions.GetTransformation(Mode));
            ComboBox.SelectedIndex = 0;
            DataContext = this;
            _conditionNames = new List<Tuple<string,Tuple<string,bool> > >();
            _conditions = new Dictionary<Tuple<string, bool>, Func<bool, int, int, bool, InitialConditions>>();
            foreach (var T in new[] {false, true})
            {
                _conditions.Add(new Tuple<string, bool>("Donut", T), InitialConditions.DonutFactory);
                _conditions.Add(new Tuple<string, bool>("Circle", T), InitialConditions.CircleFactory);
                _conditions.Add(new Tuple<string,bool>("Diagonal",T),InitialConditions.DiagonalFactory);
                _conditions.Add(new Tuple<string, bool>("NowakMay", T), InitialConditions.NowakMayFactory);
            }
            _conditionNames.AddRange(
                _conditions.Select(
                    k =>
                        new Tuple<string, Tuple<string, bool>>(k.Value(k.Key.Item2, 1,10,false).Name,
                            new Tuple<string, bool>(k.Key.Item1, k.Key.Item2))));
            ComboBoxCopy.ItemsSource = _conditionNames.Select(s=>s.Item1);
            var D = SPDAssets.GenerateLegend(Legend.Height, Mode, InitialConditions.GetTransformation(Mode));
            D.Stretch = Stretch.Fill;

            Legend.Children.Add(D);
            if (condition != null) Condition = condition;
        }
        public void CheckStringsDeclared()
        {
            var names = new List<string>();
            checker.GetAllResourceReferences(names);
            Assert.Greater(names.Count, 600, "Должно быть много ресурсных строчек");
            // убрать исключения и повторы
            names = names.Distinct().Where(n => !exceptionString.Contains(n)).ToList();

            // проверить, есть ли они в файлах ресурсов
            var errorsInFile = new Dictionary<string, List<string>>();
            var resxFileNames = Directory.GetFiles(codeBase + @"\TradeSharp.Localisation\Properties", "*.resx");
            
            foreach (var resxFileName in resxFileNames)
            {
                if (excludedResourcesFiles.Contains(resxFileName.Split('\\').Last())) continue;

                var errors = checker.GetNamesLackInResxFile(resxFileName, names);
                if (errors.Count > 0)
                    errorsInFile.Add(Path.GetFileName(resxFileName), errors);
            }

            if (errorsInFile.Count > 0)
            {
                var errorStr = string.Join("\n", errorsInFile.Select(e => e.Key + ": " + string.Join(", ", e.Value)));
                Assert.Fail(errorStr);
            }
        }
Example #19
0
        public Question CreateNewQuestion()
        {
            var subject = (Subject)_random.Next(Constants.SUBJECTS_COUNT);
            Dictionary<string, TagLib.File> rawOptions = new Dictionary<string, TagLib.File>();
            while (rawOptions.Count < Constants.OPTIONS_COUNT)
            {
                var file = _files[_random.Next(_files.Count)];
                var option = Reencode(Constants.ProjectionBySubject[subject](file.Tag));
                if (rawOptions.ContainsKey(option))
                    continue;
                rawOptions[option] = file;
            }
            var options = rawOptions.Select(kvp => new Option() { Title = kvp.Key, File=kvp.Value, IsCorrect = false }).ToList();
            var title = Constants.QuestionsBySubject[subject];

            int answer = _random.Next(Constants.OPTIONS_COUNT);
            options[answer].IsCorrect = true;
            var musicFile = new MusicFile(options[answer].File);
            return new Question()
                {
                    Title=title,
                    Options=options,
                    File = musicFile
                };
        }
        public IEnumerable<FileInfo> OrderFiles(BundleContext context, IEnumerable<FileInfo> files)
        {
            var workingItems = files.AsParallel().Select(i => new _WorkingItem {
                Path = i.FullName,
                FileInfo = i,
                Dependencies = this._GetDependencies(i.FullName),
            });

            var fileDependencies = new Dictionary<string, _WorkingItem>(_DependencyNameComparer);
            foreach (var item in workingItems) {
                _WorkingItem duplicate;
                if (fileDependencies.TryGetValue(item.Path, out duplicate))
                    throw new ArgumentException(string.Format("During dependency resolution, a collision between '{0}' and '{1}' was detected. Files in a bundle must not collide with respect to the dependency name comparer.", Path.GetFileName(item.Path), Path.GetFileName(duplicate.Path)));

                fileDependencies.Add(item.Path, item);
            }

            foreach (var item in fileDependencies.Values) {
                foreach (var dependency in item.Dependencies) {
                    if (!fileDependencies.ContainsKey(dependency))
                        throw new ArgumentException(string.Format("Dependency '{0}' referenced by '{1}' could not found. Ensure the dependency is part of the bundle and its name can be detected by the dependency name comparer. If the dependency is not supposed to be in the bundle, add it to the list of excluded dependencies.", Path.GetFileName(dependency), Path.GetFileName(item.Path)));
                }
            }

            while (fileDependencies.Count > 0) {
                var result = fileDependencies.Values.FirstOrDefault(f => f.Dependencies.All(d => !fileDependencies.ContainsKey(d)));
                if (result == null)
                    throw new ArgumentException(string.Format("During dependency resolution, a cyclic dependency was detected among the remaining dependencies {0}.", string.Join(", ", fileDependencies.Select(d => "'" + Path.GetFileName(d.Value.Path) + "'"))));
                yield return result.FileInfo;
                fileDependencies.Remove(result.Path);
            }
        }
		/// <summary>
		/// Generate data for the heatmap that display flash times for each player
		/// </summary>
		/// <returns></returns>
		public async Task<List<FlashbangDataPoint>> GetPlayersFlashTimesData()
		{
			List<FlashbangDataPoint> data = new List<FlashbangDataPoint>();
			await Task.Factory.StartNew(() =>
			{
				foreach (PlayerExtended player in Demo.Players)
				{
					Dictionary<long, float> playerFlashStats = new Dictionary<long, float>();

					foreach (PlayerExtended pl in Demo.Players)
					{
						if (!playerFlashStats.ContainsKey(pl.SteamId)) playerFlashStats.Add(pl.SteamId, 0);
					}

					foreach (PlayerBlindedEvent e in Demo.PlayerBlindedEvents.Where(e => player.SteamId == e.ThrowerSteamId))
					{
						if (!playerFlashStats.ContainsKey(e.VictimSteamId))
							playerFlashStats.Add(e.VictimSteamId, 0);
						playerFlashStats[e.VictimSteamId] += e.Duration;
					}

					data.AddRange(playerFlashStats.Select(playerStats => new FlashbangDataPoint
					{
						Flasher = player.Name,
						Flashed = Demo.Players.First(p => p.SteamId == playerStats.Key).Name,
						Duration = Math.Round((decimal)playerStats.Value, 2, MidpointRounding.AwayFromZero)
					}));
				}
			});

			return data;
		}
        public IEnumerable<KeyValuePair<string, IEnumerable<string>>> GetAllTags(IMongoQuery query)
        {
            var dataSet = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase);

            foreach (var entity in serverProvider.Database.OsmCompoundQuery(query))
            {
                foreach (var tag in entity.Tags)
                {
                    if (!dataSet.ContainsKey(tag.Key))
                    {
                        dataSet.Add(tag.Key, new HashSet<string>(StringComparer.OrdinalIgnoreCase));
                    }

                    var valueSet = dataSet[tag.Key];
                    if (!valueSet.Contains(tag.Value))
                    {
                        valueSet.Add(tag.Value);
                    }
                }
            }

            var result = dataSet.Select(kv => new KeyValuePair<string, IEnumerable<string>>(kv.Key, kv.Value));

            return result;
        }
		public static string GetOptions(this IAudioSettings settings)
		{
			var audioOptions = new Dictionary<string, string>()
			                   	{
			                   		{"-codec:a", settings.CodecName}
			                   	};
			if (settings.BitRate > 0)
			{
				audioOptions.Add("-b:a", settings.BitRate.ToString());
			}
			if (settings.Frequency > 0)
			{
				audioOptions.Add("-ar", settings.Frequency.ToString());
			}
			if (settings.Channels > 0)
			{
				audioOptions.Add("-ac", settings.Channels.ToString());
			}

			var value = audioOptions.Select(x => x.Key + " " + x.Value).Aggregate(new StringBuilder(), (x, y) => x.Append(" " + y));

			if (!string.IsNullOrEmpty(settings.Options))
			{
				if (value.Length > 0)
				{
					value.Append(" ");
				}
				value.Append(settings.Options);
			}

			return value.ToString();
		}
        public UserFormAccessList GetAuthorisedForms(SecureSession session, RoleList roleList)
        {
            IEnumerable<string> keys = AssemblyResourceReader.GetResourceKeys();
            string pattern = string.Format("Test_Data.ApplicationPermissions.FORM-([a-z0-9-]*)-USER-{0}", session.AuthenticatedUser.Id);
            Dictionary<string, List<string>> forms = new Dictionary<string, List<string>>();

            foreach (string key in keys)
            {
                Match match = Regex.Match(key, pattern, RegexOptions.IgnoreCase);
                if (!match.Success)
                {
                    continue;
                }

                string content = AssemblyResourceReader.ReadAsString(key);
                string formId = match.Groups[1].Value;

                ApplicationEntitlementList applicationEntitlements = JsonConvert.DeserializeObject<ApplicationEntitlementList>(content);
                foreach (ApplicationEntitlement entitlement in applicationEntitlements)
                {
                    if (entitlement.AccessLevel > AccessLevel.NoAccess)
                    {
                        if (!forms.ContainsKey(formId))
                        {
                            forms.Add(formId, new List<string>());
                        }

                        forms[formId].Add(entitlement.StateName);
                    }
                }
            }

            return new UserFormAccessList(forms.Select(kvp => new UserFormAccess(kvp.Key, kvp.Value.ToList())));
        }
Example #25
0
 public override IObservable<TwitterStatus> Upload(Authorize.AuthenticateInfo authInfo, string status,
     byte[] attachedImageBin, long? in_reply_to_status_id = null,
     double? geo_lat = null, double? geo_long = null)
 {
     var param = new Dictionary<string, object>()
     {
         {"key", ApplicationKey},
         {"message", status},
     }.Parametalize();
     return new MultipartableOAuthClient(ApiEndpoint.DefaultConsumerKey, ApiEndpoint.DefaultConsumerSecret,
         authInfo.AccessToken)
     {
         Url = ApiEndpointUriString,
     }
     .AsOAuthEcho()
     .GetResponse(param.Select(p => new UploadContent(p.Key, p.Value))
         .Append(UploadContent.FromBinary("media", "attach.png", attachedImageBin)))
     .ReadString()
     .Select(s =>
     {
         using (var reader = new StringReader(s))
         {
             var doc = XDocument.Load(reader);
             return doc.Element("image").Element("url").ParseString();
         }
     })
     .SelectMany(s => authInfo.Update(status + " " + s, in_reply_to_status_id, geo_lat, geo_long));
 }
		protected IEnumerable<MetaComponent> GetMetaComponents(
			IDictionary<string, IHandler> flatKeyHandlers)
		{
			var lookup = new Dictionary<IHandler, KeyValuePair<string, IList<Type>>>();
			foreach (var handler in flatKeyHandlers)
			{
				var actual = handler.Value;
				var forwarding = handler.Value as ForwardingHandler;
				if (forwarding != null)
				{
					actual = forwarding.Target;
				}
				KeyValuePair<string, IList<Type>> list;
				if (lookup.TryGetValue(actual, out list) == false)
				{
					list = new KeyValuePair<string, IList<Type>>(handler.Key, new List<Type>(4));
					lookup.Add(actual, list);
				}
				if (forwarding != null)
				{
					list.Value.Add(forwarding.Service);
				}
			}
			return lookup.Select(c => new MetaComponent(c.Value.Key, c.Key, c.Value.Value));
		}
 /// <summary>
 /// 解析lamdba,生成Sql查询条件
 /// </summary>
 /// <param name="expression"></param>
 /// <returns></returns>
 public void ResolveToSql(Expression expression)
 {
     this.index = 0;
     this.Argument = new Dictionary<string, object>();
     this.SqlWhere = Resolve(expression);
     this.Paras = Argument.Select(x => new SqlParameter(x.Key, x.Value)).ToArray();
 }
Example #28
0
        public AttachmentModel[] GetAttachments(string token)
        {
            var user = GetSession(token);
            var attachmentRepository = Repository.Get<IAttachmentRepository>();
            var files = new Dictionary<string, List<string>>();
            var catalogs = attachmentRepository.GetDirectories(user.UserId);
            foreach (var catalog in catalogs)
            {
                var list = attachmentRepository.GetFiles(catalog).Select(Path.GetFileName).ToList();
                if (list.Count > 0)
                {
                    if (catalog != null) files.Add(Path.GetFileName(catalog), list);
                }
            }

            return files.Select(file => new AttachmentModel
            {
                Catalog = file.Key,
                Urls = file.Value.Select(name => new AttachmentUrlModel
                {
                    Name = name,
                    Url = GetUrl(user.UserId, file.Key, name)
                }).ToArray()
            }).ToArray();
        }
Example #29
0
        public HttpWorker(Uri uri, HttpMethod httpMethod = HttpMethod.Get, Dictionary<string, string> headers = null, byte[] data = null)
        {
            _buffer = new byte[8192];
            _bufferIndex = 0;
            _read = 0;
            _responseType = ResponseType.Unknown;
            _uri = uri;
            IPAddress ip;
            var headersString = string.Empty;
            var contentLength = data != null ? data.Length : 0;

            if (headers != null && headers.Any())
                headersString = string.Concat(headers.Select(h => "\r\n" + h.Key.Trim() + ": " + h.Value.Trim()));

            if (_uri.HostNameType == UriHostNameType.Dns)
            {
                var host = Dns.GetHostEntry(_uri.Host);
                ip = host.AddressList.First(i => i.AddressFamily == AddressFamily.InterNetwork);
            }
            else
            {
                ip = IPAddress.Parse(_uri.Host);
            }

            _endPoint = new IPEndPoint(ip, _uri.Port);
            _request = Encoding.UTF8.GetBytes($"{httpMethod.ToString().ToUpper()} {_uri.PathAndQuery} HTTP/1.1\r\nAccept-Encoding: gzip, deflate, sdch\r\nHost: {_uri.Host}\r\nContent-Length: {contentLength}{headersString}\r\n\r\n");

            if (data == null)
                return;

            var tmpRequest = new byte[_request.Length + data.Length];
            Buffer.BlockCopy(_request, 0, tmpRequest, 0, _request.Length);
            Buffer.BlockCopy(data, 0, tmpRequest, _request.Length, data.Length);
            _request = tmpRequest;
        }
Example #30
0
 public Prog MakeProgram(IReadOnlyList<Declr> prelude,
     Dictionary<String, IReadOnlyList<IClassItem>> modules)
 {
     var p = MakeModule("prelude", prelude, false);
     var mods = modules.Select(m => MakeModule(m.Key, m.Value));
     return new Prog(MakeModule("global", p.Append(mods).ToList(), false));
 }