Exemple #1
0
        public SetInfo ToSetInfo()
        {
            TermCount = terms.Count;

            var si = new SetInfo {
                Author  = Author,
                Created = Created,
                DefinitionLanguageCode = DefinitionLanguageCode,
                Description            = Description,
                Editable         = EditPermissions.ToApiString(),
                HasAccess        = HasAccess,
                ID               = ID,
                Modified         = Modified,
                Subjects         = Subjects.Select(svm => svm.Subject).ToList(),
                TermCount        = TermCount,
                TermLanguageCode = TermLanguageCode,
                Terms            = TermsLoaded ? new List <TermInfo>() : null,
                Title            = Title,
                Uri              = Uri,
                Visibility       = Visibility.ToApiString()
            };

            if (TermsLoaded)
            {
                foreach (var t in Terms)
                {
                    si.Terms.Add(new TermInfo {
                        Term = t.Term, Definition = t.Definition
                    });
                }
            }

            return(si);
        }
Exemple #2
0
        public static void TestResults(string resultsDir, string captureIpdFileIdent, string setInfoXmlPath)
        {
            string[] subDirs = Directory.GetDirectories(resultsDir);

            SetInfo setInfo = SetInfo.ReadXml(setInfoXmlPath);

            List <decimal> trainingIpds = FileUtilities.ParseIPDFile(setInfo.TrainingFilePath);

            for (int i = 0; i < subDirs.Length; i++)
            {
                Console.WriteLine("In directory {0}", subDirs[i]);

                string[] files = Directory.GetFiles(subDirs[i], captureIpdFileIdent + "*.ipd");

                for (int j = 0; j < files.Length; j++)
                {
                    Console.WriteLine("Testing file: {0}", files[j]);

                    List <decimal> sampleIpds = FileUtilities.ParseIPDFile(files[j]);

                    Console.WriteLine("testing regularity...");
                    //I have to do "sampleIpds.FindAll(r => true)" so that it will copy the list of IPDs
                    List <decimal> regularityResults = RegularityTest.Test(sampleIpds.FindAll(r => true));

                    Console.WriteLine("testing KS...");
                    List <decimal> ksResults = KsTest.Test(sampleIpds, trainingIpds);

                    WriteResultsFile(files[j], regularityResults, ksResults);
                }
            }
        }
        private void Save_Set_Button_Clicked(object sender, EventArgs e)
        {
            // Should save the set into the database.
            // Page where the new set shows up
            // *** This line needs to be replaced because it shouldn't technically be opening a new account info page
            string old_set_name = this.SetName;

            SetDescription = setDescriptionEditor.Text;
            this.SetName   = SetNameLabel.Text;
            SetInfo newSet = new SetInfo(this.SetName, SetDescription, this.verified_username, this.verified_password);

            using (SQLiteConnection conn = new SQLiteConnection(_dbPath))
            {
                conn.CreateTable <SetInfo>();               //creates table to read from it?
                var data = conn.Table <SetInfo>().ToList(); //everything is in contacts at this point

                foreach (SetInfo s in data)
                {
                    if (s.SetName == "New Set" || s.SetName == newSet.SetName || s.SetName == old_set_name)
                    {
                        App.UserDatabase.DeleteSet(s.id);
                    }
                }

                App.UserDatabase.SaveSet(newSet);


                Navigation.PopAsync();
                Navigation.PushAsync(new HomeScreen(this.verified_username, this.verified_password)); // open another one to load in data from db
            }
        }
Exemple #4
0
        public static void ParseIPDS_TraceFile(string processDir, string traceFileIdent, string outputFileIdent, string sourceIpIdent, string setInfoXmlPath)
        {
            SetInfo setInfo = SetInfo.ReadXml(setInfoXmlPath);

            string[] subDirs = Directory.GetDirectories(processDir);

            Dictionary <string, string> ipdFiles = new Dictionary <string, string>();

            for (int i = 0; i < subDirs.Length; i++)
            {
                string traceFilePath = Path.Combine(subDirs[i], traceFileIdent);

                if (File.Exists(traceFilePath))
                {
                    List <decimal> ipds = FileUtilities.ParseTraceFile(traceFilePath, sourceIpIdent);

                    string outFilePath = Path.Combine(subDirs[i], outputFileIdent);

                    string filePath = FileUtilities.WriteIPDFile(outFilePath, ipds);

                    File.Delete(traceFilePath);

                    string fileName   = Path.GetFileName(filePath);
                    string folderName = Path.GetFileName(subDirs[i]);

                    ipdFiles.Add(folderName, fileName);
                }
            }

            CreateCceScript(processDir, ipdFiles, Path.GetFileName(setInfo.TrainingFilePath));
            CreateCceCleanupScript(processDir, ipdFiles);
        }
Exemple #5
0
        public static void CreateTestScript(string setInfoXmlPath, string processDir)
        {
            SetInfo setInfo = SetInfo.ReadXml(setInfoXmlPath);

            string[] files = Directory.GetFiles(processDir);

            Dictionary <string, string> testSets = new Dictionary <string, string>();

            for (int i = 0; i < files.Length; i++)
            {
                string folderName = Path.GetFileNameWithoutExtension(files[i]);
                string folderPath = Path.Combine(processDir, folderName);

                Directory.CreateDirectory(folderPath);

                File.Move(files[i], Path.Combine(folderPath, Path.GetFileName(files[i])));

                testSets.Add(folderName, Path.GetFileName(files[i]));
            }

            string trainingFileName = Path.GetFileName(setInfo.TrainingFilePath);

            CreateCceScript(processDir, testSets, trainingFileName);
            CreateCceCleanupScript(processDir, testSets);
        }
Exemple #6
0
        static void WriteSetInfo(SetInfo si, TextWriter writer, string newPassword = null, string newVisibility = null, string newPermissions = null, IEnumerable <long> groupIDs = null)
        {
            WriteQueryString(writer, "title", si.Title, true);
            WriteQueryString(writer, "description", si.Description);
            foreach (var s in si.Subjects)
            {
                WriteQueryString(writer, "subjects[]", s);
            }
            foreach (var term in si.Terms)
            {
                WriteQueryString(writer, "terms[]", term.Term);
            }
            foreach (var term in si.Terms)
            {
                WriteQueryString(writer, "definitions[]", term.Definition);
            }
            WriteQueryString(writer, "lang_terms", si.TermLanguageCode);
            WriteQueryString(writer, "lang_definitions", si.DefinitionLanguageCode);

            WriteQueryString(writer, "password", newPassword);
            WriteQueryString(writer, "visibility", newVisibility);
            WriteQueryString(writer, "editable", newPermissions);

            if (groupIDs != null)
            {
                foreach (var id in groupIDs)
                {
                    WriteQueryString(writer, "groups[]", id.ToString(CultureInfo.InvariantCulture));
                }
            }
        }
Exemple #7
0
 private void CreatArray()
 {
     for (int i = 0; i < UPSRateInfoArray.Length; i++)
     {
         UPSRateInfoArray[i] = new SetInfo();
     }
 }
Exemple #8
0
        private void SetUnitProject(object o)
        {
            SetInfo      info        = (SetInfo)o;
            _Engineering Engineering = info.Engineering;
            _UnitProject UnitProject = info.UnitProject;
            单位工程         dx          = info.dw;

            SetOtherProject(UnitProject.Property.OtherProject, dx.其他项目表, dx);

            _Common.Activitie = UnitProject;//给当前的单位工程赋值



            #region 分部分项对象以及赋值
            //UnitProject.Property.SubSegments = new _SubSegments(UnitProject);//分部分项对象
            SetSubSegments(UnitProject.Property.SubSegments, dx.分部分项表, UnitProject, dx);
            #endregion


            #region 措施项目对象以及赋值
            //UnitProject.Property.MeasuresProject = new _MeasuresProject(UnitProject);//措施项目对象
            //UnitProject.Property.MeasuresProject.IsInit = false;
            SetMeasuresProject(UnitProject.Property.MeasuresProject, dx.措施项目表, UnitProject, dx);
            #endregion

            //UnitProject.Property.Metaanalysis = new _Metaanalysis(UnitProject);//单位工程汇总对象
            //UnitProject.Property.Metaanalysis.IsInit = false;
            SetMetaanalysis(UnitProject.Property.Metaanalysis, dx);


            // UnitProject.Property.QuantityUnitSummaryList = new _QuantityUnitSummaryList(UnitProject);
        }
Exemple #9
0
 /// <summary>
 ///     This is the implementation of the set logic
 /// </summary>
 /// <param name="setInfo">SetInfo with all the information on the set call</param>
 private void HasChangesSetter(SetInfo setInfo)
 {
     if (!setInfo.HasOldValue || !Equals(setInfo.NewValue, setInfo.OldValue))
     {
         _changedValues.Add(setInfo.PropertyName.ToLowerInvariant());
     }
 }
        private void UpdatePublicStatus(BasePlayer player, string args)
        {
            if (!player.IsConnected)
            {
                return;
            }
            if (string.IsNullOrEmpty(args))
            {
                PrintToChat(player, Lang("PublicUsage", player.UserIDString)); return;
            }
            string setname = args.ToLower();

            if (!SetExistsFromName(player, setname))
            {
                PrintToChat(player, Lang("SetNotExist", player.UserIDString, setname)); return;
            }
            SetInfo setToUpdate = SetFromName(player, setname);

            if (setToUpdate == null)
            {
                return;
            }
            if (setToUpdate.Public)
            {
                setToUpdate.Public = false;
            }
            else
            {
                setToUpdate.Public = true;
            }
            PrintToChat(player, Lang("SetPublicUpdated", player.UserIDString, setname, FormatPublicString(setToUpdate.Public)));
        }
        private static async Task <int[, ]> GetGallagerParityMatrix(int rows, int columns)
        {
            int blocksCount = _wc;

            int[,] firstSetOfRows = new int[rows / blocksCount, columns];

            for (int i = 0; i < firstSetOfRows.GetLength(0); i++)
            {
                for (int j = i * _wr; j < (i + 1) * _wr; j++)
                {
                    firstSetOfRows[i, j] = 1;
                }
            }



            Console.WriteLine("firstSetOfRows");

            MatrixOperation.ShowMatrix(firstSetOfRows);

            TaskFactory <SetInfo> taskFactory = new TaskFactory <SetInfo>();

            Task <SetInfo>[] tasks = new Task <SetInfo> [blocksCount];

            tasks[0] = taskFactory.StartNew(() => { return(new SetInfo(firstSetOfRows, 0)); });

            for (int i = 1; i < blocksCount; i++)
            {
                int counter = i;

                tasks[i] = taskFactory.StartNew(() => CreateSet(firstSetOfRows, counter));
            }

            SetInfo parityMatrixinfo = await taskFactory.ContinueWhenAll(tasks, completedTasks =>
            {
                int[,] parityCheckMatrix = new int[rows, columns];

                foreach (var task in completedTasks)
                {
                    SetInfo set = task.Result;

                    int matrixCounter = 0;

                    for (int i = set.Matrix.GetLength(0) * set.Number; i < set.Matrix.GetLength(0) * (set.Number + 1); i++)
                    {
                        for (int j = 0; j < set.Matrix.GetLength(1); j++)
                        {
                            parityCheckMatrix[i, j] = set.Matrix[matrixCounter, j];
                        }

                        matrixCounter++;
                    }
                }

                return(new SetInfo(parityCheckMatrix, 0));
            });

            return(parityMatrixinfo.Matrix);
        }
Exemple #12
0
        public Form1()
        {
            InitializeComponent();
            si = new SetInfo(CallBackUserInfo);

            hks = HKService.GetInstance();
            InitalData();
        }
Exemple #13
0
        public async Task GetArmor(string address)
        {
            IConfiguration   config  = Configuration.Default.WithDefaultLoader(l => l.IsResourceLoadingEnabled = true).WithCss();
            IBrowsingContext context = BrowsingContext.New(config);
            var page = await context.OpenAsync(address);

            SetInfo setinfo = GetSetInfo(page);

            ConsoleWriters.StartingPageMessage($"Starting the {setinfo.armor_set} set.");
            var tables        = page.QuerySelectorAll(".table");
            var defense_trs   = tables[0].QuerySelectorAll("tbody tr").SkipLast(1);
            var skill_table   = tables[1].Children[1].Children.ToArray();
            var create_table  = tables[2].Children[1].Children.ToArray();
            var upgrade_table = tables[4].Children[1].Children.ToArray();

            // Skip the last tr, because that is the total
            foreach (var tr in defense_trs)
            {
                DefenseInfo    definfo  = GetArmorPieceDefenseInfo(tr);
                int            tr_index = tr.ParentElement.Children.Index(tr);
                ArmorSkillInfo asi      = GetArmorSkills(skill_table[tr_index]);
                Armor          piece    = new Armor()
                {
                    armor_name        = definfo.armor_name,
                    armor_set         = setinfo.armor_set,
                    armor_description = setinfo.piece_descriptions[tr_index],
                    rarity            = setinfo.rarity,
                    max_upgrade       = setinfo.max_upgrade,
                    monster_id        = setinfo.monster_id,
                    is_blademaster    = setinfo.is_blademaster,
                    is_gunner         = setinfo.is_gunner,
                    is_male           = setinfo.is_male,
                    is_female         = setinfo.is_female,
                    min_armor_defense = definfo.min_defense,
                    max_armor_defense = definfo.max_defense,
                    fire_def          = definfo.fire_defense,
                    water_def         = definfo.water_defense,
                    thunder_def       = definfo.thunder_defense,
                    ice_def           = definfo.ice_defense,
                    dragon_def        = definfo.dragon_def,
                    slots             = asi.slots,
                };
                await db.InsertAsync(piece);

                foreach (ArmorSkill skill in asi.skills)
                {
                    skill.armor_id = piece.armor_id;
                }
                await Task.WhenAll(
                    db.InsertAllAsync(asi.skills),
                    db.InsertAllAsync(GetArmorScraps(create_table[tr_index], "create", piece.armor_id)),
                    db.InsertAllAsync(GetArmorScraps(upgrade_table[tr_index], "upgrade", piece.armor_id)),
                    db.InsertAllAsync(GetArmorCrafts(create_table[tr_index], piece.armor_id)),
                    db.InsertAllAsync(GetArmorUpgradeItems(upgrade_table[tr_index], piece.armor_id))
                    );
            }
            ConsoleWriters.CompletionMessage($"Finished with the {setinfo.armor_set} set!");
        }
Exemple #14
0
            public static void DictionaryInfoData()
            {
                var droids = new Dictionary <string, SetInfo>()
                {
                    { "R2 D2", new SetInfo() }
                };
                SetInfo r2d2 = droids["R2 D2"];

                droids.Add("R2 D2", new SetInfo());
            }
        private static SetInfo CreateSetInfoFromEntity(CloudTableClient client, SetEntity set)
        {
            SetInfo setInfo = new SetInfo();

            setInfo.CompletedAt        = set.CompletedOn;
            setInfo.CompletedWorkItems = new List <WorkItem>();
            setInfo.Container          = set.ResultContainer;
            setInfo.ExpectedWorkItems  = set.TextureTilesX * set.TextureTilesY;
            setInfo.Id = set.RowKey;
            setInfo.InProgressWorkItems = new List <WorkItem>();
            setInfo.Path     = set.ResultPath;
            setInfo.QueuedAt = set.CreatedOn;
            setInfo.Status   = "NotStarted";



            TableQuery <WorkEntity> workQuery = new TableQuery <WorkEntity>().Where(
                TableQuery.GenerateFilterCondition(
                    "PartitionKey",
                    QueryComparisons.Equal,
                    WorkEntity.EncodeResultPath(set.ResultPath, set.ResultContainer))
                );

            IEnumerable <WorkEntity> workEntities = client.GetTableReference(WorkTableName).ExecuteQuery(workQuery);

            foreach (var workEntity in workEntities)
            {
                WorkItem workItem = new WorkItem();
                workItem.X           = workEntity.TextureTileX;
                workItem.Y           = workEntity.TextureTileY;
                workItem.StartedAt   = workEntity.StartTime;
                workItem.CompletedAt = workEntity.CompletedTime;

                if (workItem.CompletedAt.HasValue)
                {
                    setInfo.CompletedWorkItems.Add(workItem);
                }
                else
                {
                    setInfo.Status = "InProgress";
                    setInfo.InProgressWorkItems.Add(workItem);
                }
            }

            if (set.Completed)
            {
                setInfo.Status = "Completed";
            }
            else if (set.Failed)
            {
                setInfo.Status = "Failed";
            }

            return(setInfo);
        }
Exemple #16
0
        public void SetInfoToStringNullObjectsTest()
        {
            // Arrange
            SetInfo setInfo = new SetInfo();
            // Act
            string result = setInfo.ToString();

            // Assert
            Assert.IsTrue(result.Contains("set_id"));
            Assert.IsTrue(result.Contains("pack_item_def"));
            Assert.IsTrue(result.Contains("name"));
        }
Exemple #17
0
 public void SetUserControlInfo(SetInfo Info)
 {
     if (Info != null)
     {
         arcScaleComponent1.MaxValue       = Info.MaxValue;
         arcScaleComponent1.MinValue       = Info.MinValue;
         label_Name.Text                   = Info.Name;
         arcScaleComponent1.Value          = Info.Value;
         label_Value.Text                  = Info.Value.ToString() + Info.UnitName;
         arcScaleComponent1.MajorTickCount = Info.MajorTickCount;
     }
 }
Exemple #18
0
 /// <summary>
 ///     This is the implementation of the set logic
 /// </summary>
 /// <param name="setInfo">SetInfo with all the information on the set call</param>
 private void WriteProtectSetter(SetInfo setInfo)
 {
     if (_writeProtectedProperties.Contains(setInfo.PropertyName))
     {
         setInfo.CanContinue = false;
         setInfo.Error       = new AccessViolationException($"Property {setInfo.PropertyName} is write protected");
     }
     else if (_isProtecting)
     {
         _writeProtectedProperties.Add(setInfo.PropertyName);
     }
 }
        private void CreateSetButtonClicked(object sender, EventArgs e)
        {
            SetInfo newSet = new SetInfo(this.verified_username, this.verified_password);

            using (SQLiteConnection conn = new SQLiteConnection(_dbPath))
            {
                conn.CreateTable <SetInfo>();               //creates table to read from it?
                var data = conn.Table <SetInfo>().ToList(); //everything is in contacts at this point
                App.UserDatabase.SaveSet(newSet);
                Navigation.PopAsync();
                Navigation.PushAsync(new HomeScreen(this.verified_username, this.verified_password)); // open another one to load in data from db
            }
        }
Exemple #20
0
 public DisplaySetInfo(SetInfo winners, SetInfo losers)
 {
     if (winners.setId != losers.setId)
     {
         throw new Exception("Must construct a full set info from two set info objects for the same set.");
     }
     this.setId           = winners.setId;
     this.winner          = db.Players.Find(winners.playerId);
     this.loser           = db.Players.Find(losers.playerId);
     this.tournament      = db.Tournaments.Find(winners.tournamentId);
     this.winnerElo       = (int)winners.ELO;
     this.loserElo        = (int)losers.ELO;
     this.winnerCharacter = winners.characterId.HasValue && Enum.IsDefined(typeof(Character), winners.characterId) ? (Character)winners.characterId : Character.NoCharacter;
     this.loserCharacter  = losers.characterId.HasValue && Enum.IsDefined(typeof(Character), losers.characterId) ? (Character)losers.characterId : Character.NoCharacter;
 }
 public int SaveSet(SetInfo set)
 {
     lock (locker)
     {
         if (set.id != 0)
         {
             database.Update(set);
             return(set.id);
         }
         else
         {
             return(database.Insert(set));
         }
     }
 }
Exemple #22
0
        public bool GetTestSetInfo()
        {
            var op = new OperationResult();

            op      = SendCommand("IDN?", requestResponse: true);
            SetInfo = op.Success ? op.Messages[0] : "Could not retrieve set info";

            if (op.Success)
            {
                Model        = SetInfo.Split(',')[1];
                SerialNumber = SetInfo.Split(',')[2];
            }

            return(op.Success);
        }
Exemple #23
0
        void IniSetting()
        {
            var node = Registry.LocalMachine.OpenSubKey("SOFTWARE", true);

            SetRegistry(node);
            node.Close();
            if (this.InvokeRequired)
            {
                SetInfo si = new SetInfo(UpdateInfo);
                this.Invoke(si);
            }
            else
            {
                this.label5.Text = "";
            }
        }
Exemple #24
0
        public int  AddSetInfo(SetInfo objSetInfo)
        {
            string sql = "insert into SetInfo(PatientBednum,IsEnable)";

            sql += "values({0},{1})";
            sql  = string.Format(sql, objSetInfo.PatientBednum, objSetInfo.IsEnable);
            try
            {
                return(SQLiteHelper.Update(sql));
            }
            catch (Exception ex)
            {
                SQLiteHelper.WriteLog(" public int  AddSetInfo(SetInfo objSetInfo)", ex.Message);
                throw new Exception("添加数据出错!" + ex.Message);
            }
        }
Exemple #25
0
        public static void CalculateEntropy(string setInfoXmlPath, string ipdFilePath)
        {
            SetInfo        setInfo      = SetInfo.ReadXml(setInfoXmlPath);
            List <decimal> ipds         = FileUtilities.ParseIPDFile(ipdFilePath);
            List <decimal> trainingIpds = FileUtilities.ParseIPDFile(setInfo.TrainingFilePath);

            Entropy        en      = new Entropy(ipds, trainingIpds, setInfo.NumTrainingBins, setInfo.SampleSize);
            List <decimal> entropy = en.DetermineEntropy();

            string path = ipdFilePath + "_EN.txt";

            for (int i = 0; i < entropy.Count; i++)
            {
                File.AppendAllText(path, Convert.ToString(entropy[i]) + Environment.NewLine);
            }
        }
Exemple #26
0
        /// <summary>
        /// 获取设置信息
        /// </summary>
        /// <param name="bednum"></param>
        /// <returns></returns>
        public SetInfo GetSetInfo(int bednum)
        {
            string           sql        = "select IsEnable from SetInfo where PatientBednum=" + bednum;
            SQLiteDataReader objReader  = SQLiteHelper.GetReader(sql);
            SetInfo          objSetInfo = null;

            if (objReader.Read())
            {
                objSetInfo = new SetInfo()
                {
                    IsEnable = Convert.ToInt32(objReader["IsEnable"])
                };
            }
            objReader.Close();
            return(objSetInfo);
        }
Exemple #27
0
    /// <summary>
    /// ÒôЧÉèÖÃ
    /// </summary>
    /// <returns></returns>
    public SocketMsg ReqVoiceSetMsg(object msg)
    {
        SetInfo setInfo = msg as SetInfo;

        MessageData messageData = new MessageData();

        messageData.t = new Dictionary <string, string>
        {
            ["bg"]   = setInfo.BgVoice,
            ["game"] = setInfo.GameVoice
        };
        messageData.model = "set";
        messageData.type  = "voice";
        SocketMsg socketMsg = new SocketMsg(LoginInfo.ClientId, "ÒôЧÉèÖÃ", messageData);

        return(socketMsg);
    }
Exemple #28
0
        /// <summary>
        /// 音效设置
        /// </summary>
        /// <returns></returns>
        public SocketMsg <Dictionary <string, string> > ReqVoiceSetMsg(object msg)
        {
            SetInfo setInfo = msg as SetInfo;

            Dictionary <string, string> t = new Dictionary <string, string>
            {
                ["bg"]   = setInfo.BgVoice,
                ["game"] = setInfo.GameVoice
            };

            t.Add("username", PlayerPrefs.GetString("username"));
            t.Add("token", PlayerPrefs.GetString("token"));
            messageData.model = "consumer/player";
            messageData.type  = "voice";
            socketMsg.Change(LoginInfo.ClientId, "音效设置", messageData);
            return(socketMsg);
        }
Exemple #29
0
        public void SetInfoPropertyTest()
        {
            // Arrange
            int     testSetId       = 00;
            int     testPackItemDef = 0;
            Name    testName        = new Name();
            SetInfo setInfo         = new SetInfo();

            // Act
            setInfo.set_id        = testSetId;
            setInfo.pack_item_def = testPackItemDef;
            setInfo.name          = testName;
            // Assert
            Assert.AreEqual(testSetId, setInfo.set_id);
            Assert.AreEqual(testPackItemDef, setInfo.pack_item_def);
            Assert.AreEqual(testName, setInfo.name);
        }
Exemple #30
0
        public void CardSetPropertyTest()
        {
            // Arrange
            int             version  = 1;
            SetInfo         setInfo  = new SetInfo();
            List <CardList> cardList = new List <CardList>();
            CardSet         set      = new CardSet();

            // Act
            set.version   = version;
            set.set_info  = setInfo;
            set.card_list = cardList;
            // Assert
            Assert.AreEqual(version, set.version);
            Assert.AreEqual(setInfo, set.set_info);
            Assert.AreEqual(cardList, set.card_list);
        }
Exemple #31
0
        static void WriteSetInfo(SetInfo si, TextWriter writer, string newPassword = null, string newVisibility = null, string newPermissions = null, IEnumerable<long> groupIDs = null)
        {
            WriteQueryString(writer, "title", si.Title, true);
            WriteQueryString(writer, "description", si.Description);
            foreach (var s in si.Subjects)
                WriteQueryString(writer, "subjects[]", s);
            foreach (var term in si.Terms)
                WriteQueryString(writer, "terms[]", term.Term);
            foreach (var term in si.Terms)
                WriteQueryString(writer, "definitions[]", term.Definition);
            WriteQueryString(writer, "lang_terms", si.TermLanguageCode);
            WriteQueryString(writer, "lang_definitions", si.DefinitionLanguageCode);

            WriteQueryString(writer, "password", newPassword);
            WriteQueryString(writer, "visibility", newVisibility);
            WriteQueryString(writer, "editable", newPermissions);

            if (groupIDs != null)
                foreach(var id in groupIDs)
                    WriteQueryString(writer, "groups[]", id.ToString(CultureInfo.InvariantCulture));
        }
Exemple #32
0
        public void EditSet(SetInfo si, string newPassword, string newVisibility, string newPermissions, IEnumerable<long> groupIDs, Action success, Action<Exception> errorHandler, CancellationToken token)
        {
            var req = new HttpsRequest("PUT", string.Format(CultureInfo.InvariantCulture, "/2.0/sets/{0}", si.ID));

            var postData = new MemoryStream();
            using (var writer = new StreamWriter(postData))
                WriteSetInfo(si, writer, newPassword, newVisibility, newPermissions, groupIDs);

            req.ContentType = "application/x-www-form-urlencoded";
            req.PostData = postData.ToArray();
            AuthorizeRequest(req, true);

            FetchJSON(
                req,
                json => success(),
                errorHandler,
                token);
        }
Exemple #33
0
        public void CreateSet(SetInfo si, string password, IEnumerable<long> groupIDs, Action<long, Uri> completion, Action<Exception> errorHandler, CancellationToken token)
        {
            var req = new HttpsRequest("POST", "/2.0/sets");

            var postData = new MemoryStream();
            using (var writer = new StreamWriter(postData))
                WriteSetInfo(si, writer, password, si.Visibility, si.Editable, groupIDs);

            req.ContentType = "application/x-www-form-urlencoded";
            req.PostData = postData.ToArray();
            AuthorizeRequest(req, true);

            FetchJSON(
                req,
                json => {
                    try {
                        if (!(json is JsonDictionary))
                            throw new JsonConvertException("Expected a JSON dictionary");

                        var ctx = new JsonContext();
                        var dict = (json as JsonDictionary).Items;
                        var uri = new Uri(ctx.FromJson<string>(dict["url"]));
                        var id = ctx.FromJson<long>(dict["set_id"]);

                        completion(id, uri);
                    } catch (JsonConvertException err) {
                        errorHandler(err);
                    } catch (KeyNotFoundException err) {
                        errorHandler(new QuizletException("Invalid response from server", err));
                    }
                },
                errorHandler,
                token);
        }