Esempio n. 1
0
        private Access ParseAccess(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "Access");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as Access;
            }

            int errorCount = Errors.Count;
            Access access = null;

            access = ParseNameAccess(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(access, success, position);return access; }

            access = ParseKeyAccess(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(access, success, position);return access; }

            access = ParseMethodCall(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(access, success, position);return access; }

            access = ParseFunctionCall(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(access, success, position);return access; }

            return access;
        }
        /// <summary>
        /// Break down all groups into individual tests.
        /// Given a group test, get all the individual tests.
        /// Given a Group Test in a group test, reduce just to indivudal tests.
        /// If the given test was not a grouptest, the given testCode will be returned in the collection, This means invalid testCodes will not be filtered.
        /// </summary>
        /// <param name="testCode"></param>
        /// <returns></returns>
        private IEnumerable<Tuple2<string, bool>> getIndividualTests(Tuple2<string, bool> testCode)
        {
            var rows = groupTestsTable.Select("GROUP_TEST_ID =" + quotequote(testCode._1));

            List<Tuple2<string, bool>> codes = new List<Tuple2<string, bool>>();

            foreach (DataRow row in rows)
            {
                int count = int.Parse(row.Field<String>("DIRECT_COMPONENTS"));
                String individualOrGroup = row.Field<String>("TEST_PREFIX");
                for (int x = 0; x < count; x++)
                {
                    String code = row.Field<String>("COMPONENT_CODE" + x);
                    var tupleCode = new Tuple2<string,bool>(code, testCode._2);
                    char type = individualOrGroup[x];
                    if (type == 'G')
                        codes.AddRange(getIndividualTests(tupleCode));
                    else // type == 'I'
                    {
                        codes.Add(tupleCode);
                    }
                }
            }
            return codes.DefaultIfEmpty(testCode);
        }
        /// <summary>
        /// Find posts by category
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <returns></returns>
        public ActionResult Category(int id)
        {
            Tuple2 <PagedList <Event>, Category> result = CategoryHelper.FindCategoryAndItems <Event>(id, 1, 10, "CategoryId");

            SetPageTitle(result.Second == null ? "" : result.Second.Name);
            var entityResult = new EntityActionResult(true, "", null, result.First, true, true);
            var actionResult = BuildActionResult(entityResult, "Pages/List");

            return(actionResult);
        }
Esempio n. 4
0
    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
        {
            return(false);
        }

        Tuple2 <T> t = (Tuple2 <T>)obj;

        return(EqualityComparer <T> .Default.Equals(first, t.first) && EqualityComparer <T> .Default.Equals(second, t.second));
    }
Esempio n. 5
0
        public void ChromosomeCrossover()
        {
            var protoChrom = Initialization.MakeProtoChromosome();
            var a          = Initialization.MakeRandomChromosome(NetworkType.Rnn, protoChrom, 0);
            var b          = Initialization.MakeRandomChromosome(NetworkType.Rnn, protoChrom, 0);

            a.ShouldNotLookLike(b);

            var crossedOverChroms = Functions.CrossOverChromosomes(a, b);

            AssertIsCrossedOverVersionOf(crossedOverChroms, Tuple2.Create(a, b));
        }
    public Tuple2 <string, string> getRandomBook()
    {
        if (books.Count > 0)
        {
            Tuple2 <string, string> book = ItsRandom.pickRandom(books, personRandom);
            int bookIndex = books.IndexOf(book);
            books.RemoveAt(bookIndex);
            return(book);
        }

        return(null);
    }
Esempio n. 7
0
        /// <summary>
        /// Set up various properties before saving.
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        public override bool OnBeforeCreate(object ctx)
        {
            // Set the length;
            if (Length == 0)
            {
                Length = Contents == null ? 0 : Contents.Length;
            }

            // Set extension from file name. e.g. mypic.jpg.
            if (string.IsNullOrEmpty(Extension))
            {
                Extension = Path.GetExtension(Name);
            }

            // Get the folders
            if (IsDirectoryBased)
            {
                var parentid = ParentId;
                var lookup   = MediaFolder.Repository.ToLookUpMulti <string>("Name");

                if (parentid <= 0 && !string.IsNullOrEmpty(DirectoryName))
                {
                    var parentfolder = lookup[DirectoryName];
                    if (parentfolder != null)
                    {
                        parentid      = parentfolder.Id;
                        this.ParentId = parentid;
                    }
                }

                ToDo.Optimize(ToDo.Priority.Normal, "kishore", "Optimistic concurrency on media folder size calculation.", () =>
                {
                    var folder     = MediaFolder.Get(parentid);
                    folder.Length += this.Length;
                    folder.Update();
                });
                // Setup directory name and folder id.
                DirectoryName = lookup[parentid].Name;
            }
            if (Contents != null && Contents.Length > 0 && IsImage)
            {
                Tuple2 <int, int> dimensions = ComLib.MediaSupport.ImageHelper.GetDimensions(Contents);
                this.Height = dimensions.First;
                this.Width  = dimensions.Second;
            }

            return(true);
        }
Esempio n. 8
0
		private Tuple2<string, int> DoFindFileLine(MethodDefinition method, int offset)
		{
			Tuple2<string, int> result = DoGetFileLine(method, offset);
			
			if (result.First == "<unknown>")
			{
				TypeDefinition type = method.DeclaringType as TypeDefinition;
				if (type != null)
				{
					var temp = DoFindFileLine(type);
					result = Tuple.Make(temp.First, -1);
				}
			}
			
			return result;
		}
Esempio n. 9
0
        /// <summary>
        /// Get recents posts by page
        /// </summary>
        /// <param name="table"></param>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecords"></param>
        /// <returns></returns>
        public virtual IList <T> GetRecent(string table, int pageNumber, int pageSize, ref int totalRecords)
        {
            string             procName = table + "_GetRecent";
            List <DbParameter> dbParams = new List <DbParameter>();

            // Build input params to procedure.
            dbParams.Add(DbHelper.BuildInParam("@PageIndex", System.Data.DbType.Int32, pageNumber));
            dbParams.Add(DbHelper.BuildInParam("@PageSize", System.Data.DbType.Int32, pageSize));
            dbParams.Add(DbHelper.BuildOutParam("@TotalRows", System.Data.DbType.Int32));

            Tuple2 <IList <T>, IDictionary <string, object> > result = DbHelper.Query <T>(
                procName, System.Data.CommandType.StoredProcedure, dbParams.ToArray(), _rowMapper, new string[] { "@TotalRows" });

            // Set the total records.
            totalRecords = (int)result.Second["@TotalRows"];
            return(result.First);
        }
Esempio n. 10
0
        public void TestJoin()
        {
            var f     = FutureFactory.NewFuture <string>();
            var other = FutureFactory.NewFuture <int>();

            var f2 = f.Join <int>(other);

            f.SetResult("ok");
            Assert.False(f2.Done);
            other.SetResult(1);
            Assert.True(f2.Done);

            Tuple2 <string, int> r = f2.Result;

            Assert.Equals("ok", r.V1);
            Assert.Equals(1, r.V2);
        }
Esempio n. 11
0
        private List<Expr> ParseArgList(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "ArgList");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as List<Expr>;
            }

            int errorCount = Errors.Count;
            List<Expr> list_Expr = new List<Expr>();
            int start_position = position;

            MatchTerminal('(', out success);
            if (!success)
            {
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(list_Expr, success, position);return list_Expr;
            }

            ParseSpOpt(out success);

            while (true)
            {
                int seq_start_position1 = position;
                list_Expr = ParseExprList(out success);
                if (!success) { break; }

                ParseSpOpt(out success);
                break;
            }
            success = true;

            MatchTerminal(')', out success);
            if (!success)
            {
                Error("Failed to parse ')' of ArgList.");
                position = start_position;
            }

            if (success) { ClearError(errorCount); }
            ParsingResults[reskey] = new Tuple3<object, bool, int>(list_Expr, success, position);
            return list_Expr;
        }
 public void putMessageOnQueue(AudioClip audioClip, float delay = 0f)
 {
     // Is the clip already in queue a "generic announcement"?
     Debug.Log("Queue length: " + queue.Count);
     if (queue.Count > 0)
     {
         Tuple2 <float, AudioClip> firstInQueue = queue.First <Tuple2 <float, AudioClip> >();
         Debug.Log("First announcement in queue: " + firstInQueue.Second.name);
         if (firstInQueue.Second.name.StartsWith(GENERIC_ANNOUNCEMENT_PREFIX))
         {
             queue.Remove(firstInQueue);
             Debug.Log("Removed generic announcement from queue!");
         }
     }
     Debug.Log("Adding announcement: " + audioClip.name);
     queue.Insert(0, new Tuple2 <float, AudioClip>(delay, audioClip));
 }
Esempio n. 13
0
        public void GenericCrossOver()
        {
            var a = new[] { 1, 2, 3, 4, 5 };
            var b = new[] { 10, 20, 30, 40, 50 };

            var z = Functions.CrossOver(a, b, (x, y) => Tuple2.Create(y, x), x => x.ToList());

            z.Item1.ShouldBeOfType <List <int> >();
            z.Item2.ShouldBeOfType <List <int> >();
            z.Item1.ShouldEnumerateLike(b);
            z.Item2.ShouldEnumerateLike(a);

            var q = Functions.CrossOver(a, b, (x, y) => x % 2 == 1 ? Tuple2.Create(x, y) : Tuple2.Create(y, x), x => x.ToList());

            q.Item1.ShouldEnumerateLike(Lists.Create(1, 20, 3, 40, 5));
            q.Item2.ShouldEnumerateLike(Lists.Create(10, 2, 30, 4, 50));
        }
Esempio n. 14
0
        /// <summary>
        /// Memoize a binary function
        /// </summary>
        /// <typeparam name="TArg1"></typeparam>
        /// <typeparam name="TArg2"></typeparam>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="function"></param>
        /// <returns></returns>
        public static Func <TArg1, TArg2, TResult> Memoize2 <TArg1, TArg2, TResult>(Func <TArg1, TArg2, TResult> function)
        {
            var results = new Dictionary <Tuple2 <TArg1, TArg2>, TResult>();

            return((k1, k2) => {
                lock (results) {
                    TResult value;
                    var tupleKey = new Tuple2 <TArg1, TArg2>(k1, k2);
                    if (results.TryGetValue(tupleKey, out value))
                    {
                        return value;
                    }

                    value = function(k1, k2);
                    results.Add(tupleKey, value);
                    return value;
                }
            });
        }
Esempio n. 15
0
        /// <summary>
        /// Get recents posts by page.
        /// </summary>
        /// <param name="pageNumber">Page number.</param>
        /// <param name="pageSize">Page size.</param>
        /// <returns>List with matching records.</returns>
        public override PagedList <T> FindRecent(int pageNumber, int pageSize)
        {
            string             procName = TableName + "_GetRecent";
            List <DbParameter> dbParams = new List <DbParameter>();

            // Build input params to procedure.
            dbParams.Add(_db.BuildInParam("@PageIndex", System.Data.DbType.Int32, pageNumber));
            dbParams.Add(_db.BuildInParam("@PageSize", System.Data.DbType.Int32, pageSize));
            dbParams.Add(_db.BuildOutParam("@TotalRows", System.Data.DbType.Int32));

            Tuple2 <IList <T>, IDictionary <string, object> > result = _db.Query <T>(
                procName, System.Data.CommandType.StoredProcedure, dbParams.ToArray(), _rowMapper, new string[] { "@TotalRows" });

            // Set the total records.
            int           totalRecords = (int)result.Second["@TotalRows"];
            PagedList <T> pagedList    = new PagedList <T>(pageNumber, pageSize, totalRecords, result.First);

            return(pagedList);
        }
    public void run()
    {
        // First, try to lookup book author + title in person
        Person person = GetComponent <BagContentProperties>().person;
        Tuple2 <string, string> randomBook = person.getRandomBook();

        if (randomBook == null)
        {
            randomBook = ItsRandom.pickRandom(GenericBookText.books);
        }

        foreach (TextMeshPro author in authors)
        {
            author.text = randomBook.First;
        }
        foreach (TextMeshPro title in titles)
        {
            title.text = randomBook.Second;
        }
    }
Esempio n. 17
0
        /// <summary>
        /// Map the ini file
        /// </summary>
        /// <param name="errors">The errors.</param>
        /// <returns></returns>
        public IList <T> Map(IErrors errors)
        {
            IList <T> items = new List <T>();

            // Check inputs.
            if (_data == null || _data.Count == 0)
            {
                return(items);
            }

            int counter        = 0;
            var propMapDefault = ReflectionUtils.GetPropertiesAsMap <T>(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, false);

            foreach (DictionaryEntry entry in _data)
            {
                // Represents single object.
                if (entry.Value is IDictionary)
                {
                    Tuple2 <T, IDictionary <string, PropertyInfo> > tuple = GetNewObjectAndPropertyMapAsTuple((IDictionary)entry.Value, propMapDefault);
                    MapperHelper.MapTo <T>(tuple.First, counter, tuple.Second, entry.Value as IDictionary);
                    items.Add(tuple.First);
                    counter++;
                }
                // Multiple sections with the same name ( "post", "post" )
                else if (entry.Value is List <object> )
                {
                    List <object> sections = entry.Value as List <object>;
                    foreach (object section in sections)
                    {
                        if (section is IDictionary)
                        {
                            Tuple2 <T, IDictionary <string, PropertyInfo> > tuple = GetNewObjectAndPropertyMapAsTuple((IDictionary)section, propMapDefault);
                            MapperHelper.MapTo <T>(tuple.First, counter, tuple.Second, section as IDictionary);
                            items.Add(tuple.First);
                            counter++;
                        }
                    }
                }
            }
            return(items);
        }
Esempio n. 18
0
		private Tuple2<string, int> DoGetFileLine(MethodDefinition method, int offset)
		{
			Tuple2<string, int> result = Tuple.Make("<unknown>", -1);

			if (method.Body != null) 
			{
				Instruction instruction = DoFindInstruction(method, offset);
				if (instruction != null)
				{
					while (instruction != null && instruction.SequencePoint == null)
						instruction = instruction.Next;
					
					if (instruction != null)			// unfortunately it's fairly common for methods to have no sequence point
					{
						SequencePoint spt = instruction.SequencePoint;
						string url = spt.Document != null ? spt.Document.Url : null;
						result = Tuple.Make(url ?? "<unknown>", spt.StartLine);		// TODO: maybe StartColumn too
					}
				}
			}
						
			return result;
		}
Esempio n. 19
0
        public void MixtureCrossover()
        {
            var db         = new Database(TestHelpers.GetCleanDatabase());
            var protoChrom = Initialization.MakeProtoChromosome();
            var protoRun   = new ProtoRun(db, "MixtureCrossoverTest", -1, protoChrom, 2, 6, 4, 10, 0.05);
            var run        = new Run(protoRun, protoChrom);
            var seed       = MakeTrainingSet(db, "11/11/2001", "12/11/2001");
            var gen        = Initialization.MakeInitialGeneration(seed, run, new LocalParallelTrainer());

            gen.Mixtures.Length.ShouldEqual(2);
            var m1 = gen.Mixtures[0];
            var m2 = gen.Mixtures[1];

            var prev = Tuple2.Create(m1.Chromosomes, m2.Chromosomes);
            var cmis = Functions.CombineTwoMixtures(gen.Mixtures.Select(m => new MixtureEval(m, 1)).ToList());
            var curr = Tuple2.Create(cmis.Item1.Chromosomes, cmis.Item2.Chromosomes);

            for (int i = 0; i < m1.Chromosomes.Length; i++)
            {
                AssertIsCrossedOverVersionOf(Tuple2.Create(curr.Item1[i], curr.Item2[i]),
                                             Tuple2.Create(prev.Item1[i], prev.Item2[i]));
            }
        }
Esempio n. 20
0
    public static IEnumerator ZoomWithAmount(float amount, float time, Vector3?zoomPoint = null)
    {
        bool  hasPerspective = perspectiveCamera != null;
        float t = 0f;

        while (t <= 1f)
        {
            t += Time.deltaTime / time;
            float targetZoom = main.orthographicSize + Mathf.SmoothStep(0f, amount, t);
            // TODO - Clamp?
            if (amount > 0f)
            {
                targetZoom = Mathf.Min(targetZoom, MIN_ZOOM_LEVEL_ORTHOGRAPHIC);
            }
            else
            {
                targetZoom = Mathf.Max(targetZoom, MAX_ZOOM_LEVEL_ORTHOGRAPHIC);
            }
            float zoomDelta = main.orthographicSize - targetZoom;
            main.orthographicSize = targetZoom;

            if (hasPerspective)
            {
                perspectiveCamera.fieldOfView = GetPerspectiveForOrthographicSize(targetZoom);
            }

            // Try to zoom in towards a specific point
            Tuple2 <float, float> offsetPctFromCenter = Misc.getOffsetPctFromCenter(zoomPoint ?? new Vector3(Screen.width / 2f, Screen.height / 2f, 0f));
            float   xZoomRatio     = Misc.GetWidthRatio();
            float   yZoomRatio     = Misc.GetHeightRatio();
            Vector3 zoomOffsetMove = new Vector3((zoomDelta * xZoomRatio) * offsetPctFromCenter.First, (zoomDelta * yZoomRatio) * offsetPctFromCenter.Second, 0f);
            Singleton <SingletonInstance> .Instance.StartCoroutine(MoveWithVector(zoomOffsetMove, 0f, false));

            yield return(t);
        }
    }
Esempio n. 21
0
        static void AssertIsCrossedOverVersionOf(Tuple2 <Chromosome> curr, Tuple2 <Chromosome> prev)
        {
            var a1 = curr.Item1;
            var b1 = curr.Item2;
            var a0 = prev.Item1;
            var b0 = prev.Item2;

            Trace.WriteLine("");
            Trace.WriteLine("a0: " + a0);
            Trace.WriteLine("a1: " + a1);
            Trace.WriteLine("b0: " + b0);
            Trace.WriteLine("b1: " + b1);

            a1.ShouldNotLookLike(a0);
            b1.ShouldNotLookLike(b0);

            Lists.Repeat(a1.Genes.Length, i => {
                var a1g = a1.Genes[i];
                var b1g = b1.Genes[i];
                var a0g = a0.Genes[i];
                var b0g = b0.Genes[i];

                if (a1g.LooksLike(a0g))
                {
                    b1g.ShouldLookLike(b0g);
                }
                else if (a1g.LooksLike(b0g))
                {
                    b1g.ShouldLookLike(a0g);
                }
                else
                {
                    Assert.Fail("gene was mutated??");
                }
            });
        }
Esempio n. 22
0
    public void setConfig(Tuple2 <XmlDocument, Texture2D> personConfig)
    {
        config = new PersonConfig(personConfig.First, personConfig.Second);

        // Decide person characteristics
        personUniqueId  = config.id;
        personName      = config.name;
        nationality     = config.nationality;
        dateOfBirth     = config.dob;
        idPhrase        = config.idPhrase;
        photo           = config.photoTexture;
        voice           = config.voice;
        bodyColor       = config.bodyColor;
        favouriteColor  = config.favouriteColor;
        favouriteColor2 = config.favouriteColor2;

        if (Person.HasInstantiatedPerson)
        {
            chosenFavoriteColor = pickFavouriteColorWithBiggestDistance(favouriteColor, favouriteColor2, Person.LastPerson.getFavouriteColor());
        }
        else
        {
            chosenFavoriteColor = favouriteColor;
        }

        Person.LastPerson            = this;
        Person.HasInstantiatedPerson = true;

        books = config.personBooksConfig.books.GetRange(0, config.personBooksConfig.books.Count);

        /*
         * Dictionary<string, Dictionary<string, float>> probabilityMap = new Dictionary<string, Dictionary<string, float>>() {
         *  {"clothing", new Dictionary<string, float>() {
         *          {"briefs", 1f},
         *          {"panties", 0.1f},
         *          {"bras", 0.5f},
         *          {"shirts", 0.4f},
         *          {"jeans", 0.4f},
         *          {"dress", 0.01f},
         *          {"skirt", 0.01f},
         *          {"socks", 0.9f},
         *          {"hat", 0.05f},
         *          {"cap", 0.05f},
         *          {"slippers", 0.05f},
         *          {"shoes", 0.05f},
         *          {"gloves", 0.05f},
         *      }
         *  },
         *  {"pills", new Dictionary<string, float>() {
         *          {"allergies", 1f},
         *          {"moreThanOne", 0f},
         *          {"smuggler", 0.01f}
         *      }
         *  },
         *  {"weapons", new Dictionary<string, float>() {
         *          {"risk", 1f},
         *          {"riskGun", 1f},
         *          {"riskKnife", 1f}
         *      }
         *  },
         *  // Computers, mobile phone material
         *  {"displays", new Dictionary<string, float>() {
         *          {"piracy", 0.2f},
         *          {"worried", 0.5f},
         *          {"noob", 0.3f}
         *      }
         *  },
         *  {"personality", new Dictionary<string, float>() {
         *          {"rude", 0.2f},
         *          {"polite", 0.4f},
         *          {"impatient", 0.3f},
         *      }
         *  }
         * };
         */

        // Load information on audio clips
        clips = Resources.LoadAll <AudioClip>("voice/" + voice).ToList();
        // Greeting
        // Some people don't say greeting - in those cases, pretend we've already greeted
        // haveSaidGreeting = ItsRandom.randomBool(personRandom); // TODO
        haveSaidGreeting = false;
    }
Esempio n. 23
0
        private Chunk ParseChunk(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "Chunk");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as Chunk;
            }

            int errorCount = Errors.Count;
            Chunk chunk = new Chunk();
            int start_position = position;

            ParseSpOpt(out success);

            while (true)
            {
                while (true)
                {
                    int seq_start_position1 = position;
                    Statement statement = ParseStatement(out success);
                    if (success) { chunk.Statements.Add(statement); }
                    else { break; }

                    while (true)
                    {
                        int seq_start_position2 = position;
                        MatchTerminal(';', out success);
                        if (!success) { break; }

                        ParseSpOpt(out success);
                        break;
                    }
                    success = true;
                    break;
                }
                if (!success) { break; }
            }
            success = true;

            ParsingResults[reskey] = new Tuple3<object, bool, int>(chunk, success, position);
            return chunk;
        }
Esempio n. 24
0
        private BoolLiteral ParseBoolLiteral(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "BoolLiteral");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as BoolLiteral;
            }

            int errorCount = Errors.Count;
            ErrorStatck.Push(errorCount); errorCount = Errors.Count;
            BoolLiteral boolLiteral = new BoolLiteral();

            while (true)
            {
                boolLiteral.Text = MatchTerminalString("true", out success);
                if (success) { ClearError(errorCount); break; }

                boolLiteral.Text = MatchTerminalString("false", out success);
                if (success) { ClearError(errorCount); break; }

                break;
            }
            errorCount = ErrorStatck.Pop();
            if (success) { ClearError(errorCount); }
            else { Error("Failed to parse Text of BoolLiteral."); }
            ParsingResults[reskey] = new Tuple3<object, bool, int>(boolLiteral, success, position);
            return boolLiteral;
        }
Esempio n. 25
0
        private VariableArg ParseVariableArg(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "VariableArg");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as VariableArg;
            }

            int errorCount = Errors.Count;
            VariableArg variableArg = new VariableArg();

            variableArg.Name = MatchTerminalString("...", out success);
            if (success) { ClearError(errorCount); }
            else { Error("Failed to parse Name of VariableArg."); }
            ParsingResults[reskey] = new Tuple3<object, bool, int>(variableArg, success, position);
            return variableArg;
        }
Esempio n. 26
0
        private string ParseUnaryOperator(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "UnaryOperator");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as string;
            }

            int errorCount = Errors.Count;
            StringBuilder text = new StringBuilder();

            char ch = MatchTerminal('#', out success);
            if (success)
            {
                ClearError(errorCount);
                text.Append(ch);
                ParsingResults[reskey] = new Tuple3<object, bool, int>(text.ToString(), success, position);return text.ToString();
            }

            ch = MatchTerminal('-', out success);
            if (success)
            {
                ClearError(errorCount);
                text.Append(ch);
                ParsingResults[reskey] = new Tuple3<object, bool, int>(text.ToString(), success, position);return text.ToString();
            }

            string str = MatchTerminalString("not", out success);
            if (success)
            {
                ClearError(errorCount);
                text.Append(str);
                ParsingResults[reskey] = new Tuple3<object, bool, int>(text.ToString(), success, position);return text.ToString();
            }

            return text.ToString();
        }
Esempio n. 27
0
        private DoStmt ParseDoStmt(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "DoStmt");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as DoStmt;
            }

            int errorCount = Errors.Count;
            DoStmt doStmt = new DoStmt();
            int start_position = position;

            MatchTerminalString("do", out success);
            if (!success)
            {
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(doStmt, success, position);return doStmt;
            }

            ParseSpReq(out success);
            if (!success)
            {
                Error("Failed to parse SpReq of DoStmt.");
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(doStmt, success, position);return doStmt;
            }

            doStmt.Body = ParseChunk(out success);
            if (!success)
            {
                Error("Failed to parse Body of DoStmt.");
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(doStmt, success, position);return doStmt;
            }

            MatchTerminalString("end", out success);
            if (!success)
            {
                Error("Failed to parse 'end' of DoStmt.");
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(doStmt, success, position);return doStmt;
            }

            ParseSpReq(out success);
            if (!success)
            {
                Error("Failed to parse SpReq of DoStmt.");
                position = start_position;
            }

            if (success) { ClearError(errorCount); }
            ParsingResults[reskey] = new Tuple3<object, bool, int>(doStmt, success, position);
            return doStmt;
        }
Esempio n. 28
0
        public void ConnectSubDendritesToOtherSubDendrites()
        {
            var nodelist = new Dictionary <int, List <DendriteNode> >();

            foreach (int index in NotMergedSubDendritesIdx)
            {
                List <DendriteNode> node = sub_dendrites[index].GetEdgeNodeAndBranchNodes();
                nodelist.Add(index, node);
            }

            DendriteNode masterNode = null;
            DendriteNode slaveNode  = null;

            var cache = new Dictionary <Tuple2, NodeIndexer>();

            while (true)
            {
                // masterとslaveの距離をあらかじめ計算しておいて配列に保存し、ソートしておくことで
                // 高速に計算できるが、需要がないようなので後回しにする。
                // 配列に保存するのは距離がdistanceThreashold以下のものだけにしないとメモリが足りないと思います。
                // Masterがどこかのノードに吸収されるかもしれないので、
                // UnionFind木で管理しておきましょう

                int    masterIndex = 0;
                int    slaveIndex  = 0;
                double min         = Double.MaxValue;

                foreach (int master in NotMergedSubDendritesIdx)
                {
                    for (int master2 = 0; master2 < nodelist[master].Count; master2++)
                    {
                        var dictKey = new Tuple2(master, master2);
                        if (cache.ContainsKey(dictKey) == false || nodelist[cache[dictKey].ClusterIdx].Count == 0)
                        {
                            foreach (int slave in NotMergedSubDendritesIdx)
                            {
                                if (master == slave)
                                {
                                    continue;
                                }
                                for (int slave2 = 0; slave2 < nodelist[slave].Count; slave2++)
                                {
                                    double tmpdist = nodelist[master][master2].EuclideanDistanceTo(nodelist[slave][slave2]);

                                    // キャッシュがなかった場合は新しく追加
                                    if (cache.ContainsKey(dictKey) == false)
                                    {
                                        cache.Add(dictKey, new NodeIndexer(tmpdist, slave, slave2));
                                    }
                                    // キャッシュしていたノードが他のノードに併合されたパターン
                                    else if (nodelist[cache[dictKey].ClusterIdx].Count == 0)
                                    {
                                        cache[dictKey] = new NodeIndexer(tmpdist, slave, slave2);
                                    }
                                    // 再探索時に、キャッシュしていたノードよりも近いノードを見つけた場合には、キャッシュしている値を変更する
                                    else if (cache[dictKey].Norm >= tmpdist)
                                    {
                                        cache[dictKey] = new NodeIndexer(tmpdist, slave, slave2);
                                    }

                                    if (min >= tmpdist)
                                    {
                                        min         = tmpdist;
                                        masterNode  = nodelist[slave][slave2];
                                        slaveNode   = nodelist[master][master2];
                                        masterIndex = master;
                                        slaveIndex  = slave;
                                    }
                                }
                            }
                        }
                        // キャッシュが存在した場合はそれを利用
                        else
                        {
                            NodeIndexer nodeIndex = cache[dictKey];
                            double      tmpdist   = nodeIndex.Norm;
                            int         slave     = nodeIndex.ClusterIdx;
                            int         slave2    = nodeIndex.NodeIdx;
                            if (min >= tmpdist)
                            {
                                min         = tmpdist;
                                masterNode  = nodelist[slave][slave2];
                                slaveNode   = nodelist[master][master2];
                                masterIndex = master;
                                slaveIndex  = slave;
                            }
                        }
                    }
                }

                if (min <= param.distanceThreshold)
                {
                    //連結ノードにお互いを追加
                    masterNode.AddConnectedNode(slaveNode);
                    slaveNode.AddConnectedNode(masterNode);

                    //連結したサブノードリストはメインノードリストに吸収
                    nodelist[masterIndex].AddRange(nodelist[slaveIndex]);

                    //サブを消去
                    nodelist[slaveIndex].Clear();

                    // マージされた
                    NotMergedSubDendritesIdx.Remove(slaveIndex);
                    sub_dendrites_volume[masterIndex] += sub_dendrites_volume[slaveIndex];
                    sub_dendrites_volume[slaveIndex]   = 0;
                }
                else
                {
                    break;
                }
            }

            foreach (int index in NotMergedSubDendritesIdx)
            {
                if (nodelist[index].Count > 0)
                {
                    Dendrite node = sub_dendrites[index];
                    var      edge = node.GetEdgeNodes();
                    node.ChangeRootNode(edge.Last());
                }
            }
        }
Esempio n. 29
0
        private Term ParseTerm(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "Term");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as Term;
            }

            int errorCount = Errors.Count;
            Term term = null;

            term = ParseNilLiteral(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(term, success, position);return term; }

            term = ParseBoolLiteral(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(term, success, position);return term; }

            term = ParseNumberLiteral(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(term, success, position);return term; }

            term = ParseStringLiteral(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(term, success, position);return term; }

            term = ParseFunctionValue(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(term, success, position);return term; }

            term = ParseTableConstructor(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(term, success, position);return term; }

            term = ParseVariableArg(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(term, success, position);return term; }

            term = ParsePrimaryExpr(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(term, success, position);return term; }

            return term;
        }
Esempio n. 30
0
        private ElseifBlock ParseElseifBlock(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "ElseifBlock");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as ElseifBlock;
            }

            int errorCount = Errors.Count;
            ElseifBlock elseifBlock = new ElseifBlock();
            int start_position = position;

            MatchTerminalString("elseif", out success);
            if (!success)
            {
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(elseifBlock, success, position);return elseifBlock;
            }

            ParseSpReq(out success);
            if (!success)
            {
                Error("Failed to parse SpReq of ElseifBlock.");
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(elseifBlock, success, position);return elseifBlock;
            }

            elseifBlock.Condition = ParseExpr(out success);
            if (!success)
            {
                Error("Failed to parse Condition of ElseifBlock.");
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(elseifBlock, success, position);return elseifBlock;
            }

            MatchTerminalString("then", out success);
            if (!success)
            {
                Error("Failed to parse 'then' of ElseifBlock.");
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(elseifBlock, success, position);return elseifBlock;
            }

            ParseSpReq(out success);
            if (!success)
            {
                Error("Failed to parse SpReq of ElseifBlock.");
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(elseifBlock, success, position);return elseifBlock;
            }

            elseifBlock.ThenBlock = ParseChunk(out success);
            if (!success)
            {
                Error("Failed to parse ThenBlock of ElseifBlock.");
                position = start_position;
            }

            if (success) { ClearError(errorCount); }
            ParsingResults[reskey] = new Tuple3<object, bool, int>(elseifBlock, success, position);
            return elseifBlock;
        }
Esempio n. 31
0
        private Var ParseVar(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "Var");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as Var;
            }

            int errorCount = Errors.Count;
            Var var = new Var();
            int start_position = position;

            var.Base = ParseBaseExpr(out success);
            if (!success)
            {
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(var, success, position);return var;
            }

            while (true)
            {
                ErrorStatck.Push(errorCount); errorCount = Errors.Count;
                while (true)
                {
                    while (true)
                    {
                        int seq_start_position1 = position;
                        ParseSpOpt(out success);

                        NameAccess nameAccess = ParseNameAccess(out success);
                        if (success) { var.Accesses.Add(nameAccess); }
                        else
                        {
                            Error("Failed to parse NameAccess of Var.");
                            position = seq_start_position1;
                        }
                        break;
                    }
                    if (success) { ClearError(errorCount); break; }

                    while (true)
                    {
                        int seq_start_position2 = position;
                        ParseSpOpt(out success);

                        KeyAccess keyAccess = ParseKeyAccess(out success);
                        if (success) { var.Accesses.Add(keyAccess); }
                        else
                        {
                            Error("Failed to parse KeyAccess of Var.");
                            position = seq_start_position2;
                        }
                        break;
                    }
                    if (success) { ClearError(errorCount); break; }

                    break;
                }
                errorCount = ErrorStatck.Pop();
                if (!success) { break; }
            }
            success = true;

            ParsingResults[reskey] = new Tuple3<object, bool, int>(var, success, position);
            return var;
        }
Esempio n. 32
0
        private List<Expr> ParseExprList(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "ExprList");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as List<Expr>;
            }

            int errorCount = Errors.Count;
            List<Expr> list_Expr = new List<Expr>();
            int start_position = position;

            Expr expr = ParseExpr(out success);
            if (success) { list_Expr.Add(expr); }
            else
            {
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(list_Expr, success, position);return list_Expr;
            }

            while (true)
            {
                while (true)
                {
                    int seq_start_position1 = position;
                    ParseSpOpt(out success);

                    MatchTerminal(',', out success);
                    if (!success)
                    {
                        Error("Failed to parse ',' of ExprList.");
                        position = seq_start_position1;
                        break;
                    }

                    ParseSpOpt(out success);

                    expr = ParseExpr(out success);
                    if (success) { list_Expr.Add(expr); }
                    else
                    {
                        Error("Failed to parse Expr of ExprList.");
                        position = seq_start_position1;
                    }
                    break;
                }
                if (!success) { break; }
            }
            success = true;

            ParsingResults[reskey] = new Tuple3<object, bool, int>(list_Expr, success, position);
            return list_Expr;
        }
Esempio n. 33
0
        private VarName ParseVarName(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "VarName");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as VarName;
            }

            int errorCount = Errors.Count;
            VarName varName = new VarName();

            varName.Name = ParseName(out success);
            if (success) { ClearError(errorCount); }
            else { Error("Failed to parse Name of VarName."); }
            ParsingResults[reskey] = new Tuple3<object, bool, int>(varName, success, position);
            return varName;
        }
Esempio n. 34
0
        private Field ParseField(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "Field");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as Field;
            }

            int errorCount = Errors.Count;
            Field field = null;

            field = ParseKeyValue(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(field, success, position);return field; }

            field = ParseNameValue(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(field, success, position);return field; }

            field = ParseItemValue(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(field, success, position);return field; }

            return field;
        }
Esempio n. 35
0
        private BreakStmt ParseBreakStmt(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "BreakStmt");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as BreakStmt;
            }

            int errorCount = Errors.Count;
            BreakStmt breakStmt = new BreakStmt();
            int start_position = position;

            MatchTerminalString("break", out success);
            if (!success)
            {
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(breakStmt, success, position);return breakStmt;
            }

            ParseSpReq(out success);
            if (!success)
            {
                Error("Failed to parse SpReq of BreakStmt.");
                position = start_position;
            }

            if (success) { ClearError(errorCount); }
            ParsingResults[reskey] = new Tuple3<object, bool, int>(breakStmt, success, position);
            return breakStmt;
        }
Esempio n. 36
0
        private string ParseFoatNumber(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "FoatNumber");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as string;
            }

            int errorCount = Errors.Count;
            StringBuilder text = new StringBuilder();
            int start_position = position;

            int counter = 0;
            while (true)
            {
                char ch = ParseDigit(out success);
                if (success) { text.Append(ch); }
                else { break; }
                counter++;
            }
            if (counter > 0) { success = true; }
            if (!success)
            {
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(text.ToString(), success, position);return text.ToString();
            }

            while (true)
            {
                int seq_start_position1 = position;
                char ch = MatchTerminal('.', out success);
                if (success) { text.Append(ch); }
                else { break; }

                counter = 0;
                while (true)
                {
                    ch = ParseDigit(out success);
                    if (success) { text.Append(ch); }
                    else { break; }
                    counter++;
                }
                if (counter > 0) { success = true; }
                if (!success)
                {
                    Error("Failed to parse (Digit)+ of FoatNumber.");
                    position = seq_start_position1;
                }
                break;
            }
            success = true;

            while (true)
            {
                ErrorStatck.Push(errorCount); errorCount = Errors.Count;
                int seq_start_position2 = position;
                while (true)
                {
                    char ch = MatchTerminal('e', out success);
                    if (success)
                    {
                        ClearError(errorCount);
                        text.Append(ch);
                        break;
                    }

                    ch = MatchTerminal('E', out success);
                    if (success)
                    {
                        ClearError(errorCount);
                        text.Append(ch);
                        break;
                    }

                    break;
                }
                errorCount = ErrorStatck.Pop();
                if (!success) { break; }

                counter = 0;
                while (true)
                {
                    char ch = ParseDigit(out success);
                    if (success) { text.Append(ch); }
                    else { break; }
                    counter++;
                }
                if (counter > 0) { success = true; }
                if (!success)
                {
                    Error("Failed to parse (Digit)+ of FoatNumber.");
                    position = seq_start_position2;
                }
                break;
            }
            success = true;

            ParsingResults[reskey] = new Tuple3<object, bool, int>(text.ToString(), success, position);
            return text.ToString();
        }
Esempio n. 37
0
        private NumberLiteral ParseNumberLiteral(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "NumberLiteral");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as NumberLiteral;
            }

            int errorCount = Errors.Count;
            NumberLiteral numberLiteral = new NumberLiteral();

            numberLiteral.HexicalText = ParseHexicalNumber(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(numberLiteral, success, position);return numberLiteral; }

            numberLiteral.Text = ParseFoatNumber(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(numberLiteral, success, position);return numberLiteral; }

            return numberLiteral;
        }
Esempio n. 38
0
 public bool Equals(Tuple2 <T1, T2> other)
 {
     return(this == other);
 }
Esempio n. 39
0
        private string ParseDoubleQuotedText(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "DoubleQuotedText");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as string;
            }

            int errorCount = Errors.Count;
            StringBuilder text = new StringBuilder();

            while (true)
            {
                ErrorStatck.Push(errorCount); errorCount = Errors.Count;
                while (true)
                {
                    char ch = MatchTerminalSet("\"\\", true, out success);
                    if (success)
                    {
                        ClearError(errorCount);
                        text.Append(ch);
                        break;
                    }

                    ch = ParseEscapeChar(out success);
                    if (success)
                    {
                        ClearError(errorCount);
                        text.Append(ch);
                        break;
                    }

                    break;
                }
                errorCount = ErrorStatck.Pop();
                if (!success) { break; }
            }
            success = true;
            ParsingResults[reskey] = new Tuple3<object, bool, int>(text.ToString(), success, position);
            return text.ToString();
        }
Esempio n. 40
0
        private OperatorExpr ParseOperatorExpr(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "OperatorExpr");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as OperatorExpr;
            }

            int errorCount = Errors.Count;
            OperatorExpr operatorExpr = new OperatorExpr();
            int start_position = position;

            while (true)
            {
                int seq_start_position1 = position;
                string unaryOper = ParseUnaryOperator(out success);
                if (success) { operatorExpr.Add(unaryOper); }
                else { break; }

                ParseSpOpt(out success);
                break;
            }
            success = true;

            Term firstTerm = ParseTerm(out success);
            if (success) { operatorExpr.Add(firstTerm); }
            else
            {
                Error("Failed to parse firstTerm of OperatorExpr.");
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(operatorExpr, success, position);return operatorExpr;
            }

            ParseSpOpt(out success);

            while (true)
            {
                while (true)
                {
                    int seq_start_position2 = position;
                    string binaryOper = ParseBinaryOperator(out success);
                    if (success) { operatorExpr.Add(binaryOper); }
                    else { break; }

                    ParseSpOpt(out success);

                    Term nextTerm = ParseTerm(out success);
                    if (success) { operatorExpr.Add(nextTerm); }
                    else
                    {
                        Error("Failed to parse nextTerm of OperatorExpr.");
                        position = seq_start_position2;
                        break;
                    }

                    ParseSpOpt(out success);
                    break;
                }
                if (!success) { break; }
            }
            success = true;

            ParsingResults[reskey] = new Tuple3<object, bool, int>(operatorExpr, success, position);
            return operatorExpr;
        }
Esempio n. 41
0
        private Expr ParseExpr(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "Expr");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as Expr;
            }

            int errorCount = Errors.Count;
            Expr expr = null;

            expr = ParseOperatorExpr(out success);
            if (success) { return expr.Simplify(); }

            expr = ParseTerm(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(expr, success, position);return expr; }

            return expr;
        }
Esempio n. 42
0
        private ParamList ParseParamList(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "ParamList");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as ParamList;
            }

            int errorCount = Errors.Count;
            ParamList paramList = new ParamList();

            while (true)
            {
                int seq_start_position1 = position;
                paramList.NameList = ParseNameList(out success);
                if (!success) { break; }

                while (true)
                {
                    int seq_start_position2 = position;
                    MatchTerminal(',', out success);
                    if (!success) { break; }

                    ParseSpOpt(out success);

                    MatchTerminalString("...", out success);
                    if (!success)
                    {
                        Error("Failed to parse '...' of ParamList.");
                        position = seq_start_position2;
                    }
                    break;
                }
                paramList.HasVarArg = success;
                success = true;
                break;
            }
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(paramList, success, position);return paramList; }

            paramList.IsVarArg = MatchTerminalString("...", out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(paramList, success, position);return paramList; }

            return paramList;
        }
Esempio n. 43
0
        private ExprStmt ParseExprStmt(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "ExprStmt");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as ExprStmt;
            }

            int errorCount = Errors.Count;
            ExprStmt exprStmt = new ExprStmt();

            exprStmt.Expr = ParseExpr(out success);
            if (success) { ClearError(errorCount); }
            else { Error("Failed to parse Expr of ExprStmt."); }
            ParsingResults[reskey] = new Tuple3<object, bool, int>(exprStmt, success, position);
            return exprStmt;
        }
Esempio n. 44
0
        private PrimaryExpr ParsePrimaryExpr(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "PrimaryExpr");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as PrimaryExpr;
            }

            int errorCount = Errors.Count;
            PrimaryExpr primaryExpr = new PrimaryExpr();
            int start_position = position;

            primaryExpr.Base = ParseBaseExpr(out success);
            if (!success)
            {
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(primaryExpr, success, position);return primaryExpr;
            }

            while (true)
            {
                while (true)
                {
                    int seq_start_position1 = position;
                    ParseSpOpt(out success);

                    Access access = ParseAccess(out success);
                    if (success) { primaryExpr.Accesses.Add(access); }
                    else
                    {
                        Error("Failed to parse Access of PrimaryExpr.");
                        position = seq_start_position1;
                    }
                    break;
                }
                if (!success) { break; }
            }
            success = true;

            ParsingResults[reskey] = new Tuple3<object, bool, int>(primaryExpr, success, position);
            return primaryExpr;
        }
Esempio n. 45
0
        private List<Field> ParseFieldList(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "FieldList");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as List<Field>;
            }

            int errorCount = Errors.Count;
            List<Field> list_Field = new List<Field>();
            int start_position = position;

            Field field = ParseField(out success);
            if (success) { list_Field.Add(field); }
            else
            {
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(list_Field, success, position);return list_Field;
            }

            while (true)
            {
                while (true)
                {
                    int seq_start_position1 = position;
                    ParseFieldSep(out success);
                    if (!success) { break; }

                    ParseSpOpt(out success);

                    field = ParseField(out success);
                    if (success) { list_Field.Add(field); }
                    else
                    {
                        Error("Failed to parse Field of FieldList.");
                        position = seq_start_position1;
                    }
                    break;
                }
                if (!success) { break; }
            }
            success = true;

            while (true)
            {
                int seq_start_position2 = position;
                ParseFieldSep(out success);
                if (!success) { break; }

                ParseSpOpt(out success);
                break;
            }
            success = true;

            ParsingResults[reskey] = new Tuple3<object, bool, int>(list_Field, success, position);
            return list_Field;
        }
Esempio n. 46
0
        private RepeatStmt ParseRepeatStmt(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "RepeatStmt");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as RepeatStmt;
            }

            int errorCount = Errors.Count;
            RepeatStmt repeatStmt = new RepeatStmt();
            int start_position = position;

            MatchTerminalString("repeat", out success);
            if (!success)
            {
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(repeatStmt, success, position);return repeatStmt;
            }

            ParseSpReq(out success);
            if (!success)
            {
                Error("Failed to parse SpReq of RepeatStmt.");
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(repeatStmt, success, position);return repeatStmt;
            }

            repeatStmt.Body = ParseChunk(out success);
            if (!success)
            {
                Error("Failed to parse Body of RepeatStmt.");
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(repeatStmt, success, position);return repeatStmt;
            }

            MatchTerminalString("until", out success);
            if (!success)
            {
                Error("Failed to parse 'until' of RepeatStmt.");
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(repeatStmt, success, position);return repeatStmt;
            }

            ParseSpReq(out success);
            if (!success)
            {
                Error("Failed to parse SpReq of RepeatStmt.");
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(repeatStmt, success, position);return repeatStmt;
            }

            repeatStmt.Condition = ParseExpr(out success);
            if (!success)
            {
                Error("Failed to parse Condition of RepeatStmt.");
                position = start_position;
            }

            if (success) { ClearError(errorCount); }
            ParsingResults[reskey] = new Tuple3<object, bool, int>(repeatStmt, success, position);
            return repeatStmt;
        }
Esempio n. 47
0
        private Args ParseArgs(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "Args");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as Args;
            }

            int errorCount = Errors.Count;
            Args args = new Args();

            args.ArgList = ParseArgList(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(args, success, position);return args; }

            args.String = ParseStringLiteral(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(args, success, position);return args; }

            args.Table = ParseTableConstructor(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(args, success, position);return args; }

            return args;
        }
Esempio n. 48
0
        private ReturnStmt ParseReturnStmt(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "ReturnStmt");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as ReturnStmt;
            }

            int errorCount = Errors.Count;
            ReturnStmt returnStmt = new ReturnStmt();
            int start_position = position;

            MatchTerminalString("return", out success);
            if (!success)
            {
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(returnStmt, success, position);return returnStmt;
            }

            ParseSpReq(out success);
            if (!success)
            {
                Error("Failed to parse SpReq of ReturnStmt.");
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(returnStmt, success, position);return returnStmt;
            }

            returnStmt.ExprList = ParseExprList(out success);
            success = true;

            ParsingResults[reskey] = new Tuple3<object, bool, int>(returnStmt, success, position);
            return returnStmt;
        }
 public Recursive <Tuple2 <A, B> > wrap2 <B>(B b)
 {
     return(Recursive.a(Tuple2.a(value, b)));
 }
Esempio n. 50
0
        private Statement ParseStatement(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "Statement");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as Statement;
            }

            int errorCount = Errors.Count;
            Statement statement = null;

            statement = ParseAssignment(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(statement, success, position);return statement; }

            statement = ParseFunction(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(statement, success, position);return statement; }

            statement = ParseLocalVar(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(statement, success, position);return statement; }

            statement = ParseLocalFunc(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(statement, success, position);return statement; }

            statement = ParseReturnStmt(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(statement, success, position);return statement; }

            statement = ParseBreakStmt(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(statement, success, position);return statement; }

            statement = ParseDoStmt(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(statement, success, position);return statement; }

            statement = ParseIfStmt(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(statement, success, position);return statement; }

            statement = ParseForStmt(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(statement, success, position);return statement; }

            statement = ParseForInStmt(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(statement, success, position);return statement; }

            statement = ParseWhileStmt(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(statement, success, position);return statement; }

            statement = ParseRepeatStmt(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(statement, success, position);return statement; }

            statement = ParseExprStmt(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(statement, success, position);return statement; }

            return statement;
        }
Esempio n. 51
0
 public bool Equals(Tuple2 <A, B> other)
 {
     return(Equals(other.first, first) && Equals(other.second, second));
 }
Esempio n. 52
0
    // Returns a sequence of block movements
    public static List <Tuple2 <Tuple3 <int> > > AStar(Maze m, HeuristicMode hm)
    {
        HeuristicDelegate heuristic = null;

        switch (hm)
        {
        case HeuristicMode.Misplaced:
            heuristic = new HeuristicDelegate(Heuristic.Misplaced);
            break;

        case HeuristicMode.MisplacedManhattan:
            heuristic = new HeuristicDelegate(Heuristic.MisplacedManhattan);
            break;
        }

        // Set up current and target maps
        Block[, ,] currentMaze = m.GetBlockMaze();
        bool[, ,] currentMap   = new bool[currentMaze.GetLength(0), currentMaze.GetLength(1), currentMaze.GetLength(2)];
        bool[, ,] targetMap    = m.GetBlockMap();

        for (int i = 0; i < currentMap.GetLength(0); ++i)
        {
            for (int j = 0; j < currentMap.GetLength(1); ++j)
            {
                for (int k = 0; k < currentMap.GetLength(2); ++k)
                {
                    // If it's a block, check if there is no block in target
                    if (currentMaze [i, j, k] == null)
                    {
                        currentMap [i, j, k] = true;
                    }
                }
            }
        }

        // Set up leaves datastruct
        SortedDictionary <int, List <TreeNode <bool[, , ]> > > leaves = new SortedDictionary <int, List <TreeNode <bool[, , ]> > >();

        leaves.Add(heuristic(currentMap, targetMap), new List <TreeNode <bool[, , ]> > {
            new TreeNode <bool[, , ]> (currentMap)
        });

        // Perform A*
        while (leaves.Count > 0)
        {
            // Pop lowest key off leaves, q
            KeyValuePair <int, List <TreeNode <bool[, , ]> > > kvp = leaves.First();
            int qKey = kvp.Key;
            TreeNode <bool[, , ]> node = kvp.Value[0];
            leaves [qKey].RemoveAt(0);

            // If that key# is empty, remove
            if (leaves [qKey].Count == 0)
            {
                leaves.Remove(qKey);
            }

            // Check if goal is reached
            if (Util.MazeMapEquals(node.value, targetMap))
            {
                // Generate path of moves and return
                List <Tuple2 <Tuple3 <int> > > moves = new List <Tuple2 <Tuple3 <int> > >();

                while (node.parent != null)
                {
                    Tuple3 <int>           from = node.changeFrom;
                    Tuple3 <int>           to   = node.changeTo;
                    Tuple2 <Tuple3 <int> > move = new Tuple2 <Tuple3 <int> > (from, to);
                    moves.Add(move);
                    node = node.parent;
                }
                return(moves);
            }

            // Generate q's children
            int childrenCount = 0;
            for (int x = 0; x < node.value.GetLength(0); ++x)
            {
                for (int y = 0; y < node.value.GetLength(1); ++y)
                {
                    for (int z = 0; z < node.value.GetLength(2); ++z)
                    {
                        // If it's a block, check for spaces around it
                        if (!node.value [x, y, z])
                        {
                            List <Tuple3 <int> > children = m.GetSpaceNeighbours(x, y, z, node.value);

                            // Attach parent to children treenode and add to leaves while calculating their heuristic value
                            for (int i = 0; i < children.Count; ++i)
                            {
                                // Get childmap by swapping the block with the space
                                bool[, ,] childMap = Util.CopyMap(node.value);
                                childMap [x, y, z] = true;
                                childMap [children [i].first, children [i].second, children [i].third] = false;

                                // Attach parent to children and add to leaves with heuristic
                                Tuple3 <int>          changeFrom = new Tuple3 <int>(x, y, z);
                                Tuple3 <int>          changeTo   = new Tuple3 <int>(children [i].first, children [i].second, children [i].third);
                                TreeNode <bool[, , ]> child      = new TreeNode <bool[, , ]> (childMap, node, changeFrom, changeTo);
                                int heuristicValue = heuristic(child.value, targetMap) + child.level;
                                if (leaves.ContainsKey(heuristicValue))
                                {
                                    leaves [heuristicValue].Add(child);
                                }
                                else
                                {
                                    leaves.Add(heuristicValue, new List <TreeNode <bool[, , ]> > {
                                        child
                                    });
                                }
                                ++childrenCount;
                            }
                        }
                    }
                }
            }
            Console.Write(childrenCount);
        }
        return(null);
    }
Esempio n. 53
0
        private StringLiteral ParseStringLiteral(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "StringLiteral");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as StringLiteral;
            }

            int errorCount = Errors.Count;
            StringLiteral stringLiteral = new StringLiteral();

            while (true)
            {
                int seq_start_position1 = position;
                MatchTerminal('"', out success);
                if (!success) { break; }

                stringLiteral.Text = ParseDoubleQuotedText(out success);

                MatchTerminal('"', out success);
                if (!success)
                {
                    Error("Failed to parse '\\\"' of StringLiteral.");
                    position = seq_start_position1;
                }
                break;
            }
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(stringLiteral, success, position);return stringLiteral; }

            while (true)
            {
                int seq_start_position2 = position;
                MatchTerminal('\'', out success);
                if (!success) { break; }

                stringLiteral.Text = ParseSingleQuotedText(out success);

                MatchTerminal('\'', out success);
                if (!success)
                {
                    Error("Failed to parse ''' of StringLiteral.");
                    position = seq_start_position2;
                }
                break;
            }
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(stringLiteral, success, position);return stringLiteral; }

            stringLiteral.Text = ParseLongString(out success);
            if (success) { ClearError(errorCount); ParsingResults[reskey] = new Tuple3<object, bool, int>(stringLiteral, success, position);return stringLiteral; }

            return stringLiteral;
        }
Esempio n. 54
0
        private TableConstructor ParseTableConstructor(out bool success)
        {
            var reskey = new Tuple2<int, string>(position, "TableConstructor");
            if (ParsingResults.ContainsKey(reskey))
            {
                var parsingResult = ParsingResults[reskey];
                success = parsingResult.Item2;
                position = parsingResult.Item3;
                return parsingResult.Item1 as TableConstructor;
            }

            int errorCount = Errors.Count;
            TableConstructor tableConstructor = new TableConstructor();
            int start_position = position;

            MatchTerminal('{', out success);
            if (!success)
            {
                position = start_position;
                ParsingResults[reskey] = new Tuple3<object, bool, int>(tableConstructor, success, position);return tableConstructor;
            }

            ParseSpOpt(out success);

            tableConstructor.FieldList = ParseFieldList(out success);
            success = true;

            MatchTerminal('}', out success);
            if (!success)
            {
                Error("Failed to parse '}' of TableConstructor.");
                position = start_position;
            }

            if (success) { ClearError(errorCount); }
            ParsingResults[reskey] = new Tuple3<object, bool, int>(tableConstructor, success, position);
            return tableConstructor;
        }