public void ThenCanFormatScenarioOutlineWithMissingNameCorrectly() { var table = new Table { HeaderRow = new TableRow("Var1", "Var2", "Var3", "Var4"), DataRows = new List<TableRow>(new[] { new TableRow("1", "2", "3", "4"), new TableRow("5", "6", "7", "8") }) }; var example = new Example { Name = "Some examples", Description = "An example", TableArgument = table }; var examples = new List<Example>(); examples.Add(example); var scenarioOutline = new ScenarioOutline { Description = "We need to make sure that scenario outlines work properly", Examples = examples }; var htmlScenarioOutlineFormatter = Container.Resolve<HtmlScenarioOutlineFormatter>(); var output = htmlScenarioOutlineFormatter.Format(scenarioOutline, 0); Check.That(output).ContainsGherkinScenario(); Check.That(output).ContainsGherkinTable(); }
protected override void setupWithDatabase(Example.ExampleContext db) { base.setupWithDatabase(db); m = db.ModelsWithDynamicProxies.Create(); db.ModelsWithDynamicProxies.Add(m); save(); }
public void Should_build_string_step(string stringStep) { var step = new StringStep(stringStep, "whatever"); var example = new Example(new ExampleColumns(new[] { new ExampleColumn("param"), }), new Dictionary<string, string> { { "param", "12" } }); var newStep = step.BuildStep(example); Assert.That(newStep.Step, Is.EqualTo("Given a 12")); }
public void QueryingUsingObjects() { using (var store = NewDocumentStore()) { store.Conventions.CustomizeJsonSerializer += serializer => { serializer.TypeNameHandling = TypeNameHandling.All; }; using (var session = store.OpenSession()) { var obj = new Outer { Examples = new List<IExample>() { new Example { Provider = "Test", Id = "Abc" } } }; session.Store(obj); session.SaveChanges(); } using (var session = store.OpenSession()) { var ex = new Example { Provider = "Test", Id = "Abc" }; var arr = session.Query<Outer>().Customize(c => c.WaitForNonStaleResults()) .Where(o => o.Examples.Any(e => e == ex)) .ToArray(); WaitForUserToContinueTheTest(store); Assert.Equal(1, arr.Length); } } }
public static void Main() { Example e = new Example(1, 2.5); // use constructor // this creates the first Example object with reference e Console.WriteLine("e.n = {0}", e.GetN()); // prints 1 Console.WriteLine("e.d = {0}", e.GetD()); // prints 2.5 Console.WriteLine(e); // prints Example: n = 1, d = 2.5 e.SetN(25); e.SetD(3.14159); Console.WriteLine("e.n = {0}", e.GetN()); // prints 25 Console.WriteLine("e.d = {0}", e.GetD()); // prints 3.14159 Console.WriteLine(e); // prints Example: n = 25, d = 3.14159 Example e2 = new Example(3, 10.5); // this creates the second Example object with reference e2 Console.WriteLine(e2); // prints Example: n = 3, d = 10.5 e = e2; // now both e and e2 reference the second object // the first Example object is now no longer referenced // and its memory can be reclaimed at runtime if necessary Console.WriteLine(e); // prints Example: n = 3, d = 10.5 e2.SetN(77); // symbolism uses e2, not e Console.WriteLine(e2); // prints Example: n = 77, d = 0 Console.WriteLine(e); // prints Example: n = 77, d = 0 // but e is the same object - so its fields are changed }
public object[] GetParametersForStep(StringStep stringStep, Example example) { var action = _actionCatalog.GetAction(stringStep); Func<string, string> getValues = i => example.ColumnValues[i]; var paramNames = action.ParameterInfo.Select(a => a.Name).ToList(); return GetParametersForStep(action, paramNames, getValues); }
public void ThenCanFormatScenarioOutlineWithMissingDescriptionCorrectly() { var table = new Table { HeaderRow = new TableRow("Var1", "Var2", "Var3", "Var4"), DataRows = new List<TableRow>(new[] { new TableRow("1", "2", "3", "4"), new TableRow("5", "6", "7", "8") }) }; var example = new Example { Name = "Some examples", Description = "An example", TableArgument = table }; var examples = new List<Example>(); examples.Add(example); var scenarioOutline = new ScenarioOutline { Name = "Testing a scenario outline", Examples = examples }; var htmlScenarioOutlineFormatter = Container.Resolve<HtmlScenarioOutlineFormatter>(); var output = htmlScenarioOutlineFormatter.Format(scenarioOutline, 0); output.ShouldContainGherkinScenario(); output.ShouldContainGherkinTable(); }
public string Write( Example e, int level = 1 ) { var failure = e.ExampleLevelException == null ? "" : " - FAILED - {0}".With( e.ExampleLevelException.CleanMessage() ); var whiteSpace = Environment.NewLine + indent.Times( level ); return e.Pending ? whiteSpace + e.Spec + " - PENDING" : whiteSpace + e.Spec + failure; }
public void pending_example() { var it = new Example("Bar", Spec.Pending, new ActiveExampleContainer("Foo", null, null), null); it.Execute(Listener); Listener.Calls[0].ShouldStartWith("Pending - Foo\r\nBar"); }
public void notifies_listener_on_success() { var it = new Example("Bar", () => Assert.IsTrue(true), new ActiveExampleContainer("Foo", null, null), null); it.Execute(Listener); Listener.Calls[0].ShouldBe("Success - Foo\r\nBar"); }
public void notifies_listener_on_failure() { var it = new Example("Bar", () => Assert.IsTrue(false), new ActiveExampleContainer("Foo", null, null), null); it.Execute(Listener); Listener.Calls[0].ShouldBe("Failed - Foo\r\nBar - AssertionException"); }
public void handles_predicate_expression_success() { var it = new Example("Bar", () => true, new ActiveExampleContainer("Foo", null, null), null); it.Execute(Listener); Listener.Calls[0].ShouldBe("Success - Foo\r\nBar"); }
public void ShouldBeSerializable() { var e = new Example(new ExampleColumns(new[] { "a" }), new Dictionary<string, string> { { "a", "a" } }); var ser = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); using (var ms = new MemoryStream()) ser.Serialize(ms, e); Assert.IsTrue(true, "Serialization succeded"); }
static Example Create(AbstractFactory factory) { Example example = new Example(); example.product1 = factory.CreateProduct1(10); example.product2 = factory.CreateProduct2(20f); example.product3 = factory.CreateProduct3("thirty"); return example; }
private ExampleResult ExecuteExample(ExampleGroup exampleGroup, Example example) { stratergyOption.Into(stratergy => stratergy.ExecuteAction(exampleGroup.BeforeEach)); var result = stratergyOption.Into(stratergy => stratergy.ExecuteActionWithResult(example.Action).ToExampleResult(example)).Or(example.ToExampleResult()).First(); stratergyOption.Into(stratergy => stratergy.ExecuteAction(exampleGroup.AfterEach)); return result; }
public void handles_predicate_expression_failure() { int foo = 4; var it = new Example("Bar", () => foo == 5, new ActiveExampleContainer("Foo", null, null), null); it.Execute(Listener); Listener.Calls[0].ShouldStartWith("Failed - Foo\r\nBar"); }
private ScenarioResult RunExample(Scenario scenario, Func<IEnumerable<StringStep>, IEnumerable<StepResult>> runSteps, Example example) { var steps = BuildSteps(scenario, example); var scenarioResult = new ScenarioResult(scenario.Feature, scenario.Title); var stepResults = runSteps(steps); scenarioResult.AddActionStepResults(stepResults); return scenarioResult; }
public void Write(Example e, int level) { var failure = e.Exception == null ? "" : " - FAILED - {0}".With(e.Exception.CleanMessage()); var whiteSpace = indent.Times(level); var result = e.Pending ? whiteSpace + e.Spec + " - PENDING" : whiteSpace + e.Spec + failure; Console.WriteLine(result); }
public static ExampleResult ToExampleResult(this ActionResult result, Example example) { return new ExampleResult { Reason = example.Reason, Status = result.Status, Message = result.Message, StackTrace = result.StackTrace, ElapsedTime = result.ElapsedTime }; }
public void DeserializationOfDefaultsWorkInJson() { var writer = new StringWriter(); var obj = new Example { MyString = null }; RoundtripEmitDefaultsJsonCompatibleSerializer.Serialize(writer, obj, typeof(Example)); Dump.WriteLine(writer); var result = Deserializer.Deserialize<Example>(UsingReaderFor(writer)); result.MyString.Should().BeNull(); }
public void EstablishContext() { const string colName = "colName"; const string colValue = "a really wide column value"; var columnNames = new ExampleColumns { new ExampleColumn(colName) }; var columnValues = new Dictionary<string, string> { { "colName" , colValue } }; _row = new Example(columnNames, columnValues); }
public void Should_create_table_instance_from_string() { var columnNames = new ExampleColumns(new[] { new ExampleColumn("colA"), new ExampleColumn("colB"), }); var columnValues = new Dictionary<string, string> { { "colA", "A" }, { "colB", "B" } }; var example = new Example(columnNames, columnValues); var str = example.ToString(); var exampleFromString = ExampleBuilder.BuildFromString(str); CollectionAssert.AreEqual(exampleFromString.ColumnNames, example.ColumnNames); CollectionAssert.AreEqual(exampleFromString.ColumnValues, example.ColumnValues); }
public void Should_be_able_to_serialize_binary() { var s = new StringTableStep("Given x", "source"); var columns = new ExampleColumns(new[] { new ExampleColumn("a") }); var values = new Dictionary<string, string> { { "a", "value" } }; var row = new Example(columns, values); s.AddTableStep(row); var b = new BinaryFormatter(); using (Stream stream = new MemoryStream()) b.Serialize(stream, s); Assert.Pass("Should not throw exception"); }
static bool RunExample(Example ex) { numTotal++; System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch(); timer.Start(); object result = null; try { object[] input = (object[])DeepClone(ex.input); $CLASSNAME$ instance = new $CLASSNAME$(); $IODECL$ } catch (Exception e) { if (ex.id.Length > 0) Console.Write("{0}: ", ex.id); ColorWrite(ConsoleColor.Red, "Exception thrown\n"); Console.Write("Input: {0}\n", ToTopCoderString2(ex.input)); if (ex.answer != null) Console.Write("Expected: {0}\n", ToTopCoderString(ex.answer)); Console.Write("{0}\n\n", e.ToString()); numFailed++; return false; } timer.Stop(); if (ex.id.Length > 0) Console.Write("{0}: ", ex.id); if (ex.answer == null) { // didn't crash Console.Write("Elapsed: {0} ms\n", timer.ElapsedMilliseconds); Console.Write("Input: {0}\n", ToTopCoderString2(ex.input)); Console.Write("Received: {0}\n\n", ToTopCoderString(result)); return true; } else if (!Verify(result, ex.answer)) { // WA ColorWrite(ConsoleColor.Red, "WRONG ANSWER"); Console.Write(" [{0} ms]\n", timer.ElapsedMilliseconds); Console.Write("Input: {0}\n", ToTopCoderString2(ex.input)); Console.Write("Received: {0}\n", ToTopCoderString(result)); Console.Write("Expected: {0}\n\n", ToTopCoderString(ex.answer)); numFailed++; return false; } else { ColorWrite(ConsoleColor.Green, "OK"); Console.Write(" [{0} ms]\n\n", timer.ElapsedMilliseconds); numPassed++; return true; } }
public string WriteFailure(Example example) { var failure = Environment.NewLine + example.FullName().Replace("_", " ") + Environment.NewLine; failure += example.Exception.CleanMessage() + Environment.NewLine; var stackTrace = FailureLines(example.Exception); stackTrace.AddRange(FailureLines(example.Exception.InnerException)); var flattenedStackTrace = stackTrace.Flatten(Environment.NewLine).TrimEnd() + Environment.NewLine; failure += example.Context.GetInstance().StackTraceToPrint(flattenedStackTrace); return failure; }
public string WriteFailure( Example example ) { var failure = Environment.NewLine + example.FullName().Replace( "_", " " ) + Environment.NewLine; failure += example.ExampleLevelException.CleanMessage() + Environment.NewLine; var stackTrace = example.ExampleLevelException .GetOrFallback( e => e.StackTrace, "" ).Split( '\n' ) .Where( l => !internalNameSpaces.Any( l.Contains ) ); var flattenedStackTrace = stackTrace.Flatten( Environment.NewLine ).TrimEnd() + Environment.NewLine; failure += flattenedStackTrace; return failure; }
static void Main(string[] args) { try { Example eg1 = new Example(); Example eg2 = new Example(); SeleniumLog log = SeleniumLog.Instance(); bool result1 = log.AreEqual(expected: eg1, actual: eg1, message: "This test should pass ", throwException: false); bool result2 = log.AreEqual(expected: eg1, actual: eg2, message: "This test should fail ", throwException: false); } catch (Exception e) { Console.WriteLine(e.Message); Console.ReadLine(); } }
public void ThenSingleScenarioOutlineWithStepsAddedSuccessfully() { var excelScenarioFormatter = Container.Resolve<ExcelScenarioOutlineFormatter>(); var exampleTable = new Table(); exampleTable.HeaderRow = new TableRow("Var1", "Var2", "Var3", "Var4"); exampleTable.DataRows = new List<TableRow>(new[] {new TableRow("1", "2", "3", "4"), new TableRow("5", "6", "7", "8")}); var example = new Example {Name = "Examples", Description = string.Empty, TableArgument = exampleTable}; var examples = new List<Example>(); examples.Add(example); var scenarioOutline = new ScenarioOutline { Name = "Test Feature", Description = "In order to test this feature,\nAs a developer\nI want to test this feature", Examples = examples }; var given = new Step {NativeKeyword = "Given", Name = "a precondition"}; var when = new Step {NativeKeyword = "When", Name = "an event occurs"}; var then = new Step {NativeKeyword = "Then", Name = "a postcondition"}; scenarioOutline.Steps = new List<Step>(new[] {given, when, then}); using (var workbook = new XLWorkbook()) { IXLWorksheet worksheet = workbook.AddWorksheet("SHEET1"); int row = 3; excelScenarioFormatter.Format(worksheet, scenarioOutline, ref row); worksheet.Cell("B3").Value.ShouldEqual(scenarioOutline.Name); worksheet.Cell("C4").Value.ShouldEqual(scenarioOutline.Description); worksheet.Cell("B9").Value.ShouldEqual("Examples"); worksheet.Cell("D10").Value.ShouldEqual("Var1"); worksheet.Cell("E10").Value.ShouldEqual("Var2"); worksheet.Cell("F10").Value.ShouldEqual("Var3"); worksheet.Cell("G10").Value.ShouldEqual("Var4"); worksheet.Cell("D11").Value.ShouldEqual(1.0); worksheet.Cell("E11").Value.ShouldEqual(2.0); worksheet.Cell("F11").Value.ShouldEqual(3.0); worksheet.Cell("G11").Value.ShouldEqual(4.0); worksheet.Cell("D12").Value.ShouldEqual(5.0); worksheet.Cell("E12").Value.ShouldEqual(6.0); worksheet.Cell("F12").Value.ShouldEqual(7.0); worksheet.Cell("G12").Value.ShouldEqual(8.0); row.ShouldEqual(13); } }
public void Write(Example e, int level) { var failure = e.Exception == null ? "" : " - FAILED - {0}".With(e.Exception.CleanMessage()); var whiteSpace = indent.Times(level); var result = e.Pending ? whiteSpace + e.Spec + " - PENDING" : whiteSpace + e.Spec + failure; if (failure != "") Console.ForegroundColor = ConsoleColor.Red; else if (e.Pending) Console.ForegroundColor = ConsoleColor.Yellow; else Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(result); Console.ForegroundColor = ConsoleColor.White; }
public void ThenSingleScenarioOutlineAddedSuccessfully() { var excelScenarioFormatter = Container.Resolve<ExcelScenarioOutlineFormatter>(); var exampleTable = new Table(); exampleTable.HeaderRow = new TableRow("Var1", "Var2", "Var3", "Var4"); exampleTable.DataRows = new List<TableRow>(new[] {new TableRow("1", "2", "3", "4"), new TableRow("5", "6", "7", "8")}); var example = new Example {Name = "Examples", Description = string.Empty, TableArgument = exampleTable}; var examples = new List<Example>(); examples.Add(example); var scenarioOutline = new ScenarioOutline { Name = "Test Feature", Description = "In order to test this feature,\nAs a developer\nI want to test this feature", Examples = examples }; using (var workbook = new XLWorkbook()) { IXLWorksheet worksheet = workbook.AddWorksheet("SHEET1"); int row = 3; excelScenarioFormatter.Format(worksheet, scenarioOutline, ref row); worksheet.Cell("B3").Value.ShouldEqual(scenarioOutline.Name); worksheet.Cell("C4").Value.ShouldEqual(scenarioOutline.Description); worksheet.Cell("B6").Value.ShouldEqual("Examples"); worksheet.Cell("D7").Value.ShouldEqual("Var1"); worksheet.Cell("E7").Value.ShouldEqual("Var2"); worksheet.Cell("F7").Value.ShouldEqual("Var3"); worksheet.Cell("G7").Value.ShouldEqual("Var4"); worksheet.Cell("D8").Value.ShouldEqual(1.0); worksheet.Cell("E8").Value.ShouldEqual(2.0); worksheet.Cell("F8").Value.ShouldEqual(3.0); worksheet.Cell("G8").Value.ShouldEqual(4.0); worksheet.Cell("D9").Value.ShouldEqual(5.0); worksheet.Cell("E9").Value.ShouldEqual(6.0); worksheet.Cell("F9").Value.ShouldEqual(7.0); worksheet.Cell("G9").Value.ShouldEqual(8.0); row.ShouldEqual(10); } }
public static void Main() { Example ex = new Example(); Console.WriteLine(test.Value); }
static void Main(string[] args) { var example = new Example(); example.Run(); //Lists are a general purpose collection that is pretty good at everything var instructors = new List <string>(); var students = new List <string>(); var evening11 = new List <string>(); var numbers = new List <int>(); //adding single item instructors.Add("Jameka"); instructors.Add("Nathan"); instructors.Add("Dylan"); //foreach (var instructor in instructors) //{ // //this will blow up with an invalid operation exception, collections can't be modified while being iterated // instructors.Add("asdf"); //} //items need to be of the right type numbers.Add(1); numbers.Add(3); numbers.Add(5); students.Add("Aaron"); students.Add("John"); students.Add("Monique"); //add multiple at once from an existing list evening11.AddRange(instructors); evening11.AddRange(students); foreach (var person in evening11) { Console.WriteLine($"{person} is in evening cohort 11."); } //is the iten in the list? var steveIsInE11 = evening11.Contains("Steve"); //ternary inside interpolated strings have to be in parantheses Console.WriteLine($"Steve is {(steveIsInE11 ? "" : "not ")}in E11."); //just the first match var matchingPerson = evening11.Find(person => person.StartsWith("J")); Console.WriteLine($"{matchingPerson} starts with J."); //in a list, the index is the key Console.WriteLine($"{students[1]} is the student at the index of 1."); //dictionaries have 2 generic type parameters var words = new Dictionary <string, string>(); //dictionary entries are made of key value pairs, and both must be supplied to add anything words.Add("pedantic", "Like a pedant"); words.Add("congratulate", "to be excited for; celebrate"); words.Add("scrupulous", "diligent, thorough, extremely attentive to details"); words.Any(word => word.Key == "pendantic"); var keys = words.Select(word => word.Key); //keys must be unique, this won't work //words.Add("congratulate", "not a real thing"); //validate uniqueness so you don't get an exception if (words.ContainsKey("congratulate")) { words["congratulate"] = "adsfasdf"; } else { words.Add("congratulate", "asdfasdf"); } //same as above, just some different syntax if (!words.TryAdd("congratulate", "asdfasdf")) { words["congratulate"] = "adsfasdf"; } Console.WriteLine($"The fake definition of Congratulations is {words["congratulate"]}"); //foreach (var entry in words) //{ // string word; // string definition; // entry.Deconstruct(out word, out definition); // Console.WriteLine($"The fake definition of {entry.Key} is {entry.Value}"); //} foreach (var(word, definition) in words) { Console.WriteLine($"The fake definition of {word} is {definition}"); } //using the collection initiallizer var wordsWithMultipleDefinitions = new Dictionary <string, List <string> > { { "Scrupulous", new List <string> { "Diligent", "Thorough", "Extremely attentive to detail" } } }; //won't work if you use the collection initializer for "Scrupulous" //wordsWithMultipleDefinitions.Add("Scrupulous", new List<string>() //{ // "Diligent", // "Thorough", // "Extremely attentive to detail" //}); foreach (var(word, definitions) in wordsWithMultipleDefinitions) { Console.WriteLine($"{word} is defined as :"); definitions.Add("poop"); foreach (var definition in definitions) { Console.WriteLine($" {definition}"); } } //queue reads first item first var queue = new Queue <string>(); queue.Enqueue("this is first"); queue.Enqueue("Second"); queue.Enqueue("third"); foreach (var item in queue) { Console.WriteLine(item); } //stack reads last item first var stack = new Stack <string>(); stack.Push("third"); stack.Push("Second"); stack.Push("this is first"); foreach (var item in stack) { Console.WriteLine(item); } //Language Integrated Query (LINQ) }
// Use this for initialization void Start() { Example exp = new Example(); exp.Start(); }
public void ExampleLoadTextFile_ValidNameShouldWork() { string actual = Example.ExampleLoadTextFile("This is a valid file name"); Assert.True(actual.Length > 0); }
public string DescriptionFor(Example example) { return(example?.Description ?? "The Radzen Blazor component library provides more than 50 UI controls for building rich ASP.NET Core web applications."); }
public BestExample(Example e, double d) { example = e; distance = d; }
public static void Main() { Example ex = new Example(); ex.HookUpDelegate(); }
// A sample method with a ByRef parameter. // public void Test(ref Example e) { }
public string Predict(Example e) { return(result); }
public void GenerateClasses() { if (CodeWriter == null) { CodeWriter = new CSharpCodeWriter(); } if (ExplicitDeserialization && !(CodeWriter is CSharpCodeWriter)) { throw new ArgumentException("Explicit deserialization is obsolete and is only supported by the C# provider."); } if (used) { throw new InvalidOperationException("This instance of JsonClassGenerator has already been used. Please create a new instance."); } used = true; var writeToDisk = TargetFolder != null; if (writeToDisk && !Directory.Exists(TargetFolder)) { Directory.CreateDirectory(TargetFolder); } JObject[] examples; var example = Example.StartsWith("HTTP/") ? Example.Substring(Example.IndexOf("\r\n\r\n")) : Example; using (var sr = new StringReader(example)) using (var reader = new JsonTextReader(sr)) { var json = JToken.ReadFrom(reader); if (json is JArray) { examples = ((JArray)json).Cast <JObject>().ToArray(); } else if (json is JObject) { examples = new[] { (JObject)json }; } else { throw new Exception("Sample JSON must be either a JSON array, or a JSON object."); } } Types = new List <JsonType>(); Names.Add(MainClass); var rootType = new JsonType(this, examples[0]); rootType.IsRoot = true; rootType.AssignName(MainClass); GenerateClass(examples, rootType); if (writeToDisk) { var parentFolder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); if (writeToDisk && !NoHelperClass && ExplicitDeserialization) { File.WriteAllBytes(Path.Combine(TargetFolder, "JsonClassHelper.cs"), Properties.Resources.JsonClassHelper); } if (SingleFile) { WriteClassesToFile(Path.Combine(TargetFolder, MainClass + CodeWriter.FileExtension), Types); } else { foreach (var type in Types) { var folder = TargetFolder; if (!UseNestedClasses && !type.IsRoot && SecondaryNamespace != null) { var s = SecondaryNamespace; if (s.StartsWith(Namespace + ".")) { s = s.Substring(Namespace.Length + 1); } folder = Path.Combine(folder, s); Directory.CreateDirectory(folder); } WriteClassesToFile(Path.Combine(folder, (UseNestedClasses && !type.IsRoot ? MainClass + "." : string.Empty) + type.AssignedName + CodeWriter.FileExtension), new[] { type }); } } } else if (OutputStream != null) { WriteClassesToFile(OutputStream, Types); } }
public void ExampleLoadTextFile_InvalidNameShouldFail() { Assert.Throws <ArgumentException>("file", () => Example.ExampleLoadTextFile("")); }
/// <summary> /// Handles template list display (dotnet new3 --list). /// </summary> /// <param name="args">user command input.</param> /// <param name="cancellationToken">cancellation token.</param> /// <returns></returns> internal async Task <NewCommandStatus> DisplayTemplateGroupListAsync( ListCommandArgs args, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ListTemplateResolver resolver = new ListTemplateResolver(_constraintManager, _templatePackageManager, _hostSpecificDataLoader); TemplateResolutionResult resolutionResult = await resolver.ResolveTemplatesAsync(args, _defaultLanguage, cancellationToken).ConfigureAwait(false); //IReadOnlyDictionary<string, string?>? appliedParameterMatches = resolutionResult.GetAllMatchedParametersList(); if (resolutionResult.TemplateGroupsWithMatchingTemplateInfoAndParameters.Any()) { Reporter.Output.WriteLine( string.Format( LocalizableStrings.TemplatesFoundMatchingInputParameters, GetInputParametersString(args /*, appliedParameterMatches*/))); Reporter.Output.WriteLine(); TabularOutputSettings settings = new TabularOutputSettings(_engineEnvironmentSettings.Environment, args); TemplateGroupDisplay.DisplayTemplateList( _engineEnvironmentSettings, resolutionResult.TemplateGroupsWithMatchingTemplateInfoAndParameters, settings, reporter: Reporter.Output, selectedLanguage: args.Language); return(NewCommandStatus.Success); } else { //if there is no criteria and filters it means that dotnet new list was run but there is no templates installed. if (args.ListNameCriteria == null && !args.AppliedFilters.Any()) { //No templates installed. Reporter.Output.WriteLine(LocalizableStrings.NoTemplatesFound); Reporter.Output.WriteLine(); // To search for the templates on NuGet.org, run: Reporter.Output.WriteLine(LocalizableStrings.SearchTemplatesCommand); Reporter.Output.WriteCommand( Example .For <NewCommand>(args.ParseResult) .WithSubcommand <SearchCommand>() .WithArgument(SearchCommand.NameArgument)); Reporter.Output.WriteLine(); return(NewCommandStatus.Success); } // at least one criteria was specified. // No templates found matching the following input parameter(s): {0}. Reporter.Error.WriteLine( string.Format( LocalizableStrings.NoTemplatesMatchingInputParameters, GetInputParametersString(args /*, appliedParameterMatches*/)) .Bold().Red()); if (resolutionResult.HasTemplateGroupMatches && resolutionResult.ListFilterMismatchGroupCount > 0) { // {0} template(s) partially matched, but failed on {1}. Reporter.Error.WriteLine( string.Format( LocalizableStrings.TemplatesNotValidGivenTheSpecifiedFilter, resolutionResult.ListFilterMismatchGroupCount, GetPartialMatchReason(resolutionResult, args /*, appliedParameterMatches*/)) .Bold().Red()); } if (resolutionResult.HasTemplateGroupMatches && resolutionResult.ContraintsMismatchGroupCount > 0) { // {0} template(s) are not displayed due to their constraints are not satisfied. // To display them add "--ignore-constraints" option. Reporter.Error.WriteLine( string.Format( LocalizableStrings.TemplateListCoordinator_Error_FailedConstraints, resolutionResult.ContraintsMismatchGroupCount, ListCommand.IgnoreConstraintsOption.Aliases.First()) .Bold().Red()); } Reporter.Error.WriteLine(); // To search for the templates on NuGet.org, run: Reporter.Error.WriteLine(LocalizableStrings.SearchTemplatesCommand); if (string.IsNullOrWhiteSpace(args.ListNameCriteria)) { Reporter.Error.WriteCommand( Example .For <NewCommand>(args.ParseResult) .WithSubcommand <SearchCommand>() .WithArgument(SearchCommand.NameArgument)); } else { Reporter.Error.WriteCommand( Example .For <NewCommand>(args.ParseResult) .WithSubcommand <SearchCommand>() .WithArgument(SearchCommand.NameArgument, args.ListNameCriteria)); } Reporter.Error.WriteLine(); return(NewCommandStatus.NotFound); } }
public void usage_whenJsonDeserialize(Example example) { Assert.Equal(999, example.Value); }
public void usage_whenMultipleParameters(Example one, Example two) { Assert.Equal(1, one.Value); Assert.Equal(2, two.Value); }
// // GET: /Example/Delete/5 public ActionResult Delete(int id) { Example example = db.Examples.Find(id); return(View(example)); }
public bool CanNavigateTo(Example example) { return(_examplesFrame.CanNavigateTo(Module.ChartingPages[example.PageId].Uri)); }
/// <summary> /// Validate the object. /// </summary> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (AdditionalItems != null) { AdditionalItems.Validate(); } if (AdditionalProperties != null) { AdditionalProperties.Validate(); } if (AllOf != null) { foreach (var element in AllOf) { if (element != null) { element.Validate(); } } } if (AnyOf != null) { foreach (var element1 in AnyOf) { if (element1 != null) { element1.Validate(); } } } if (DefaultProperty != null) { DefaultProperty.Validate(); } if (Definitions != null) { foreach (var valueElement in Definitions.Values) { if (valueElement != null) { valueElement.Validate(); } } } if (Dependencies != null) { foreach (var valueElement1 in Dependencies.Values) { if (valueElement1 != null) { valueElement1.Validate(); } } } if (EnumProperty != null) { foreach (var element2 in EnumProperty) { if (element2 != null) { element2.Validate(); } } } if (Example != null) { Example.Validate(); } if (Items != null) { Items.Validate(); } if (Not != null) { Not.Validate(); } if (OneOf != null) { foreach (var element3 in OneOf) { if (element3 != null) { element3.Validate(); } } } if (PatternProperties != null) { foreach (var valueElement2 in PatternProperties.Values) { if (valueElement2 != null) { valueElement2.Validate(); } } } if (Properties != null) { foreach (var valueElement3 in Properties.Values) { if (valueElement3 != null) { valueElement3.Validate(); } } } }
private static DecisionTree.DecisionTree CreateTree(string connStr, int limit) { MySqlConnection connection; try { connection = new MySqlConnection(connStr); connection.Open(); MySqlCommand cmd; MySqlDataReader reader; String listStr = null; int maxId = -1; { cmd = new MySqlCommand(); cmd.Connection = connection; cmd.CommandText = "SELECT MAX(id) FROM flights"; cmd.CommandTimeout = int.MaxValue; cmd.Prepare(); reader = cmd.ExecuteReader(); while (reader.Read()) { maxId = reader.GetInt32(0); } reader.Close(); } if (limit > -1) { Random rand = new Random(); var listStrBuilder = new StringBuilder("("); Console.WriteLine("Creating list string..."); for (int i = 0; i < limit; i++) { int id = rand.Next(maxId) + 1; listStrBuilder.Append(id); if (i != limit - 1) { listStrBuilder.Append(","); } } listStrBuilder.Append(")"); listStr = listStrBuilder.ToString(); } Console.WriteLine("Querying flights..."); cmd = new MySqlCommand(); cmd.Connection = connection; cmd.CommandText = "SELECT * FROM flights"; if (listStr != null) { cmd.CommandText += " WHERE ID in " + listStr; } cmd.CommandTimeout = int.MaxValue; cmd.Prepare(); Stopwatch watch = new Stopwatch(); watch.Start(); List <Example> trainingSet = new List <Example>(); Console.WriteLine("Retrieving data set..."); reader = cmd.ExecuteReader(); while (reader.Read()) { var delay = reader.GetInt32("DEPARTURE_DELAY"); // it is considered delayed if it leaves more than 5 mins // after scheduled departure time var isDelayed = delay > 5; // construct the example with the classification as // "true" or "false" depending on if it was delayed var example = new Example(isDelayed + ""); // fetch attributes var month = reader.GetInt32("MONTH"); var day = reader.GetInt32("DAY"); var dayOfWeek = reader.GetInt32("DAY_OF_WEEK"); var airline = reader.GetString("AIRLINE"); var airport = reader.GetString("ORIGIN_AIRPORT"); // add attributes example.AddAttribute(Attrs.Month, month); example.AddAttribute(Attrs.Day, day); example.AddAttribute(Attrs.DayOfWeek, dayOfWeek); example.AddAttribute(Attrs.Airline, airline); example.AddAttribute(Attrs.Airport, airport); trainingSet.Add(example); } // // Console.WriteLine("Selecting " + limit + " random entries from data set..."); // Random rand = new Random(); // // var filteredSet = new List<Example>(); // // while (filteredSet.Count < limit) // { // int index = rand.Next(trainingSet.Count); // filteredSet.Add(trainingSet[index]); // trainingSet.RemoveAt(index); // } // // // discard the data // trainingSet.Clear(); Console.WriteLine("Building decision tree..."); var tree = new DecisionTree.DecisionTree(); tree.BuildTree(trainingSet); Console.WriteLine("Done."); Console.Write("Elapsed Time (ms): "); Console.WriteLine(watch.ElapsedMilliseconds); return(tree); } catch (MySqlException ex) { Console.WriteLine(ex.ToString()); return(null); } }
public void CanCreateIndex() { var rootId = Guid.NewGuid().ToString(); var childId = Guid.NewGuid().ToString(); var grandChildId = Guid.NewGuid().ToString(); using (var documentStore = GetDocumentStore()) { using (var session = documentStore.OpenSession()) { for (int i = 0; i < 20; i++) { var ex = new Example { OwnerId = rootId, Name = string.Format("Example_{0}", i), Description = "Ex Description" }; var child = new ExampleOverride { OwnerId = childId, OverriddenValues = new Dictionary <string, object> { { "Name", string.Format("Child_{0}", i) } } }; ex.Overrides.Add(child); var grandChild = new ExampleOverride { OwnerId = grandChildId, OverriddenValues = new Dictionary <string, object> { { "Name", string.Format("GrandChild_{0}", i) } } }; child.Overrides.Add(grandChild); session.Store(ex); } session.SaveChanges(); } new ExampleIndexCreationTask().Execute(documentStore); using (var session = documentStore.OpenSession()) { var examples = session.Query <ExampleProjection, ExampleIndexCreationTask>() .Customize(x => x.WaitForNonStaleResults()) .ProjectFromIndexFieldsInto <ExampleProjection>() .Take(1024) .ToList(); Assert.NotEmpty(examples); } } }
public static void Main() { Example ex = new Example(); }
async Task showAQI() { if (k == 0) { var status = await Permissions.CheckStatusAsync <Permissions.LocationWhenInUse>(); if (status == PermissionStatus.Granted) { if (Preferences.Get("togl", true)) { orderLocation = true; } else { orderLocation = false; } } else { status = await Permissions.RequestAsync <Permissions.LocationWhenInUse>(); if (status == PermissionStatus.Granted) { orderLocation = true; Preferences.Set("togl", true); } else { orderLocation = false; Preferences.Set("togl", false); } } List <Datum> stations = null; await Task.Run(async() => { stations = await AQIAPI.GetAvailableSTations(); }); if (stations.Count == 0) { Label lbb = new Label() { Text = "There is a problem with getting data.\nPlease try again later", HorizontalTextAlignment = TextAlignment.Center }; stek.Children.Add(lbb); return; } List <Example> stt = new List <Example>(); List <Example> problemStations = new List <Example>(); foreach (var st in stations) { Example station = null; await Task.Run(async() => { station = await AQIAPI.GetStationInfo(st); }); try { if (orderLocation) { var location = await Geolocation.GetLastKnownLocationAsync(); var distance = Location.CalculateDistance(station.data.city.geo[0], station.data.city.geo[1], location, DistanceUnits.Kilometers); station.data.city.distance = distance; } int notImportant = 0; var well = Int32.TryParse(station.data.aqi, out notImportant); if (well) { stt.Add(station); } else { problemStations.Add(station); station.data.aqi = "0"; } } catch (Exception e) { problemStations.Add(station); station.data.aqi = "0"; } } if (!orderLocation) { ordered = stt.OrderBy(f => Int32.Parse(f.data.aqi)).ToList(); } else { ordered = stt.OrderBy(f => f.data.city.distance).ToList(); ordered.Reverse(); } ordered.AddRange(problemStations); all = ordered; } stek.Children.Clear(); for (int i = ordered.Count - 1; i >= 0; i--) { if (ordered[i].data.city.name.ToLower().Contains("kosovo")) { continue; } Frame frfr = new Frame() { CornerRadius = 5, HasShadow = true, Margin = new Thickness(10, 5), BackgroundColor = Color.FromHex("#121212") }; Grid grgr = new Grid(); grgr.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(3, GridUnitType.Star) }); grgr.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) }); grgr.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) }); grgr.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); grgr.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); grgr.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); grgr.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); Label name, AQI; name = new Label() { FontSize = 18, FontAttributes = FontAttributes.Bold, Text = ordered[i].data.city.name, TextColor = Color.White }; try { AQI = new Label() { FontSize = 23, FontAttributes = FontAttributes.Bold, Text = ordered[i].data.aqi.ToString() + "\nAQI", HorizontalTextAlignment = TextAlignment.End }; if (Int32.Parse(ordered[i].data.aqi) <= 50) { AQI.TextColor = Color.FromHex("#6cf58e"); } else if (Int32.Parse(ordered[i].data.aqi) > 50 && Int32.Parse(ordered[i].data.aqi) < 100) { AQI.TextColor = Color.FromHex("#ff954f"); } else { AQI.TextColor = Color.FromHex("#FF7595"); } } catch (Exception e) { AQI = new Label() { FontSize = 23, FontAttributes = FontAttributes.Bold, Text = "0\nAQI", HorizontalTextAlignment = TextAlignment.End }; AQI.TextColor = Color.FromHex("#6cf58e"); } Label pm10; if (ordered[i].data.iaqi.pm10 != null) { pm10 = new Label() { FontSize = 15, Text = ordered[i].data.iaqi.pm10.v.ToString(), HorizontalTextAlignment = TextAlignment.Center, TextColor = Color.White } } ; else { pm10 = new Label() { FontSize = 15, Text = "непознато", HorizontalTextAlignment = TextAlignment.Center, TextColor = Color.White } }; Label coo; if (ordered[i].data.iaqi.co != null) { coo = new Label() { FontSize = 15, Text = ordered[i].data.iaqi.co.v.ToString(), HorizontalTextAlignment = TextAlignment.Center, TextColor = Color.White } } ; else { coo = new Label() { FontSize = 15, Text = "непознато", HorizontalTextAlignment = TextAlignment.Center, TextColor = Color.White } }; Label so2o; if (ordered[i].data.iaqi.so2 != null) { so2o = new Label() { FontSize = 15, Text = ordered[i].data.iaqi.so2.v.ToString(), HorizontalTextAlignment = TextAlignment.Center, TextColor = Color.White } } ; else { so2o = new Label() { FontSize = 15, Text = "непознато", HorizontalTextAlignment = TextAlignment.Center, TextColor = Color.White } }; Label no2o; if (ordered[i].data.iaqi.no2 != null) { no2o = new Label() { FontSize = 15, Text = ordered[i].data.iaqi.no2.v.ToString(), HorizontalTextAlignment = TextAlignment.Center, TextColor = Color.White } } ; else { no2o = new Label() { FontSize = 15, Text = "непознато", HorizontalTextAlignment = TextAlignment.Center, TextColor = Color.White } }; Label pm10LABEL = new Label() { FontSize = 8, Text = "PM10", HorizontalTextAlignment = TextAlignment.Center, TextColor = Color.White }; Label coLABEL = new Label() { FontSize = 8, Text = "CO", HorizontalTextAlignment = TextAlignment.Center, TextColor = Color.White }; Label so2LABEL = new Label() { FontSize = 8, Text = "SO2", HorizontalTextAlignment = TextAlignment.Center, TextColor = Color.White }; Label no2LABEL = new Label() { FontSize = 8, Text = "NO2", HorizontalTextAlignment = TextAlignment.Center, TextColor = Color.White }; grgr.Children.Add(name, 0, 0); Grid.SetColumnSpan(name, 3); grgr.Children.Add(AQI, 3, 0); grgr.Children.Add(pm10, 0, 1); grgr.Children.Add(coo, 1, 1); grgr.Children.Add(so2o, 2, 1); grgr.Children.Add(no2o, 3, 1); grgr.Children.Add(pm10LABEL, 0, 2); grgr.Children.Add(coLABEL, 1, 2); grgr.Children.Add(so2LABEL, 2, 2); grgr.Children.Add(no2LABEL, 3, 2); frfr.Content = grgr; Console.WriteLine(i.ToString()); stek.Children.Add(frfr); CrossMTAdmob.Current.LoadInterstitial("ca-app-pub-6638560950207737/4239069970"); } }
private void OnCreateExample(Example response, Dictionary <string, object> customData) { Log.Debug("ExampleAssistantV1.OnCreateExample()", "Response: {0}", customData["json"].ToString()); _createExampleTested = true; }
public void TestTemplate() { Example example = serializer.Read(Example.class, EXAMPLE);
public void Setup() { _exampleInst = A.Fake <Example>(x => x.WithArgumentsForConstructor(() => new Example())); }
public static void should <T>(this T o, Expression <Predicate <T> > predicate) { Assert.IsTrue(predicate.Compile()(o), Example.Parse(predicate.Body)); }
public void Insert(Example Example) { ExampleRepository.Insert(Example); }
public String predict(Example e) { return((String)tree.predict(e)); }
public void Run() { var sample = new Example(); Console.WriteLine(sample.Hello("Steve")); }
// // GET: /Example/Details/5 public ViewResult Details(int id) { Example example = db.Examples.Find(id); return(View(example)); }
public void Push(Example example) { _history.Push(example); }