示例#1
0
            public async Task SplitsTree()
            {
                // Given
                TestDocument[] inputs = GetDocumentsFromRelativePaths(
                    "root/a/2.txt",
                    "root/b/index.html",
                    "root/a/1.txt",
                    "root/b/4.txt");
                CreateTree tree = new CreateTree()
                                  .WithNesting()
                                  .WithRoots(Config.FromDocument(doc => doc.Destination.FullPath.EndsWith("b/index.html")));

                // When
                IReadOnlyList <IDocument> results = await ExecuteAsync(inputs, tree);

                // Then
                results.Count.ShouldBe(2);
                VerifyTree(
                    results[0].GetChildren().ToList(),
                    results[0],
                    "root/b/index.html",
                    "root/b/4.txt");
                VerifyTree(
                    results[1].GetChildren().ToList(),
                    results[1],
                    "index.html",
                    "root/index.html",
                    "root/a/index.html",
                    "root/a/1.txt",
                    "root/a/2.txt");
            }
示例#2
0
            public async Task GetsTree()
            {
                // Given
                TestDocument[] inputs = GetDocumentsFromRelativePaths(
                    "a/2.txt",
                    "b/3.txt",
                    "a/1.txt",
                    "b/x/4.txt",
                    "c/d/5.txt",
                    "6.txt");
                CreateTree tree = new CreateTree().WithNesting();

                // When
                IReadOnlyList <TestDocument> results = await ExecuteAsync(inputs, tree);

                // Then
                VerifyTree(
                    results,
                    results.Single(),
                    "index.html",
                    "6.txt",
                    "a/index.html",
                    "a/1.txt",
                    "a/2.txt",
                    "b/index.html",
                    "b/3.txt",
                    "b/x/index.html",
                    "b/x/4.txt",
                    "c/index.html",
                    "c/d/index.html",
                    "c/d/5.txt");
            }
        public void CalculateTreeTest2()
        {
            string expr = "(* (+ 1 1) 2)";

            tree = CreateTree.TreeBuilder(expr);
            Assert.AreEqual(4, tree.CalculateTree());
        }
        public void CalculateTreeTest3()
        {
            string expr = "(/ (+ 1 1) 0)";

            tree = CreateTree.TreeBuilder(expr);
            tree.CalculateTree();
        }
示例#5
0
        static public void ReadLine(string str)
        {
            //   try
            // {
            var tokenStream = LexicalAnalyzer.Lexicalanalysis(str.Remove(str.Count() - 1, 1));

            if (tokenStream == null)
            {
                Console.WriteLine("( ;∀;) token error!!");
                return;
            }

            //デバッグ用

            /*for (int i = 0; i < tokenStream.Size; i++)
             *   tokenStream[i].DebugPrint();*/


            var func = CreateTree.CreateStatement(tokenStream);

            if (func == null)
            {
                Console.WriteLine("( ;∀;) Tree error!!");
                return;
            }
            func();
            //}

            /* catch (Exception except)
             * {
             *   Console.WriteLine(except.Message);
             *   return;
             * }*/
        }
示例#6
0
    void FixedUpdate()
    {
        Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
        RaycastHit hit;

        // Does the ray intersect any objects excluding the player layer
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity))
        {
            if (Input.GetMouseButtonDown(0))
            {
                Debug.Log(hit.collider.gameObject.name);
                if (hit.collider.gameObject.name.Contains("Node"))
                {
                    Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow, 1F);
                    Debug.Log(CreateTree.SearchNodeWithName(hit.collider.gameObject.name));
                }
            }
        }

        /*
         * ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         * Debug.DrawRay(transform.position, transform.forward, Color.green);
         *
         * if(Physics.Raycast(ray, out hit))
         * {
         *  Debug.DrawRay(transform.position, transform.forward, Color.green);
         *  print(hit.collider.name);
         *  if(Input.GetMouseButtonDown(0))
         *      print(hit.collider.name);
         * }
         */
    }
示例#7
0
        public ActionResult Index([Bind(Include = "ID,UserName,Password")] LoginModel loginModel)
        {
            if (ModelState.IsValid)
            {
                Contact user = context.ContactSet
                               .Where(a => a.expl_PortalLogin.Equals(loginModel.UserName))
                               .Select(row => row).FirstOrDefault();

                if (null == user)
                {
                    TempData["loginError"] = "Nie ma takiego użytkownika.";
                    return(RedirectToAction("Index"));
                }


                if (null == user.expl_passwordhash)
                {
                    TempData["loginError"] = "Użytkownik nie posiada uprawnień do logowania do Portalu.";
                    return(RedirectToAction("Index"));
                }

                PasswordHash pHash = PasswordHash.Create(user.expl_salt, user.expl_passwordhash);

                if (pHash.Verify(loginModel.Password))
                {
                    Session["loggedUser"] = loginModel.UserName;
                    Session["guid"]       = user.ContactId;
                    Session["userName"]   = user.FullName;

                    string check = "";

                    CreateTree ct = new CreateTree(context, (Guid)user.ContactId);
                    Session["tree"] = check = ct.Html;

                    CreateTreeAdversumSettlement ctas = new CreateTreeAdversumSettlement(context, (Guid)user.ContactId);
                    Session["treeAS"] = ctas.Html;


                    if (check != "")
                    {
                        Session["netUser"] = 1;
                    }
                    else
                    {
                        Session["netUser"] = 0;
                    }


                    return(RedirectToAction("AccountOrContact", "Login"));
                }

                TempData["loginError"] = "Błędne hasło.";
                return(RedirectToAction("Index"));
            }

            return(View(loginModel));
        }
示例#8
0
        public static (byte[] DllFile, byte[] PdbFile) CompileForStore(string script, ISchemaProvider provider)
        {
            var items = new BuildItems
            {
                SchemaProvider = provider,
                RawQuery       = script
            };

            var chain = new CreateTree(
                new TransformTree(
                    new TurnQueryIntoRunnableCode(null)));

            chain.Build(items);

            return(items.DllFile, items.PdbFile);
        }
示例#9
0
        public object Run(string script, TSQLEngine engine)
        {
            var items = new BuildItems
            {
                RawQuery = script,
                Engine   = engine,
            };

            BuildChain chain =
                new CreateTree(
                    new TransformToQueryableStreamTree(null));

            chain.Build(items);

            return(items.Result);
        }
示例#10
0
        static void Main(string[] args)
        {
            Console.WriteLine("Enter height of a tree (less than 100)");
            string Input    = "";
            int    Enter    = 0;
            bool   Continue = true;

            while (Continue)
            {
                Input = Console.ReadLine();
                bool Cont = true;
                while (Cont)
                {
                    try
                    {
                        int m = Convert.ToInt32(Input);
                        Cont = false;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("You should enter a number");
                        Input = Console.ReadLine();
                    }
                }

                Enter = int.Parse(Input);
                if (Enter >= 100)
                {
                    Console.WriteLine("Enter not more than 100");
                }
                else if (Enter <= 0)
                {
                    Console.WriteLine("Your tree is too short");
                }
                else
                {
                    Continue = false;
                }
            }
            int        Height = Enter;
            int        CONST  = Height;
            CreateTree Tree   = new CreateTree();

            Tree.Create(Height, CONST);
            Console.ReadKey();
        }
示例#11
0
        public static (byte[] DllFile, byte[] PdbFile) CompileForStore(string script, string assemblyName, ISchemaProvider provider)
        {
            var items = new BuildItems
            {
                SchemaProvider = provider,
                RawQuery       = script,
                AssemblyName   = assemblyName
            };

            RuntimeLibraries.CreateReferences();

            var chain = new CreateTree(
                new TransformTree(
                    new TurnQueryIntoRunnableCode(null)));

            chain.Build(items);

            return(items.DllFile, items.PdbFile);
        }
示例#12
0
            public async Task CollapseRoot()
            {
                // Given
                TestDocument[] inputs = GetDocumentsFromRelativePaths(
                    "a/2.txt",
                    "b/3.txt",
                    "a/1.txt",
                    "b/x/4.txt",
                    "c/d/5.txt",
                    "6.txt");
                CreateTree tree = new CreateTree().WithNesting(true, true);

                // When
                IReadOnlyList <TestDocument> results = await ExecuteAsync(inputs, tree);

                // Then
                results.Count.ShouldBe(4);
                results.Select(x => x.Destination.FullPath)
                .ShouldBe(new[] { "a/index.html", "b/index.html", "c/index.html", "6.txt" }, true);
            }
示例#13
0
            public async Task GetsPlaceholderWithSource()
            {
                // Given
                TestDocument[] inputs = GetDocumentsFromRelativePaths(
                    "a/2.txt",
                    "a/1.txt");
                CreateTree tree = new CreateTree().WithNesting();

                // When
                IReadOnlyList <TestDocument> results = await ExecuteAsync(inputs, tree);

                // Then
                VerifyTree(
                    results,
                    results.Single(),
                    "index.html",
                    "a/index.html",
                    "a/1.txt",
                    "a/2.txt");
                results.Single().Source.FullPath.ShouldBe("/input/index.html");
            }
示例#14
0
            public async Task FlatTree()
            {
                // Given
                TestDocument[] inputs = GetDocumentsFromRelativePaths(
                    "root/a/b/2.txt",
                    "root/a/3.txt",
                    "root/a/1.txt");
                CreateTree tree = new CreateTree();

                // When
                IReadOnlyList <TestDocument> results = await ExecuteAsync(inputs, tree);

                // Then
                VerifyTreeChildren(
                    results[0],
                    "root/a/b/2.txt");
                VerifyTreeChildren(
                    results[1],
                    "root/a/3.txt");
                VerifyTreeChildren(
                    results[2],
                    "root/a/1.txt");
                VerifyTreeChildren(
                    results[3],
                    "root/a/b/index.html",
                    "root/a/b/2.txt");
                VerifyTreeChildren(
                    results[4],
                    "root/a/index.html",
                    "root/a/b/index.html",
                    "root/a/3.txt",
                    "root/a/1.txt");
                VerifyTreeChildren(
                    results[5],
                    "root/index.html",
                    "root/a/index.html");
            }
示例#15
0
        public override ResultTable Evaluate()
        {
            var watch = new Stopwatch();

            watch.Start();

            var query   = GetQuery();
            var plugins = LoadPlugins();

            if (Configuration.DebugInfo)
            {
                System.Console.WriteLine($"Loaded plugins ({plugins.Count}):");
                foreach (var plugin in plugins)
                {
                    System.Console.WriteLine($"Assembly {plugin.Value.FullName}");
                }
            }

            var tempDir = Path.Combine(Path.GetTempPath(), "Musoq", "Compiled");

            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }

            byte[] queryHash;
            using (var hashCreator = new MD5CryptoServiceProvider())
            {
                queryHash = hashCreator.ComputeHash(Encoding.UTF8.GetBytes(query));
            }

            var queryHashString = BitConverter.ToString(queryHash).Replace("-", "");

            var dllPath = Path.Combine(tempDir, $"{queryHashString}.dll");
            var pdbPath = Path.Combine(tempDir, $"{queryHashString}.pdb");

            var schemaProvider = new DynamicSchemaProvider(plugins);

            Assembly assembly;

            if (!File.Exists(dllPath) || Configuration.CompileOnly)
            {
                var items = new BuildItems
                {
                    SchemaProvider = schemaProvider,
                    RawQuery       = query
                };

                new Environment().SetValue(Constants.NetStandardDllEnvironmentName, EnvironmentUtils.GetOrCreateEnvironmentVariable());

                var throwAfterSave       = false;
                CompilationException exc = null;
                try
                {
                    BuildChain chain = new CreateTree(
                        new TransformTree(
                            new TurnQueryIntoRunnableCode(null)));

                    chain.Build(items);
                }
                catch (CompilationException ce)
                {
                    throwAfterSave = true;
                    exc            = ce;
                }

                if (items.DllFile?.Length > 0)
                {
                    using (var writer = new BinaryWriter(File.OpenWrite(dllPath)))
                    {
                        writer.Write(items.DllFile);
                    }
                }

                if (items.PdbFile?.Length > 0)
                {
                    using (var writer = new BinaryWriter(File.OpenWrite(pdbPath)))
                    {
                        writer.Write(items.PdbFile);
                    }
                }

                if (!string.IsNullOrEmpty(Configuration.OutputTranslatedQuery))
                {
                    var path     = Configuration.OutputTranslatedQuery;
                    var fileInfo = new FileInfo(path);

                    if (fileInfo.Directory == null || !fileInfo.Directory.Exists)
                    {
                        throw new DirectoryNotFoundException(fileInfo.DirectoryName);
                    }

                    var builder = new StringBuilder();
                    using (var writer = new StringWriter(builder))
                    {
                        items.Compilation?.SyntaxTrees.ElementAt(0).GetRoot().WriteTo(writer);
                    }

                    using (var file = new StreamWriter(File.OpenWrite(path)))
                    {
                        file.Write(builder.ToString());
                    }
                }

                if (throwAfterSave)
                {
                    throw exc;
                }

                assembly = Assembly.Load(items.DllFile, items.PdbFile);
            }
            else
            {
                assembly = Assembly.LoadFile(dllPath);
            }

            if (Configuration.CompileOnly || !string.IsNullOrEmpty(Configuration.OutputTranslatedQuery))
            {
                return(new ResultTable(string.Empty, new string[0], new object[0][], new string[0], TimeSpan.Zero));
            }

            var runnableType = assembly.GetTypes().Single(type => type.FullName.ToLowerInvariant().Contains("query"));

            var instance = (IRunnable)Activator.CreateInstance(runnableType);

            instance.Provider = schemaProvider;

            var compiledQuery = new CompiledQuery(instance);
            var table         = compiledQuery.Run();

            watch.Stop();

            var columns = table.Columns.Select(f => f.ColumnName).ToArray();
            var rows    = table.Select(f => f.Values).ToArray();
            var result  = new ResultTable(table.Name, columns, rows, new string[0], watch.Elapsed);

            return(result);
        }
示例#16
0
        public static CompiledQuery CompileForExecution(string script, ISchemaProvider schemaProvider)
        {
            var items = new BuildItems
            {
                SchemaProvider = schemaProvider,
                RawQuery       = script
            };

            var compiled = true;

            BuildChain chain =
                new CreateTree(
                    new TransformTree(
                        new TurnQueryIntoRunnableCode(null)));

            CompilationException compilationError = null;

            try
            {
                chain.Build(items);
            }
            catch (CompilationException ce)
            {
                compilationError = ce;
                compiled         = false;
            }

            if (compiled && !Debugger.IsAttached)
            {
                return(new CompiledQuery(CreateRunnable(items)));
            }

            var tempPath     = Path.Combine(Path.GetTempPath(), "Musoq");
            var tempFileName = $"InMemoryAssembly";
            var assemblyPath = Path.Combine(tempPath, $"{tempFileName}.dll");
            var pdbPath      = Path.Combine(tempPath, $"{tempFileName}.pdb");
            var csPath       = Path.Combine(tempPath, $"{tempFileName}.cs");

            var builder = new StringBuilder();

            using (var writer = new StringWriter(builder))
            {
                items.Compilation?.SyntaxTrees.ElementAt(0).GetRoot().WriteTo(writer);
            }

            using (var file = new StreamWriter(File.Open(csPath, FileMode.Create)))
            {
                file.Write(builder.ToString());
            }

            if (items.DllFile != null && items.DllFile.Length > 0)
            {
                using (var file = new BinaryWriter(File.Open(assemblyPath, FileMode.Create)))
                {
                    if (items.DllFile != null)
                    {
                        file.Write(items.DllFile);
                    }
                }
            }

            if (items.PdbFile != null && items.PdbFile.Length > 0)
            {
                using (var file = new BinaryWriter(File.Open(pdbPath, FileMode.Create)))
                {
                    if (items.PdbFile != null)
                    {
                        file.Write(items.PdbFile);
                    }
                }
            }

            if (!compiled && compilationError != null)
            {
                throw compilationError;
            }

            var runnable = new RunnableDebugDecorator(CreateRunnable(items), csPath, assemblyPath, pdbPath);

            return(new CompiledQuery(runnable));
        }
示例#17
0
        public ActionResult Index()
        {
            //instantiate classes
            Random     rand                   = new Random();
            CreateTree createTree             = new CreateTree();
            FindNode   node                   = new FindNode();
            FindingCallNumbersModel     model = new FindingCallNumbersModel();
            FindingCallNumbersViewModel vm    = new FindingCallNumbersViewModel();

            model.TopLevel    = new List <string>();
            model.SecondLevel = new List <string>();
            model.ThirdLevel  = new List <string>();
            //set question amount
            model.QuestionAmt = 4;

            //call method from Helper class to assign to Tree
            var tree = createTree.GetTree();

            //call method to assign model with values from tree
            tree.Nodes.ForEach(x => node.GetNode(x, 0, model));

            //instantiate view model
            vm.TopLevelQ       = new List <string>();
            vm.SecondLevelQ    = new List <string>();
            vm.ThirdLevelQ     = new List <string>();
            vm.TimeRunningList = new List <TimeSpan>();

            //TOP LEVEL QUESTIONS
            //get 4 top-level questions
            List <int> randIndexes = new List <int>();

            //get list of random indexes that are unique
            randIndexes = rg.randomNumberList(0, 10, randIndexes, rand);
            //call method that returns random list of unique values
            vm.TopLevelQ = rg.RandomizeList(model.TopLevel, randIndexes);
            //shuffle list again to ensure randomization
            vm.TopLevelQ = vm.TopLevelQ.OrderBy(x => rand.Next()).Take(model.QuestionAmt).ToList();
            //get answer randomly
            vm.topLevelAns = vm.TopLevelQ[rand.Next(0, model.QuestionAmt)];
            //gets first char to get relevant children
            string identifier = vm.topLevelAns[0].ToString();

            //create random index to be the correct answer
            int randNum2 = rand.Next(0, model.QuestionAmt);
            int randNum3 = rand.Next(0, model.QuestionAmt);


            //SECOND LEVEL QUESTIONS
            //second level child questions
            vm.SecondLevelQ = model.SecondLevel.FindAll(x => x.StartsWith(identifier)).Take(model.QuestionAmt).ToList();
            //clear random number list
            randIndexes.Clear();
            //generate new random number list
            randIndexes = rg.randomNumberList(0, model.QuestionAmt, randIndexes, rand);
            //randomize list
            vm.SecondLevelQ = rg.RandomizeList(vm.SecondLevelQ, randIndexes);
            //shuffle list again to ensure randomization
            vm.SecondLevelQ = vm.SecondLevelQ.OrderBy(x => rand.Next()).Take(model.QuestionAmt).ToList();
            //second level child random answer
            vm.secondLevelAns = vm.SecondLevelQ[randNum2].ToString();
            //get first two characters to get children of third level
            string secondLvlIdentifier = vm.secondLevelAns.Substring(0, 2);

            //THIRD LEVEL QUESTIONS
            //third level child questions
            vm.ThirdLevelQ = model.ThirdLevel.FindAll(x => x.StartsWith(secondLvlIdentifier)).Take(model.QuestionAmt).ToList();
            //clear random number list
            randIndexes.Clear();
            //generate new random number list
            randIndexes = rg.randomNumberList(0, model.QuestionAmt, randIndexes, rand);
            //randomize list
            vm.ThirdLevelQ = rg.RandomizeList(vm.ThirdLevelQ, randIndexes);
            //shuffle questions for randomization
            vm.ThirdLevelQ = vm.ThirdLevelQ.OrderBy(x => rand.Next()).Take(model.QuestionAmt).ToList();
            //third level child random answer
            vm.thirdLevelAns = vm.ThirdLevelQ[randNum3].ToString();

            //now need to get only description part of call number to display as question
            vm.question = vm.thirdLevelAns.Substring(vm.thirdLevelAns.IndexOf(' ') + 1);

            //assign the current questions as top level questions
            vm.questionsList = vm.TopLevelQ;
            vm.currentLevel  = 1;
            //assign total marks for test from leaderboard
            //get length of test from leaderboards
            var leaderboards = db.Leaderboards.Where(p => p.Name.Contains("Finding")).FirstOrDefault();

            vm.TotalMarks = leaderboards.TotalMarks;

            //assign tempdata to be accessed in other methods
            TempData["FindingCallNumbersModel"] = vm;

            return(View(vm));
        }