コード例 #1
0
 public CcNode(BGCcTreeView tree, CcData ccData, Action <Type> typeWasChosenAction)
     : base(tree)
 {
     this.ccData = ccData;
     this.typeWasChosenAction = typeWasChosenAction;
     singleAndAdded           = ccData.Single && tree.Curve.GetComponent(ccData.Type) != null;
 }
コード例 #2
0
        public object GetFileContent(CcData item, string path)
        {
            var course           = _courseService[item.CourseName];
            var courseYearConfig = course[item.CourseYear];
            var problem          = courseYearConfig[item.Problem];

            var files = BrowseFiles(item, problem).SelectMany(Flatten);
            var file  = files.FirstOrDefault(i => i.RelPath == path);

            if (file == null)
            {
                return(null);
            }

            var info = new FileInfo(file.RawPath);

            if (!info.Exists)
            {
                return(null);
            }

            var images    = new[] { ".png", ".jpg", ".gif", ".jpeg" };
            var extension = $".{file.Filename.ToLower().Split('.').Last()}";
            var isImage   = images.Any(i => extension == i);

            if (isImage)
            {
                var bytes = File.ReadAllBytes(info.FullName);
                return(new FileContent(bytes, extension));
            }

            return(new FileContent(info.FullName.ReadAllTextOrPeek(), extension));
        }
コード例 #3
0
        public ProcessItem(
            ILogger <ProcessItem> logger, CourseService courseService, LanguageService languageService,
            IdService idService, AppOptions appOptions, IHubContext <LiveHub> liveHub,
            CompareService compareService, MatlabServer matlabServer, EvaluationService evaluationService,
            CcData item)
        {
            _logger            = logger;
            _courseService     = courseService;
            _languageService   = languageService;
            _liveHub           = liveHub;
            _idService         = idService;
            _appOptions        = appOptions;
            _compareService    = compareService;
            _matlabServer      = matlabServer;
            _evaluationService = evaluationService;

            Item    = item;
            Context = new CourseContext(
                _courseService,
                _languageService,
                Item
                );

            _matlabServer.Initialize(ProcessService.ContainerName);

            var timeout = Context.CourseProblem.Timeout < 1 ? DefaultTimeoutPerCase : Context.CourseProblem.Timeout;

            TimeBank = new TimeBank(
                Context.Language,
                Item.Action == "input" ? IncreaseTimeoutForInput(timeout) : timeout
                );
            Item.Result.TimeLimit = TimeBank.TimeLeft;
        }
コード例 #4
0
        public List <string> GetUsersRelatedToResult(CcData ccData)
        {
            var sender = _userService.CurrentUser.Id;

            var settingsConfig = _courseService[ccData.CourseName][ccData.CourseYear][ccData.Problem]
                                 .CourseYearConfig.SettingsConfig;

            var students = ccData.UserOrGroupUsers;

            // all teachers for given users
            var teachers = students
                           .SelectMany(i => settingsConfig.TeachersFor(i))
                           .Select(i => i.Id)
                           .Distinct()
                           .ToList();

            var recipients = new List <string>()
            {
                sender
            };

            recipients.AddRange(students);
            recipients.AddRange(teachers);
            recipients.AddRange(ccData?.Comments?.Select(i => i.User) ?? new List <string>());
            recipients = recipients
                         .Distinct()
                         .ToList();

            return(recipients);
        }
コード例 #5
0
        public static CcData HideHiddenFiles(this CcData item, bool isRoot)
        {
            item.Solutions = item.Solutions
                             .Where(i => isRoot || !i.Hidden)
                             .ToList();

            return(item);
        }
コード例 #6
0
        public CcData ConvertToExtendedSimple(CcData item)
        {
            var course           = _courseService[item.CourseName];
            var courseYearConfig = course[item.CourseYear];
            var problem          = courseYearConfig[item.Problem];

            item.IsActive = problem.IsActive;
            return(item);
        }
コード例 #7
0
        private CcData CreateItemTemplate(string courseName, string courseYear, string problemId, string langId, IList <SimpleFileDto> files)
        {
            var id        = ObjectId.GenerateNewId();
            var problem   = Problem(courseName, courseYear, problemId);
            var language  = _languageService[langId];
            var solutions = new List <CcDataSolution>();

            if (problem.Type == ProblemType.Unittest)
            {
                var unittestSpec = problem.Unittest.SingleOrDefault(i => i.Lang == langId)
                                   ?? throw new NotSupportedException($"Language {langId} has no tests defined, contact your teacher");

                var entryPointSrc = problem.ProblemDir().RootFile(unittestSpec.Entrypoint).ReadAllText();
                solutions.Add(CcDataSolution.Single(entryPointSrc, unittestSpec.Entrypoint, 2, false, unittestSpec.Hidden));
                solutions.AddRange(files.Select(i => CcDataSolution.Single(i.Content, i.Path)));
            }
            else
            {
                // add all files
                solutions.AddRange(files.Select(i => CcDataSolution.Single(i.Content, i.Path)));
            }

            // add other required files
            solutions.AddRange(language.Files.Select(i =>
                                                     CcDataSolution.Single(i.Values.First(), i.Keys.First(), 9, false, true)));

            var ccData = new CcData
            {
                Id         = id,
                CourseName = courseName,
                CourseYear = courseYear,
                Action     = "solve",
                Docker     = true,
                Problem    = problemId,
                Language   = langId,
                Solutions  = solutions,

                Result = new CcDataResult
                {
                    Status   = ProcessStatus.InQueue.Value,
                    Duration = 0,
                    Message  = null,
                    Score    = 0,
                    Scores   = new[] { 0, 0, 0 },
                },
                SubmissionStatus =
                    DateTime.Now <= problem.Avail
                        ? SubmissionStatus.Intime
                        : DateTime.Now <= problem.Deadline
                            ? SubmissionStatus.Late
                            : SubmissionStatus.None,
            };

            return(ccData);
        }
コード例 #8
0
        public CcData CreateItemGenerateInputOutput(string userId, string courseName, string courseYear, string problemId, string action)
        {
            if (User.Role != AppUserRoles.Root)
            {
                throw new PermissionDeniedException();
            }

            var id       = ObjectId.GenerateNewId();
            var problem  = Problem(courseName, courseYear, problemId);
            var language = _languageService[problem.Reference.Lang];

            var courseDir  = _courseService[courseName].CourseDir;
            var problemDir = Path.Combine(courseDir, courseYear, "problems", problemId);

            var solutions = new List <CcDataSolution> {
                CcDataSolution.Single(
                    Path.Combine(problemDir, problem.Reference.Name).ReadAllText(),
                    problem.Reference.Name
                    ),
                CcDataSolution.Single(string.Empty, ".debug", int.MaxValue, false)
            };

            // add other required files
            solutions.AddRange(language.Files.Select(i =>
                                                     CcDataSolution.Single(i.Values.First(), i.Keys.First(), 9, false, true)));

            var ccData = new CcData
            {
                Id         = id,
                User       = userId,
                CourseName = courseName,
                CourseYear = courseYear,
                Problem    = problemId,
                Action     = action,
                Language   = language.Id,
                Solutions  = solutions,
                Result     = new CcDataResult
                {
                    Status   = ProcessStatus.InQueue.Value,
                    Duration = 0,
                    Message  = null,
                    Score    = 0,
                    Scores   = new[] { 0, 0, 0 },
                },
                SubmissionStatus =
                    DateTime.Now <= problem.Avail
                        ? SubmissionStatus.Intime
                        : DateTime.Now <= problem.Deadline
                            ? SubmissionStatus.Late
                            : SubmissionStatus.None,
            };

            return(ccData);
        }
コード例 #9
0
        public CcData IncludeDirectories(CcData item)
        {
            var course           = _courseService[item.CourseName];
            var courseYearConfig = course[item.CourseYear];
            var problem          = courseYearConfig[item.Problem];

            item.IsActive = problem.IsActive;
            item.Files    = BrowseFiles(item, problem).ToList();

            return(item);
        }
コード例 #10
0
        public CcData ConvertToExtended(CcData item)
        {
            var course           = _courseService[item.CourseName];
            var courseYearConfig = course[item.CourseYear];
            var problem          = courseYearConfig[item.Problem];

            item.IsActive = problem.IsActive;

            item.Solutions = item.Solutions
                             .Where(i => !i.Hidden || _userService.CurrentUser?.Role == "root")
                             .OrderBy(i => i.IsMain ? 0 : int.MaxValue)
                             .ThenBy(i => i.Index)
                             .ToList();

            item.Solutions.Insert(0, CcDataSolution.Seperator("Solution Files"));


            if (problem.Export.Any())
            {
                var context = new CourseContext(_courseService, _languageService, item);
                item.Solutions.Add(CcDataSolution.Seperator("Result files"));
                foreach (var f in problem.Export)
                {
                    var filepath = context.StudentDir.RootFile(f);
                    if (System.IO.File.Exists(filepath))
                    {
                        item.Solutions.Add(new CcDataSolution
                        {
                            Filename = f,
                            Content  = Convert.ToBase64String(System.IO.File.ReadAllBytes(filepath))
                        });
                    }
                }
            }


            item.Solutions.Add(CcDataSolution.Seperator("Browser Directories"));

            item.Solutions.AddRange(
                new[] {
                problem.Type == ProblemType.Unittest ? null : CcDataSolution.Dynamic("Input", item.ObjectId),
                CcDataSolution.Dynamic("Output", item.ObjectId),
                CcDataSolution.Dynamic("Error", item.ObjectId),
                problem.Type == ProblemType.Unittest ? null : CcDataSolution.Dynamic("Reference", item.ObjectId)
            }
                );

            item.Solutions = item.Solutions
                             .Where(i => i != null)
                             .ToList();

            return(item);
        }
コード例 #11
0
ファイル: LiveHub.cs プロジェクト: code-critic/cc.net
 public static Task ItemChanged(this IClientProxy clients, CcData item)
 {
     try
     {
         return(clients.SendAsync("OnProcessStart", item));
     }
     catch (Exception e)
     {
         Console.WriteLine(e.StackTrace);
         return(Task.CompletedTask);
     }
 }
コード例 #12
0
 public static CcDataLight SingleCcData2CcDataLight(CcData p)
 {
     return(new CcDataLight
     {
         Id = p.Id,
         ObjectId = p.ObjectId,
         Status = p.Result.Status,
         Attempt = p.Attempt,
         ReviewRequest = p.ReviewRequest,
         Points = p.Points,
         User = p.User,
         GroupUsers = p.GroupUsers,
     });
 }
コード例 #13
0
        public UserAccessItem CheckAccess(CcData ccData, bool strict = true)
        {
            var user   = _userService.CurrentUser;
            var access = new UserAccessItem {
                AccessAuthor = ccData.UserOrGroupUsers.Any(i => i == user.Id),
                AccessAdmin  = user.IsCurrentlyRoot
            };

            Console.WriteLine($"{ccData.ObjectId}: AccessAuthor={access.AccessAuthor}, AccessAdmin={access.AccessAdmin}");

            if (!access.HaveAccess && strict)
            {
                throw new PermissionDeniedException();
            }

            return(access.HaveAccess ? access : null);
        }
コード例 #14
0
        private PlagResult ComparePair(CcData a, CcData b, bool sideBySide = false)
        {
            var item = new PlagResult
            {
                Language = a.Language,
                AId      = a.ObjectId,
                BId      = b.ObjectId,
                AName    = $"{a.User}#{a.Attempt}",
                BName    = $"{b.User}#{b.Attempt}",
            };

            var aSols = a.Solutions.Where(i => i.IsMain).ToList();
            var bSols = b.Solutions.Where(i => i.IsMain).ToList();

            aSols.ForEach(aSol =>
            {
                var bSolIdx = aSol.Filename.FindMin(bSols.Select(i => i.Filename));
                var bSol    = bSols[bSolIdx];

                var lines = EnumerableUtils.ZipLines(aSol.Content, bSol.Content);
                var equal = 0;
                lines.ForEach(zip =>
                {
                    var localCost = zip.First.DistanceTo(zip.Second, true);
                    var maxCost   = Math.Max(zip.First.Length, zip.Second.Length);
                    var minCost   = 1 + (int)Math.Ceiling(maxCost * 0.1);
                    var isSame    = localCost <= minCost;

                    if (isSame)
                    {
                        equal++;
                    }
                });

                item.TotalLines += lines.Count;
                item.EqualLines += equal;

                if (sideBySide)
                {
                    var diff = _compareService.CompareString(aSol.Content, bSol.Content, aSol.Filename, bSol.Filename);
                    item.Diffs.Add(diff);
                }
            });

            return(item);
        }
コード例 #15
0
        public CourseContext(CourseService courseService, LanguageService languageService, CcData item, bool problemDir, string id = null)
        {
            CourseService   = courseService;
            LanguageService = languageService;
            Item            = item;
            Id        = id ?? Guid.Empty.ToString();
            CourseDir = courseService[item.CourseName].CourseDir;

            _tmpDir     = Path.Combine(Path.GetTempPath(), "automatest", Id);
            _problemDir = Path.Combine(CourseDir, Item.CourseYear, "problems", Item.Problem);
            _studentDir = problemDir ? _problemDir : Item.ResultDir(CourseDir);
            _dockerDir  = $"/tmp/{Id}";

            ProblemDir = new FileTree(_problemDir);
            TmpDir     = new FileTree(_tmpDir);
            StudentDir = new FileTree(_studentDir);
            DockerDir  = new FileTree(_dockerDir);
        }
コード例 #16
0
        private IEnumerable <SimpleFile> BrowseFiles(CcData item, CourseProblem problem)
        {
            var context            = new CourseContext(_courseService, _languageService, item);
            var referenceRootDir   = new DirectoryInfo(context.ProblemDir.Root);
            var referenceOutputDir = new DirectoryInfo(context.ProblemDir.OutputDir);
            var allowedDirs        = new List <string> {
                "output", "input", "error", ".verification"
            };
            var resultDir  = item.ResultDir(problem.CourseYearConfig.Course.CourseDir);
            var studentDir = new DirectoryInfo(context.StudentDir.Root);

            var files = new List <SimpleFile>();

            if (item.Action == "solve")
            {
                files.AddRange(problem.Export.Select(i => ToSimpleFile(new FileInfo($"{resultDir}/{i}"))));
                files.Add(new SimpleFile
                {
                    RawPath  = studentDir.FullName,
                    Filename = "generated",
                    IsDir    = true,
                    Files    = studentDir.Exists
                            ? studentDir.GetDirectories()
                               .Where(i => allowedDirs.Contains(i.Name))
                               .Select(i => ToSimpleFile(i)).ToList()
                            : new List <SimpleFile>()
                });

                files.Add(ToSimpleFile(referenceOutputDir, "reference"));
                files.ForEach(i => PopulateRelPath(i));

                return(FilterEmptyFiles(files));
            }
            else
            {
                files.Add(ToSimpleFile(referenceRootDir, "reference"));
                files.ForEach(i => PopulateRelPath(i));
                return(FilterEmptyFiles(files));
            }
        }
コード例 #17
0
 public static CcDataDto FromCcData(CcData item)
 {
     return(new CcDataDto
     {
         ObjectId = item.ObjectId,
         Attempt = item.Attempt,
         Date = item.Id.CreationTime,
         IsLate = item.SubmissionStatus.ToAbbrev(),
         Users = item.UserOrGroupUsers,
         Language = item.Language,
         Course = item.CourseName,
         Year = item.CourseYear,
         Problem = item.Problem,
         ReviewRequest = item.ReviewRequest,
         Comments = item.Comments.Count,
         Score = item.Result.Scores.Select(i => i.ToString()).AsString("-"),
         Points = item.Points,
         Status = ProcessStatus.All.FirstOrDefault(i => i.Value == item.Result.Status)?.Letter,
         Group = item.GroupName,
         Duration = item.Result.Duration,
     });
 }
コード例 #18
0
ファイル: BGCcAddWindow.cs プロジェクト: Pau5erra/classe-IA
 public CcNode(Tree tree, CcData ccData)
     : base(tree)
 {
     this.ccData    = ccData;
     singleAndAdded = ccData.Single && tree.Curve.GetComponent(ccData.Type) != null;
 }
コード例 #19
0
 public static CcData IncludeDirectories(this CcData item, UtilService utilService)
 {
     return(utilService.IncludeDirectories(item));
 }
コード例 #20
0
 public CourseContext(CourseService courseService, LanguageService languageService, CcData item, string id = null)
     : this(courseService, languageService, item, false, id)
 {
 }
コード例 #21
0
ファイル: ProcessService.cs プロジェクト: code-critic/cc.net
 private async Task SaveResultOrDoNothing(IDbService dbService, CcData item)
 {
     // no need to save the result since we are using in memory db
     await dbService.Data.UpdateDocumentAsync(item);
 }
コード例 #22
0
 public UserAccessItem RequireAccess(CcData ccData)
 {
     return(CheckAccess(ccData, true));
 }