Example #1
0
        public void AddStartStopSymbolsTest()
        {
            var tokens = new[] {"this", "is", "a", "test"};
            List<string> actual = tokens.ToList();
            List<string> expected = tokens.ToList();
            var model = new NGramModel(Unigram);
            model.AddStartStopSymbols(actual);
            CollectionAssert.AreEqual(expected, actual);

            model = new NGramModel(Bigram);
            actual = tokens.ToList();
            expected = new[] {"<s0>", "this", "is", "a", "test", "</s>"}.ToList();
            model.AddStartStopSymbols(actual);
            CollectionAssert.AreEqual(expected, actual);

            model = new NGramModel(Trigram);
            actual = tokens.ToList();
            expected = new[] {"<s1>", "<s0>", "this", "is", "a", "test", "</s>"}.ToList();
            model.AddStartStopSymbols(actual);
            CollectionAssert.AreEqual(expected, actual);

            model = new NGramModel(4);
            actual = tokens.ToList();
            expected = new[] {"<s2>", "<s1>", "<s0>", "this", "is", "a", "test", "</s>"}.ToList();
            model.AddStartStopSymbols(actual);
            CollectionAssert.AreEqual(expected, actual);
        }
Example #2
0
        public static void Mod_Test()
        {
            var num1 = new[] {23.4m, 45, 0.96m, 31.2m, 0.87m, 0.8m};
            var num2 = 0.5m;

            Console.WriteLine(num1.Select(x => x.ToString()).Aggregate((x, y) => x + "," + y));
            num1.ToList().ForEach(x => Console.WriteLine("{0} 对 {1} 的余数: {2}", x, num2, x%num2));
            Console.WriteLine("-----------------------------------------------------------------");
            num1.ToList().ForEach(x => Console.WriteLine("{0} 项上取整 {1} 数", x, Math.Ceiling(x)));
            Console.WriteLine("-----------------------------------------------------------------");
            num1.ToList().ForEach(x => Console.WriteLine("{0}/0.5 项上取整 {1} 数", x, Math.Ceiling(x/0.5m)));
        }
        public static Commit BuildCommit(this Guid streamId)
        {
            const int StreamRevision = 2;
            const int CommitSequence = 2;
            var commitId = Guid.NewGuid();
            var headers = new Dictionary<string, object> { { "Key", "Value" }, { "Key2", (long)1234 }, { "Key3", null } };
            var events = new[]
            {
                new EventMessage
                {
                    Headers =
                    {
                        { "MsgKey1", TimeSpan.MinValue },
                        { "MsgKey2", Guid.NewGuid() },
                        { "MsgKey3", 1.1M },
                        { "MsgKey4", (ushort)1 }
                    },
                    Body = "some value"
                },
                new EventMessage
                {
                    Headers =
                    {
                        { "MsgKey1", new Uri("http://www.google.com/") },
                        { "MsgKey4", "some header" }
                    },
                    Body = new[] { "message body" }
                }
            };

            return new Commit(streamId, StreamRevision, commitId, CommitSequence, SystemTime.UtcNow, headers, events.ToList());
        }
Example #4
0
		protected override void OnCreate (Bundle savedInstanceState)
		{
			base.OnCreate (savedInstanceState);
			SetContentView (Resource.Layout.recyclerview);

			recyclerView = FindViewById<RecyclerView> (Resource.Id.recycler_view);

			// Layout Managers:
			recyclerView.SetLayoutManager (new LinearLayoutManager (this));

			// Item Decorator:
			recyclerView.AddItemDecoration (new DividerItemDecoration (Resources.GetDrawable (Resource.Drawable.divider)));
			recyclerView.SetItemAnimator (new FadeInLeftAnimator ());

			// Adapter:
			var adapterData = new [] {
				"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", 
				"Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", 
				"Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", 
				"Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", 
				"Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", 
				"New Hampshire", "New Jersey", "New Mexico", "New York", 
				"North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", 
				"Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", 
				"Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", 
				"West Virginia", "Wisconsin", "Wyoming"
			};
			adapter = new RecyclerViewAdapter (this, adapterData.ToList ());
			adapter.Mode = Attributes.Mode.Single;
			recyclerView.SetAdapter (adapter);

			// Listeners
			recyclerView.SetOnScrollListener (new ScrollListener ());
		}
Example #5
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            SetContentView (Resource.Layout.Main);

            Button button = FindViewById<Button> (Resource.Id.btnRun);

            button.Click += (a, b) =>
            {
                var runs = new[]{
                    new{alg= (IPrime)new AlgorithmAJavaMath(), label= FindViewById<TextView>(Resource.Id.lblAlgAJava), text = "A (java.lang.Math): "},
                    new{alg= (IPrime)new AlgorithmAMonoMath(), label= FindViewById<TextView>(Resource.Id.lblAlgAMono), text = "A (System.Math): "},
                    new{alg= (IPrime)new AlgorithmB(), label= FindViewById<TextView>(Resource.Id.lblAlgB), text = "B: "},
                };

                const int iterations = 100000;

                runs.ToList().ForEach(x =>
                {
                    var elapsed = TheBenchmark.Timed(() =>
                    {
                        for(int i=0; i<iterations; i++)
                        {
                            x.alg.IsPrime(i);
                        }
                    });
                    x.label.Text = x.text + " " + elapsed.TotalMilliseconds;
                });
            };
        }
        protected override System.IAsyncResult OnBeginWorkflowCompleted(System.Activities.ActivityInstanceState completionState, System.Collections.Generic.IDictionary<string, object> workflowOutputs, System.Exception terminationException, System.TimeSpan timeout, System.AsyncCallback callback, object state) {

            if(terminationException == null) {
                MailMessage mail = new MailMessage();
                mail.To.Add(Email);

                mail.From = new MailAddress("foo@bar.com");

                mail.Subject = "The workflow has completed";

                StringBuilder stringBuilder = new StringBuilder();
                
                stringBuilder.AppendLine("The result of the workflow was: ");
                
                workflowOutputs.ToList().ForEach(kvp => 
                    stringBuilder.AppendLine(string.Format("{0}: {1}", kvp.Key, kvp.Value))
                );
                
                mail.Body = stringBuilder.ToString();

                mail.IsBodyHtml = false;

                SmtpClient smtp = new SmtpClient();
                smtp.Send(mail);
                
            }

            return base.OnBeginWorkflowCompleted(completionState, workflowOutputs, terminationException, timeout, callback, state);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            btnBenchmark.TouchUpInside += (object sender, EventArgs e) =>
            {
                var runs = new[]{
                    new{alg= (IPrime)new AlgorithmAMonoMath(), label= lblStackOverflow, text = "A: "},
                    new{alg= (IPrime)new AlgorithmB(), label= lblPerls, text = "B: "},
                };

                const int iterations = 100000;

                runs.ToList().ForEach(x =>
                {
                    var elapsed = TheBenchmark.Timed(() =>
                    {
                        for(int i=0; i<iterations; i++)
                        {
                            var p = x.alg.IsPrime(i);
                        }
                    });
                    x.label.Text = x.text + " " + elapsed.TotalMilliseconds;
                });
            };
        }
        public CacheSet<string> SelectByIDs(string EntityName, System.Collections.Generic.IEnumerable<string> EntityIDs)
        {
            CacheSet<string> Result = new CacheSet<string>();

            if (!EntityNames.Contains(EntityName))
            {
                Result.WantIDs = EntityIDs.ToList<string>();

                return Result;
            }

            List<string> IDs = new List<string>();
            List<string> Contents = new List<string>();

            StringBuilder QueryBuilder = new StringBuilder();
            QueryBuilder.AppendFormat("select * from {0} where ID in ({1}) order by ID", EntityName, ToCommaList(EntityIDs));

            DataTable Table = SQLLite.GetDataTable(QueryBuilder.ToString());

            for (int i=0; i < Table.Rows.Count; i++)
            {
                IDs.Add(Table.Rows[i][0].ToString());
                Contents.Add(Table.Rows[i][1].ToString());
            }

            Result.Records = Contents;

            Result.WantIDs = EntityIDs.Except<string>(IDs).ToList<string>();

            return Result;
        }
Example #9
0
        public void GetParsedEntities_should_return_two_entities_when_all_pattern_groups_are_used()
        {
            var correctAnswer = new[] { (Entity)new RawTextEntity("|"), new TestEntity("treasure") };
            var answer = Apply_GetParsedEntities("|treasure|some text|");

            CollectionAssert.AreEqual(correctAnswer.ToList(), answer);
        }
        public void GivenProductsWithCurrentCampaignWithSomeThatApplyToTheMember_WhenQuerying_ThenReturnTheProductsThatApplyToTheMember()
        {
            var member = new MemberBuilder().InState(State.Wa).WithAge(10, _now).Build();
            var products = new[]
            {
                new ProductBuilder().WithName("1").WithCampaign(_now,
                    new CampaignBuilder()
                        .ForAllMembers()
                        .StartingAt(_now.AddDays(-1))
                        .EndingAt(_now.AddDays(1))
                ).Build(),
                new ProductBuilder().WithName("2").WithCampaign(_now,
                    new CampaignBuilder()
                        .ForState(State.Act)
                        .StartingAt(_now.AddDays(-1))
                        .EndingAt(_now.AddDays(1))
                ).Build(),
                new ProductBuilder().WithName("2").WithCampaign(_now,
                    new CampaignBuilder()
                        .ForState(State.Wa)
                        .WithMinimumAge(9)
                        .WithMaximumAge(11)
                        .StartingAt(_now.AddDays(-1))
                        .EndingAt(_now.AddDays(1))
                ).Build()
            };
            products.ToList().ForEach(p => Session.Save(p));

            var result = Execute(new GetProductsForMember(_now, member));

            Assert.That(result.Select(p => p.Name).ToArray(), Is.EqualTo(new[]{products[0].Name, products[2].Name}));
        }
Example #11
0
        public void GetParsedEntities_should_return_one_entity_when_first_pattern_group_is_empty()
        {
            var correctAnswer = new[] { (Entity)new TestEntity("treasure") };
            var answer = Apply_GetParsedEntities("treasure|some text|");

            CollectionAssert.AreEqual(correctAnswer.ToList(), answer);
        }
Example #12
0
		public void EventTest ()
		{
			var automationEventsArray = new [] {
				new {Sender = (object) null, Args = (AutomationPropertyChangedEventArgs) null}};
			var automationEvents = automationEventsArray.ToList ();
			automationEvents.Clear ();

			var dock = (DockPattern)
				splitter1Element.GetCurrentPattern (DockPattern.Pattern);

			dock.SetDockPosition (DockPosition.Top);

			SWA.Automation.AddAutomationPropertyChangedEventHandler (splitter1Element,
				TreeScope.Element,
				(o, e) => automationEvents.Add (new { Sender = o, Args = e }),
				DockPattern.DockPositionProperty);

			dock.SetDockPosition (DockPosition.Right);
			Thread.Sleep (200);
			Assert.AreEqual (1, automationEvents.Count, "event count");
			Assert.AreEqual (DockPattern.DockPositionProperty,
				automationEvents [0].Args.Property, "event property");
			Assert.AreEqual (splitter1Element,
				automationEvents [0].Sender, "event sender");
			Assert.AreEqual (3,
				automationEvents [0].Args.NewValue, "event new val");
		}
        protected override Expression VisitBinary(BinaryExpression node)
        {
            if (node == null)
            {
                throw new ArgumentNullException("node");
            }

            var allowedProperties = new[] { "Project", "Definition", "Number", "Reason", "Quality", "Status", "RequestedBy", "RequestedFor", "StartTime", "FinishTime", "BuildFinished" };

            if (node.NodeType == ExpressionType.OrElse)
            {
                throw new NotSupportedException("Logical OR operators are not supported for Build Custom filters");
            }

            if (node.Left is MemberExpression && node.Right is ConstantExpression)
            {
                var fieldName = (node.Left as MemberExpression).Member.Name;
                var value = (node.Right as ConstantExpression).Value;

                if (!allowedProperties.ToList().Contains(fieldName))
                {
                    throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "You can only filter by the following properties: {0}. (e.g. /Builds/$filter=Number gt 100 and  Quality eq 'Healthy') ", string.Join(", ", allowedProperties)));
                }

                this.AddFilterNode(fieldName, value, FilterNode.ParseFilterExpressionType(node.NodeType), FilterNodeRelationship.And);
            }
            else if (node.Left.NodeType == ExpressionType.Conditional)
            {
                throw new NotSupportedException("Only equality and inequality operators between fields and constant expressions are allowed with Build Custom filters");
            }

            return base.VisitBinary(node);
        }
        protected override Expression VisitBinary(BinaryExpression node)
        {
            if (node == null)
            {
                throw new ArgumentNullException("node");
            }

            var allowedProperties = new[] { "Id", "ArtifactUri", "Comment", "Committer", "CreationDate", "Owner", "Branch" };

            if (node.NodeType == ExpressionType.OrElse)
            {
                throw new NotSupportedException("Logical OR operators are not supported for Changeset Custom filters");
            }

            if (node.Left is MemberExpression && node.Right is ConstantExpression)
            {
                var fieldName = (node.Left as MemberExpression).Member.Name;
                var value = (node.Right as ConstantExpression).Value;

                if (!allowedProperties.ToList().Contains(fieldName))
                {
                    throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "You can only filter by the following properties: {0}. (e.g. /Changesets/$filter=Committer eq 'john' and  CreationDate gt datetime'2010-10-18') ", string.Join(", ", allowedProperties)));
                }

                this.AddFilterNode(fieldName, value, FilterNode.ParseFilterExpressionType(node.NodeType), FilterNodeRelationship.And);
            }
            else if (node.Left.NodeType == ExpressionType.Conditional)
            {
                throw new NotSupportedException("Only equality and inequality operators between fields and constant expressions are allowed with Changeset Custom filters");
            }

            return base.VisitBinary(node);
        }
Example #15
0
		public void PropertyEventTest ()
		{
			var automationEventsArray = new [] {
				new {Sender = (object) null, Args = (AutomationPropertyChangedEventArgs) null}};
			var automationEvents = automationEventsArray.ToList ();
			automationEvents.Clear ();

			string magicStr1 = "ValuePatternTest.PropertyEventTest.m1";
			string magicStr2 = "ValuePatternTest.PropertyEventTest.m2";
			ValuePattern pattern = (ValuePattern) textbox1Element.GetCurrentPattern (ValuePatternIdentifiers.Pattern);
			pattern.SetValue (magicStr1);
			Thread.Sleep (500);

			AutomationPropertyChangedEventHandler handler = 
				(o, e) => automationEvents.Add (new { Sender = o, Args = e });

			At.AddAutomationPropertyChangedEventHandler (textbox1Element,
				TreeScope.Element, handler,
				ValuePattern.ValueProperty,
				ValuePattern.IsReadOnlyProperty );

			pattern.SetValue (magicStr2);
			Thread.Sleep (500);
			Assert.AreEqual (1, automationEvents.Count, "event count");
			Assert.AreEqual (textbox1Element, automationEvents [0].Sender, "event sender");
			Assert.AreEqual (magicStr2, automationEvents [0].Args.NewValue, "new Value");
			// LAMESPEC: The value should be equal to "magicStr1" but is returning null instead
			Assert.IsNull (automationEvents [0].Args.OldValue, "old Value");
			automationEvents.Clear ();

			At.RemoveAutomationPropertyChangedEventHandler (textbox1Element, handler);
			pattern.SetValue (magicStr1);
			Thread.Sleep (500);
			Assert.AreEqual (0, automationEvents.Count, "event count");
		}
Example #16
0
        public static GuidAsBasicType GetSampleInstance()
        {
            var guids = new []
                            {
                                new Guid("fed92f33-e351-47bd-9018-69c89928329e"),
                                new Guid("042ba99c-b679-4975-ac4d-2fe563a5dc3e"),
                                new Guid("82071c51-ea20-473b-a541-1ebdf8f158d3"),
                                new Guid("81a3478b-5779-451a-b2aa-fbf69bb11424"),
                                new Guid("d626ba2b-a095-4a34-a376-997e5628dfb9"),
                            };

            var dicKey = new Dictionary<Guid, int> {{guids[0], 1}, {guids[1], 2}, {guids[2], 3}};
            var dicValue = new Dictionary<int, Guid> { { 1, guids[0] }, { 2, guids[2]}, { 3, guids[4]} };

            return new GuidAsBasicType
                       {
                            GuidAsAttr = guids[0],
                            GuidAsElem = guids[1],
                            GuidArray = guids,
                            GuidsList = guids.ToList(),
                            GuidArraySerially = guids,
                            DicKeyAttrGuid = dicKey,
                            DicKeyGuid = dicKey,
                            DicValueAttrGuid = dicValue,
                            DicValueGuid = dicValue
                       };
        }
Example #17
0
        static void Main(String[] args)
        {
            #region dynamic

            dynamic ola = "ta se loco!";
            ola += 10;
            int i = 10;

            dynamic oi = new ExpandoObject();
            oi.saudacao = "ta se loco!";
            Console.WriteLine(oi.saudacao);

            #endregion

            #region Arraii
            var numeros = new[] { 1, 2, 3 };
            numeros.ToList().Add(4);

            /*
            //FOR
            for (int e = 0; e < 10000; e++)
            {
                Console.WriteLine(e);
            }
            //FOREACH
            foreach (var u in numeros)
            {
                Console.WriteLine(u);
            }
            */
            Console.WriteLine("Ana".ToBacon());

            //var numeros = new[] { 1, 2, 3 }.ToList(); -> para poder manipular essa cesta de gatos, tem que tornala uma lista;
            //numeros.AddRange(new[] {4,5}); -> inserir mais numeros na list
            // interfaces em C# começam com I. ex.: IList<int> num = new List<int>();
            //var numeros = new List<int> (capacity: 10);
            //capacity - > para predefinir a capacidade inicial da lista, pode aumentar(elastica)

            #endregion

            # region herança

            var yoda = new Jedi
            {
                Nome = "Yoda"
            };

            //yoda.Nome = "Yoda";

            Console.WriteLine(yoda.Nome);

            #endregion

            #region datetime
            DateTime agora = DateTime.Now;
            Console.WriteLine(agora);
            #endregion

            Console.ReadLine();
        }
Example #18
0
        public void Run()
        {
            var array = new[] { 16, 14, 10, 8, 7, 9, 30, 20, 4, 1, 15 };

            Sort(array);

            array.ToList().ForEach(Console.WriteLine);
        }
Example #19
0
        //http://www.cnblogs.com/kkun/archive/2011/11/23/2260286.html
        //Top K
        public void Run()
        {
            var array = new[] { 16, 14, 10, 8, 7, 9, 3, 2, 4, 1 };

            HeapSortFunction(array);

            array.ToList().ForEach(Console.WriteLine);
        }
Example #20
0
        //http://www.cnblogs.com/morewindows/archive/2011/08/13/2137415.html
        public void Run()
        {
            int[] array = new[] { 20, 2, 4, 45, 6, 7, 8, 6, 4, 3, 4, 45, 67, 3 };

            QSort(array, 0, array.Length - 1);

            array.ToList().ForEach(q => Console.WriteLine(q));
        }
 /// <summary>
 /// Creates the model.
 /// </summary>
 /// <param name="pages">The pages.</param>
 /// <param name="request">The request.</param>
 /// <param name="count">The count.</param>
 /// <param name="categoriesFuture">The categories future.</param>
 /// <param name="layouts">The layouts.</param>
 /// <returns>
 /// Model
 /// </returns>
 protected override PagesGridViewModel<SiteSettingPageViewModel> CreateModel(System.Collections.Generic.IEnumerable<SiteSettingPageViewModel> pages,
     PagesFilter request, NHibernate.IFutureValue<int> count,
     System.Collections.Generic.IList<LookupKeyValue> layouts)
 {
     return new UntranslatedPagesGridViewModel<SiteSettingPageViewModel>(
         pages.ToList(),
         request as UntranslatedPagesFilter,
         count.Value) { Layouts = layouts };
 }
Example #22
0
        public void AnonymousTypesTest()
        {
            var source = new[] {
                new {Id = 1, Widget = "Hello"},
                new {Id = 2, Widget = "Foobar"}
            };

            var list = source.ToList();
        }
Example #23
0
    public void Accumulate_is_lazy()
    {
        var counter = 0;
        var accumulation = new[] { 1, 2, 3 }.Accumulate(x => x * counter++);

        Assert.That(counter, Is.EqualTo(0));
        accumulation.ToList();
        Assert.That(counter, Is.EqualTo(3));
    }
Example #24
0
 public OverTurnStonesPhase(System.Drawing.Point placePos,
     System.Drawing.Point[] turnPosArray,
     CellState colorToTurn)
 {
     _placePos = placePos;
     _turnPosList = turnPosArray.ToList();
     _colorToTurn = colorToTurn;
     _turnPosList.Add(_placePos);
     Init();
 }
Example #25
0
		public void should_redirect_non_https_request_to_Index_action_of_Home_controller()
		{
			var testCases = new[] {
				new{ApplicationPath = "/myapplication"},
				new{ApplicationPath = "/"},
				new{ApplicationPath = ""}
			};

			testCases.ToList().ForEach(e => redirect_result_test_cases(e.ApplicationPath));
		}
Example #26
0
        public void PrintSortedArray()
        {
            string[] strings = new[] { "ddd", "ccc", "bbb", "aaa" };

            List<string> strs = strings.ToList();
            strs.Sort();
            foreach (var str in strs)
            {
                System.Console.WriteLine(str);
            }
        }
 public void SimpleFibonacciTest()
 {
     var res = new[]
         {
             1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711,
             28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887,
             9227465, 14930352, 24157817, 39088169
         };
     var i = 0;
     res.ToList().ForEach(fib => Assert.AreEqual(Fibonacci.GetFibonacci(i++), fib));
 }
Example #28
0
 public void SetUpDefaults()
 {
     TraceLogger.UnInitialize();
     TraceLogger.SetRuntimeLogLevel(Severity.Verbose);
     TraceLogger.SetAppLogLevel(Severity.Info);
     var overrides = new [] {
         new Tuple<string, Severity>("Runtime.One", Severity.Warning),
         new Tuple<string, Severity>("Grain.Two", Severity.Verbose3)
     };
     TraceLogger.SetTraceLevelOverrides(overrides.ToList());
     timingFactor = UnitTestSiloHost.CalibrateTimings();
 }
		public override Configuration Deserialize()
		{
			var dependencies = new[]
			{
				Assembly.GetExecutingAssembly().Location
			};

			if (!_persister.IsNewConfigurationRequired(SerializedConfigFile, dependencies.ToList()))
				return _persister.ReadConfiguration(SerializedConfigFile);

			return null;
		}
 public static IEnumerable<SelectListItem> GetStorageLocations()
 {
     List<SelectListItem> myList = new List<SelectListItem>();
     var data = new[]{
          new SelectListItem{ Value="1",Text="HDFS"},
          new SelectListItem{ Value="2",Text="Elastic"},
          new SelectListItem{ Value="3",Text="HBase"},
          new SelectListItem{ Value="4",Text="Other"},
      };
     myList = data.ToList();
     return myList;
 }