private static void ProcessPackageIncludes( IBuildConfig config, PackagingSettings settings, string location, string projectName, string projectPackageConfig, Encoding encoding) { PackageContents includes = null; if (File.Exists($"{projectName}.{PackageIncludeFile}")) { includes = new PackageContents(projectPackageConfig); } else if (File.Exists(Path.Combine(location, PackageIncludeFile))) { includes = new PackageContents(Path.Combine(location, PackageIncludeFile)); } if (includes != null) { var expander = new Expander(); var nupkg = Path.Combine(location, expander.Expand(config, "${id}.nuspec")); if (!File.Exists(nupkg)) { return; } XDocument doc; using (var reader = new StreamReader(nupkg, encoding)) { doc = XDocument.Load(reader); } if (doc?.Root == null) { return; } var filesEelement = doc.Root.Element(XName.Get("files")); if (filesEelement == null) { doc.Root.Add(new XElement("files")); filesEelement = doc.Root.Element(XName.Get("files")); } foreach (var packageInclude in includes) { if (settings.ExcludeMissingFiles && !File.Exists(Path.Combine(location, packageInclude.Source))) { continue; } var includeElement = new XElement( "file", new XAttribute("src", expander.Expand(config, packageInclude.Source)), new XAttribute("target", expander.Expand(config, packageInclude.Destination))); filesEelement.Add(includeElement); } using (var writer = new StreamWriter(nupkg, false, encoding)) { doc.Save(writer); } } }
public void DatabaseSingleItem() { Guid projectId = ProjectTestUtilities.CreateFullDbHierarchy(); Project sourceObject = null; using (var db = new TestModelContext()) { sourceObject = db.Projects.Find(projectId); } object result = _expander.Expand(sourceObject, includes: PropertyReference.Parse($"[{nameof(ProjectProjection.Name)}]")); result.ShouldNotBeNull(); ProjectProjection projection = result as ProjectProjection; projection.ShouldNotBeNull(); // Verify the properties in this object were projected correctly projection.Name.ShouldBe(sourceObject.Name); projection.Description.ShouldBeNull(); // And verify the navigation property was retrieved correctly projection.Environments.ShouldBeNull(); projection.CredentialDefinitions.ShouldBeNull(); projection.Sections.ShouldBeNull(); }
protected Block getExpandedBlock(Arguments arguments) { var region = new Region(); using var popper = new RegionPopper(region, "invoke expanded"); items.Must().HaveCountOfExactly(2).OrThrow(LOCATION, () => "There must be exactly two functions"); var item0 = items[0]; var item1 = items[1]; var lambda0 = item0.Lambda; var lambda1 = item1.Lambda; var parameters0 = lambda0.Parameters; var parameters1 = lambda1.Parameters; parameters0.AnyComparisands.Must().BeTrue().OrThrow(LOCATION, () => "The first function must have a comparisand"); var values = parameters1.GetArguments(arguments); popper.Push(); var(checkExpression, checkVariable) = firstComparisand(lambda0.Parameters); var expander = new Expander(functionName, item1.Lambda.Block, checkExpression, checkVariable, lambda0.Block, region); SetArguments(values); foreach (var parameter in parameters1.GetParameters()) { expander.AddParameter(parameter); } var block = expander.Expand(); return(block); }
public void MapDefault() { var relationship = new UserRelationship { Owner = new User(), Child = new User() }; var relationshipProjected = _expander.Expand(relationship, null, includes: "[Owner]") as UserRelationship; relationshipProjected.ShouldNotBeNull(); relationshipProjected.Owner.ShouldNotBeNull(); relationshipProjected.Owner.Name.ShouldBe(TestName); relationshipProjected.Owner.Email.ShouldBe(TestEmail); relationshipProjected.Child.ShouldBeNull(); }
public void DefaultIncludesAttribute() { _expander = new Expander(); var config = new PopcornConfiguration(_expander); config.Map <RootObject, IncludeByDefaultRootObjectProjection>(); var root = new RootObject { Id = Guid.NewGuid(), StringValue = "Name", NonIncluded = "A description", ExcludedFromProjection = "Some Details", Child = new ChildObject { Id = Guid.NewGuid(), Name = "Name", Description = "Description" } }; var result = _expander.Expand(root); result.ShouldNotBeNull(); IncludeByDefaultRootObjectProjection projection = result as IncludeByDefaultRootObjectProjection; projection.ShouldNotBeNull(); projection.StringValue.ShouldBe(root.StringValue); projection.Id.ShouldBe(root.Id); projection.NonIncluded.ShouldBeNull(); projection.Child.ShouldBeNull(); }
Block getExpandedBlock(Arguments arguments) { var region = new Region(); using (var popper = new RegionPopper(region, "invoke expanded")) { Assert(items.Count == 2, LOCATION, "There must be exactly two functions"); var item0 = items[0]; var item1 = items[1]; var lambda0 = item0.Lambda; var lambda1 = item1.Lambda; var parameters0 = lambda0.Parameters; var parameters1 = lambda1.Parameters; Assert(parameters0.AnyComparisands, LOCATION, "The first function must have a comparisand"); var values = parameters1.GetArguments(arguments); popper.Push(); (var checkExpression, var checkVariable) = firstComparisand(lambda0.Parameters); var expander = new Expander(functionName, item1.Lambda.Block, checkExpression, checkVariable, lambda0.Block, region); SetArguments(values); foreach (var parameter in parameters1.GetParameters()) { expander.AddParameter(parameter); } var block = expander.Expand(); return(block); } }
/// <summary> /// マスタ展開. /// </summary> /// <param name="Host">ホスト</param> /// <param name="UserName">ユーザ名</param> /// <param name="Password">パスワード</param> /// <returns>成功したらtrueを返す</returns> private bool ExpandMaster(string Host, string UserName, string Password) { ISQLExpand Expander = null; if (!Util.IsLocalHost(Host)) { Expander = new RemoteSQLExpander(Host, UserName, Password); } else { Expander = new LocalSQLExpander(UserName, Password); } string[] AllFiles = Directory.GetFiles(Config.TemporaryDirectoryPath); List <string> Files = new List <string>(); foreach (var File in AllFiles) { if (Path.GetExtension(File) == ".sql") { Files.Add(File); } } if (!Expander.Expand(Files.ToArray())) { MessageBox.Show("SQLの展開に失敗しました。"); return(false); } return(true); }
public override void OnActionExecuted(ActionExecutedContext context) { if (context.Result is ObjectResult) { var resultObject = ((ObjectResult)context.Result).Value; if (_expander.WillExpand(resultObject)) { // see if we can find some include statements string includes = "[]"; if (context.HttpContext.Request.Query.ContainsKey("include")) { includes = context.HttpContext.Request.Query["include"]; } else if (context.HttpContext.Request.Headers?.ContainsKey("API-INCLUDE") ?? false) { includes = context.HttpContext.Request.Headers["API-INCLUDE"]; } // Use our expander and expand the object resultObject = _expander.Expand(resultObject, _context, PropertyReference.Parse(includes)); } // Sort should there be anything to sort if (resultObject != null) { // Assign sortDirection where necessary, but default to Ascending if nothing passed in SortDirection sortDirection = SortDirection.Ascending; if (context.HttpContext.Request.Query.ContainsKey("sortDirection")) { // Assign the proper sort direction, but invalidate an invalid value try { sortDirection = (SortDirection)Enum.Parse(typeof(SortDirection), context.HttpContext.Request.Query["sortDirection"]); } catch (ArgumentException) { throw new ArgumentException(context.HttpContext.Request.Query["sortDirection"]); } } // Do any sorting as specified if (context.HttpContext.Request.Query.ContainsKey("sort")) { resultObject = _expander.Sort(resultObject, context.HttpContext.Request.Query["sort"], sortDirection); } } // Apply our inspector to the expanded content if (_inspector != null) { resultObject = _inspector(resultObject, _context); } context.Result = new JsonResult(resultObject, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); } base.OnActionExecuted(context); }
protected override void AddNodes(IQueue <T> fringe, T node, ISearchProblem <A, S, C> problem) { if (!closed.Contains(node.State)) { closed.Add(node.State); fringe.AddRange(Expander.Expand(problem, node)); } }
protected override void Read( ) { var expander = new Expander(); IBuildConfig cfg = new BuildConfigChain(this, rawConfig); foreach (var key in rawConfig.Keys) { var expandedValue = expander.Expand(cfg, rawConfig[key]); this[key] = expandedValue; } }
private C RBFS(T node, C F_N, C bound) { var f_N = problem.Heuristic(node.State); if (f_N.CompareTo(bound) > 0) { return(f_N); } if (problem.IsGoal(node.State)) { throw new Exception(); } var children = Expander.Expand(problem, node); if (!children.Any()) { return(Cost.Maximum()); } foreach (var N_i in children) { if (f_N.CompareTo(F_N) < 0) { N_i.F = F_N.Max(N_i.EstCost); } else { N_i.F = N_i.EstCost; } } children = children.OrderBy(x => x.F); /* * RBFS (node: N, value: F(N), bound: B) * IF f(N)>B, RETURN f(N) * IF N is a goal, EXIT algorithm * IF N has no children, RETURN infinity * FOR each child Ni of N, * IF f(N)<F(N), F[i] := MAX(F(N),f(Ni)) * ELSE F[i] := f(Ni) * sort Ni and F[i] in increasing order of F[i] * IF only one child, F[2] := infinity * WHILE (F[1] <= B and F[1] < infinity) * F[1] := RBFS(N1, F[1], MIN(B, F[2])) * insert Ni and F[1] in sorted order * RETURN F[1] */ }
/** * <summary> * Layered expansion method. Basically just repeats an expansion using * the given HexExpander for the given number of passes. On each pass, * the number of hexes that will be modified is reduced by a random * amount between the two proportion bounds of this class. * </summary> * <param name="passes">Number of expansion passes.</param> */ public void Expand(int passes) { int hexesToModify = ValidCoords.Count; for (int i = 0; i < passes; i++) { double proportionThisRound = _rand.GenerateDouble(); proportionThisRound *= (UpperProportionBound - LowerProportionBound); proportionThisRound += LowerProportionBound; hexesToModify = (int)(hexesToModify * proportionThisRound); Expander.Expand(ValidCoords, hexesToModify); } }
// TODO: Clean up and build API static void Main(string[] args) { var input = "35x-01x*4+91*0+3340/2-x"; Console.WriteLine("Input: " + input); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Tokenized:"); var tokenizer = new Tokenizer(); var tokenized = tokenizer.Tokenize(input); List(tokenized); Console.WriteLine(); Console.WriteLine("Expanded:"); var expander = new Expander(); var expanded = expander.Expand(tokenized); List(expanded); Console.WriteLine(); Console.WriteLine("Grouped:"); var grouper = new Grouper(); var grouped = grouper.Group(expanded); List(grouped); Console.WriteLine(); Console.WriteLine("Cleaned:"); var cleaner = new Cleaner(); var cleaned = cleaner.Clean(grouped); List(cleaned); Console.WriteLine(""); Console.WriteLine(""); Format(cleaned); var calc = new Calculator(); var dict = new Dictionary <string, double>() { { "x", 2 } }; Console.WriteLine("Variables: x=2"); Console.WriteLine("Calculated: " + calc.Calculate(cleaned, dict)); }
public void ExpandFromProof() { var expander = new Expander(); var config = new PopcornConfiguration(expander); config.ScanAssemblyForMapping(this.GetType().GetTypeInfo().Assembly); ExpandFromClass testObject = new ExpandFromClass { Field1 = "field1", Field2 = 2 }; var result = (ExpandFromClassProjection)expander.Expand(testObject, null); Assert.AreEqual(testObject.Field1, result.Field1); Assert.AreEqual(testObject.Field2, result.Field2); }
/// <summary> /// Toggles the expander content. /// </summary> /// <param name="expanded"> /// A value indicating whether to toggle expanded. /// </param> /// <returns> /// The <see cref="ExpanderPage"/>. /// </returns> public ExpanderPage ToggleHorizontalExpander(bool expanded) { Expander expander = this.WindowsApp.FindElement(this.horizontalExpanderQuery); if (expanded) { expander.Expand(); } else { expander.Collapse(); } return(this); }
public static void ProcessFiles(string location, string projectName, Encoding fileEncoding) { Directory.SetCurrentDirectory(location); var config = BuildConfiguration.Get(location, projectName, fileEncoding); var x = new Expander(); foreach (var pair in GetReplacementPairs(location)) { var replacedContents = x.Expand(config, File.ReadAllText(pair.RawFile.FullName, fileEncoding)); using (var fileStream = new FileStream(pair.TargetFile.FullName, FileMode.Create, FileAccess.Write)) using (var writer = new StreamWriter(fileStream, fileEncoding)) { writer.Write(replacedContents); writer.Flush(); fileStream.Flush(); } } }
public async Task SimpleExpandLazyLoading() { using (var context = new TestContext(dbname)) { // Get the employee that has cars lazily loaded var employee = await context.Employees.FirstOrDefaultAsync(); employee.ShouldNotBeNull(); employee.Cars.ShouldNotBeNull(); // Set up our expander var expander = new Expander(); var config = new PopcornConfiguration(expander); config.EnableBlindExpansion(true); // Expand it and make sure we only have our three expected properties. var expanded = (Dictionary <string, object>)expander.Expand(employee); expanded.ShouldNotBeNull(); expanded.Count.ShouldBe(3); } }
//================================ // Methods //================================ public string GetExpandedUrl() { return(Expander.Expand(this.Url)); }
private DotExpression Eval(string program) { return(Evaluator.Eval(Expander.Expand(_parser.Read(program).AST))); }
private string Run(string template) { Builder builder = new Builder(); Expander expander = new Expander(); Parser parser = new Parser(); Dictionary<string, string> values = new Dictionary<string, string> { {"abc", "xxx"}, {"def", "yyy"}, {"ghi", "zzz"}, {"jkl", "123"}, {"mno", "456"}, {"pqr", ""}, {"stu", null}, {"v w x", "789"}, }; var parsed = parser.Parse(template); var parsedText = NodesToString(parsed); var expanded = expander.Expand(parsed); var expandedText = NodesToString(expanded); var actual = builder.Build(expanded)(values); return actual; }
/// <summary> /// Generic tree search. See page 72 in Russell and Norvig /// </summary> protected override void AddNodes(IQueue <T> fringe, T node, ISearchProblem <A, S, C> problem) { fringe.AddRange(Expander.Expand(problem, node)); }
public void SimpleMapping() { var root = new RootObject { Id = Guid.NewGuid(), StringValue = "Name", NonIncluded = "A description", ExcludedFromProjection = "Some Details", }; object result = _expander.Expand(root, null, PropertyReference.Parse($"[{nameof(RootObjectProjection.Id)},{nameof(RootObjectProjection.StringValue)}]")); result.ShouldNotBeNull(); RootObjectProjection projection = result as RootObjectProjection; projection.ShouldNotBeNull(); projection.StringValue.ShouldBe(root.StringValue); projection.Id.ShouldBe(root.Id); projection.NonIncluded.ShouldBeNull(); projection.Additional.ShouldBeNull(); projection.Child.ShouldBeNull(); projection.Children.ShouldBeNull(); projection.Upconvert.ShouldBeNull(); projection.ValueFromTranslator.ShouldBeNull(); projection.Downconvert.ShouldBeNull(); }
public override void OnActionExecuted(HttpActionExecutedContext context) { if (!_expandAllEndpoints) { var filterDescriptor = context.ActionContext .ActionDescriptor .GetFilters() .SingleOrDefault(f => f.GetType() == typeof(ExpandResultAttribute)); //Cast the filter to ExpandResultAttribute var attributeInstance = filterDescriptor as ExpandResultAttribute; //If the attribute is null, i.e. not present, or false, it shouldn't expand and we return here if (!(attributeInstance?.ShouldExpand ?? false)) { return; } } var doNotExpandAttribute = context.ActionContext .ActionDescriptor .GetFilters() .SingleOrDefault(f => f.GetType() == typeof(DoNotExpandResultAttribute)); if (doNotExpandAttribute != null) { return; } Exception exceptionResult = null; object resultObject = null; // Set the error out of the gate should something have gone wrong coming into Popcorn if (context.Exception != null) { exceptionResult = context.Exception; if (context.Response == null || context.Response.StatusCode == System.Net.HttpStatusCode.Accepted) { context.Response = context.Request.CreateResponse(System.Net.HttpStatusCode.InternalServerError);; } } else if (context.Response.Content is ObjectContent) // Disect the response if there is something to unfold and no exception { resultObject = ((ObjectContent)context.Response.Content).Value; // Wrap the main work here in a try/catch that we can then pass to our inspector try { var queryParams = context.Request.GetQueryNameValuePairs().ToDictionary((kv) => kv.Key, (kv) => kv.Value); if (_expander.WillExpand(resultObject)) { // see if we can find some include statements string includes = "[]"; if (queryParams.ContainsKey("include")) { includes = queryParams["include"]; } else if (context.Request.Headers?.Contains("API-INCLUDE") ?? false) { includes = context.Request.Headers.GetValues("API-INCLUDE").FirstOrDefault() ?? ""; } // Use our expander and expand the object resultObject = _expander.Expand(resultObject, _context, PropertyReference.Parse(includes)); } // Sort should there be anything to sort if (resultObject != null) { // Assign sortDirection where necessary, but default to Ascending if nothing passed in SortDirection sortDirection = SortDirection.Ascending; if (queryParams.ContainsKey("sortDirection")) { // Assign the proper sort direction, but invalidate an invalid value try { sortDirection = (SortDirection)Enum.Parse(typeof(SortDirection), queryParams["sortDirection"]); } catch (ArgumentException) { throw new ArgumentException(queryParams["sortDirection"]); } } // Do any sorting as specified if (queryParams.ContainsKey("sort")) { resultObject = _expander.Sort(resultObject, queryParams["sort"], sortDirection); } } } catch (Exception e) { exceptionResult = e; // Set the response code as appropriate for a caught error context.Response.StatusCode = System.Net.HttpStatusCode.InternalServerError; } } // Apply our inspector to the expanded content if (_inspector != null) { resultObject = _inspector(resultObject, _context, exceptionResult); } else if (exceptionResult != null) // Have to rethrow the error if there is no inspector set so as to not return false positives { throw exceptionResult; } var json = JsonConvert.SerializeObject(resultObject, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); context.Response.Content = new StringContent(json, Encoding.UTF8, "application/json"); base.OnActionExecuted(context); }
public virtual string GetExpandedPath() { return(Expander.Expand(this.Path)); }
/// <summary> /// Generic tree search. See page 72 in Russell and Norvig /// </summary> protected override void AddNodes(IQueue <SpriteGeneratorSearchNode> fringe, SpriteGeneratorSearchNode node, ISearchProblem <CodeSequence, SpriteGeneratorState, IntegerCost> problem) { fringe.AddRange(Expander.Expand(problem, node)); }