示例#1
0
        public void ProcessNumberVariableConstant()
        {
            SimpleContext sc   = new SimpleContext("");
            IEvaluator    etor = new PolishEvaluator();

            sc.Assign("a", 5);
            sc.Assign("b", 12);
            sc.Assign("na", -5);
            sc.Assign("nb", -12);

            var res = etor.Eval("$a $b +", sc);

            Assert.AreEqual(res, 17);

            res = etor.Eval("$a $nb +", sc);
            Assert.AreEqual(res, -7);

            res = etor.Eval("$b $na -", sc);
            Assert.AreEqual(res, 17);

            res = etor.Eval("$na $nb -", sc);
            Assert.AreEqual(res, 7);

            res = etor.Eval("2 $na 3 + -", sc);
            Assert.AreEqual(res, 4);
        }
示例#2
0
        public ELContext CreateElContext(IVariableContext variableContext)
        {
            SimpleContext elContext = new SimpleContext(resolver);

            elContext.PutContext(typeof(IVariableContext), variableContext);
            return(elContext);
        }
示例#3
0
            public void ShouldBeExecutedAsStaticIfInStaticScope()
            {
                var context = new SimpleContext();

                // Arrange
                Context.Initialize.Clear();

                // Need to emulate the InStaticScope method here for easier testing.
                _staticStack = new Stack();
                Context.Initialize.With(() => _staticStack);

                var newThread = new Thread(() => Context.Execute(context.Wait));

                // Act & Assert
                _staticStack.Count.Should().Equal(0);

                // Start the thread, wait for it to set the context.
                newThread.Start();
                Thread.Sleep(10);

                // Other thread is inside its context here, and since they share context it should be found.
                _staticStack.Count.Should().Equal(1);

                newThread.Join(30);
            }
示例#4
0
        public static void Clock()
        {
            float  epsilon         = .2f;
            string uniqueKey       = "clock";
            int    numFeatures     = 1000;
            int    numIter         = 1000;
            int    numWarmup       = 100;
            int    numInteractions = 1;
            uint   numActions      = 10;

            double timeInit = 0, timeChoose = 0, timeSerializedLog = 0;

            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            for (int iter = 0; iter < numIter + numWarmup; iter++)
            {
                watch.Restart();

                StringRecorder <SimpleContext> recorder = new StringRecorder <SimpleContext>();
                StringPolicy policy = new StringPolicy();
                MwtExplorer <SimpleContext>           mwt      = new MwtExplorer <SimpleContext>("mwt", recorder);
                EpsilonGreedyExplorer <SimpleContext> explorer = new EpsilonGreedyExplorer <SimpleContext>(policy, epsilon, numActions);

                timeInit += (iter < numWarmup) ? 0 : watch.Elapsed.TotalMilliseconds;

                Feature[] f = new Feature[numFeatures];
                for (int i = 0; i < numFeatures; i++)
                {
                    f[i].Id    = (uint)i + 1;
                    f[i].Value = 0.5f;
                }

                watch.Restart();

                SimpleContext context = new SimpleContext(f);

                for (int i = 0; i < numInteractions; i++)
                {
                    mwt.ChooseAction(explorer, uniqueKey, context);
                }

                timeChoose += (iter < numWarmup) ? 0 : watch.Elapsed.TotalMilliseconds;

                watch.Restart();

                string interactions = recorder.GetRecording();

                timeSerializedLog += (iter < numWarmup) ? 0 : watch.Elapsed.TotalMilliseconds;

                for (int i = 0; i < numInteractions; i++)
                {
                    mwt.ChooseAction(explorer, uniqueKey, context);
                }
            }
            Console.WriteLine("--- PER ITERATION ---");
            Console.WriteLine("# iterations: {0}, # interactions: {1}, # context features {2}", numIter, numInteractions, numFeatures);
            Console.WriteLine("Init: {0} micro", timeInit * 1000 / numIter);
            Console.WriteLine("Choose Action: {0} micro", timeChoose * 1000 / (numIter * numInteractions));
            Console.WriteLine("Get Serialized Log: {0} micro", timeSerializedLog * 1000 / numIter);
            Console.WriteLine("--- TOTAL TIME: {0} micro", (timeInit + timeChoose + timeSerializedLog) * 1000);
        }
 public void Any_returns_false_for_empty_sets()
 {
     using (var db = new SimpleContext())
     {
         db.Artists.Any();
     }
 }
 public async Task CanConnect_returns_true(bool async)
 {
     using (var context = new SimpleContext())
     {
         Assert.True(async ? await context.Database.CanConnectAsync() : context.Database.CanConnect());
     }
 }
 public void TestResourses()
 {
     Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-GB");
     using (var db = new SimpleContext()) {
         var test = db.SimpleEntities.FirstOrDefault();
     }
 }
        public void WrongPassedIdentityTest()
        {
            ISimpleService service = Simply.Do[ConfigKey].Resolve <ISimpleService>();

            SimpleContext.Get().Username = null;
            service.TestPassedIdentity().Should().Be.False();
        }
示例#9
0
            public void ShouldBeExecutedAsThreadStaticIfInThreadScope()
            {
                var context = new SimpleContext();

                // Arrange
                Context.Initialize.Clear();

                // Need to emulate the InThreadScope method here for easier testing.
                var stack = new ThreadLocal <Stack>(() => new Stack());

                Context.Initialize.With(() => stack.Value);

                var newThread = new Thread(() => Context.Execute(context.Wait));

                // Act & Assert
                stack.Value.Count.Should().Equal(0);

                // Start the thread, wait for it to set the context.
                newThread.Start();
                Thread.Sleep(10);

                // Other thread is inside its context here, but this context stack should be empty.
                stack.Value.Count.Should().Equal(0);

                newThread.Join(30);
            }
        public static QueryInput GetQueryParameters(this SimpleContext context)
        {
            var query      = context.Request.Query;
            var parameters = new QueryInput();

            foreach (var key in query.Keys)
            {
                int number;
                switch (key.ToLowerInvariant())
                {
                case "skip":
                    parameters.Skip = int.TryParse(query[key].LastOrDefault(), out number) ? number : 0;
                    break;

                case "take":
                    parameters.Take = int.TryParse(query[key].LastOrDefault(), out number) ? number : 0;
                    break;

                case "q":
                    parameters.Query = QueryParser.Parse(query[key].LastOrDefault());
                    break;
                }
            }
            return(parameters);
        }
示例#11
0
        static void Main(string[] args)
        {
            Console.WriteLine(Help);

            var input = (string)null;

            using (var context = new SimpleContext()) { var x = context.Simple.ToList(); };
            do
            {
                Console.WriteLine("Choose option:");
                input = Console.ReadLine();
                switch (input)
                {
                case "0": return;

                case "1": option1(); break;

                case "2": option2(); break;

                case "3": option3(); break;

                case "4": option4(); break;

                case "5": option5(); break;

                case "6": option6(); break;

                default: Console.WriteLine(Help); break;
                }
            } while (!"0".Equals(input));
        }
        public int TestHeaderPassingAndReturning()
        {
            int a = (int)SimpleContext.Get().ExtendedInfo["returnMe"];

            SimpleContext.Get().ExtendedInfo["returnMe"] = a + 2;
            return(a);
        }
示例#13
0
 private static void option2()
 {
     Console.WriteLine("How many records per batch:");
     if (int.TryParse(Console.ReadLine(), out int batch))
     {
         if (batch > 0)
         {
             using (var context = new SimpleContext())
             {
                 context.Database.ExecuteSqlCommand("DELETE FROM dbo.SimpleSnapshot");
                 context.Configuration.AutoDetectChangesEnabled = false;
                 context.Configuration.ValidateOnSaveEnabled    = false;
                 var start = DateTime.Now;
                 var count = 0;
                 foreach (var line in File.ReadAllLines("Bulk.txt"))
                 {
                     var split = line.Split(';');
                     count++;
                     context.SimpleSnapshot.Add(new SimpleSnapshotTable()
                     {
                         BusinessKey = int.Parse(split[0]), Payload = split[1]
                     });
                     if (count % batch == 0)
                     {
                         context.SaveChanges();
                     }
                 }
                 context.SaveChanges();
                 var end = DateTime.Now;
                 Console.WriteLine("Writing of {0} records finished in {1} seconds", count, (end - start).TotalSeconds);
             }
         }
     }
 }
示例#14
0
 private static void option5()
 {
     using (var context = new SimpleContext())
     {
         context.Database.ExecuteSqlCommand("TRUNCATE TABLE dbo.Simple;");
     }
 }
示例#15
0
        public async Task <string> Render(SimpleContext context, object model)
        {
            var layout = await _fileLoader.GetAsync("Views/_Layout.html");

            if (model == null)
            {
                return("<html><head><meta charset=\"UTF-8\"/><title>Null</title></head><body>Null</body></html>");
            }
            var content = await _fileLoader.GetOrDefaultAsync($"Views/{model.GetType().Name}.html") ??
                          await _fileLoader.GetAsync("Views/Json.html");

            var dictionary = new Dictionary <string, object>
            {
                ["@BasePath"] = context.Request.PathBase,
                ["@Path"]     = context.Request.Path,
                ["@Model"]    = _toJson(model)
            };

            foreach (var pair in context.ViewBag)
            {
                dictionary[$"@ViewBag.{pair.Key}"] = pair.Value;
            }

            var html = layout.Replace("@Content", content);

            return(DoRender(html, dictionary));
        }
示例#16
0
        /// <summary>
        /// Returns the number of new posts across all teams for the given user, for this assignment
        /// </summary>
        /// <returns></returns>
        public int GetNewPostsCount(int currentCourseUserId)
        {
            int returnVal = 0;

            if (this.Type == AssignmentTypes.CriticalReviewDiscussion || this.Type == AssignmentTypes.DiscussionAssignment)
            {
                using (ContextBase db = new SimpleContext())
                {
                    if (this.HasDiscussionTeams)
                    {
                        //Sum new posts across all teams
                        foreach (DiscussionTeam dt in this.DiscussionTeams)
                        {
                            returnVal += dt.GetNewPostsCount(currentCourseUserId);
                        }
                    }
                    else //Class wide discussion
                    {
                        //Get new posts for any discussion team, since the whole class is posting together.
                        if (this.DiscussionTeams != null)
                        {
                            if (this.DiscussionTeams.FirstOrDefault() != null)
                            {
                                returnVal = this.DiscussionTeams.FirstOrDefault().GetNewPostsCount(currentCourseUserId);
                            }
                        }
                    }
                }
            }
            return(returnVal);
        }
示例#17
0
        private async Task <object> DbInfo(SimpleContext context, Match match)
        {
            context.ViewBag["Title"] = "Index";
            var db = await _options.DataStore.GetInfo().ConfigureAwait(false);

            return(db);
        }
示例#18
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional, action = RouteParameter.Optional }
                );

            var builder = new ContainerBuilder();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            var simpleContext = new SimpleContext();

            builder.RegisterInstance(simpleContext).As <SimpleContext>().SingleInstance();

            builder.RegisterType <ProductRepository>().As <IProductRepository>().InstancePerLifetimeScope();
            builder.RegisterType <OrderRepository>().As <IOrderRepository>().InstancePerLifetimeScope();

            var container = builder.Build();

            using (var scope = container.BeginLifetimeScope())
            {
                config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            }
        }
示例#19
0
        private void EndToEnd(MwtExplorer <SimpleContext> mwtt, IExplorer <SimpleContext> explorer, TestRecorder <SimpleContext> recorder)
        {
            uint numActions = 10;

            Random rand = new Random();

            List <float> rewards = new List <float>();

            for (int i = 0; i < 1000; i++)
            {
                Feature[] f = new Feature[rand.Next(800, 1201)];
                for (int j = 0; j < f.Length; j++)
                {
                    f[j].Id    = (uint)(j + 1);
                    f[j].Value = (float)rand.NextDouble();
                }
                SimpleContext c = new SimpleContext(f);

                mwtt.ChooseAction(explorer, i.ToString(), c);

                rewards.Add((float)rand.NextDouble());
            }

            var testInteractions = recorder.GetAllInteractions();

            Interaction[] partialInteractions = new Interaction[testInteractions.Count];
            for (int i = 0; i < testInteractions.Count; i++)
            {
                partialInteractions[i] = new Interaction()
                {
                    ApplicationContext = new OldSimpleContext(testInteractions[i].Context.GetFeatures(), null),
                    ChosenAction       = testInteractions[i].Action,
                    Probability        = testInteractions[i].Probability,
                    Id = testInteractions[i].UniqueKey
                };
            }

            MwtRewardReporter mrr = new MwtRewardReporter(partialInteractions);

            for (int i = 0; i < partialInteractions.Length; i++)
            {
                Assert.AreEqual(true, mrr.ReportReward(partialInteractions[i].GetId(), rewards[i]));
            }

            Interaction[] completeInteractions = mrr.GetAllInteractions();
            MwtOptimizer  mop = new MwtOptimizer(completeInteractions, numActions);

            string modelFile = "model";

            mop.OptimizePolicyVWCSOAA(modelFile);

            Assert.IsTrue(System.IO.File.Exists(modelFile));

            float evaluatedValue = mop.EvaluatePolicyVWCSOAA(modelFile);

            Assert.IsFalse(float.IsNaN(evaluatedValue));

            System.IO.File.Delete(modelFile);
        }
示例#20
0
        public void Default_ContextSeeder_Creates_No_Null_MockCollections()
        {
            var           seeder = new ContextSeeder <SimpleContext>();
            SimpleContext db     = seeder.SeedDatabase();

            Assert.IsTrue(db.Customers.All(c => c != null));
            Assert.IsTrue(db.Products.All(c => c != null));
        }
示例#21
0
        public void ContexSeeder_Returns_Empty_MockContext()
        {
            var           seeder = new ContextSeeder <SimpleContext>();
            SimpleContext db     = seeder.SeedDatabase(0);

            Assert.IsNotNull(db);
            Assert.IsTrue(db.Customers.Count == 0);
        }
示例#22
0
        public void Default_ContextSeeder_Creates_Data()
        {
            var           seeder = new ContextSeeder <SimpleContext>();
            SimpleContext db     = seeder.SeedDatabase();

            Assert.IsTrue(db.Customers.Count == 30);
            Assert.IsTrue(db.Products.Count == 30);
        }
 public void Any_returns_false_for_empty_sets()
 {
     using (var db = new SimpleContext())
     {
         // ReSharper disable once AccessToDisposedClosure
         Assert.DoesNotThrow(() => db.Artists.Any());
     }
 }
        /// <summary>
        /// Updates the current parameter in the session's signatures, based on information in the specified <see cref="SimpleContext"/>.
        /// </summary>
        /// <param name="session">The <see cref="IParameterInfoSession"/> to update.</param>
        /// <param name="context">The <see cref="SimpleContext"/> to examine.</param>
        /// <returns>
        /// <c>true</c> if an update was made; otherwise, <c>false</c>.
        /// </returns>
        protected virtual bool UpdateCurrentParameter(IParameterInfoSession session, SimpleContext context)
        {
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var updated = false;

            if ((context != null) && (session != null))
            {
                // Loop through signatures in the session
                foreach (var signatureItem in session.Items)
                {
                    if (signatureItem != null)
                    {
                        // Get the content provider if it is a parameterized one (allows parameter updating)
                        var contentProvider = signatureItem.ContentProvider as IParameterizedContentProvider;
                        if (contentProvider != null)
                        {
                            // Get the function declaration
                            var functionDecl = signatureItem.Tag as FunctionDeclaration;
                            if ((functionDecl != null) && (functionDecl.Parameters.Count > 0))
                            {
                                if (context.ArgumentIndex.HasValue)
                                {
                                    // Get the parameter index and set if valid
                                    int parameterIndex = context.ArgumentIndex.Value;

                                    // If the parameter index is valid...
                                    if ((parameterIndex >= 0) && (parameterIndex < functionDecl.Parameters.Count))
                                    {
                                        if (contentProvider.ParameterIndex != parameterIndex)
                                        {
                                            updated = true;
                                            contentProvider.ParameterIndex = parameterIndex;
                                        }
                                        continue;
                                    }
                                }

                                // Clear the current parameter
                                if (contentProvider.ParameterIndex.HasValue)
                                {
                                    updated = true;
                                    contentProvider.ParameterIndex = null;
                                }
                            }
                        }
                    }
                }
            }
            return(updated);
        }
示例#25
0
        private async Task <object> ClearAllCollections(SimpleContext context, Match match)
        {
            await _options.DataStore.ClearAllCollections().ConfigureAwait(false);

            return(new ResponseMessage
            {
                Message = "Cleared all collections"
            });
        }
示例#26
0
        private async Task <object> ClearCollection(SimpleContext context, Match match)
        {
            var collection = match.Groups["collection"].Value;
            await _options.DataStore.ClearCollection(collection).ConfigureAwait(false);

            return(new ResponseMessage
            {
                Message = $"Cleared {collection}"
            });
        }
示例#27
0
        private async Task <object> QueryCollection(SimpleContext context, Match match)
        {
            var parameters = context.GetQueryParameters();
            var collection = match.Groups["collection"].Value;

            context.ViewBag["Title"] = collection;
            var result = await _options.DataStore.QueryCollection(collection, parameters).ConfigureAwait(false);

            return(result);
        }
示例#28
0
 public void SimpleContextThrowsError()
 {
     var client = new TargetProcessClient
     {
         ApiSiteInfo = new ApiSiteInfo(TargetProcessRoutes.Route.SimpleContexts)
     };
     var simpleContext = new SimpleContext
     {
     };
 }
示例#29
0
        public Models.ListContactsViewModel GetListContactsViewModel()
        {
            var model = new ListContactsViewModel();

            SimpleContext db = new SimpleContext();

            model.Contacts = db.Contacts.ToList();

            return(model);
        }
        public void HeaderPassingTest()
        {
            ISimpleService service = Simply.Do[ConfigKey].Resolve <ISimpleService>();

            SimpleContext.Get().ExtendedInfo["returnMe"] = "123";
            service.TestHeaderPassing().Should().Be("123");

            SimpleContext.Get().ExtendedInfo["returnMe"] = "1234";
            service.TestHeaderPassing().Should().Be("1234");
        }
 public SimpleDataSeeder(SimpleContext ctx)
 {
     _ctx = ctx;
 }
示例#32
0
 public InsertSimpleContext(SimpleContext simpleCtxt)
     : base(null)
 {
     _simpleCtxt = simpleCtxt;
 }
示例#33
0
            public void ShouldReturnAValueIfAFuncIsUsed()
            {
                // Arrange
                var context1 = new SimpleContext();

                // Act
                var output = Context.ExecuteAndReturn(context1.ReturnAValue);

                // Assert
                output.Should().Equal(TestPropertyMessage);
            }
示例#34
0
 public ModifyFromInput(string partName, SimpleContext simpleCtxt)
     : base(partName)
 {
     _simpleCtxt = simpleCtxt;
 }
示例#35
0
            public void ShouldThrowExceptionIfAnObjectIsSuppliedThatHasNoExecuteMethod()
            {
                // Arrange
                var context = new SimpleContext();

                // Act
                Context.Execute(context);

                // Assert
            }
示例#36
0
            public void CanSetContextSpecificallyByASecondParameter()
            {
                // Arrange
                var context1 = new SimpleContext();
                var context2 = new SimpleContext();

                // Act
                Context.Execute(context1.AssignTestPropertyToContext, context2);

                // Assert
                context2.TestProperty.Should().Equal(TestPropertyMessage);
            }
示例#37
0
    public static void Main(string[] args)
    {
        /*
        Assembly a = Assembly.LoadFrom ("SharpHsql.dll");
        Console.WriteLine (a.CodeBase);
        Assembly al = Assembly.LoadFrom ("SharpHsql.Linq.dll");
        Console.WriteLine (al.CodeBase);
        */
        using (var context = new SimpleContext ()) {
            var person = new Person {
                FirstName = "Joe",
                LastName = "Bloggs"
            };

            context.People.Add (person);
            context.SaveChanges ();
        }
    }
示例#38
0
            public void ShouldPutTheExecutingObjectAsContext()
            {
                // Arrange
                var context = new SimpleContext();

                // Act
                Context.Execute(context.AssignTestPropertyToContext);

                // Assert
                context.TestProperty.Should().Equal(TestPropertyMessage);
            }
 public StudentRepository(SimpleContext ctx)
 {
     _ctx = ctx;
 }
示例#40
0
            public void ShouldBeExecutedAsStaticIfInStaticScope()
            {
                var context = new SimpleContext();

                // Arrange
                Context.Initialize.Clear();

                // Need to emulate the InStaticScope method here for easier testing.
                _staticStack = new Stack();
                Context.Initialize.With(() => _staticStack);

                var newThread = new Thread(() => Context.Execute(context.Wait));

                // Act & Assert
                _staticStack.Count.Should().Equal(0);

                // Start the thread, wait for it to set the context.
                newThread.Start();
                Thread.Sleep(10);

                // Other thread is inside its context here, and since they share context it should be found.
                _staticStack.Count.Should().Equal(1);

                newThread.Join(30);
            }
示例#41
0
            public void ShouldBeExecutedAsThreadStaticIfInThreadScope()
            {
                var context = new SimpleContext();

                // Arrange
                Context.Initialize.Clear();

                // Need to emulate the InThreadScope method here for easier testing.
                var stack = new ThreadLocal<Stack>(() => new Stack());
                Context.Initialize.With(() => stack.Value);

                var newThread = new Thread(() => Context.Execute(context.Wait));

                // Act & Assert
                stack.Value.Count.Should().Equal(0);

                // Start the thread, wait for it to set the context.
                newThread.Start();
                Thread.Sleep(10);

                // Other thread is inside its context here, but this context stack should be empty.
                stack.Value.Count.Should().Equal(0);

                newThread.Join(30);
            }