public static string CreateArchiveInUpFolder(string fullPathFolder, string masc) { var upfolder = FS.GetDirectoryName(fullPathFolder); var zipPath = FS.Combine(upfolder, FS.GetFileName(fullPathFolder) + AllExtensions._7z); return(CreateArchive(zipPath, fullPathFolder, masc)); }
/// <summary> /// /// </summary> /// <param name="slozku"></param> /// <param name="p"></param> private string OdstranZJmenaSouboru(string slozku, string p) { string c = FS.GetDirectoryName(slozku); string s = FS.GetFileName(slozku).Replace(p, ""); return(FS.Combine(c, s)); }
public void LoadContest(string dir, string databaseFile = "contest.ojdb") { string problemDir = FS.Combine(dir, "Problems"); if (!FS.DirectoryExist(problemDir)) { throw new JudgeDirectoryNotFoundException(problemDir); } string userDir = FS.Combine(dir, "Users"); if (!FS.DirectoryExist(userDir)) { throw new JudgeDirectoryNotFoundException(userDir); } LoadProblemsDirectory(problemDir); LoadUsersDirectory(userDir); string offlineJudgeDBFile = FS.Combine(dir, databaseFile); if (!FS.FileExist(offlineJudgeDBFile)) { judgeModel.Save(offlineJudgeDBFile); } else { judgeModel.Load(offlineJudgeDBFile); } CurrentContestDir = dir; IsOpen = true; }
public static void Start(Action <string> onComplete = null, Action <Exception> onError = null, int threadsCount = 2, TimeSpan?duraction = null) { if (session != null) { throw new Exception("Предыдущая запись еще не завершена."); } string captureFolder = GetCaptureFolder(); string subfolder = string.Format("{0:yyyy-MM-dd HH-mm-ss ffffff}", DateTime.Now); string folder = FS.Combine(captureFolder, subfolder); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } if (duraction == null) { duraction = TimeSpan.FromSeconds(30); } DateTime endDate = DateTime.Now.Add(duraction.Value); session = new Session(folder, threadsCount, endDate, onComplete, onError); }
public void LoadConfig() { string configFile = Path.Combine(ParentDirectory, ProblemName, "config.json"); if (File.Exists(configFile)) { using (TextReader textReader = new StreamReader(Path.Combine(ParentDirectory, ProblemName, "config.json"))) { Problem temp = JsonSerializer.Deserialize <Problem>(textReader.ReadToEnd()); textReader.Close(); Checker = temp.Checker; Input = temp.Input; Memorylimit = temp.Memorylimit; Output = temp.Output; ProblemType = temp.ProblemType; Testcases = temp.Testcases; Timelimit = temp.Timelimit; UseStdin = temp.UseStdin; UseStdout = temp.UseStdout; } //Reload testcases SortedList <string, double> map = new SortedList <string, double>(); for (int i = 0; i < Testcases.Count; ++i) { map.Add(Testcases[i].TestcaseName.ToLower(), Testcases[i].Point); } List <Testcase> testcases = new List <Testcase>(); string[] subDir = Directory.GetDirectories(Path.Combine(ParentDirectory, ProblemName)); for (int i = 0; i < subDir.Length; ++i) { Testcase test = new Testcase() { TestcaseName = Path.GetFileName(subDir[i]), Point = 1.0 }; if (map.ContainsKey(test.TestcaseName.ToLower())) { test.Point = map[test.TestcaseName.ToLower()]; } //check input & output if (!FS.FileExist(FS.Combine(subDir[i], this.Input)) || !FS.FileExist(FS.Combine(subDir[i], this.Output))) { continue; } //add testcases.Add(test); } this.Testcases = testcases; this.SaveConfig(); } else { CreateDefaultConfig(); } }
private void Save(string input, string folder, Bitmap bmp, Func <Image, Icon> convertToIco, string v) { var f = FS.Combine(folder, v + AllExtensions.ico); var icon = convertToIco.Invoke(bmp); using (FileStream fs = new FileStream(f, FileMode.OpenOrCreate)) { icon.Save(fs); } }
/// <summary> /// Externally called from many places /// </summary> public void InitializeMultilingualResources() { #region Load strings from MultilingualResources file var path = FS.Combine(basePathXlf, "MultilingualResources\\"); foreach (var item in FS.GetFiles(path, "*.xlf", System.IO.SearchOption.TopDirectoryOnly)) { Langs l2 = XmlLocalisationInterchangeFileFormat.GetLangFromFilename(item); if (!filesWithTranslation.ContainsKey(l2)) { filesWithTranslation.Add(l2, item); } } #endregion }
public void GenerateFilesCsFileFilterTests() { var fi = GetConsts(); foreach (var item in fi) { if (item.Name.EndsWith("Pp")) { var path = FS.Combine(p, "auto", "+" + item.GetValue(null)); if (!FS.ExistsFile(path, false)) { TF.WriteAllText(path, "a"); } } } }
public List <string> GetSubmissionPath(string problemName, string userName) { User user = userModel[userName]; problemName = problemName.ToLower(); List <string> result = new List <string>(); foreach (UserSubmission sub in user.UserSubmissions) { if (sub.Name.ToLower() == problemName) { result.Add(FS.Combine(userModel.UserDirectory, userName, sub.ToString())); } } return(result); }
public void ExtractArchive(string archiveFilenameIn, string outFolder) { if (!FS.ExistsDirectory(outFolder)) { FS.CreateDirectory(outFolder); } ZipFile zf = null; try { FileStream fs = File.OpenRead(archiveFilenameIn); zf = new ZipFile(fs); foreach (ZipEntry zipEntry in zf) { String entryFileName = zipEntry.Name; byte[] buffer = new byte[4096]; // 4K is optimum Stream zipStream = zf.GetInputStream(zipEntry); // Manipulate the output filename here as desired. String fullZipToPath = FS.Combine(outFolder, entryFileName).TrimEnd(AllChars.bs); string directoryName = FS.GetDirectoryName(fullZipToPath); if (directoryName.Length > 0) { FS.CreateDirectory(directoryName); } using (FileStream streamWriter = File.Create(fullZipToPath)) { StreamUtils.Copy(zipStream, streamWriter, buffer); } } } finally { if (zf != null) { zf.IsStreamOwner = true; // Makes close also shut the underlying stream zf.Close(); // Ensure we release resources } } }
private void SaveThreadMethod() { try { while (!this.isCompleting || this.toSave.Count > 0) { KeyValuePair <Bitmap, DateTime>?pair = null; lock (this.toSave) { if (this.toSave.Count > 0) { pair = this.toSave[0]; this.toSave.RemoveAt(0); } } if (pair == null) { Thread.Sleep(10); continue; } Bitmap bitmap = pair.Value.Key; string file = FS.Combine(this.folder, string.Format(@"{0:yyyyMMdd HH mm ss ffffff}.png", pair.Value.Value)); bitmap.Save(file); bitmap.Dispose(); } } catch (Exception ex) { this.ShowError(ex); } finally { if (this.onComplete != null) { this.onComplete.Invoke(this.folder); } } }
/// <summary> /// Ulozi soubory A2 do A3. /// A1 je k tomu, aby se mohla zjistit relativni cesta. /// </summary> /// <param name="slozku"></param> /// <param name="soubory"></param> /// <param name="soubor"></param> public void CreateArchive(string slozku, List <string> soubory, string soubor) { #region Nac. jedn soubory a ukkladam do ZipOutputStream using (ZipOutputStream s = new ZipOutputStream(File.Create(soubor))) { s.SetLevel(9); for (int i = 0; i < soubory.Length(); i++) { string var = getRelativePath2(soubory[i], slozku); ZipEntry ze = new ZipEntry(var); //ze.IsFile = true; s.PutNextEntry(ze); try { FileStream fs = new FileStream(FS.Combine(slozku, var), FileMode.Open); byte[] fero = new byte[fs.Length]; fs.Read(fero, 0, (int)fs.Length); fs.Flush(); fs.Close(); fs.Dispose(); fs = null; List <byte> b = new List <byte>(fero); foreach (byte var2 in b) { s.WriteByte(var2); } } catch (UnauthorizedAccessException ex) { } } s.Flush(); s.Finish(); } #endregion }
private SandBoxStatus startRun(int id, string cmd, string workdir, int timeLimit, int memLimit, string input, string output, bool convertExitCodeNonZerotoRTE) { try { string statis = FS.Combine(workdir, "statis.txt"); StringBuilder sb = new StringBuilder(); sb.Append("-Xacp -x "); sb.Append(string.Format("-s \"{0}\" ", statis)); if (timeLimit >= 0) { sb.Append(string.Format("-t {0}ms ", timeLimit)); } if (memLimit >= 0) { sb.Append(string.Format("-m {0}K ", memLimit)); } if (!string.IsNullOrEmpty(workdir)) { sb.Append(string.Format("-d \"{0}\" ", workdir)); } if (!string.IsNullOrEmpty(input)) { sb.Append(string.Format("-i \"{0}\" ", input)); } if (!string.IsNullOrEmpty(output)) { sb.Append(string.Format("-o \"{0}\" ", output)); } sb.Append('"'); for (int i = 0; i < cmd.Length; ++i) { if (cmd[i] == '"') { sb.Append("\\\""); } else { sb.Append(cmd[i]); } } sb.Append('"'); ProcessStartInfo psi = new ProcessStartInfo() { FileName = FS.RunEXE, Arguments = sb.ToString(), UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, WorkingDirectory = workdir }; int exit_code = -1; int timeExe = 0; int memUsed = 0; string stdout = ""; SandBoxStatusType statusType = SandBoxStatusType.UnknownError; using (Process p = new Process()) { p.StartInfo = psi; p.EnableRaisingEvents = true; StringBuilder sbOut = new StringBuilder(); p.OutputDataReceived += (sender, args) => sbOut.Append(args.Data ?? ""); p.Start(); p.BeginOutputReadLine(); p.WaitForExit(timeLimit + 1000); bool tleRun = false; if (!p.HasExited) { p.Kill(); tleRun = true; } stdout = sbOut.ToString(); stdout = stdout.Substring(stdout.LastIndexOf("press ESC to terminate...")); Match match = Regex.Match(stdout, "(successfully|Time limit exceeded|Memory limit exceeded|Crash)"); if (tleRun) { exit_code = p.ExitCode; statusType = SandBoxStatusType.TLE; } else { if (convertExitCodeNonZerotoRTE && p.ExitCode != 0) { exit_code = p.ExitCode; statusType = SandBoxStatusType.RTE; } else if (match.Success) { if (match.Value[0] == 'T') { statusType = SandBoxStatusType.TLE; } else if (match.Value[0] == 'M') { statusType = SandBoxStatusType.MLE; } else if (match.Value[0] == 'C') { statusType = SandBoxStatusType.RTE; } else { string[] lines = File.ReadAllText(statis).Split(new string[] { Environment.NewLine }, StringSplitOptions.None); int cnt = 0; for (int i = 0; i < lines.Length; ++i) { string[] line = lines[i].Split(new char[] { '=' }); if (line[0] == "last.memoryConsumed") { memUsed = Convert.ToInt32(line[1]); cnt++; } else if (line[0] == "last.timeConsumed") { timeExe = Convert.ToInt32(line[1]); cnt++; } } exit_code = 0; statusType = SandBoxStatusType.Success; } } else { exit_code = -1; statusType = SandBoxStatusType.UnknownError; } } } return(new SandBoxStatus() { ID = id, ExitCode = exit_code, Status = statusType, MemoryUsed = memUsed / 1024, TimeExecuted = timeExe, Stderr = "", Stdout = stdout }); } catch (Exception) { return(null); } }
private XlfEngine() { acceptHotkey = new HotKey(Key.Enter, KeyModifier.Ctrl | KeyModifier.Alt | KeyModifier.Shift | KeyModifier.Win, HotKey.DummyMethod); pathXlfKeys = FS.Combine(DefaultPaths.sunamo, @"sunamo\Constants\XlfKeys.cs"); basePathXlf = FS.Combine(DefaultPaths.sunamo, "sunamo"); }
/// <summary> /// /// Path will be combined with ThisApp.Name and ThisApp.Project /// </summary> public static string GetFileInProjectsFolder(string fileRelativeToProjectPath) { return(FS.Combine(DefaultPaths.vsProjects, ThisApp.Name, ThisApp.Project, fileRelativeToProjectPath)); }
public void SaveContest(string output = "contest.ojdb") { judgeModel.Save(FS.Combine(CurrentContestDir, output)); }
/// <summary> /// Kdy� komprimuji celou slo�ku A1, vr�t� mi arch�v zip jm�na slo�ky A1 ve slo�ce ve kter� je A1. /// </summary> /// <param name="slozku"></param> private string VratJmenoSouboruZip(string slozku) { string soubor = FS.Combine(FS.GetDirectoryName(slozku), FS.GetFileNameWithoutExtensionLower(slozku) + ".zip"); return(soubor); }
private double GradeOneSubmission(string problemName, string userName, out JudgeUpdateScoreType status) { status = JudgeUpdateScoreType.OK; int total = problemModel[problemName].Testcases.Count; //Remove old submission judgeModel.RemoveSubmission(problemName, userName); OnUpdateScore?.Invoke(this, new JudgeUpdateScoreSubmissionEvent() { ProblemName = problemName, UserName = userName, Status = JudgeUpdateScoreType.RemoveSubmission, Points = 0, }); OnGradeStatusChanged?.Invoke(this, new JudgeGradingEvent() { Event = JudgeGradingEventType.BeginGradingSubmission, ProblemName = problemName, UserName = userName }); //--------------- check submission existed & get user, problem object User user = userModel[userName]; Problem problem = problemModel[problemName]; List <UserSubmission> submissions = user.GetSubmission(problemName); if (submissions.Count == 0) { //Submission not found OnGradeStatusChanged?.Invoke(this, new JudgeGradingEvent() { Event = JudgeGradingEventType.SubmissionNotFound, UserName = userName, ProblemName = problemName }); TestcasesGraded += total; judgeModel.CreateNewSubmission(problemName, userName, "Not found submission!", "MS", "(null)"); status = JudgeUpdateScoreType.SubmissionNotFound; return(0); } //--------------- make directory string currentDir = FS.Combine(workSpace, DateTime.Now.Ticks.ToString()); string currentUserDir = FS.Combine(currentDir, user.UserName); string currentProblemDir = FS.Combine(currentDir, problem.ProblemName); string inputRun = FS.Combine(currentProblemDir, "input.txt"); FS.CreateDirectory(currentDir); FS.CreateDirectory(currentUserDir); FS.CreateDirectory(currentProblemDir); FS.CreateEmptyFile(inputRun); Compiler compiler = null; UserSubmission submission = null; CompileStatus compileResult = null; //--------------- compile foreach (UserSubmission sub in submissions) { submission = sub; string userSourceCode = FS.Combine(userModel.UserDirectory, userName, sub.ToString()); string newSource = FS.Combine(currentUserDir, sub.ToString()); FS.CopyFile(userSourceCode, newSource); if (!compilerManager.Contains(sub.Extension)) { continue; } List <Compiler> compilers = compilerManager[sub.Extension]; bool found = false; foreach (Compiler com in compilers) { compiler = com; OnGradeStatusChanged.Invoke(this, new JudgeGradingEvent() { Event = JudgeGradingEventType.Compiling, Status = com.Name, UserName = userName, ProblemName = problemName }); compileResult = com.Compile(sandbox, sub.ToString(), currentUserDir); if (!IsGrading) //cancel { FS.DeleteDirectory(currentDir); TestcasesGraded += total; return(0); } if (compileResult.Success) { found = true; break; } } if (found) { break; } } if (compiler == null) { //Submission not found OnGradeStatusChanged?.Invoke(this, new JudgeGradingEvent() { Event = JudgeGradingEventType.CompilerNotFound, UserName = userName, ProblemName = problemName }); TestcasesGraded += total; judgeModel.CreateNewSubmission(problemName, userName, "Not found submission!", "MS", "(null)"); status = JudgeUpdateScoreType.CompilerNotFound; return(0); } if (!compileResult.Success) { //Compile error OnGradeStatusChanged?.Invoke(this, new JudgeGradingEvent() { Status = compileResult.Message, UserName = userName, ProblemName = problemName, Event = JudgeGradingEventType.CompileError }); TestcasesGraded += total; FS.DeleteDirectory(currentDir); judgeModel.CreateNewSubmission(problemName, userName, compileResult.Message, "CE", compiler.Name); status = JudgeUpdateScoreType.CompileError; return(0); } //OK OnGradeStatusChanged.Invoke(this, new JudgeGradingEvent() { Event = JudgeGradingEventType.CompileSuccessfully, UserName = userName, ProblemName = problemName, Status = compiler.Name }); //Check execute exist if (!FS.FileExist(FS.Combine(currentUserDir, compileResult.OutputFileName))) { OnGradeStatusChanged?.Invoke(this, new JudgeGradingEvent() { ProblemName = problemName, UserName = userName, Event = JudgeGradingEventType.SubmissionNotFound }); OnGradeStatusChanged?.Invoke(this, new JudgeGradingEvent() { ProblemName = problemName, UserName = userName, Event = JudgeGradingEventType.NotFoundExecute }); judgeModel.CreateNewSubmission(problemName, userName, "Not found execute", "NFE", compiler.Name); status = JudgeUpdateScoreType.ExecuteNotFound; return(0); } //3. Run testcase List <SubmissionTestcaseResult> gradingTestcaseResult = new List <SubmissionTestcaseResult>(); foreach (Testcase test in problem.Testcases) { OnGradeStatusChanged?.Invoke(this, new JudgeGradingEvent() { Event = JudgeGradingEventType.BeginRunTest }); string currentTestDir = FS.Combine(currentProblemDir, test.TestcaseName); string sourceInput = FS.Combine(problem.ParentDirectory, problem.ProblemName, test.TestcaseName, problem.Input); string sourceOutput = FS.Combine(problem.ParentDirectory, problem.ProblemName, test.TestcaseName, problem.Output); string destOutput = FS.Combine(currentTestDir, problem.Output); //create testcase directory FS.CreateDirectory(currentTestDir); //copy execute FS.CopyFile(FS.Combine(currentUserDir, compileResult.OutputFileName), FS.Combine(currentTestDir, compileResult.OutputFileName)); //copy input if (!problem.UseStdin) { string destInput = FS.Combine(currentTestDir, problem.Input); FS.CopyFile(sourceInput, destInput); } //run var running_status = sandbox.StartRun(-1, ('"' + compiler.RunProgram + '"' + " " + compiler.RunArgs).Replace("$NAME$", submission.Name), currentTestDir, problem.Timelimit, problem.Memorylimit * 1024, problem.UseStdin ? sourceInput : inputRun, problem.UseStdout ? destOutput : null, TreatExitCodeNonZeroAsRTE ); if (!IsGrading) //cancel { TestcasesGraded += total; FS.DeleteDirectory(currentDir); return(0); } TestcasesGraded++; total--; string grading_status = running_status.Status.ToString(); double points = 0.0; int timeExecute = running_status.TimeExecuted; int memUsed = running_status.MemoryUsed; //check if (running_status.ExitCode != 0) { if (running_status.Status == SandBoxStatusType.TLE) { OnGradeStatusChanged?.Invoke(this, new JudgeGradingEvent() { Event = JudgeGradingEventType.EndRunTest, ProblemName = problemName, UserName = userName, TestCaseName = test.TestcaseName, TimeExecuted = timeExecute, Status = "TLE" }); } else if (running_status.Status == SandBoxStatusType.MLE) { OnGradeStatusChanged?.Invoke(this, new JudgeGradingEvent() { Event = JudgeGradingEventType.EndRunTest, ProblemName = problemName, UserName = userName, TestCaseName = test.TestcaseName, Status = "MLE" }); } else if (running_status.Status == SandBoxStatusType.RTE) { OnGradeStatusChanged?.Invoke(this, new JudgeGradingEvent() { Event = JudgeGradingEventType.EndRunTest, ProblemName = problemName, UserName = userName, TestCaseName = test.TestcaseName, Status = "RTE" }); } else if (running_status.Status == SandBoxStatusType.UnknownError) { OnGradeStatusChanged?.Invoke(this, new JudgeGradingEvent() { Event = JudgeGradingEventType.EndRunTest, ProblemName = problemName, UserName = userName, TestCaseName = test.TestcaseName, Status = "Unknown" }); } else { throw new Exception("JUDGER ERROR"); } } else { //if run ok -> copy output & rename FS.CopyFile(sourceOutput, destOutput + "$"); //check result bool checker_result = checker.Compare(problem.Checker, problem.Output, problem.Output + "$", currentTestDir); if (checker_result) { grading_status = "AC"; points = test.Point; } else { grading_status = "WA"; } OnGradeStatusChanged?.Invoke(this, new JudgeGradingEvent() { Event = JudgeGradingEventType.EndRunTest, MemoryUsed = memUsed, TimeExecuted = timeExecute, Status = grading_status, Points = points, TestCaseName = test.TestcaseName, ProblemName = problemName, UserName = userName, }); } gradingTestcaseResult.Add(new SubmissionTestcaseResult() { ProblemName = problemName, UserName = userName, TestcaseName = test.TestcaseName, Points = points, MemoryUsed = memUsed, TimeExecuted = timeExecute, Status = grading_status }); } //update status to database & calc score double totalScore = 0; int submission_id = judgeModel.CreateNewSubmission(problemName, userName, compileResult.Message, "OK", compiler.Name); foreach (SubmissionTestcaseResult r in gradingTestcaseResult) { if (r.Status == "AC") { judgeModel.UpdateLanguageTimeGrading(compiler.Name, r.TimeExecuted); } judgeModel.UpdateStatus(submission_id, r.TestcaseName, r.Points, r.Status, r.TimeExecuted, r.MemoryUsed); totalScore += r.Points; } //4. Clean FS.DeleteDirectory(currentDir); OnGradeStatusChanged?.Invoke(this, new JudgeGradingEvent() { Event = JudgeGradingEventType.EndGradingSubmission }); status = JudgeUpdateScoreType.OK; return(totalScore); }
public static string TestFile(object featureOrType, string fn) { return(FS.Combine(FolderForTestFiles(featureOrType), fn)); }