protected override void SetupDependencies()
        {
            base.SetupDependencies();
            _streamId = Guid.NewGuid();
            _events = new[] {"event 1", "event 2", "event 3", "event 4", "event 5"};

            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();
                var trans = connection.BeginTransaction();
                var cmd = new SQLiteCommand("insert into EventStore (StreamId, Sequence, EventData) values (@StreamId, @Sequence, @EventData)") {Connection = connection, Transaction = trans};

                var sequenceGenerator = new SequenceGenerator(_streamId);

                cmd.Parameters.AddWithValue("@StreamId", _streamId);
                cmd.Parameters.Add("@Sequence", DbType.Int32);
                cmd.Parameters.Add("@EventData", DbType.Binary);

                foreach (var @event in _events)
                {
                    var stream = new MemoryStream();
                    _formatter.Serialize(stream, @event);
                    cmd.Parameters["@Sequence"].Value = sequenceGenerator.NextSequence();
                    cmd.Parameters["@EventData"].Value = stream.ToArray();
                    cmd.ExecuteNonQuery();
                }

                trans.Commit();
            }
        }
        public void SequenceGeneratorProducesVariationsWithoutRepetitionForMemebers()
        {
            var values = new []{1, 2};

            var sut = new SequenceGenerator();

            var actual = sut.GenerateMembers(values, 2);

            Assert.IsNotNull(actual);
            Assert.AreEqual(2, actual.Count());
            CollectionAssert.AreEquivalent(new []{1,2}, actual.ToList()[0].ToArray());
            CollectionAssert.AreEquivalent(new []{2,1}, actual.ToList()[1].ToArray());
        }
    // Use this for initialization
    void Start () {
		GameObject MainCamera = GameObject.Find("Main Camera");
		getInputFromUser = MainCamera.GetComponent<GetInputFromUser>();
		sequenceGenerator = MainCamera.GetComponent<SequenceGenerator> ();

		for (int i = letters.Length-1; i > -1; i--)
        {
          letters[i].transform.position = new Vector3(-200f,-200f,0);
        }

		//findLetterImage(p_1, p_2); //read char arrays from other script

    }
Exemple #4
0
        public async Task NextAsyncReturnsExpectedValueForZeroIncrement()
        {

            var stateProvider = GetStateProvider();

            var sequenceGenerator = new SequenceGenerator(stateProvider);

            var sequence = await CreateSequence(stateProvider,increment: 0, startAt: 5);

            var sequenceKey = await stateProvider.AddAsync(sequence);

            var nextValue1 = await sequenceGenerator.NextAsync(sequenceKey);

            var nextValue2 = await sequenceGenerator.NextAsync(sequenceKey);

            Assert.IsTrue(nextValue1 == 5);

            Assert.IsTrue(nextValue2 == 5);
        }
Exemple #5
0
        public async Task NextAsyncReturnsExpectedValue()
        {

            var stateProvider = GetStateProvider();

            var sequenceGenerator = new SequenceGenerator(stateProvider);

            var sequence = await CreateSequence(stateProvider);

            var sequenceKey = await  stateProvider.AddAsync(sequence);

            var nextValue1 = await sequenceGenerator.NextAsync(sequenceKey);

            var nextValue2 = await sequenceGenerator.NextAsync(sequenceKey);

            Assert.IsTrue(nextValue1 == 1);

            Assert.IsTrue(nextValue2 == 2);
        }
Exemple #6
0
        public static void FirstOnNameException()
        {
            Program.IntroLine(true, "First");
            Console.WriteLine("Heeft de reeks van customers en pakt de eerste customer van");
            Console.WriteLine("Omdat de customer niet te vinden is, zal de functie een exception gooien.");
            Program.WhiteLine();

            var stopwatch = new Stopwatch();

            stopwatch.Start();
            try
            {
                var customer = SequenceGenerator.Customers().First(c => c.Name.Contains("TEST123"));
                Console.WriteLine($"{customer.Id} | {customer.Name}");
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine(e);
            }

            stopwatch.Stop();
            Program.WhiteLine();
            Program.StopwatchLine(stopwatch.ElapsedMilliseconds);
        }
Exemple #7
0
        public LGSPSequenceGenerator(IGraphModel model, ActionsTypeInformation actionsTypeInformation,
                                     bool fireDebugEvents, bool emitProfiling)
        {
            this.model = model;

            this.actionNames = new ActionNames(actionsTypeInformation);

            this.env = new SequenceCheckingEnvironmentCompiled(actionNames, actionsTypeInformation, model);

            this.seqHelper = new SequenceGeneratorHelper(model, actionsTypeInformation, env);

            SequenceExpressionGenerator exprGen = new SequenceExpressionGenerator(model, env, seqHelper);

            this.seqHelper.SetSequenceExpressionGenerator(exprGen);

            SequenceComputationGenerator compGen = new SequenceComputationGenerator(model, env, exprGen, seqHelper, fireDebugEvents);

            this.seqGen = new SequenceGenerator(model, env, compGen, exprGen, seqHelper, fireDebugEvents, emitProfiling);

            this.neededEntitiesEmitter = new NeededEntitiesEmitter(seqHelper);

            this.fireDebugEvents = fireDebugEvents;
            this.emitProfiling   = emitProfiling;
        }
 public IClassBody WithMethods(SequenceGenerator <IMethod <IClassBody> > sequenceGenerator) => WithMultipleObjects(sequenceGenerator);
Exemple #9
0
 protected override void OnDeleting()
 {
     base.OnDeleting();
     SequenceGenerator.ReleaseSequence(this);
 }
        private static void space_Committed(object sender, EventArgs e, IObjectSpace space)
        {
            if (sequenceGenerator != null)
            {
                sequenceGenerator.Accept();
                sequenceGenerator.Dispose();
                sequenceGenerator = null;
            }

            space.Committed -= new EventHandler((s, args) => space_Committed(s, args, space));
        }
 public SaslList(ITypeTranscoder transcoder, uint timeout)
     : this(string.Empty, null, transcoder, null, SequenceGenerator.GetNext(), timeout)
 {
 }
        public void Emit(SourceBuilder source, SequenceGenerator seqGen, bool fireDebugEvents)
        {
            String matchListName = "MatchList_" + seqMulti.Id;

            source.AppendFrontFormat("List<GRGEN_LIBGR.IMatch> {0} = new List<GRGEN_LIBGR.IMatch>();\n", matchListName);

            // emit code for matching all the contained rules
            for (int i = 0; i < seqMulti.MultiRulePrefixedSequence.RulePrefixedSequences.Count; ++i)
            {
                new SequenceMultiSequenceBacktrackRuleGenerator(seqMulti,
                                                                seqMulti.MultiRulePrefixedSequence.RulePrefixedSequences[i].Rule,
                                                                seqMulti.MultiRulePrefixedSequence.RulePrefixedSequences[i].Sequence,
                                                                seqExprGen, seqHelper)
                .EmitMatching(source, seqGen, matchListName);
            }

            // emit code for match class (non-rule-based) filtering
            foreach (SequenceFilterCall sequenceFilterCall in seqMulti.MultiRulePrefixedSequence.Filters)
            {
                seqExprGen.EmitMatchClassFilterCall(source, (SequenceFilterCallCompiled)sequenceFilterCall, matchListName, false);
            }

            source.AppendFront("if(" + matchListName + ".Count == 0) {\n");
            source.Indent();
            source.AppendFront(COMP_HELPER.SetResultVar(seqMulti, "false"));
            source.Unindent();
            source.AppendFront("} else {\n");
            source.Indent();
            source.AppendFront(COMP_HELPER.SetResultVar(seqMulti, "true")); // shut up compiler

            String originalToCloneName = "originalToClone_" + seqMulti.Id;

            source.AppendFrontFormat("Dictionary<GRGEN_LIBGR.IMatch, GRGEN_LIBGR.IMatch> {0} = new Dictionary<GRGEN_LIBGR.IMatch, GRGEN_LIBGR.IMatch>();\n", originalToCloneName);

            // emit code for cloning the matches objects of the rules
            for (int i = 0; i < seqMulti.MultiRulePrefixedSequence.RulePrefixedSequences.Count; ++i)
            {
                new SequenceMultiSequenceBacktrackRuleGenerator(seqMulti,
                                                                seqMulti.MultiRulePrefixedSequence.RulePrefixedSequences[i].Rule,
                                                                seqMulti.MultiRulePrefixedSequence.RulePrefixedSequences[i].Sequence,
                                                                seqExprGen, seqHelper)
                .EmitCloning(source, seqGen, matchListName, originalToCloneName);
            }

            String originalMatchList = "originalMatchList_" + seqMulti.Id;

            source.AppendFrontFormat("List<GRGEN_LIBGR.IMatch> {0} = new List<GRGEN_LIBGR.IMatch>({1});\n", originalMatchList, matchListName);
            source.AppendFrontFormat("{0}.Clear();\n", matchListName);

            String originalMatch = "originalMatch_" + seqMulti.Id;

            source.AppendFrontFormat("foreach(GRGEN_LIBGR.IMatch {0} in {1})\n", originalMatch, originalMatchList);
            source.AppendFrontIndentedFormat("{0}.Add({1}[{2}]);", matchListName, originalToCloneName, originalMatch);

            // apply the rules and the following sequence for every match found,
            // until the first rule and sequence execution succeeded
            // rolling back the changes of failing executions until then
            String enumeratorName   = "enum_" + seqMulti.Id;
            String matchesTriedName = "matchesTried_" + seqMulti.Id;

            source.AppendFront("int " + matchesTriedName + " = 0;\n");
            source.AppendFront("IEnumerator<GRGEN_LIBGR.IMatch> " + enumeratorName + " = " + matchListName + ".GetEnumerator();\n");
            source.AppendFront("while(" + enumeratorName + ".MoveNext())\n");
            source.AppendFront("{\n");
            source.Indent();
            source.AppendFront("++" + matchesTriedName + ";\n");

            String transactionIdName = "transID_" + seqMulti.Id;

            source.AppendFront("int " + transactionIdName + " = procEnv.TransactionManager.Start();\n");
            String oldRewritesPerformedName = "oldRewritesPerformed_" + seqMulti.Id;

            source.AppendFront("int " + oldRewritesPerformedName + " = procEnv.PerformanceInfo.RewritesPerformed;\n");

            source.AppendFront("switch(" + enumeratorName + ".Current.Pattern.PackagePrefixedName)\n");
            source.AppendFront("{\n");
            source.Indent();

            // emit code for rewriting the current match (for each rule, rule fitting to the match is selected by rule name)
            // and code for executing the corresponding sequence
            for (int i = 0; i < seqMulti.MultiRulePrefixedSequence.RulePrefixedSequences.Count; ++i)
            {
                new SequenceMultiSequenceBacktrackRuleGenerator(seqMulti,
                                                                seqMulti.MultiRulePrefixedSequence.RulePrefixedSequences[i].Rule,
                                                                seqMulti.MultiRulePrefixedSequence.RulePrefixedSequences[i].Sequence,
                                                                seqExprGen, seqHelper)
                .EmitRewriting(source, seqGen, matchListName, enumeratorName, fireDebugEvents);
            }

            source.AppendFrontFormat("default: throw new Exception(\"Unknown pattern \" + {0}.Current.Pattern.PackagePrefixedName + \" in match!\");", enumeratorName);
            source.Unindent();
            source.AppendFront("}\n");

            // if sequence execution failed, roll the changes back and try the next match
            source.AppendFront("if(!" + COMP_HELPER.GetResultVar(seqMulti) + ") {\n");
            source.Indent();
            source.AppendFront("procEnv.TransactionManager.Rollback(" + transactionIdName + ");\n");
            source.AppendFront("procEnv.PerformanceInfo.RewritesPerformed = " + oldRewritesPerformedName + ";\n");

            source.AppendFront("if(" + matchesTriedName + " < " + matchListName + ".Count) {\n"); // further match available -> try it
            source.Indent();
            source.AppendFront("continue;\n");
            source.Unindent();
            source.AppendFront("} else {\n"); // all matches tried, all failed later on -> end in fail
            source.Indent();
            source.AppendFront("break;\n");
            source.Unindent();
            source.AppendFront("}\n");

            source.Unindent();
            source.AppendFront("}\n");

            // if sequence execution succeeded, commit the changes so far and succeed
            source.AppendFront("procEnv.TransactionManager.Commit(" + transactionIdName + ");\n");
            source.AppendFront("break;\n");

            source.Unindent();
            source.AppendFront("}\n");

            source.Unindent();
            source.AppendFront("}\n");
        }
Exemple #13
0
        public void Emit(SourceBuilder source, SequenceGenerator seqGen, bool fireDebugEvents)
        {
            String matchListName = "MatchList_" + seqMulti.Id;

            source.AppendFrontFormat("List<GRGEN_LIBGR.IMatch> {0} = new List<GRGEN_LIBGR.IMatch>();\n", matchListName);

            // emit code for matching all the contained rules
            SequenceRuleCallMatcherGenerator[] ruleMatcherGenerators =
                new SequenceRuleCallMatcherGenerator[seqMulti.Rules.Sequences.Count];
            for (int i = 0; i < seqMulti.Rules.Sequences.Count; ++i)
            {
                ruleMatcherGenerators[i] = new SequenceRuleCallMatcherGenerator((SequenceRuleCall)seqMulti.Rules.Sequences[i], seqExprGen, seqHelper);
                ruleMatcherGenerators[i].EmitMatchingAndCloning(source, "procEnv.MaxMatches");
            }

            SequenceRuleCallMatcherGenerator.EmitPreMatchEventFiring(source, ruleMatcherGenerators);

            // emit code for rule-based filtering
            for (int i = 0; i < seqMulti.Rules.Sequences.Count; ++i)
            {
                ruleMatcherGenerators[i].EmitFiltering(source);
                ruleMatcherGenerators[i].EmitAddRange(source, matchListName);
            }

            // emit code for match class (non-rule-based) filtering
            foreach (SequenceFilterCallBase sequenceFilterCall in seqMulti.Rules.Filters)
            {
                seqExprGen.EmitMatchClassFilterCall(source, sequenceFilterCall, matchListName, false);
            }

            source.AppendFront("if(" + matchListName + ".Count == 0) {\n");
            source.Indent();
            source.AppendFront(COMP_HELPER.SetResultVar(seqMulti, "false"));
            source.Unindent();
            source.AppendFront("} else {\n");
            source.Indent();
            source.AppendFront(COMP_HELPER.SetResultVar(seqMulti, "true")); // shut up compiler

            // apply the rules and the following sequence for every match found,
            // until the first rule and sequence execution succeeded
            // rolling back the changes of failing executions until then
            String enumeratorName   = "enum_" + seqMulti.Id;
            String matchesTriedName = "matchesTried_" + seqMulti.Id;

            source.AppendFront("int " + matchesTriedName + " = 0;\n");
            source.AppendFront("IEnumerator<GRGEN_LIBGR.IMatch> " + enumeratorName + " = " + matchListName + ".GetEnumerator();\n");
            source.AppendFront("while(" + enumeratorName + ".MoveNext())\n");
            source.AppendFront("{\n");
            source.Indent();
            source.AppendFront("++" + matchesTriedName + ";\n");

            String transactionIdName = "transID_" + seqMulti.Id;

            source.AppendFront("int " + transactionIdName + " = procEnv.TransactionManager.Start();\n");
            String oldRewritesPerformedName = "oldRewritesPerformed_" + seqMulti.Id;

            source.AppendFront("int " + oldRewritesPerformedName + " = procEnv.PerformanceInfo.RewritesPerformed;\n");

            source.AppendFront("switch(" + enumeratorName + ".Current.Pattern.PackagePrefixedName)\n");
            source.AppendFront("{\n");
            source.Indent();

            // emit code for rewriting the current match (for each rule, rule fitting to the match is selected by rule name)
            for (int i = 0; i < seqMulti.Rules.Sequences.Count; ++i)
            {
                SequenceMultiBacktrackRuleRewritingGenerator ruleRewritingGenerator = new SequenceMultiBacktrackRuleRewritingGenerator(
                    seqMulti, (SequenceRuleCall)seqMulti.Rules.Sequences[i], seqExprGen, seqHelper);
                ruleRewritingGenerator.EmitRewriting(source, seqGen, matchListName, enumeratorName, fireDebugEvents);
            }

            source.AppendFrontFormat("default: throw new Exception(\"Unknown pattern \" + {0}.Current.Pattern.PackagePrefixedName + \" in match!\");", enumeratorName);
            source.Unindent();
            source.AppendFront("}\n");

            // rule applied, now execute the sequence
            seqGen.EmitSequence(seqMulti.Seq, source);

            // if sequence execution failed, roll the changes back and try the next match
            source.AppendFront("if(!" + COMP_HELPER.GetResultVar(seqMulti.Seq) + ") {\n");
            source.Indent();
            source.AppendFront("procEnv.TransactionManager.Rollback(" + transactionIdName + ");\n");
            source.AppendFront("procEnv.PerformanceInfo.RewritesPerformed = " + oldRewritesPerformedName + ";\n");

            source.AppendFront("if(" + matchesTriedName + " < " + matchListName + ".Count) {\n"); // further match available -> try it
            source.Indent();
            source.AppendFront("continue;\n");
            source.Unindent();
            source.AppendFront("} else {\n"); // all matches tried, all failed later on -> end in fail
            source.Indent();
            source.AppendFront(COMP_HELPER.SetResultVar(seqMulti, "false"));
            source.AppendFront("break;\n");
            source.Unindent();
            source.AppendFront("}\n");

            source.Unindent();
            source.AppendFront("}\n");

            // if sequence execution succeeded, commit the changes so far and succeed
            source.AppendFront("procEnv.TransactionManager.Commit(" + transactionIdName + ");\n");
            source.AppendFront(COMP_HELPER.SetResultVar(seqMulti, "true"));
            source.AppendFront("break;\n");

            source.Unindent();
            source.AppendFront("}\n");

            source.Unindent();
            source.AppendFront("}\n");
        }
        public void Generator_ForSequence1()
        {
            int[] expected = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 };

            CollectionAssert.AreEqual(expected, SequenceGenerator.GenerateSequence(expected.Length, 1, 1, (x1, x2) => x1 + x2));
        }
Exemple #15
0
        public static void MethodSelectManyProductIds()
        {
            Program.IntroLine(true, "SelectMany");
            Console.WriteLine("De lambda functie van SelectMany kan een IEnumerable ontvangen, deze kan hij verwerken.");
            Console.WriteLine("Deze functie koppelt de product_id van Order naar de products");
            Console.WriteLine("zal de functie Selectmany door projectie een IEnumerable van Products teruggeven.");
            Program.WhiteLine();
            ConsoleTableHeader(false);

            var stopwatch = new Stopwatch();

            stopwatch.Start();
            var sequence = SequenceGenerator.Orders().SelectMany(order => order.ProductIds,
                                                                 (order, productid) => SequenceGenerator.Products().FirstOrDefault(product => product.Id == productid));

            foreach (var item in sequence)
            {
                if (item != null)
                {
                    Console.WriteLine($"{item.Id}         | {item.Description}");
                }
            }
            stopwatch.Stop();

            Program.WhiteLine();
            Program.StopwatchLine(stopwatch.ElapsedMilliseconds);
        }
 public SlowSet(string key, T value, ITypeTranscoder transcoder, IVBucket vBucket, uint timeout)
     : base(key, value, vBucket, transcoder, SequenceGenerator.GetNext(), timeout)
 {
 }
        private const uint OperationLifespan = 2500; //ms

        public SlowSet(string key, T value, IVBucket vBucket, ITypeTranscoder transcoder)
            : base(key, value, vBucket, transcoder, SequenceGenerator.GetNext(), OperationLifespan)
        {
        }
 private void CreateSequenceGenerator()
 {
     _sequenceGenerator = new SequenceGenerator(Now.TimestampSec(StartTime));
 }
Exemple #19
0
 public ResultTest(SequenceGenerator generator)
 {
     this.generator = generator;
 }
Exemple #20
0
        static void OneToMany()
        {
            var grammar   = new SequenceGenerator(dictionarySize: 10, minSize: 5, maxSize: 5, noRepeat: true, isStochastic: false);
            var sequences = grammar.GenerateSequences().Take(1000).ToList();
            var builder   = BrightWireProvider.CreateDataTableBuilder();

            builder.AddColumn(ColumnType.Vector, "Summary");
            builder.AddColumn(ColumnType.Matrix, "Sequence");

            foreach (var sequence in sequences)
            {
                var sequenceData = sequence
                                   .GroupBy(ch => ch)
                                   .Select(g => (g.Key, g.Count()))
                                   .ToDictionary(d => d.Item1, d => (float)d.Item2)
                ;
                var summary = grammar.Encode(sequenceData.Select(kv => (kv.Key, kv.Value)));
                var list    = new List <FloatVector>();
                foreach (var item in sequenceData.OrderBy(kv => kv.Key))
                {
                    var row = grammar.Encode(item.Key, item.Value);
                    list.Add(row);
                }
                builder.Add(summary, FloatMatrix.Create(list.ToArray()));
            }
            var data = builder.Build().Split(0);

            using (var lap = BrightWireProvider.CreateLinearAlgebra(false)) {
                var graph       = new GraphFactory(lap);
                var errorMetric = graph.ErrorMetric.BinaryClassification;

                // create the property set
                var propertySet = graph.CurrentPropertySet
                                  .Use(graph.GradientDescent.RmsProp)
                                  .Use(graph.WeightInitialisation.Xavier)
                ;

                // create the engine
                const float TRAINING_RATE = 0.1f;
                var         trainingData  = graph.CreateDataSource(data.Training);
                var         testData      = trainingData.CloneWith(data.Test);
                var         engine        = graph.CreateTrainingEngine(trainingData, TRAINING_RATE, 8);
                engine.LearningContext.ScheduleLearningRate(30, TRAINING_RATE / 3);

                // build the network
                const int HIDDEN_LAYER_SIZE = 128;
                var       memory            = new float[HIDDEN_LAYER_SIZE];
                var       network           = graph.Connect(engine)
                                              //.AddSimpleRecurrent(graph.ReluActivation(), memory)
                                              //.AddGru(memory)
                                              .AddLstm(memory)
                                              .AddFeedForward(engine.DataSource.OutputSize)
                                              .Add(graph.SigmoidActivation())
                                              .AddBackpropagation(errorMetric)
                ;

                engine.Train(40, testData, errorMetric);

                var networkGraph    = engine.Graph;
                var executionEngine = graph.CreateEngine(networkGraph);

                var output = executionEngine.Execute(testData);
                Console.WriteLine(output.Average(o => o.CalculateError(errorMetric)));
            }
        }
Exemple #21
0
        public async Task NextMethodThrowsExceptionIfSequencyCanNotBeFound()
        {
            //var stateProvider = GetStateProvider();
            var stateProvider = new InMemoryStateProvider();

            var sequenceGenerator = new SequenceGenerator(stateProvider);


            var nextValue1 = await sequenceGenerator.NextAsync(new SequenceKey { Value = "1234"});
        }
 // Override this method to create multiple sequences based on the current object's property values
 protected virtual string GetSequenceName()
 {
     return(SequenceGenerator.GetBaseSequenceName(ClassInfo));
 }
Exemple #23
0
        public async Task NextMethodCyclesWhenMaximumValueIsReached()
        {
            var stateProvider = GetStateProvider();

            var sequenceGenerator = new SequenceGenerator(stateProvider);

            var sequence = await CreateSequence(stateProvider, maxValue: 2, cycle: true);

            var sequenceKey = await stateProvider.AddAsync(sequence);

            var nextValue1 = await sequenceGenerator.NextAsync(sequenceKey);

            var nextValue2 = await sequenceGenerator.NextAsync(sequenceKey);

            var nextValue3 = await sequenceGenerator.NextAsync(sequenceKey);

            Assert.IsTrue(nextValue1 == 1);

            Assert.IsTrue(nextValue2 == 2);

            Assert.IsTrue(nextValue3 == 1);
        }
        public void Generator_ForSequence2()
        {
            int[] expected = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 };

            CollectionAssert.AreEqual(expected, SequenceGenerator.GenerateSequence(expected.Length, 1, 2, (x1, x2) => 6 * x2 - 8 * x1));
        }
Exemple #25
0
        public async Task NextMethodThrowsExceptionWhenMinimumValueIsReached()
        {
            var stateProvider = GetStateProvider();

            var sequenceGenerator = new SequenceGenerator(stateProvider);

            var sequence = await CreateSequence(stateProvider,minValue: 2, startAt: 4, increment: -1, cycle: false);

            var sequenceKey = await stateProvider.AddAsync(sequence);

            var nextValue1 = await sequenceGenerator.NextAsync(sequenceKey);

            var nextValue2 = await sequenceGenerator.NextAsync(sequenceKey);

            var nextValue3 = await sequenceGenerator.NextAsync(sequenceKey);

            Assert.IsTrue(nextValue1 == 3);

            Assert.IsTrue(nextValue2 == 2);

           
        }
 public SaslStep(string key, string value, ITypeTranscoder transcoder, uint timeout)
     : base(key, value, null, transcoder, SequenceGenerator.GetNext(), timeout)
 {
 }
Exemple #27
0
        public async Task NextMethodThrowsExceptionWhenIfMaxRetryAttemptIsReach()
        {
            var stateProvider = new InMemoryStateProvider();
            
            stateProvider.UpdateValue = false;

            var sequenceGenerator = new SequenceGenerator(stateProvider);

            var sequence = await CreateSequence(stateProvider);

            var sequenceKey = await stateProvider.AddAsync(sequence);

             await sequenceGenerator.NextAsync(sequenceKey);
        }
        public void Emit(SourceBuilder source, SequenceGenerator seqGen, bool fireDebugEvents)
        {
            String parameters = seqHelper.BuildParameters(seqRule, ArgumentExpressions, source);

            seqMatcherGen.EmitMatching(source, parameters, "procEnv.MaxMatches");
            SequenceRuleCallMatcherGenerator.EmitPreMatchEventFiring(source, matchesName);
            seqMatcherGen.EmitFiltering(source);
            seqMatcherGen.EmitCloning(source);

            source.AppendFront("if(" + matchesName + ".Count == 0) {\n");
            source.Indent();
            source.AppendFront(COMP_HELPER.SetResultVar(seq, "false"));
            source.Unindent();
            source.AppendFront("} else {\n");
            source.Indent();
            source.AppendFront(COMP_HELPER.SetResultVar(seq, "true")); // shut up compiler
            if (fireDebugEvents)
            {
                source.AppendFront("procEnv.Finishing(" + matchesName + ", " + specialStr + ");\n");
            }

            String returnParameterDeclarations;
            String returnArguments;
            String returnAssignments;
            String returnParameterDeclarationsAllCall;
            String intermediateReturnAssignmentsAllCall;
            String returnAssignmentsAllCall;

            seqHelper.BuildReturnParameters(seqRule, ReturnVars,
                                            out returnParameterDeclarations, out returnArguments, out returnAssignments,
                                            out returnParameterDeclarationsAllCall, out intermediateReturnAssignmentsAllCall, out returnAssignmentsAllCall);

            // apply the rule and the following sequence for every match found,
            // until the first rule and sequence execution succeeded
            // rolling back the changes of failing executions until then
            String enumeratorName   = "enum_" + seq.Id;
            String matchesTriedName = "matchesTried_" + seq.Id;

            source.AppendFront("int " + matchesTriedName + " = 0;\n");
            source.AppendFront("IEnumerator<" + matchType + "> " + enumeratorName + " = " + matchesName + ".GetEnumeratorExact();\n");
            source.AppendFront("while(" + enumeratorName + ".MoveNext())\n");
            source.AppendFront("{\n");
            source.Indent();
            source.AppendFront(matchType + " " + matchName + " = " + enumeratorName + ".Current;\n");
            source.AppendFront("++" + matchesTriedName + ";\n");

            // start a transaction
            String transactionIdName = "transID_" + seq.Id;

            source.AppendFront("int " + transactionIdName + " = procEnv.TransactionManager.Start();\n");
            String oldRewritesPerformedName = "oldRewritesPerformed_" + seq.Id;

            source.AppendFront("int " + oldRewritesPerformedName + " = procEnv.PerformanceInfo.RewritesPerformed;\n");
            if (fireDebugEvents)
            {
                source.AppendFront("procEnv.Matched(" + matchesName + ", " + matchName + ", " + specialStr + ");\n");
            }
            if (returnParameterDeclarations.Length != 0)
            {
                source.AppendFront(returnParameterDeclarations + "\n");
            }

            source.AppendFront(ruleName + ".Modify(procEnv, " + matchName + returnArguments + ");\n");
            if (returnAssignments.Length != 0)
            {
                source.AppendFront(returnAssignments + "\n");
            }
            source.AppendFront("++procEnv.PerformanceInfo.RewritesPerformed;\n");
            if (fireDebugEvents)
            {
                source.AppendFront("procEnv.Finished(" + matchesName + ", " + specialStr + ");\n");
            }

            // rule applied, now execute the sequence
            seqGen.EmitSequence(seq.Seq, source);

            // if sequence execution failed, roll the changes back and try the next match of the rule
            source.AppendFront("if(!" + COMP_HELPER.GetResultVar(seq.Seq) + ") {\n");
            source.Indent();
            source.AppendFront("procEnv.TransactionManager.Rollback(" + transactionIdName + ");\n");
            source.AppendFront("procEnv.PerformanceInfo.RewritesPerformed = " + oldRewritesPerformedName + ";\n");

            source.AppendFront("if(" + matchesTriedName + " < " + matchesName + ".Count) {\n"); // further match available -> try it
            source.Indent();
            source.AppendFront("continue;\n");
            source.Unindent();
            source.AppendFront("} else {\n"); // all matches tried, all failed later on -> end in fail
            source.Indent();
            source.AppendFront(COMP_HELPER.SetResultVar(seq, "false"));
            source.AppendFront("break;\n");
            source.Unindent();
            source.AppendFront("}\n");

            source.Unindent();
            source.AppendFront("}\n");

            // if sequence execution succeeded, commit the changes so far and succeed
            source.AppendFront("procEnv.TransactionManager.Commit(" + transactionIdName + ");\n");
            source.AppendFront(COMP_HELPER.SetResultVar(seq, "true"));
            source.AppendFront("break;\n");

            source.Unindent();
            source.AppendFront("}\n");

            source.Unindent();
            source.AppendFront("}\n");
        }
Exemple #29
0
        public virtual void CodeGenerateOneSequence(string sequenceName, string schemaName)
        {
            SequenceGenerator seqGen = new SequenceGenerator(this);

            seqGen.Render(Output, schemaName, sequenceName);
        }
        public static void GenerateSequence(ISerialDataObject instance, IObjectSpace space)
        {
            var typeToExistsMap = new Dictionary<string, bool>();
            if (sequenceGenerator == null)
            {
                sequenceGenerator = new SequenceGenerator(typeToExistsMap);
            }

            instance.Number = (int)sequenceGenerator.GetNextSequence(XafTypesInfo.Instance.FindTypeInfo(instance.GetType()));

            if (!(space is XPNestedObjectSpace))
            {
                space.Committed += new EventHandler((s, e) => space_Committed(s, e, space));
            }
        }
 public IClassBody WithFields(SequenceGenerator <IField> sequenceGenerator) => WithMultipleObjects(sequenceGenerator);
Exemple #32
0
        public void Emit(SourceBuilder source, SequenceGenerator seqGen, bool fireDebugEvents)
        {
            String parameterDeclarations = null;
            String parameters            = null;

            if (seqRule.Subgraph != null)
            {
                parameters = seqHelper.BuildParametersInDeclarations(seqRule, ArgumentExpressions, source, out parameterDeclarations);
            }
            else
            {
                parameters = seqHelper.BuildParameters(seqRule, ArgumentExpressions, source);
            }

            if (seqRule.Subgraph != null)
            {
                source.AppendFront(parameterDeclarations + "\n");
                source.AppendFront("procEnv.SwitchToSubgraph((GRGEN_LIBGR.IGraph)" + seqHelper.GetVar(seqRule.Subgraph) + ");\n");
                source.AppendFront("graph = ((GRGEN_LGSP.LGSPActionExecutionEnvironment)procEnv).graph;\n");
            }

            source.AppendFront(matchesType + " " + matchesName + " = " + ruleName
                               + ".Match(procEnv, " + (seqRule.SequenceType == SequenceType.RuleCall ? "1" : "procEnv.MaxMatches")
                               + parameters + ");\n");
            source.AppendFront("procEnv.PerformanceInfo.MatchesFound += " + matchesName + ".Count;\n");
            for (int i = 0; i < seqRule.Filters.Count; ++i)
            {
                seqExprGen.EmitFilterCall(source, (SequenceFilterCallCompiled)seqRule.Filters[i], patternName, matchesName, seqRule.PackagePrefixedName, false);
            }

            if (seqRule is SequenceRuleCountAllCall)
            {
                SequenceRuleCountAllCall seqRuleCountAll = (SequenceRuleCountAllCall)seqRule;
                source.AppendFront(seqHelper.SetVar(seqRuleCountAll.CountResult, matchesName + ".Count"));
            }

            String insufficientMatchesCondition;

            if (seqRule is SequenceRuleAllCall &&
                ((SequenceRuleAllCall)seqRule).ChooseRandom &&
                ((SequenceRuleAllCall)seqRule).MinSpecified)
            {
                SequenceRuleAllCall seqRuleAll = (SequenceRuleAllCall)seqRule;
                String minMatchesVarName       = "minmatchesvar_" + seqRuleAll.Id;
                source.AppendFrontFormat("int {0} = (int){1};\n", minMatchesVarName, seqHelper.GetVar(seqRuleAll.MinVarChooseRandom));
                insufficientMatchesCondition = matchesName + ".Count < " + minMatchesVarName;
            }
            else
            {
                insufficientMatchesCondition = matchesName + ".Count == 0";
            }

            source.AppendFrontFormat("if({0}) {{\n", insufficientMatchesCondition);
            source.Indent();
            source.AppendFront(COMP_HELPER.SetResultVar(seqRule, "false"));
            source.Unindent();
            source.AppendFront("} else {\n");
            source.Indent();
            source.AppendFront(COMP_HELPER.SetResultVar(seqRule, "true"));
            if (fireDebugEvents)
            {
                source.AppendFront("procEnv.Matched(" + matchesName + ", null, " + specialStr + ");\n");
            }
            if (fireDebugEvents)
            {
                source.AppendFront("procEnv.Finishing(" + matchesName + ", " + specialStr + ");\n");
            }

            SequenceRuleOrRuleAllCallRewritingGenerator rewritingGen = new SequenceRuleOrRuleAllCallRewritingGenerator(this);

            if (seqRule.SequenceType == SequenceType.RuleCall)
            {
                rewritingGen.EmitRewritingRuleCall(source);
            }
            else if (seqRule.SequenceType == SequenceType.RuleCountAllCall || !((SequenceRuleAllCall)seqRule).ChooseRandom) // seq.SequenceType == SequenceType.RuleAll
            {
                rewritingGen.EmitRewritingRuleCountAllCallOrRuleAllCallNonRandom(source);
            }
            else // seq.SequenceType == SequenceType.RuleAll && ((SequenceRuleAll)seqRule).ChooseRandom
            {
                rewritingGen.EmitRewritingRuleAllCallRandom(source);
            }

            if (fireDebugEvents)
            {
                source.AppendFront("procEnv.Finished(" + matchesName + ", " + specialStr + ");\n");
            }

            source.Unindent();
            source.AppendFront("}\n");

            if (seqRule.Subgraph != null)
            {
                source.AppendFront("procEnv.ReturnFromSubgraph();\n");
                source.AppendFront("graph = ((GRGEN_LGSP.LGSPActionExecutionEnvironment)procEnv).graph;\n");
            }
        }
Exemple #33
0
        private void NextSeq(object o)
        {
            var type = o.GetType();
            var mem  = loadedTypes[type];

            string tableName = mem.TableName;

            foreach (var c in mem.fields)
            {
                SequenceGenerator seq = null;
                var otrs = c.Mem.GetCustomAttributes(typeof(SequenceGenerator), true);
                if (otrs.Length != 0)
                {
                    seq = (SequenceGenerator)otrs[0];
                }

                if (seq == null)
                {
                    continue;
                }

                lock (lc)
                {
                    DbProviderFactory m_factory = DbProviderFactories.GetFactory(conf.providerName);
                    using (var _connection = m_factory.CreateConnection())
                    {
                        _connection.ConnectionString = conf.connectionString;
                        _connection.Open();

                        //  var tr = _connection.BeginTransaction();

                        using (var com = _connection.CreateCommand())
                        {
                            //  com.Transaction = tr;
                            com.CommandText = "select parval from " + HibTableName + " where parcode = " + conf.parPre + "p";
                            var p = com.CreateParameter();
                            p.DbType        = System.Data.DbType.String;
                            p.ParameterName = "p";
                            p.Value         = "seq_state_" + tableName + "_" + c.colName;
                            com.Parameters.Add(p);

                            using (var rd = com.ExecuteReader())
                            {
                                if (!rd.Read())
                                {
                                    rd.Close();
                                    com.CommandText = "INSERT INTO " + HibTableName + " (parcode , parval ) VALUES (" + conf.parPre + "p1 , " + conf.parPre + "p2)";

                                    p               = com.CreateParameter();
                                    p.DbType        = System.Data.DbType.String;
                                    p.ParameterName = "p1";
                                    p.Value         = "seq_state_" + tableName + "_" + c.colName;
                                    com.Parameters.Add(p);

                                    p               = com.CreateParameter();
                                    p.DbType        = System.Data.DbType.String;
                                    p.ParameterName = "p2";
                                    p.Value         = seq.MinValue - seq.Incriment;
                                    com.Parameters.Add(p);

                                    com.ExecuteNonQuery();
                                }
                                else
                                {
                                    rd.Close();
                                }
                            }

                            com.CommandText = "select parval from " + HibTableName + " where parcode = " + conf.parPre + "p";
                            com.Parameters.Clear();
                            p               = com.CreateParameter();
                            p.DbType        = System.Data.DbType.String;
                            p.ParameterName = "p";
                            p.Value         = "seq_state_" + tableName + "_" + c.colName;
                            com.Parameters.Add(p);


                            Int64 tmp = 0;

                            using (var rd = com.ExecuteReader())
                            {
                                rd.Read();
                                tmp = Convert.ToInt64(rd[0]) + seq.Incriment;
                                rd.Close();
                            }

                            if (c.type != typeof(Int64))
                            {
                                throw new ErrorSeqColumnType();
                            }
                            c.SetValue(o, tmp);


                            if (tmp >= seq.MaxValue)
                            {
                                throw new ExSeqLimit();
                            }

                            com.CommandText = "update  " + HibTableName + " set parval = " + conf.parPre + "v where parcode = " + conf.parPre + "p";
                            com.Parameters.Clear();
                            p               = com.CreateParameter();
                            p.DbType        = System.Data.DbType.String;
                            p.ParameterName = "p";
                            p.Value         = "seq_state_" + tableName + "_" + c.colName;
                            com.Parameters.Add(p);

                            p               = com.CreateParameter();
                            p.DbType        = System.Data.DbType.String;
                            p.ParameterName = "v";
                            p.Value         = tmp.ToString();
                            com.Parameters.Add(p);

                            com.ExecuteNonQuery();
                        }

                        //  tr.Commit();

                        _connection.Close();
                    }
                }
            }
        }
        public void EmitRewriting(SourceBuilder source, SequenceGenerator seqGen,
                                  String totalMatchToApply, String curTotalMatch, String firstRewrite, bool fireDebugEvents)
        {
            if (seqSome.Random)
            {
                source.AppendFront("if(" + matchesName + ".Count != 0 && " + curTotalMatch + " <= " + totalMatchToApply + ") {\n");
            }
            else
            {
                source.AppendFront("if(" + matchesName + ".Count != 0) {\n");
            }
            source.Indent();

            SequenceSomeRuleCallRewritingGenerator rewritingGen = new SequenceSomeRuleCallRewritingGenerator(this, totalMatchToApply, curTotalMatch);

            if (seqRule.SequenceType == SequenceType.RuleCall)
            {
                if (seqSome.Random)
                {
                    source.AppendFront("if(" + curTotalMatch + " == " + totalMatchToApply + ") {\n");
                    source.Indent();
                }

                rewritingGen.EmitRewritingRuleCall(source, firstRewrite, fireDebugEvents);

                if (seqSome.Random)
                {
                    source.Unindent();
                    source.AppendFront("}\n");
                    source.AppendFront("++" + curTotalMatch + ";\n");
                }
            }
            else if (seqRule.SequenceType == SequenceType.RuleCountAllCall || !((SequenceRuleAllCall)seqRule).ChooseRandom) // seq.SequenceType == SequenceType.RuleAll
            {
                if (seqSome.Random)
                {
                    source.AppendFront("if(" + curTotalMatch + " == " + totalMatchToApply + ") {\n");
                    source.Indent();
                }

                rewritingGen.EmitRewritingRuleCountAllCallOrRuleAllCallNonRandom(source, firstRewrite, fireDebugEvents);

                if (seqSome.Random)
                {
                    source.Unindent();
                    source.AppendFront("}\n");
                    source.AppendFront("++" + curTotalMatch + ";\n");
                }
            }
            else // seq.SequenceType == SequenceType.RuleAll && ((SequenceRuleAll)seqRule).ChooseRandom
            {
                if (seqSome.Random)
                {
                    rewritingGen.EmitRewritingRuleAllCallRandomSequenceRandom(source, firstRewrite, fireDebugEvents);
                }
                else
                {
                    rewritingGen.EmitRewritingRuleAllCallRandomSequenceNonRandom(source, firstRewrite, fireDebugEvents);
                }
            }

            source.Unindent();
            source.AppendFront("}\n");
        }
Exemple #35
0
 public SlowSet(string key, T value, ITypeTranscoder transcoder, IVBucket vBucket, IByteConverter converter)
     : base(key, value, transcoder, vBucket, converter, SequenceGenerator.GetNext(), DefaultTimeout)
 {
 }
 public IClassBody WithProperties(SequenceGenerator <IProperty <IClassBody> > sequenceGenerator) => WithMultipleObjects(sequenceGenerator);
        static void SequenceToSequence()
        {
            const int SEQUENCE_LENGTH = 5;
            var       grammar         = new SequenceGenerator(8, SEQUENCE_LENGTH, SEQUENCE_LENGTH, true, false);
            var       sequences       = grammar.GenerateSequences().Take(2000).ToList();
            var       builder         = BrightWireProvider.CreateDataTableBuilder();

            builder.AddColumn(ColumnType.Matrix, "Input");
            builder.AddColumn(ColumnType.Matrix, "Output");
            foreach (var sequence in sequences)
            {
                var encodedSequence  = grammar.Encode(sequence);
                var reversedSequence = new FloatMatrix
                {
                    Row = encodedSequence.Row.Reverse().Take(SEQUENCE_LENGTH - 1).ToArray()
                };
                builder.Add(encodedSequence, reversedSequence);
            }

            var data = builder.Build().Split(0);

            using var lap = BrightWireProvider.CreateLinearAlgebra();
            var graph       = new GraphFactory(lap);
            var errorMetric = graph.ErrorMetric.BinaryClassification;

            // create the property set
            var propertySet = graph.CurrentPropertySet.Use(graph.GradientDescent.RmsProp).
                              Use(graph.WeightInitialisation.Xavier);
            const int   BATCH_SIZE        = 16;
            int         HIDDEN_LAYER_SIZE = 64;
            const float TRAINING_RATE     = 0.1f;

            // create the encoder
            var encoderLearningContext = graph.CreateLearningContext(TRAINING_RATE, BATCH_SIZE,
                                                                     TrainingErrorCalculation.Fast, true);
            var trainingData = graph.CreateDataSource(data.Training, encoderLearningContext,
                                                      wb => wb.AddLstm(HIDDEN_LAYER_SIZE, "encoder").
                                                      WriteNodeMemoryToSlot("shared-memory", wb.Find("encoder") as IHaveMemoryNode).
                                                      AddFeedForward(grammar.DictionarySize).Add(graph.SigmoidActivation()).
                                                      AddBackpropagationThroughTime(errorMetric));
            var testData = trainingData.CloneWith(data.Test);

            // create the engine
            var engine = graph.CreateTrainingEngine(trainingData, TRAINING_RATE, BATCH_SIZE);

            engine.LearningContext.ScheduleLearningRate(30, TRAINING_RATE / 3);
            engine.LearningContext.ScheduleLearningRate(40, TRAINING_RATE / 9);

            // create the decoder
            var wb2 = graph.Connect(engine);

            wb2.JoinInputWithMemory("shared-memory").IncrementSizeBy(HIDDEN_LAYER_SIZE).
            AddLstm(HIDDEN_LAYER_SIZE, "decoder").AddFeedForward(trainingData.OutputSize).
            Add(graph.SigmoidActivation()).AddBackpropagationThroughTime(errorMetric);
            engine.Train(50, testData, errorMetric);

            //var dataSourceModel = (trainingData as IAdaptiveDataSource).GetModel();
            //var testData2 = graph.CreateDataSource(data.Test, dataSourceModel);
            //var networkGraph = engine.Graph;
            //var executionEngine = graph.CreateEngine(networkGraph);

            //var output = executionEngine.Execute(testData2);
            //Console.WriteLine(output.Average(o => o.CalculateError(errorMetric)));
        }
 public SubDocDelete(MutateInBuilder <T> builder, string key, T value, IVBucket vBucket, ITypeTranscoder transcoder, uint timeout)
     : base(builder, key, value, vBucket, transcoder, SequenceGenerator.GetNext(), timeout)
 {
     CurrentSpec = builder.FirstSpec();
     Path        = CurrentSpec.Path;
 }
        private void btn_Submit_Click(object sender, EventArgs e)
        {
            this.OutputSequences = "";
            if (string.IsNullOrEmpty(this.InputSequences))
            {
                MessageBox.Show("Please do not submit empty content. ");
                return;
            }
            FastaParser       parser       = new FastaParser(this.InputSequences);
            List <FastaEntry> fastaEntries = parser.ParseFasta();

            if (fastaEntries == null)
            {
                switch (this.Countpart)
                {
                case CountpartType.ReverseComplement:
                    this.OutputSequences = SequenceGenerator.ReverseComplementSequence(this.InputSequences);
                    break;

                case CountpartType.Reverse:
                    this.OutputSequences = SequenceGenerator.ReverseSequence(this.InputSequences);
                    break;

                case CountpartType.Complement:
                    this.OutputSequences = SequenceGenerator.ComplementSequence(this.InputSequences);
                    break;

                default:
                    MessageBox.Show("Please choose a counterpart. ");
                    break;
                }
                this.rtx_OutputSequences.Text = this.OutputSequences;
                return;
            }
            foreach (FastaEntry f in fastaEntries)
            {
                switch (this.Countpart)
                {
                case CountpartType.ReverseComplement:
                    f.Sequence = new StringBuilder(SequenceGenerator.ReverseComplementSequence(f.Sequence.ToString()));
                    break;

                case CountpartType.Reverse:
                    f.Sequence = new StringBuilder(SequenceGenerator.ReverseSequence(f.Sequence.ToString()));
                    break;

                case CountpartType.Complement:
                    f.Sequence = new StringBuilder(SequenceGenerator.ComplementSequence(f.Sequence.ToString()));
                    break;

                default:
                    MessageBox.Show("Please choose a counterpart. ");
                    break;
                }
            }
            foreach (FastaEntry entry in fastaEntries)
            {
                this.OutputSequences += entry.ToString();
            }
            this.rtx_OutputSequences.Text = this.OutputSequences;
        }
        public void Emit(SourceBuilder source, SequenceGenerator seqGen, bool fireDebugEvents)
        {
            String parameters = seqHelper.BuildParameters(seqRule, ArgumentExpressions, source);

            seqMatcherGen.EmitMatching(source, parameters, "procEnv.MaxMatches");
            SequenceRuleCallMatcherGenerator.EmitPreMatchEventFiring(source, matchesName);
            seqMatcherGen.EmitFiltering(source);
            seqMatcherGen.EmitCloning(source);

            source.AppendFront("if(" + matchesName + ".Count == 0) {\n");
            source.Indent();
            source.AppendFront(COMP_HELPER.SetResultVar(seq, "false"));
            source.Unindent();
            source.AppendFront("} else {\n");
            source.Indent();
            source.AppendFront(COMP_HELPER.SetResultVar(seq, "false"));
            if (fireDebugEvents)
            {
                source.AppendFront("procEnv.Finishing(" + matchesName + ", " + specialStr + ");\n");
            }

            String returnParameterDeclarations;
            String returnArguments;
            String returnAssignments;
            String returnParameterDeclarationsAllCall;
            String intermediateReturnAssignmentsAllCall;
            String returnAssignmentsAllCall;

            seqHelper.BuildReturnParameters(seqRule, ReturnVars,
                                            out returnParameterDeclarations, out returnArguments, out returnAssignments,
                                            out returnParameterDeclarationsAllCall, out intermediateReturnAssignmentsAllCall, out returnAssignmentsAllCall);

            // apply the rule and the following sequence for every match found
            String enumeratorName = "enum_" + seq.Id;

            source.AppendFront("IEnumerator<" + matchType + "> " + enumeratorName + " = " + matchesName + ".GetEnumeratorExact();\n");
            source.AppendFront("while(" + enumeratorName + ".MoveNext())\n");
            source.AppendFront("{\n");
            source.Indent();
            source.AppendFront(matchType + " " + matchName + " = " + enumeratorName + ".Current;\n");

            source.AppendFront("procEnv.Matched(" + matchesName + ", " + matchName + ", " + specialStr + ");\n");
            if (returnParameterDeclarations.Length != 0)
            {
                source.AppendFront(returnParameterDeclarations + "\n");
            }

            source.AppendFront(ruleName + ".Modify(procEnv, " + matchName + returnArguments + ");\n");
            if (returnAssignments.Length != 0)
            {
                source.AppendFront(returnAssignments + "\n");
            }
            source.AppendFront("++procEnv.PerformanceInfo.RewritesPerformed;\n");
            if (fireDebugEvents)
            {
                source.AppendFront("procEnv.Finished(" + matchesName + ", " + specialStr + ");\n");
            }

            // rule applied, now execute the sequence
            seqGen.EmitSequence(seq.Sequence, source);

            source.AppendFront(COMP_HELPER.SetResultVar(seq, COMP_HELPER.GetResultVar(seq) + "|" + COMP_HELPER.GetResultVar(seq.Sequence)));

            source.Unindent();
            source.AppendFront("}\n");

            source.Unindent();
            source.AppendFront("}\n");
        }
Exemple #41
0
    private void Awake()
    {
        sequenceDict = new Dictionary <string, Sequence>();

        gameEvent           = new GameEvent();
        this.gameEvent.Name = "start sequence";

        //char[] MyChar = { '.', 'j', 's', 'o', 'n' };
        //string newName = fileName.TrimEnd(MyChar);
        string newName = fileName.Replace(".json", "");

        fileName = newName;

        if (LanguageSelector.instance.GetCurrentLanguage() == null)
        {
            Debug.LogError("ERROR: Global Language not set up propertly. Switching to en_UK.");
            LanguageSelector.instance.SetLanguage("en_UK");
            jsonFile = Resources.Load <TextAsset>("Localization/" + "en_UK" + "/Dictionaries" + fileName);
        }
        else
        {
            jsonFile = Resources.Load <TextAsset>("Localization/" + LanguageSelector.instance.GetCurrentLanguage() + "/" + fileName);
        }

        string     fileContents = jsonFile.text;
        JSONObject json         = JSONObject.Create(fileContents);

        foreach (Transform child in transform)
        {
            if (!child.GetComponent <ThrowDialog>())
            {
                Debug.LogWarning("The object with the name " + child.gameObject.name + " doesn't have ThrowDialog component");
            }
            else
            {
                ThrowDialog dialog   = child.GetComponent <ThrowDialog>();
                String      saveName = dialog.fieldName;
                String      name     = saveName.First().ToString().ToLower() + saveName.Substring(1);
                if (!sequenceDict.ContainsKey(saveName))
                {
                    try
                    {
                        if (json.HasField(name))
                        {
                            sequenceDict.Add(saveName, SequenceGenerator.createSimplyDialog(name, json, variablesObject));
                        }
                        else if (json.HasField(name.ToLower()))
                        {
                            sequenceDict.Add(saveName, SequenceGenerator.createSimplyDialog(name.ToLower(), json, variablesObject));
                        }
                        else
                        {
                            Debug.LogWarning("Dialog with key " + name + " doesn't exist in file " + fileName);
                        }
                    } catch (Exception e)
                    {
                        Debug.LogError("Error in " + jsonFile.name + " file. The error is: " + e.Message);
                    }
                }
            }
        }
    }