Пример #1
0
 protected override bool HandleTripleInternal(Triple t)
 {
     if (t.Subject.NodeType == NodeType.Uri)
     {
         if (t.Predicate.Equals(this._rdfType))
         {
             if (t.Object.Equals(this._rdfsClass) || t.Object.Equals(this._rdfsDatatype) || t.Object.Equals(this._rdfProperty))
             {
                 if (!this._terms.Contains(t.Subject))
                 {
                     this._terms.Add(t.Subject);
                 }
             }
         }
         else if (t.Predicate.Equals(this._rdfsLabel) && t.Object.NodeType == NodeType.Literal)
         {
             if (!this._termLabels.ContainsKey(t.Subject))
             {
                 this._termLabels.Add(t.Subject, ((ILiteralNode)t.Object).Value);
             }
         }
         else if (t.Predicate.Equals(this._rdfsComment) && t.Object.NodeType == NodeType.Literal)
         {
             if (!this._termComments.ContainsKey(t.Subject))
             {
                 this._termLabels.Add(t.Subject, ((ILiteralNode)t.Object).Value);
             }
         }
     }
     return true;
 }
Пример #2
0
 private void AddLoaderException(Triple<Assembly, Type, Exception> loaderException)
 {
     lock (this)
     {
         this.loaderExceptions.Add(loaderException);
     }
 }
Пример #3
0
        private static Model.Triple MakeBrighstarTriple(Triple t, string uniqueImportId)
        {
            var ret = new Model.Triple
            {
                Subject = Stringify(t.Subject, uniqueImportId),
                Predicate = Stringify(t.Predicate, uniqueImportId)
            };


            if (t.Object is UriNode)
            {
                ret.Object = t.Object.ToString();
            }
            else if (t.Object is LiteralNode)
            {
                var ln = (LiteralNode)t.Object;
                ret.DataType = ln.DataType == null ? Constants.DefaultDatatypeUri : ln.DataType.ToString();
                ret.IsLiteral = true;
                ret.Object = ln.Value;
                ret.LangCode = ln.Language;
            }
            else if (t.Object is BlankNode)
            {
                ret.Object = String.Format("{0}/{1}/{2}", Constants.GeneratedUriPrefix, uniqueImportId,
                                            ((BlankNode) t.Object).InternalID);
            }
            if (t.GraphUri != null)
            {
                ret.Graph = t.GraphUri.ToString();
            }
            return ret;
        }
Пример #4
0
        /// <summary>
        /// Adds the literal triple to a graph.
        /// </summary>
        /// <param name="graph">The graph.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="predicate">The predicate.</param>
        /// <param name="obj">The object (resource).</param>
        /// <remarks></remarks>
        public static void AddTripleLiteral(Graph graph, string subject, string predicate, string obj, string datatype)
        {
            string xmlSchemaDatatype;
            switch (datatype)
            {
                case "Url":
                    xmlSchemaDatatype = XmlSpecsHelper.XmlSchemaDataTypeAnyUri;
                    break;
                case "Date":
                    xmlSchemaDatatype = XmlSpecsHelper.XmlSchemaDataTypeDateTime;
                    break;
                case "Integer":
                    xmlSchemaDatatype = XmlSpecsHelper.XmlSchemaDataTypeInteger;
                    break;
                case "Ntext":
                    xmlSchemaDatatype = XmlSpecsHelper.XmlSchemaDataTypeString;
                    break;
                case "Nvarchar":
                    xmlSchemaDatatype = XmlSpecsHelper.XmlSchemaDataTypeString;
                    break;
                default:
                    xmlSchemaDatatype = XmlSpecsHelper.XmlSchemaDataTypeString;
                    break;
            }

            Triple triple = null;
            if (subject.StartsWith("http") && predicate.StartsWith("http"))
            {
                triple = new Triple(
                        graph.CreateUriNode(new Uri(subject)),
                        graph.CreateUriNode(new Uri(predicate)),
                        graph.CreateLiteralNode(obj, new Uri(xmlSchemaDatatype))
                        );
            }
            else if (!subject.StartsWith("http") && predicate.StartsWith("http"))
            {
                triple = new Triple(
                        graph.CreateUriNode(subject),
                        graph.CreateUriNode(new Uri(predicate)),
                        graph.CreateLiteralNode(obj, new Uri(xmlSchemaDatatype))
                        );
            }
            else if (subject.StartsWith("http") && !predicate.StartsWith("http"))
            {
                triple = new Triple(
                        graph.CreateUriNode(new Uri(subject)),
                        graph.CreateUriNode(predicate),
                        graph.CreateLiteralNode(obj, new Uri(xmlSchemaDatatype))
                        );
            }
            else if (!subject.StartsWith("http") && !predicate.StartsWith("http"))
            {
                triple = new Triple(
                        graph.CreateUriNode(subject),
                        graph.CreateUriNode(predicate),
                        graph.CreateLiteralNode(obj, new Uri(xmlSchemaDatatype))
                        );
            }
            graph.Assert(triple);
        }
Пример #5
0
 /// <summary> Multiplies a 3x3 matrix by a 1x3 pythagorean triple. </summary>
 static Triple Multiply(int[,] matrix, Triple triple)
 {
     Triple result;
     result.a = matrix[0,0]*triple.a + matrix[1,0]*triple.b + matrix[2,0]*triple.c;
     result.b = matrix[0,1]*triple.a + matrix[1,1]*triple.b + matrix[2,1]*triple.c;
     result.c = matrix[0,2]*triple.a + matrix[1,2]*triple.b + matrix[2,2]*triple.c;
     return result;
 }
Пример #6
0
		// the version of gambatte in bizhawk
		public static Triple GambatteColor(Triple c)
		{
			Triple ret;
			ret.r = (c.r * 13 + c.g * 2 + c.b) >> 1;
			ret.g = (c.g * 3 + c.b) << 1;
			ret.b = (c.r * 3 + c.g * 2 + c.b * 11) >> 1;
			return ret;
		}
Пример #7
0
        private void NewCommand_Execute(object sender, ExecutedRoutedEventArgs e)
        {
            ellipses.Clear();
            vd = null;
            triple = null;
            triples.Clear();

            gg_triples.Children.Clear();
            gg_others.Children.Clear();
        }
Пример #8
0
 /// <summary>
 /// Formats a Triple as a String
 /// </summary>
 /// <param name="t">Triple</param>
 /// <returns></returns>
 public override string Format(Triple t)
 {
     if (t.GraphUri == null)
     {
         return base.Format(t);
     }
     else
     {
         return this.Format(t.Subject, TripleSegment.Subject) + " " + this.Format(t.Predicate, TripleSegment.Predicate) + " " + this.Format(t.Object, TripleSegment.Object) + " <" + this.FormatUri(t.GraphUri) + "> .";
     }
 }
Пример #9
0
        public static Statement ToJena(Triple t, JenaMapping mapping)
        {
            Resource s;
            Property p;
            RDFNode o;
            s = ToJenaResource(t.Subject, mapping);
            p = ToJenaProperty(t.Predicate, mapping);
            o = ToJenaNode(t.Object, mapping);

            return mapping.Model.createStatement(s, p, o);
        }
Пример #10
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="g"></param>
        /// <param name="LO"></param>
        public void insertLearningObject(ref Graph g, LearningObjectContextModel LO)
        {
            g.NamespaceMap.AddNamespace("onto", new Uri("http://www.owl-ontologies.com/OntoAdapt2.owl#"));

            IUriNode sujeito = g.CreateUriNode("onto:" + LO.LearningObject_ID);
            INode rdfType = g.CreateUriNode("rdf:type");
            INode objeto = g.CreateUriNode("onto:LearningObject");

            Triple triple = new Triple(sujeito, rdfType, objeto);
            g.Assert(triple);
        }
Пример #11
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="g"></param>
        /// <param name="strLearningStyle"></param>
        public void insertDeviceMediaPreference(ref Graph g)
        {
            g = new Graph();
            g.NamespaceMap.AddNamespace("onto", new Uri("http://www.owl-ontologies.com/OntoAdapt2.owl#"));

            IUriNode sujeito = g.CreateUriNode("onto:" + Device.model_name);
                INode rdfType = g.CreateUriNode("onto:hasDeviceMediaPreference");
                IUriNode objeto = g.CreateUriNode(new Uri("http://www.owl-ontologies.com/OntoAdapt2.owl#" + Device.MediaPreference));

                Triple triple = new Triple(sujeito, rdfType, objeto);
                g.Assert(triple);
        }
Пример #12
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="g"></param>
        public void InsertDeviceBrand(ref Graph g)
        {
            g = new Graph();
            g.NamespaceMap.AddNamespace("onto", new Uri("http://www.owl-ontologies.com/OntoAdapt2.owl#"));

            IUriNode sujeito = g.CreateUriNode("onto:" + Device.model_name);
            INode rdfType = g.CreateUriNode("onto:Brand");
            ILiteralNode literal = g.CreateLiteralNode(Device.Brand_Name);

            Triple triple = new Triple(sujeito, rdfType, literal);
            g.Assert(triple);
        }
Пример #13
0
        /// <summary>
        /// Insere LO a comunidade
        /// </summary>
        /// <param name="g"></param>
        /// <param name="LO"></param>
        public void insertLearningObjectComunidade(ref Graph g, LearningObjectContextModel LO)
        {
            g = new Graph();
            g.NamespaceMap.AddNamespace("onto", new Uri("http://www.owl-ontologies.com/OntoAdapt2.owl#"));

            IUriNode sujeito = g.CreateUriNode("onto:" + LO.LearningObject_ID);
            INode rdfType = g.CreateUriNode("onto:LO_MoodleCommunity");
            ILiteralNode objeto = g.CreateLiteralNode(LO.MoodleCommunity);

            Triple triple = new Triple(sujeito, rdfType, objeto);
            g.Assert(triple);
        }
Пример #14
0
 /// <summary>
 /// Checks whether the Triple exists in the Collection
 /// </summary>
 /// <param name="t">Triple to check for</param>
 /// <returns></returns>
 /// <exception cref="RdfStorageException">Thrown if the underlying StatementSource is not a SelectableSource</exception>
 public override bool Contains(Triple t)
 {
     if (this._source is SelectableSource)
     {
         Statement stmt = SemWebConverter.ToSemWeb(t, this._mapping);
         return ((SelectableSource)this._source).Contains(stmt);
     }
     else
     {
         throw new RdfStorageException("The underlying StatementSource does not support the Contains() operation");
     }
 }
Пример #15
0
 /// <summary>
 /// Handles Triples by asserting them into the appropriate Graph creating the Graph if necessary
 /// </summary>
 /// <param name="t">Triple</param>
 /// <returns></returns>
 protected override bool HandleTripleInternal(Triple t)
 {
     if (!this._store.HasGraph(t.GraphUri))
     {
         Graph g = new Graph();
         g.BaseUri = t.GraphUri;
         this._store.Add(g);
     }
     IGraph target = this._store.Graph(t.GraphUri);
     target.Assert(t.CopyTriple(target));
     return true;
 }
Пример #16
0
 /// <summary>
 /// Asserts a Triple in the Graph
 /// </summary>
 /// <param name="t">The Triple to add to the Graph</param>
 public override void Assert(Triple t)
 {
     try
     {
         this._lockManager.EnterWriteLock();
         base.Assert(t);
     }
     finally
     {
         this._lockManager.ExitWriteLock();
     }
 }
Пример #17
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="g"></param>
        public void insertComunidadeMoodle(ref Graph g)
        {
            g = new Graph();
            g.NamespaceMap.AddNamespace("onto", new Uri("http://www.owl-ontologies.com/OntoAdapt2.owl#"));

            IUriNode sujeito = g.CreateUriNode("onto:" + student.Matricula);
            INode rdfType = g.CreateUriNode("onto:ComunidadeMoodle");
            ILiteralNode literal = g.CreateLiteralNode(student.ComunidadeMoodle);

            Triple triple = new Triple(sujeito, rdfType, literal);
            g.Assert(triple);
        }
Пример #18
0
 public bool add(dotSesame.Resource r, dotSesame.URI uri, dotSesame.Value v, params dotSesame.Resource[] rarr)
 {
     Triple t = new Triple(SesameConverter.FromSesameResource(r, this._mapping), SesameConverter.FromSesameUri(uri, this._mapping), SesameConverter.FromSesameValue(v, this._mapping));
     if (this._g.ContainsTriple(t))
     {
         return false;
     }
     else
     {
         this._g.Assert(t);
         return true;
     }
 }
Пример #19
0
 /// <summary>
 /// Returns true if this triple matches the specified triple allowing
 /// NULL in Graph, Subject, Predicate an Object to stand for a wildcard
 /// </summary>
 /// <param name="other">The other triple to match with</param>
 /// <returns>True if there is a match in the non-null parts of both triples, false otherwise</returns>
 public bool Matches(Triple other)
 {
     return NullOrMatch(Graph, other.Graph) &&
            NullOrMatch(Subject, other.Subject) &&
            NullOrMatch(Predicate, other.Predicate) &&
            (Object == null || other.Object == null ||
             (
                 IsLiteral == other.IsLiteral &&
                 DataType == other.DataType &&
                 LangCode == other.LangCode &&
                 Object == other.Object
             ));
 }
Пример #20
0
 private IEnumerable<Triple> GetTriples(Resource r, Property p, RDFNode rdfn)
 {
     if (r == null)
     {
         if (p == null)
         {
             //Object specified
             return this._g.GetTriplesWithObject(JenaConverter.FromJenaNode(rdfn, this._mapping));
         }
         else if (rdfn == null)
         {
             //Predicate specified
             return this._g.GetTriplesWithPredicate(JenaConverter.FromJenaProperty(p, this._mapping));
         }
         else
         {
             //Object and Predicate specified
             return this._g.GetTriplesWithPredicateObject(JenaConverter.FromJenaProperty(p, this._mapping), JenaConverter.FromJenaNode(rdfn, this._mapping));
         }
     }
     else if (p == null)
     {
         if (rdfn == null)
         {
             //Subject specified
             return this._g.GetTriplesWithSubject(JenaConverter.FromJenaResource(r, this._mapping));
         }
         else
         {
             //Subject and Object specified
             return this._g.GetTriplesWithSubjectObject(JenaConverter.FromJenaResource(r, this._mapping), JenaConverter.FromJenaNode(rdfn, this._mapping));
         }
     }
     else if (rdfn == null)
     {
         //Subject and Predicate specified
         return this._g.GetTriplesWithSubjectPredicate(JenaConverter.FromJenaResource(r, this._mapping), JenaConverter.FromJenaProperty(p, this._mapping));
     }
     else
     {
         Triple t = new Triple(JenaConverter.FromJenaResource(r, this._mapping), JenaConverter.FromJenaProperty(p, this._mapping), JenaConverter.FromJenaNode(rdfn, this._mapping));
         if (this._g.ContainsTriple(t))
         {
             return t.AsEnumerable();
         }
         else
         {
             return Enumerable.Empty<Triple>();
         }
     }
 }
 protected void Page_Init(object sender, EventArgs e)
 {
     _element = PageElement as PageElementWithErrorDto;
     if (_element == null)
     {
         throw new BugException("Crm literature received an incompatible page element \"" + PageElement.GetType().Name + "\"");
     }
         _controls = new List<Triple<PersonalDataSectionElements, WebControl, Label>>();
         countryRegionControl = null;
         if (_questionnaire.QuestionnaireId == 4258)
             QuestionnaireID = "4259";
         else
             QuestionnaireID = _questionnaire.QuestionnaireId.ToString();            
 }
 public override Triple this[Triple t]
 {
     get 
     {
         if (this.Contains(t))
         {
             return t;
         }
         else
         {
             throw new KeyNotFoundException("The given Triple does not exist in this Triple Collection");
         }
     }
 }
 /// <summary>
 /// Formats a Triple
 /// </summary>
 /// <param name="t">Triple</param>
 /// <returns></returns>
 public override string Format(Triple t)
 {
     StringBuilder output = new StringBuilder();
     output.Append(this.Format(t.Subject));
     output.Append(this._deliminatorChar);
     output.Append(this.Format(t.Predicate));
     output.Append(this._deliminatorChar);
     output.Append(this.Format(t.Object));
     if (this._lineEndChar != null)
     {
         output.Append(this._lineEndChar);
     }
     return output.ToString();
 }
Пример #24
0
		public static Triple OldVBAColor(Triple c)
		{
			Triple ret;
			ret.r = gbGetValue(gbGetValue(4, 14, c.g),
				gbGetValue(24, 29, c.g), c.r) - 4;
			ret.g = gbGetValue(gbGetValue(4 + gbGetValue(0, 5, c.r),
				14 + gbGetValue(0, 3, c.r), c.b),
				gbGetValue(24 + gbGetValue(0, 3, c.r),
				29 + gbGetValue(0, 1, c.r), c.b), c.g) - 4;
			ret.b = gbGetValue(gbGetValue(4 + gbGetValue(0, 5, c.r),
				14 + gbGetValue(0, 3, c.r), c.g),
				gbGetValue(24 + gbGetValue(0, 3, c.r),
				29 + gbGetValue(0, 1, c.r), c.g), c.b) - 4;
			return ret.Bit5to8Bad();
		}
Пример #25
0
            public static List<Point2d> Точки_плотного_размещения(Triple<Circle, DeloneCircle> triple, Circle data)
            {
                List<Point2d> points = new List<Point2d>();

                if (double.IsInfinity(triple.Delone_Circle.R))
                {
                    Vertex<Circle, DeloneCircle> vertex = triple.Vertex;
                    while (vertex.Data != null)
                        vertex = vertex.Next;
                    if (CircleExt.Расширенное_расстояние(vertex.Next.Data, vertex.Prev.Data) <= 2 * data.R)
                        points.Add(CircleExt.Точка_пересечения_границ(new Circle() { R = vertex.Next.Data.R + data.R, X = vertex.Next.Data.X, Y = vertex.Next.Data.Y }, new Circle() { R = vertex.Prev.Data.R + data.R, X = vertex.Prev.Data.X, Y = vertex.Prev.Data.Y }));
                }
                else
                {
                    if (triple.Delone_Circle.R >= data.R)
                    {
                        Vertex<Circle, DeloneCircle> vertex = triple.Vertex;
                        do
                        {

                            if (CircleExt.Расширенное_расстояние(vertex.Next.Data, vertex.Prev.Data) <= 2 * data.R)
                            {
                                if (double.IsInfinity(vertex.Cros.Delone_Circle.R))
                                {
                                    StripLine strip_line = new StripLine() { PX = vertex.Next.Data.X, PY = vertex.Next.Data.Y, VX = vertex.Prev.Data.X - vertex.Next.Data.X, VY = vertex.Prev.Data.Y - vertex.Next.Data.Y };
                                    if (PlaneExt.Расширенное_расстояние(strip_line, vertex.Delone_Circle.Center) < 0)
                                        points.Add(CircleExt.Точка_пересечения_границ(new Circle() { R = vertex.Next.Data.R + data.R, X = vertex.Next.Data.X, Y = vertex.Next.Data.Y }, new Circle() { R = vertex.Prev.Data.R + data.R, X = vertex.Prev.Data.X, Y = vertex.Prev.Data.Y }));
                                }
                                else
                                {
                                    StripLine strip_line = new StripLine() { PX = vertex.Next.Data.X, PY = vertex.Next.Data.Y, VX = vertex.Prev.Data.X - vertex.Next.Data.X, VY = vertex.Prev.Data.Y - vertex.Next.Data.Y };
                                    double r = PlaneExt.Расширенное_расстояние(strip_line, vertex.Delone_Circle.Center);
                                    double rr = PlaneExt.Расширенное_расстояние(strip_line, vertex.Cros.Delone_Circle.Center);

                                    if (r * rr < 0)
                                        points.Add(CircleExt.Точка_пересечения_границ(new Circle() { R = vertex.Next.Data.R + data.R, X = vertex.Next.Data.X, Y = vertex.Next.Data.Y }, new Circle() { R = vertex.Prev.Data.R + data.R, X = vertex.Prev.Data.X, Y = vertex.Prev.Data.Y }));
                                    else
                                        if (vertex.Cros.Delone_Circle.R < data.R)
                                            points.Add(CircleExt.Точка_пересечения_границ(new Circle() { R = vertex.Next.Data.R + data.R, X = vertex.Next.Data.X, Y = vertex.Next.Data.Y }, new Circle() { R = vertex.Prev.Data.R + data.R, X = vertex.Prev.Data.X, Y = vertex.Prev.Data.Y }));
                                }
                            }
                            vertex = vertex.Next;
                        } while (vertex != triple.Vertex);
                    }
                }

                return points;
            }
Пример #26
0
        public Hypercube Toggle(int from, int to)
        {
            INode f = this._corners[from];
            INode t = this._corners[to];

            Triple triple = new Triple(f, this._rdfValue, t);
            if (this._g.ContainsTriple(triple))
            {
                this._g.Retract(triple);
            }
            else
            {
                this._g.Assert(triple);
            }
            return this;
        }
Пример #27
0
        public Graph CreateExampleGraph(string uri)
        {
            Graph newGraph = new Graph();
            newGraph.BaseUri = UriFactory.Create(uri);

            Triple triple = new Triple(
                newGraph.CreateUriNode(UriFactory.Create("http://example/book1")),
                newGraph.CreateUriNode(UriFactory.Create("http://example.org/ns#price")),
                newGraph.CreateLiteralNode("42", new Uri(XmlSpecsHelper.XmlSchemaDataTypeInteger))
                );
            newGraph.Assert(triple);

            connector.SaveGraph(newGraph);

            return newGraph;
        }
Пример #28
0
		public void TripleAsKey()
		{
			Triple<int, string, int> key1 = new Triple<int, string, int>(3, "foo", 6);
			Triple<int, string, int> key1b = new Triple<int, string, int>(3, "foo", 6);
			Triple<int, string, int> key2 = new Triple<int, string, int>(4, "foo", 6);
			Triple<int, string, int> key3 = new Triple<int, string, int>(3, "bar", 6);
			Triple<int, string, int> key4 = new Triple<int, string, int>(3, "foo", 7);

			Dictionary<Triple<int, string, int>, int> test = new Dictionary<Triple<int, string, int>, int>();
			test[key1] = 5;
			test[key2] = 6;
			test[key3] = 7;
			test[key4] = 12;
			Assert.AreEqual(5, test[key1], "retrieve a value");
			Assert.AreEqual(6, test[key2], "retrieve with first different");
			Assert.AreEqual(7, test[key3], "retrieve with second different");
			Assert.AreEqual(12, test[key4], "retrieve with third different");
			Assert.AreEqual(5, test[key1b], "retrieve a value with equal but not RefEqual key");
		}
Пример #29
0
    public IList<IList<int>> ThreeSum(int[] nums)
    {
        // a +b+c = 0   <=> a+b = -c
        var r = new List<IList<int>>();

        if(nums == null || nums.Length<3){ return r;}

        var s =  new Dictionary<int,int>();
        for(int i = 0; i< nums.Length; i++){
            if(!s.ContainsKey(nums[i])){
                s.Add(nums[i], 1);
            }
            else{
                s[nums[i]]++;
            }
        }

        var dup = new HashSet<long>();

        for(int i = 0; i<nums.Length; i++){
            if(i > 0 && nums[i] == nums[i-1]){ continue;}
            for(int j = i+1; j< nums.Length; j++){
                if(j > i+1 && nums[j] == nums[j-1]){ continue;}

                var a = nums[i];
                var b = nums[j];
                var c = (a+b) * (-1);

                var t = new Triple(a,b,c);
                if(!dup.Contains(t.Key) && s.ContainsKey(c) && (
                s[c] == 1 && c!= a && c!= b
                || s[c] == 2 && (c!= a || c!= b)
                || s[c] >= 3
                )){
                    r.Add(t.List);
                    dup.Add(t.Key);
                }
            }
        }

        return r;
    }
Пример #30
0
        /// <summary>
        /// Converts a dotNetRDF Triple to a SemWeb Statement
        /// </summary>
        /// <param name="t">Triple</param>
        /// <param name="mapping">Mapping of Blank Nodes</param>
        /// <returns></returns>
        public static Statement ToSemWeb(Triple t, SemWebMapping mapping)
        {
            Entity s, p;
            Resource o;
            Statement stmt;
            if (t.IsGroundTriple)
            {
                //Easy to map across without need for BNode mapping
                stmt = new Statement(ToSemWebEntity(t.Subject), ToSemWebEntity(t.Predicate), ToSemWeb(t.Object));
            }
            else
            {
                s = ToSemWebEntity(t.Subject, mapping);
                p = ToSemWebEntity(t.Predicate, mapping);
                o = ToSemWeb(t.Object, mapping);

                stmt = new Statement(s, p, o);
            }
            return stmt;
        }
Пример #31
0
 /// <summary>
 /// Handles Triples by setting the <see cref="AnyHandler.Any">Any</see> flag and terminating parsing
 /// </summary>
 /// <param name="t">Triple</param>
 /// <returns></returns>
 protected override bool HandleTripleInternal(Triple t)
 {
     this._any = true;
     return(false);
 }
Пример #32
0
        /// <summary>
        /// Handles Triples by getting all inner handlers to handler it.
        /// </summary>
        /// <param name="t">Triple.</param>
        /// <returns></returns>
        /// <remarks>
        /// Handling ends if any of the Handlers indicates it should stop but all Handlers are given the chance to finish the current handling action first.
        /// </remarks>
        protected override bool HandleTripleInternal(Triple t)
        {
            List <bool> results = _handlers.Select(h => h.HandleTriple(t)).ToList();

            return(results.All(x => x));
        }
Пример #33
0
 /// <summary>
 /// Handles a Triple.
 /// </summary>
 /// <param name="t">Triple.</param>
 /// <returns></returns>
 protected override bool HandleTripleInternal(Triple t)
 {
     return(_handler.HandleTriple(t));
 }
Пример #34
0
 /// <summary>
 /// Handles Triples/Quads by counting the Triples and distinct Graph URIs
 /// </summary>
 /// <param name="t">Triple</param>
 /// <returns></returns>
 protected override bool HandleTripleInternal(Triple t)
 {
     this._counter++;
     this._graphs.Add(t.GraphUri.ToSafeString());
     return(true);
 }
        public static ICollection <SurfacePattern> GetContext(IList <CoreLabel> sent, int i, ICollection <CandidatePhrase> stopWords)
        {
            ICollection <SurfacePattern> prevpatterns     = new HashSet <SurfacePattern>();
            ICollection <SurfacePattern> nextpatterns     = new HashSet <SurfacePattern>();
            ICollection <SurfacePattern> prevnextpatterns = new HashSet <SurfacePattern>();
            CoreLabel token = sent[i];
            string    tag   = null;

            if (usePOS4Pattern)
            {
                string fulltag = token.Tag();
                if (useCoarsePOS)
                {
                    tag = Sharpen.Runtime.Substring(fulltag, 0, Math.Min(fulltag.Length, 2));
                }
                else
                {
                    tag = fulltag;
                }
            }
            string nerTag = token.Get(typeof(CoreAnnotations.NamedEntityTagAnnotation));

            for (int maxWin = 1; maxWin <= maxWindow4Pattern; maxWin++)
            {
                IList <Token>  previousTokens   = new List <Token>();
                IList <string> originalPrev     = new List <string>();
                IList <string> originalNext     = new List <string>();
                IList <Token>  nextTokens       = new List <Token>();
                int            numStopWordsprev = 0;
                int            numStopWordsnext = 0;
                // int numPrevTokensSpecial = 0, numNextTokensSpecial = 0;
                int          numNonStopWordsNext = 0;
                int          numNonStopWordsPrev = 0;
                bool         useprev             = false;
                bool         usenext             = false;
                PatternToken twithoutPOS         = null;
                //TODO: right now using numWordsCompoundMax.
                if (addPatWithoutPOS)
                {
                    twithoutPOS = new PatternToken(tag, false, numWordsCompoundMax > 1, numWordsCompoundMax, nerTag, useTargetNERRestriction, useTargetParserParentRestriction, token.Get(typeof(CoreAnnotations.GrandparentAnnotation)));
                }
                PatternToken twithPOS = null;
                if (usePOS4Pattern)
                {
                    twithPOS = new PatternToken(tag, true, numWordsCompoundMax > 1, numWordsCompoundMax, nerTag, useTargetNERRestriction, useTargetParserParentRestriction, token.Get(typeof(CoreAnnotations.GrandparentAnnotation)));
                }
                if (usePreviousContext)
                {
                    // int j = Math.max(0, i - 1);
                    int j         = i - 1;
                    int numTokens = 0;
                    while (numTokens < maxWin && j >= 0)
                    {
                        // for (int j = Math.max(i - maxWin, 0); j < i; j++) {
                        CoreLabel tokenj = sent[j];
                        string    tokenjStr;
                        if (useLemmaContextTokens)
                        {
                            tokenjStr = tokenj.Lemma();
                        }
                        else
                        {
                            tokenjStr = tokenj.Word();
                        }
                        // do not use this word in context consideration
                        if (useFillerWordsInPat && fillerWords.Contains(tokenj.Word().ToLower()))
                        {
                            j--;
                            continue;
                        }
                        //          if (!tokenj.containsKey(answerClass.get(label))) {
                        //            throw new RuntimeException("how come the class "
                        //                + answerClass.get(label) + " for token "
                        //                + tokenj.word() + " in " + sent + " is not set");
                        //          }
                        Triple <bool, Token, string> tr = GetContextTokenStr(tokenj);
                        bool   isLabeledO  = tr.first;
                        Token  strgeneric  = tr.second;
                        string strOriginal = tr.third;
                        if (!isLabeledO)
                        {
                            // numPrevTokensSpecial++;
                            previousTokens.Add(0, strgeneric);
                            // previousTokens.add(0,
                            // "[{answer:"
                            // + tokenj.get(answerClass.get(label)).toString()
                            // + "}]");
                            originalPrev.Add(0, strOriginal);
                            numNonStopWordsPrev++;
                        }
                        else
                        {
                            if (tokenj.Word().StartsWith("http"))
                            {
                                useprev = false;
                                previousTokens.Clear();
                                originalPrev.Clear();
                                break;
                            }
                            else
                            {
                                Token str = SurfacePattern.GetContextToken(tokenj);
                                previousTokens.Add(0, str);
                                originalPrev.Add(0, tokenjStr);
                                if (DoNotUse(tokenjStr, stopWords))
                                {
                                    numStopWordsprev++;
                                }
                                else
                                {
                                    numNonStopWordsPrev++;
                                }
                            }
                        }
                        numTokens++;
                        j--;
                    }
                }
                if (useNextContext)
                {
                    int numTokens = 0;
                    int j         = i + 1;
                    while (numTokens < maxWin && j < sent.Count)
                    {
                        // for (int j = i + 1; j < sent.size() && j <= i + maxWin; j++) {
                        CoreLabel tokenj = sent[j];
                        string    tokenjStr;
                        if (useLemmaContextTokens)
                        {
                            tokenjStr = tokenj.Lemma();
                        }
                        else
                        {
                            tokenjStr = tokenj.Word();
                        }
                        // do not use this word in context consideration
                        if (useFillerWordsInPat && fillerWords.Contains(tokenj.Word().ToLower()))
                        {
                            j++;
                            continue;
                        }
                        //          if (!tokenj.containsKey(answerClass.get(label))) {
                        //            throw new RuntimeException(
                        //                "how come the dict annotation for token " + tokenj.word()
                        //                    + " in " + sent + " is not set");
                        //          }
                        Triple <bool, Token, string> tr = GetContextTokenStr(tokenj);
                        bool   isLabeledO  = tr.first;
                        Token  strgeneric  = tr.second;
                        string strOriginal = tr.third;
                        // boolean isLabeledO = tokenj.get(answerClass.get(label))
                        // .equals(SeqClassifierFlags.DEFAULT_BACKGROUND_SYMBOL);
                        if (!isLabeledO)
                        {
                            // numNextTokensSpecial++;
                            numNonStopWordsNext++;
                            nextTokens.Add(strgeneric);
                            // nextTokens.add("[{" + label + ":"
                            // + tokenj.get(answerClass.get(label)).toString()
                            // + "}]");
                            originalNext.Add(strOriginal);
                        }
                        else
                        {
                            // originalNextStr += " "
                            // + tokenj.get(answerClass.get(label)).toString();
                            if (tokenj.Word().StartsWith("http"))
                            {
                                usenext = false;
                                nextTokens.Clear();
                                originalNext.Clear();
                                break;
                            }
                            else
                            {
                                // if (!tokenj.word().matches("[.,?()]")) {
                                Token str = SurfacePattern.GetContextToken(tokenj);
                                nextTokens.Add(str);
                                originalNext.Add(tokenjStr);
                                if (DoNotUse(tokenjStr, stopWords))
                                {
                                    numStopWordsnext++;
                                }
                                else
                                {
                                    numNonStopWordsNext++;
                                }
                            }
                        }
                        j++;
                        numTokens++;
                    }
                }
                // String prevContext = null, nextContext = null;
                // int numNonSpecialPrevTokens = previousTokens.size()
                // - numPrevTokensSpecial;
                // int numNonSpecialNextTokens = nextTokens.size() - numNextTokensSpecial;
                Token[] prevContext = null;
                //String[] prevContext = null;
                //String[] prevOriginalArr = null;
                // if (previousTokens.size() >= minWindow4Pattern
                // && (numStopWordsprev < numNonSpecialPrevTokens ||
                // numNonSpecialPrevTokens > numMinStopWordsToAdd)) {
                if (previousTokens.Count >= minWindow4Pattern && (numNonStopWordsPrev > 0 || numStopWordsprev > numMinStopWordsToAdd))
                {
                    // prevContext = StringUtils.join(previousTokens, fw);
                    IList <Token>  prevContextList = new List <Token>();
                    IList <string> prevOriginal    = new List <string>();
                    foreach (Token p in previousTokens)
                    {
                        prevContextList.Add(p);
                        if (!fw.IsEmpty())
                        {
                            prevContextList.Add(fw);
                        }
                    }
                    // add fw and sw to the the originalprev
                    foreach (string p_1 in originalPrev)
                    {
                        prevOriginal.Add(p_1);
                        if (!fw.IsEmpty())
                        {
                            prevOriginal.Add(" FW ");
                        }
                    }
                    if (!sw.IsEmpty())
                    {
                        prevContextList.Add(sw);
                        prevOriginal.Add(" SW ");
                    }
                    // String str = prevContext + fw + sw;
                    if (IsASCII(StringUtils.Join(prevOriginal)))
                    {
                        prevContext = Sharpen.Collections.ToArray(prevContextList, new Token[0]);
                        //prevOriginalArr = prevOriginal.toArray(new String[0]);
                        if (previousTokens.Count >= minWindow4Pattern)
                        {
                            if (twithoutPOS != null)
                            {
                                SurfacePattern pat = new SurfacePattern(prevContext, twithoutPOS, null, SurfacePatternFactory.Genre.Prev);
                                prevpatterns.Add(pat);
                            }
                            if (twithPOS != null)
                            {
                                SurfacePattern patPOS = new SurfacePattern(prevContext, twithPOS, null, SurfacePatternFactory.Genre.Prev);
                                prevpatterns.Add(patPOS);
                            }
                        }
                        useprev = true;
                    }
                }
                Token[] nextContext = null;
                //String [] nextOriginalArr = null;
                // if (nextTokens.size() > 0
                // && (numStopWordsnext < numNonSpecialNextTokens ||
                // numNonSpecialNextTokens > numMinStopWordsToAdd)) {
                if (nextTokens.Count > 0 && (numNonStopWordsNext > 0 || numStopWordsnext > numMinStopWordsToAdd))
                {
                    // nextContext = StringUtils.join(nextTokens, fw);
                    IList <Token>  nextContextList = new List <Token>();
                    IList <string> nextOriginal    = new List <string>();
                    if (!sw.IsEmpty())
                    {
                        nextContextList.Add(sw);
                        nextOriginal.Add(" SW ");
                    }
                    foreach (Token n in nextTokens)
                    {
                        if (!fw.IsEmpty())
                        {
                            nextContextList.Add(fw);
                        }
                        nextContextList.Add(n);
                    }
                    foreach (string n_1 in originalNext)
                    {
                        if (!fw.IsEmpty())
                        {
                            nextOriginal.Add(" FW ");
                        }
                        nextOriginal.Add(n_1);
                    }
                    if (nextTokens.Count >= minWindow4Pattern)
                    {
                        nextContext = Sharpen.Collections.ToArray(nextContextList, new Token[0]);
                        //nextOriginalArr =  nextOriginal.toArray(new String[0]);
                        if (twithoutPOS != null)
                        {
                            SurfacePattern pat = new SurfacePattern(null, twithoutPOS, nextContext, SurfacePatternFactory.Genre.Next);
                            nextpatterns.Add(pat);
                        }
                        if (twithPOS != null)
                        {
                            SurfacePattern patPOS = new SurfacePattern(null, twithPOS, nextContext, SurfacePatternFactory.Genre.Next);
                            nextpatterns.Add(patPOS);
                        }
                    }
                    usenext = true;
                }
                if (useprev && usenext)
                {
                    // String strprev = prevContext + fw + sw;
                    // String strnext = sw + fw + nextContext;
                    if (previousTokens.Count + nextTokens.Count >= minWindow4Pattern)
                    {
                        if (twithoutPOS != null)
                        {
                            SurfacePattern pat = new SurfacePattern(prevContext, twithoutPOS, nextContext, SurfacePatternFactory.Genre.Prevnext);
                            prevnextpatterns.Add(pat);
                        }
                        if (twithPOS != null)
                        {
                            SurfacePattern patPOS = new SurfacePattern(prevContext, twithPOS, nextContext, SurfacePatternFactory.Genre.Prevnext);
                            prevnextpatterns.Add(patPOS);
                        }
                    }
                }
            }
            //    Triple<Set<Integer>, Set<Integer>, Set<Integer>> patterns = new Triple<Set<Integer>, Set<Integer>, Set<Integer>>(
            //        prevpatterns, nextpatterns, prevnextpatterns);
            // System.out.println("For word " + sent.get(i) + " in sentence " + sent +
            // " prev patterns are " + prevpatterns);
            // System.out.println("For word " + sent.get(i) + " in sentence " + sent +
            // " next patterns are " + nextpatterns);
            // System.out.println("For word " + sent.get(i) + " in sentence " + sent +
            // " prevnext patterns are " + prevnextpatterns);
            //getPatternIndex().finishCommit();
            return(CollectionUtils.UnionAsSet(prevpatterns, nextpatterns, prevnextpatterns));
        }
Пример #36
0
 public bool ContainsTriple(Triple t)
 {
     throw new NotImplementedException();
 }
Пример #37
0
        /// <summary>
        /// Generates the Output for a Graph
        /// </summary>
        /// <param name="context">Context for writing the Graph</param>
        private void GenerateOutput(TurtleWriterContext context)
        {
            //Write Base Uri
            if (context.Graph.BaseUri != null)
            {
                context.Output.WriteLine("@base <" + context.UriFormatter.FormatUri(context.Graph.BaseUri) + ">.");
                context.Output.WriteLine();
            }

            //Write Prefixes
            foreach (String prefix in context.Graph.NamespaceMap.Prefixes)
            {
                if (TurtleSpecsHelper.IsValidQName(prefix + ":", this._syntax))
                {
                    context.Output.Write("@prefix " + prefix + ": <");
                    String nsUri = context.UriFormatter.FormatUri(context.Graph.NamespaceMap.GetNamespaceUri(prefix));
                    context.Output.WriteLine(nsUri + ">.");
                }
            }
            context.Output.WriteLine();

            //Decide which write mode to use
            bool   hiSpeed   = false;
            double subjNodes = context.Graph.Triples.SubjectNodes.Count();
            double triples   = context.Graph.Triples.Count;

            if ((subjNodes / triples) > 0.75)
            {
                hiSpeed = true;
            }

            if (hiSpeed && context.HighSpeedModePermitted)
            {
                //High Speed Writing Mode
                //Writes everything as individual Triples
                this.RaiseWarning("High Speed Write Mode in use - minimal syntax compressions will be used");
                context.NodeFormatter = new UncompressedTurtleFormatter();
                foreach (Triple t in context.Graph.Triples)
                {
                    context.Output.Write(this.GenerateNodeOutput(context, t.Subject, TripleSegment.Subject));
                    context.Output.Write(" ");
                    context.Output.Write(this.GenerateNodeOutput(context, t.Predicate, TripleSegment.Predicate));
                    context.Output.Write(" ");
                    context.Output.Write(this.GenerateNodeOutput(context, t.Object, TripleSegment.Object));
                    context.Output.WriteLine(".");
                }
            }
            else
            {
                //Get the Triples as a Sorted List
                List <Triple> ts = context.Graph.Triples.ToList();
                ts.Sort();

                //Variables we need to track our writing
                INode lastSubj, lastPred;
                lastSubj = lastPred = null;
                int    subjIndent = 0, predIndent = 0;
                String temp;

                for (int i = 0; i < ts.Count; i++)
                {
                    Triple t = ts[i];
                    if (lastSubj == null || !t.Subject.Equals(lastSubj))
                    {
                        //Terminate previous Triples
                        if (lastSubj != null)
                        {
                            context.Output.WriteLine(".");
                        }

                        //Start a new set of Triples
                        temp = this.GenerateNodeOutput(context, t.Subject, TripleSegment.Subject);
                        context.Output.Write(temp);
                        context.Output.Write(" ");
                        subjIndent = temp.Length + 1;
                        lastSubj   = t.Subject;

                        //Write the first Predicate
                        temp = this.GenerateNodeOutput(context, t.Predicate, TripleSegment.Predicate);
                        context.Output.Write(temp);
                        context.Output.Write(" ");
                        predIndent = temp.Length + 1;
                        lastPred   = t.Predicate;
                    }
                    else if (lastPred == null || !t.Predicate.Equals(lastPred))
                    {
                        //Terminate previous Predicate Object list
                        context.Output.WriteLine(";");

                        if (context.PrettyPrint)
                        {
                            context.Output.Write(new String(' ', subjIndent));
                        }

                        //Write the next Predicate
                        temp = this.GenerateNodeOutput(context, t.Predicate, TripleSegment.Predicate);
                        context.Output.Write(temp);
                        context.Output.Write(" ");
                        predIndent = temp.Length + 1;
                        lastPred   = t.Predicate;
                    }
                    else
                    {
                        //Continue Object List
                        context.Output.WriteLine(",");

                        if (context.PrettyPrint)
                        {
                            context.Output.Write(new String(' ', subjIndent + predIndent));
                        }
                    }

                    //Write the Object
                    context.Output.Write(this.GenerateNodeOutput(context, t.Object, TripleSegment.Object));
                }

                //Terminate Triples
                if (ts.Count > 0)
                {
                    context.Output.WriteLine(".");
                }
            }
        }
Пример #38
0
        /// <summary>
        /// Generates the Output for a Triple as a String in Turtle syntax
        /// </summary>
        /// <param name="globalContext">Context for writing the Store</param>
        /// <param name="context">Context for writing the Graph</param>
        private void GenerateTripleOutput(TriGWriterContext globalContext, TurtleWriterContext context)
        {
            // Decide which write mode to use
            bool   hiSpeed   = false;
            double subjNodes = context.Graph.Triples.SubjectNodes.Count();
            double triples   = context.Graph.Triples.Count;

            if ((subjNodes / triples) > 0.75)
            {
                hiSpeed = true;
            }

            if (globalContext.CompressionLevel == WriterCompressionLevel.None || hiSpeed && context.HighSpeedModePermitted)
            {
                // Use High Speed Write Mode
                String indentation = new String(' ', 4);
                context.Output.Write(indentation);
                if (globalContext.CompressionLevel > WriterCompressionLevel.None)
                {
                    context.Output.WriteLine("# Written using High Speed Mode");
                }
                foreach (Triple t in context.Graph.Triples)
                {
                    context.Output.Write(indentation);
                    context.Output.Write(this.GenerateNodeOutput(globalContext, context, t.Subject, TripleSegment.Subject));
                    context.Output.Write(' ');
                    context.Output.Write(this.GenerateNodeOutput(globalContext, context, t.Predicate, TripleSegment.Predicate));
                    context.Output.Write(' ');
                    context.Output.Write(this.GenerateNodeOutput(globalContext, context, t.Object, TripleSegment.Object));
                    context.Output.WriteLine(".");
                }
            }
            else
            {
                // Get the Triples as a Sorted List
                List <Triple> ts = context.Graph.Triples.ToList();
                ts.Sort();

                // Variables we need to track our writing
                INode lastSubj, lastPred;
                lastSubj = lastPred = null;
                int    subjIndent = 0, predIndent = 0;
                int    baseIndent = 4;
                String temp;

                for (int i = 0; i < ts.Count; i++)
                {
                    Triple t = ts[i];
                    if (lastSubj == null || !t.Subject.Equals(lastSubj))
                    {
                        // Terminate previous Triples
                        if (lastSubj != null)
                        {
                            context.Output.WriteLine(".");
                        }

                        if (context.PrettyPrint)
                        {
                            context.Output.Write(new String(' ', baseIndent));
                        }

                        // Start a new set of Triples
                        temp = this.GenerateNodeOutput(globalContext, context, t.Subject, TripleSegment.Subject);
                        context.Output.Write(temp);
                        context.Output.Write(" ");
                        subjIndent = baseIndent + temp.Length + 1;
                        lastSubj   = t.Subject;

                        // Write the first Predicate
                        temp = this.GenerateNodeOutput(globalContext, context, t.Predicate, TripleSegment.Predicate);
                        context.Output.Write(temp);
                        context.Output.Write(" ");
                        predIndent = temp.Length + 1;
                        lastPred   = t.Predicate;
                    }
                    else if (lastPred == null || !t.Predicate.Equals(lastPred))
                    {
                        // Terminate previous Predicate Object list
                        context.Output.WriteLine(";");

                        if (context.PrettyPrint)
                        {
                            context.Output.Write(new String(' ', subjIndent));
                        }

                        // Write the next Predicate
                        temp = this.GenerateNodeOutput(globalContext, context, t.Predicate, TripleSegment.Predicate);
                        context.Output.Write(temp);
                        context.Output.Write(" ");
                        predIndent = temp.Length + 1;
                        lastPred   = t.Predicate;
                    }
                    else
                    {
                        // Continue Object List
                        context.Output.WriteLine(",");

                        if (context.PrettyPrint)
                        {
                            context.Output.Write(new String(' ', subjIndent + predIndent));
                        }
                    }

                    // Write the Object
                    context.Output.Write(this.GenerateNodeOutput(globalContext, context, t.Object, TripleSegment.Object));
                }

                // Terminate Triples
                if (ts.Count > 0)
                {
                    context.Output.WriteLine(".");
                }
            }
        }
Пример #39
0
 public override bool Contains(Triple t)
 {
     return(_dataset.ContainsQuad(_graphUri, t));
 }
Пример #40
0
 internal bool ContainsTriple(Triple t)
 {
     return(_spinConfiguration.ContainsTriple(t));
 }
Пример #41
0
 protected internal override bool Delete(Triple t)
 {
     return(_dataset.RemoveQuad(_graphUri, t));
 }
Пример #42
0
        /// <summary>
        /// Internal method which actually parses the Result Set by traversing the RDF Graph appropriately.
        /// </summary>
        /// <param name="context">Parser Context.</param>
        private void Parse(SparqlRdfParserContext context)
        {
            try
            {
                context.Handler.StartResults();

                // Create relevant Nodes
                context.Graph.NamespaceMap.AddNamespace("rdf", UriFactory.Create(NamespaceMapper.RDF));
                context.Graph.NamespaceMap.AddNamespace("rs", UriFactory.Create(SparqlSpecsHelper.SparqlRdfResultsNamespace));
                IUriNode rdfType        = context.Graph.CreateUriNode("rdf:type");
                IUriNode resultSetClass = context.Graph.CreateUriNode("rs:ResultSet");
                IUriNode resultVariable = context.Graph.CreateUriNode("rs:resultVariable");
                IUriNode solution       = context.Graph.CreateUriNode("rs:solution");
                IUriNode binding        = context.Graph.CreateUriNode("rs:binding");
                IUriNode value          = context.Graph.CreateUriNode("rs:value");
                IUriNode variable       = context.Graph.CreateUriNode("rs:variable");
                IUriNode boolean        = context.Graph.CreateUriNode("rs:boolean");

                // Try to get a ResultSet object
                Triple rset = context.Graph.Triples.WithPredicateObject(rdfType, resultSetClass).FirstOrDefault();
                if (rset != null)
                {
                    INode rsetID = rset.Subject;

                    // Find the Variables the Result Set contains or the Boolean Value
                    List <Triple> temp = context.Graph.Triples.WithSubjectPredicate(rsetID, boolean).ToList();
                    if (temp.Count > 0)
                    {
                        if (temp.Count > 1)
                        {
                            throw new RdfParseException("Result Set has more than one boolean result defined for it");
                        }

                        Triple booleanResult = temp.First();
                        INode  result        = booleanResult.Object;
                        if (result.NodeType == NodeType.Literal)
                        {
                            ILiteralNode lit = (ILiteralNode)result;
                            if (lit.DataType != null)
                            {
                                if (lit.DataType.AbsoluteUri.Equals(XmlSpecsHelper.XmlSchemaDataTypeBoolean))
                                {
                                    bool b;
                                    if (Boolean.TryParse(lit.Value, out b))
                                    {
                                        context.Handler.HandleBooleanResult(b);
                                        return;
                                    }
                                    else
                                    {
                                        throw new RdfParseException("Result Set has a boolean result which is a Literal typed as boolean but which does not contain a valid boolean value");
                                    }
                                }
                                else
                                {
                                    throw new RdfParseException("Result Set has a boolean result which is a Literal which is not boolean typed");
                                }
                            }
                            else
                            {
                                throw new RdfParseException("Result Set has a boolean result which is a Literal which is not typed as a boolean");
                            }
                        }
                        else
                        {
                            throw new RdfParseException("Result Set has a boolean result which is not a Literal Node");
                        }
                    }
                    else
                    {
                        // We're expected one/more variables
                        temp = context.Graph.Triples.WithSubjectPredicate(rsetID, resultVariable).ToList();
                        if (temp.Count > 0)
                        {
                            foreach (Triple t in temp)
                            {
                                if (t.Object.NodeType == NodeType.Literal)
                                {
                                    if (!context.Handler.HandleVariable(((ILiteralNode)t.Object).Value))
                                    {
                                        ParserHelper.Stop();
                                    }
                                    context.Variables.Add(((ILiteralNode)t.Object).Value);
                                }
                                else
                                {
                                    throw new RdfParseException("Result Set has a result variable definition which is not a Literal Node");
                                }
                            }
                        }
                        else
                        {
                            throw new RdfParseException("Result Set does not define any result variables or a boolean result");
                        }

                        // Then we're expecting some Solutions
                        temp = context.Graph.Triples.WithSubjectPredicate(rsetID, solution).ToList();
                        foreach (Triple slnTriple in temp)
                        {
                            // Each Solution has some Bindings
                            INode        slnID = slnTriple.Object;
                            bool         ok    = false;
                            SparqlResult r     = new SparqlResult();

                            foreach (Triple bindingTriple in context.Graph.Triples.WithSubjectPredicate(slnID, binding))
                            {
                                // Each Binding has a Variable and a Value
                                ok = true;
                                INode  bindingID = bindingTriple.Object;
                                String var       = String.Empty;
                                INode  val       = null;

                                // Retrieve the Variable and the Bound Value
                                foreach (Triple valueTriple in context.Graph.Triples.WithSubject(bindingID))
                                {
                                    if (valueTriple.Predicate.Equals(variable))
                                    {
                                        if (!var.Equals(String.Empty))
                                        {
                                            throw new RdfParseException("Result Set contains a Binding which refers to more than one Variable");
                                        }
                                        if (valueTriple.Object.NodeType != NodeType.Literal)
                                        {
                                            throw new RdfParseException("Result Set contains a Binding which refers to a Variable but not by a Literal Node as required");
                                        }
                                        var = ((ILiteralNode)valueTriple.Object).Value;
                                    }
                                    else if (valueTriple.Predicate.Equals(value))
                                    {
                                        if (val != null)
                                        {
                                            throw new RdfParseException("Result Set contains a Binding which has more than one Value");
                                        }
                                        val = valueTriple.Object;
                                    }
                                }
                                if (var.Equals(String.Empty) || val == null)
                                {
                                    throw new RdfParseException("Result Set contains a Binding which doesn't contain both a Variable and a Value");
                                }

                                // Check that the Variable was defined in the Header
                                if (!context.Variables.Contains(var))
                                {
                                    throw new RdfParseException("Unable to Parse a SPARQL Result Set since a <binding> element attempts to bind a value to the variable '" + var + "' which is not defined in the <head> by a <variable> element!");
                                }

                                r.SetValue(var, val);
                            }
                            if (!ok)
                            {
                                throw new RdfParseException("Result Set contains a Solution which has no Bindings");
                            }

                            // Check that all Variables are bound for a given result binding nulls where appropriate
                            foreach (String v in context.Variables)
                            {
                                if (!r.HasValue(v))
                                {
                                    r.SetValue(v, null);
                                }
                            }

                            if (!context.Handler.HandleResult(r))
                            {
                                ParserHelper.Stop();
                            }
                        }
                    }
                }
                else
                {
                    throw new RdfParseException("No Result Set object is defined in the Graph");
                }

                context.Handler.EndResults(true);
            }
            catch (RdfParsingTerminatedException)
            {
                context.Handler.EndResults(true);
            }
            catch
            {
                context.Handler.EndResults(false);
                throw;
            }
        }
Пример #43
0
 /// <summary>
 /// Formats a Triple as a String.
 /// </summary>
 /// <param name="t">Triple.</param>
 /// <returns></returns>
 public virtual String Format(Triple t)
 {
     return(Format(t.Subject, TripleSegment.Subject) + " " + Format(t.Predicate, TripleSegment.Predicate) + " " + Format(t.Object, TripleSegment.Object) + " .");
 }
Пример #44
0
        public void SparqlUpdateInsertDeleteWithBlankNodes()
        {
            //This test adapted from a contribution by Tomasz Pluskiewicz
            //It demonstrates an issue in SPARQL Update caused by incorrect Graph
            //references that can result when using GraphPersistenceWrapper in a SPARQL Update
            String initData = @"@prefix ex: <http://www.example.com/>.
@prefix rr: <http://www.w3.org/ns/r2rml#>.

ex:triplesMap rr:predicateObjectMap _:blank .
_:blank rr:object ex:Employee, ex:Worker .";

            String update = @"PREFIX rr: <http://www.w3.org/ns/r2rml#>

DELETE { ?map rr:object ?value . }
INSERT { ?map rr:objectMap [ rr:constant ?value ] . }
WHERE { ?map rr:object ?value }";

            String query = @"prefix ex: <http://www.example.com/>
prefix rr: <http://www.w3.org/ns/r2rml#>

select *
where
{
ex:triplesMap rr:predicateObjectMap ?predObjMap .
?predObjMap rr:objectMap ?objMap .
}";

            String expectedData = @"@prefix ex: <http://www.example.com/>.
@prefix rr: <http://www.w3.org/ns/r2rml#>.

ex:triplesMap rr:predicateObjectMap _:blank.
_:blank rr:objectMap _:autos1.
_:autos1 rr:constant ex:Employee.
_:autos2 rr:constant ex:Worker.
_:blank rr:objectMap _:autos2.";

            // given
            IGraph graph = new Graph();

            graph.LoadFromString(initData);
            IGraph expectedGraph = new Graph();

            expectedGraph.LoadFromString(expectedData);

            Console.WriteLine("Initial Graph:");
            TestTools.ShowGraph(graph);
            Console.WriteLine();

            // when
            TripleStore store = new TripleStore();

            store.Add(graph);

            var dataset = new InMemoryDataset(store, graph.BaseUri);
            ISparqlUpdateProcessor processor = new LeviathanUpdateProcessor(dataset);
            var updateParser = new SparqlUpdateParser();

            processor.ProcessCommandSet(updateParser.ParseFromString(update));

            Console.WriteLine("Resulting Graph:");
            TestTools.ShowGraph(graph);
            Console.WriteLine();

            Triple x         = graph.GetTriplesWithPredicate(graph.CreateUriNode("rr:predicateObjectMap")).FirstOrDefault();
            INode  origBNode = x.Object;

            Assert.True(graph.GetTriples(origBNode).Count() > 1, "Should be more than one Triple using the BNode");
            IEnumerable <Triple> ys = graph.GetTriplesWithSubject(origBNode);

            foreach (Triple y in ys)
            {
                Assert.Equal(origBNode, y.Subject);
            }

            //Graphs should be equal
            GraphDiffReport diff = graph.Difference(expectedGraph);

            if (!diff.AreEqual)
            {
                TestTools.ShowDifferences(diff);
            }
            Assert.Equal(expectedGraph, graph);

            //Test the Query
            SparqlResultSet results = graph.ExecuteQuery(query) as SparqlResultSet;

            TestTools.ShowResults(results);
            Assert.False(results.IsEmpty, "Should be some results");
        }
Пример #45
0
 /// <summary>
 /// Creates a new Batch Triple
 /// </summary>
 /// <param name="t">Triple</param>
 /// <param name="graphID">Graph ID to store Triple for</param>
 public BatchTriple(Triple t, String graphID)
 {
     _t       = t;
     _graphID = graphID;
 }
Пример #46
0
        public void OS_Continuation_Returns()
        {
            var osc = _set.OS("4", "4", new Triple("4", "4", ("4", 4)));

            Assert.AreEqual(new Triple("4", "5", ("4", 4)), osc.First());

            var oc = _set.O("4", new Triple("3", "4", ("4", 4)));

            Assert.AreEqual(new Triple("3", "5", ("4", 4)), oc.First());

            Assert.AreEqual(44, _set.O("5", new Triple("5", "5", ("5", 5))).ToArray().Count());
            Assert.AreEqual(4, _set.OS("5", "5", new Triple("5", "5", ("5", 5))).ToArray().Count());

            Assert.ThrowsException <InvalidOperationException>(() => _set.O("5", new Triple("4", "3", ("1", 1))));
            Assert.ThrowsException <InvalidOperationException>(() => _set.OS("1", "3", new Triple("2", "3", ("1", 1))));

            Assert.AreEqual(0, _set.O("5", new Triple("5", "5", ("6", 6))).ToArray().Count());
            Assert.AreEqual(0, _set.OS("6", "4", new Triple("5", "5", ("6", 6))).ToArray().Count());
        }
        private int ProcessEvaluationTest(SparqlQueryParser parser, Triple commentDef, String queryFile, String dataFile, List <String> dataFiles, String resultFile)
        {
            Console.WriteLine("# Processing Evaluation Test " + Path.GetFileName(queryFile));

            if (commentDef != null)
            {
                Console.WriteLine(commentDef.Object.ToString());
                Console.WriteLine();
            }

            if (dataFiles.Contains(dataFile))
            {
                dataFiles.Remove(dataFile);
            }
            if (queryFile.StartsWith("file:///"))
            {
                queryFile = queryFile.Substring(8);
            }
            if (dataFile != null && dataFile.StartsWith("file:///"))
            {
                dataFile = dataFile.Substring(8);
            }
            if (resultFile.StartsWith("file:///"))
            {
                resultFile = resultFile.Substring(8);
            }

            Console.WriteLine("Query File is " + queryFile);
            if (evaluationTestOverride.Any(x => queryFile.EndsWith(x)))
            {
                Console.WriteLine();
                Console.WriteLine("# Test Result = Manually overridden to Pass (Test Passed)");
                testsPassed++;
                testsEvaluationPassed++;
                return(1);
            }
            if (dataFile != null)
            {
                Console.WriteLine("Default Graph File is " + dataFile);
            }
            foreach (String file in dataFiles)
            {
                Console.WriteLine("Uses Named Graph File " + file);
            }
            Console.WriteLine("Expected Result File is " + resultFile);
            Console.WriteLine();

            SparqlQuery query;

            try
            {
                query = parser.ParseFromFile(queryFile);

                Console.WriteLine(query.ToString());
                Console.WriteLine();
                Console.WriteLine("Formatted with SparqlFormatter");
                SparqlFormatter formatter = new SparqlFormatter(query.NamespaceMap);
                Console.WriteLine(formatter.Format(query));
                Console.WriteLine();

                try
                {
                    Console.WriteLine(query.ToAlgebra().ToString());
                    Console.WriteLine();
                }
                catch
                {
                    //Do Nothing
                }
            }
            catch (RdfParseException parseEx)
            {
                this.ReportError("Query Parser Error", parseEx);
                testsFailed++;
                testsEvaluationFailed++;
                Console.WriteLine("# Test Result = Unable to parse query (Test Failed)");
                return(-1);
            }

            IInMemoryQueryableStore store;

            if (dataFile != null)
            {
                store = new TripleStore();
            }
            else
            {
                store = new WebDemandTripleStore();
            }

            //Load Default Graph
            Graph defaultGraph = new Graph();

            try
            {
                if (dataFile != null)
                {
                    FileLoader.Load(defaultGraph, dataFile);
                }
                store.Add(defaultGraph);
            }
            catch (RdfParseException parseEx)
            {
                this.ReportError("Parser Error", parseEx);
                testsFailed++;
                testsEvaluationFailed++;
                Console.WriteLine("# Test Result = Unable to parse Default Graph (Test Failed)");
                return(-1);
            }

            //Load Named Graphs
            try
            {
                foreach (String graphFile in dataFiles)
                {
                    Graph namedGraph = new Graph();
                    if (graphFile.StartsWith("file:///"))
                    {
                        FileLoader.Load(namedGraph, graphFile.Substring(8));
                    }
                    else
                    {
                        FileLoader.Load(namedGraph, graphFile);
                    }
                    store.Add(namedGraph);
                }
            }
            catch (RdfParseException parseEx)
            {
                this.ReportError("Parser Error", parseEx);
                testsFailed++;
                testsEvaluationFailed++;
                Console.WriteLine("# Test Result - Unable to parse Named Graph (Test Failed)");
                return(-1);
            }

            //Create a Dataset and then Set Graphs
            //ISparqlDataset dataset = new InMemoryQuadDataset(store);
            ISparqlDataset dataset = new InMemoryDataset(store);

            if (!query.DefaultGraphs.Any())
            {
                query.AddDefaultGraph(defaultGraph.BaseUri);
            }
            if (!query.NamedGraphs.Any())
            {
                foreach (String namedGraphUri in dataFiles)
                {
                    query.AddNamedGraph(new Uri(namedGraphUri));
                }
            }

            //Try and get the result
            Object results = null;

            try
            {
                LeviathanQueryProcessor processor = new LeviathanQueryProcessor(dataset);
                results = processor.ProcessQuery(query);
            }
            catch (RdfQueryException queryEx)
            {
                this.ReportError("Query Error", queryEx);
                testsFailed++;
                testsEvaluationFailed++;
                Console.WriteLine("# Test Result - Query execution failed (Test Failed)");
                return(-1);
            }
            catch (Exception ex)
            {
                this.ReportError("Other Error", ex);
                testsFailed++;
                testsEvaluationFailed++;
                Console.WriteLine("# Test Result - Query failed (Test Failed)");
                return(-1);
            }

            if (results == null)
            {
                testsFailed++;
                testsEvaluationFailed++;
                Console.WriteLine("# Test Result - No result was returned from the Query (Test Failed)");
                return(-1);
            }

            //Load in the expected results
            if (results is SparqlResultSet)
            {
                //Save our Results so we can manually compare as needed
                SparqlResultSet ourResults = (SparqlResultSet)results;
                SparqlXmlWriter writer     = new SparqlXmlWriter();
                writer.Save(ourResults, resultFile + ".out");
                SparqlResultSet expectedResults = new SparqlResultSet();

                if (resultFile.EndsWith(".srx"))
                {
                    try
                    {
                        SparqlXmlParser resultSetParser = new SparqlXmlParser();
                        resultSetParser.Load(expectedResults, resultFile);
                    }
                    catch (RdfParseException parseEx)
                    {
                        this.ReportError("Result Set Parser Error", parseEx);
                        testsIndeterminate++;
                        testsEvaluationIndeterminate++;
                        Console.WriteLine("# Test Result - Error loading expected Result Set (Test Indeterminate)");
                        return(0);
                    }
                }
                else if (resultFile.EndsWith(".ttl") || resultFile.EndsWith(".rdf"))
                {
                    try
                    {
                        SparqlRdfParser resultSetParser = new SparqlRdfParser();
                        resultSetParser.Load(expectedResults, resultFile);
                    }
                    catch (RdfParseException parseEx)
                    {
                        this.ReportError("Result Set Parser Error", parseEx);
                        testsIndeterminate++;
                        testsEvaluationIndeterminate++;
                        Console.WriteLine("# Test Result - Error loading expected Result Set (Test Indeterminate)");
                        return(0);
                    }
                }
                else
                {
                    testsIndeterminate++;
                    testsEvaluationIndeterminate++;
                    Console.WriteLine("# Test Result - Unable to load the expected Result Set (Test Indeterminate)");
                    return(0);
                }

                try
                {
                    ourResults.Trim();
                    expectedResults.Trim();
                    if (ourResults.Equals(expectedResults))
                    {
                        testsPassed++;
                        testsEvaluationPassed++;
                        Console.WriteLine("# Test Result - Result Set as expected (Test Passed)");
                        return(1);
                    }
                    else
                    {
                        Console.WriteLine("Final Query");
                        Console.WriteLine(query.ToString());
                        Console.WriteLine();
                        this.ShowTestData(store);
                        this.ShowResultSets(ourResults, expectedResults);
                        testsFailed++;
                        testsEvaluationFailed++;
                        Console.WriteLine("# Test Result - Result Set not as expected (Test Failed)");
                        return(-1);
                    }
                }
                catch (NotImplementedException)
                {
                    this.ShowResultSets(ourResults, expectedResults);
                    testsIndeterminate++;
                    testsEvaluationIndeterminate++;
                    Console.WriteLine("# Test Result - Unable to establish if Result Set was as expected (Test Indeterminate)");
                    return(0);
                }
            }
            else if (results is Graph)
            {
                if (resultFile.EndsWith(".ttl"))
                {
                    //Save our Results so we can manually compare as needed
                    Graph ourResults = (Graph)results;
                    CompressingTurtleWriter writer = new CompressingTurtleWriter();
                    writer.Save(ourResults, resultFile + ".out");

                    try
                    {
                        Graph        expectedResults = new Graph();
                        TurtleParser ttlparser       = new TurtleParser();
                        ttlparser.Load(expectedResults, resultFile);

                        try
                        {
                            if (ourResults.Equals(expectedResults))
                            {
                                testsPassed++;
                                testsEvaluationPassed++;
                                Console.WriteLine("# Test Result - Graph as expected (Test Passed)");
                                return(1);
                            }
                            else
                            {
                                this.ShowTestData(store);
                                this.ShowGraphs(ourResults, expectedResults);
                                testsFailed++;
                                testsEvaluationFailed++;
                                Console.WriteLine("# Test Result - Graph not as expected (Test Failed)");
                                return(-1);
                            }
                        }
                        catch (NotImplementedException)
                        {
                            this.ShowGraphs(ourResults, expectedResults);
                            testsIndeterminate++;
                            testsEvaluationIndeterminate++;
                            Console.WriteLine("# Test Result - Unable to establish if Graph was as expected (Test Indeterminate)");
                            return(0);
                        }
                    }
                    catch (RdfParseException parseEx)
                    {
                        this.ReportError("Graph Parser Error", parseEx);
                        testsIndeterminate++;
                        testsEvaluationIndeterminate++;
                        Console.WriteLine("# Test Result - Error loading expected Graph (Test Indeterminate)");
                        return(0);
                    }
                }
                else
                {
                    testsIndeterminate++;
                    testsEvaluationIndeterminate++;
                    Console.WriteLine("# Test Result - Unable to load expected Graph (Test Indeterminate)");
                    return(0);
                }
            }
            else
            {
                testsFailed++;
                testsEvaluationFailed++;
                Console.WriteLine("# Test Result - Didn't produce a Graph as expected (Test Failed)");
                return(-1);
            }
        }
Пример #48
0
        /// <summary>
        /// Internal method which generates the RDF/Json Output for a Graph
        /// </summary>
        /// <param name="g">Graph to save</param>
        /// <param name="output">Stream to save to</param>
        private void GenerateOutput(IGraph g, TextWriter output)
        {
            //Get a Blank Node Output Mapper
            BlankNodeOutputMapper bnodeMapper = new BlankNodeOutputMapper(WriterHelper.IsValidBlankNodeID);

            //Get the Writer and Configure Options
            JsonTextWriter writer = new JsonTextWriter(output);

            if (this._prettyprint)
            {
                writer.Formatting = Newtonsoft.Json.Formatting.Indented;
            }
            else
            {
                writer.Formatting = Newtonsoft.Json.Formatting.None;
            }

            //Start the overall Object which represents the Graph
            writer.WriteStartObject();

            //Get the Triples as a Sorted List
            List <Triple> ts = g.Triples.ToList();

            ts.Sort(new FullTripleComparer(new FastNodeComparer()));

            //Variables we need to track our writing
            INode lastSubj, lastPred;

            lastSubj = lastPred = null;

            for (int i = 0; i < ts.Count; i++)
            {
                Triple t = ts[i];
                if (lastSubj == null || !t.Subject.Equals(lastSubj))
                {
                    //Terminate previous Triples
                    if (lastSubj != null)
                    {
                        writer.WriteEndArray();
                        writer.WriteEndObject();
                    }

                    //Start a new set of Triples
                    //Validate Subject
                    switch (t.Subject.NodeType)
                    {
                    case NodeType.GraphLiteral:
                        throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("RDF/JSON"));

                    case NodeType.Literal:
                        throw new RdfOutputException(WriterErrorMessages.LiteralSubjectsUnserializable("RDF/JSON"));

                    case NodeType.Blank:
                        break;

                    case NodeType.Uri:
                        //OK
                        break;

                    default:
                        throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("RDF/JSON"));
                    }

                    //Write out the Subject
                    if (t.Subject.NodeType != NodeType.Blank)
                    {
                        writer.WritePropertyName(t.Subject.ToString());
                    }
                    else
                    {
                        //Remap Blank Node IDs as appropriate
                        writer.WritePropertyName("_:" + bnodeMapper.GetOutputID(((IBlankNode)t.Subject).InternalID));
                    }

                    //Start an Object for the Subject
                    writer.WriteStartObject();

                    lastSubj = t.Subject;

                    //Write the first Predicate
                    //Validate Predicate
                    switch (t.Predicate.NodeType)
                    {
                    case NodeType.GraphLiteral:
                        throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("RDF/JSON"));

                    case NodeType.Blank:
                        throw new RdfOutputException(WriterErrorMessages.BlankPredicatesUnserializable("RDF/JSON"));

                    case NodeType.Literal:
                        throw new RdfOutputException(WriterErrorMessages.LiteralPredicatesUnserializable("RDF/JSON"));

                    case NodeType.Uri:
                        //OK
                        break;

                    default:
                        throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("RDF/JSON"));
                    }

                    //Write the Predicate
                    writer.WritePropertyName(t.Predicate.ToString());

                    //Create an Array for the Objects
                    writer.WriteStartArray();

                    lastPred = t.Predicate;
                }
                else if (lastPred == null || !t.Predicate.Equals(lastPred))
                {
                    //Terminate previous Predicate Object list
                    writer.WriteEndArray();

                    //Write the next Predicate
                    //Validate Predicate
                    switch (t.Predicate.NodeType)
                    {
                    case NodeType.GraphLiteral:
                        throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("RDF/JSON"));

                    case NodeType.Blank:
                        throw new RdfOutputException(WriterErrorMessages.BlankPredicatesUnserializable("RDF/JSON"));

                    case NodeType.Literal:
                        throw new RdfOutputException(WriterErrorMessages.LiteralPredicatesUnserializable("RDF/JSON"));

                    case NodeType.Uri:
                        //OK
                        break;

                    default:
                        throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("RDF/JSON"));
                    }

                    //Write the Predicate
                    writer.WritePropertyName(t.Predicate.ToString());

                    //Create an Array for the Objects
                    writer.WriteStartArray();

                    lastPred = t.Predicate;
                }

                //Write the Object
                //Create an Object for the Object
                INode obj = t.Object;
                writer.WriteStartObject();
                writer.WritePropertyName("value");
                switch (obj.NodeType)
                {
                case NodeType.Blank:
                    //Remap Blank Node IDs as appropriate
                    writer.WriteValue("_:" + bnodeMapper.GetOutputID(((IBlankNode)obj).InternalID));
                    writer.WritePropertyName("type");
                    writer.WriteValue("bnode");
                    break;

                case NodeType.GraphLiteral:
                    throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("RDF/JSON"));

                case NodeType.Literal:
                    ILiteralNode lit = (ILiteralNode)obj;
                    writer.WriteValue(lit.Value);

                    if (!lit.Language.Equals(String.Empty))
                    {
                        writer.WritePropertyName("lang");
                        writer.WriteValue(lit.Language);
                    }
                    else if (lit.DataType != null)
                    {
                        writer.WritePropertyName("datatype");
                        writer.WriteValue(lit.DataType.AbsoluteUri);
                    }
                    writer.WritePropertyName("type");
                    writer.WriteValue("literal");
                    break;

                case NodeType.Uri:
                    writer.WriteValue(obj.ToString());
                    writer.WritePropertyName("type");
                    writer.WriteValue("uri");
                    break;

                default:
                    throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("RDF/JSON"));
                }
                writer.WriteEndObject();
            }

            //Terminate the Object which represents the Graph
            writer.WriteEndObject();
        }
        private void ProcessTestDirectory(String dir)
        {
            Console.WriteLine("## Processing Directory '" + dir + "'");

            //if (dir.EndsWith("il8n\\"))
            //{
            //    Console.WriteLine("Disabling URI Normalization for the Internationalization Tests");
            //    Options.UriNormalization = false;
            //}

            //First need to find the manifest file
            if (File.Exists(dir + "manifest.ttl"))
            {
                Graph manifest = new Graph();
                try
                {
                    FileLoader.Load(manifest, dir + "manifest.ttl");
                    Console.WriteLine("Loaded Tests Manifest OK");
                    Console.WriteLine();
                }
                catch (RdfParseException parseEx)
                {
                    this.ReportError("Manifest Parser Error for Directory '" + dir + "'", parseEx);
                }

                //Create necessary Uri Nodes
                IUriNode rdfType            = manifest.CreateUriNode("rdf:type");
                IUriNode rdfsComment        = manifest.CreateUriNode("rdfs:comment");
                IUriNode positiveSyntaxTest = manifest.CreateUriNode("mf:PositiveSyntaxTest");
                IUriNode negativeSyntaxTest = manifest.CreateUriNode("mf:NegativeSyntaxTest");
                IUriNode evaluationTest     = manifest.CreateUriNode("mf:QueryEvaluationTest");
                IUriNode action             = manifest.CreateUriNode("mf:action");
                IUriNode result             = manifest.CreateUriNode("mf:result");
                IUriNode approval           = manifest.CreateUriNode("dawgt:approval");
                IUriNode approvedTest       = manifest.CreateUriNode("dawgt:Approved");
                IUriNode query     = manifest.CreateUriNode("qt:query");
                IUriNode data      = manifest.CreateUriNode("qt:data");
                IUriNode graphData = manifest.CreateUriNode("qt:graphData");

                //Create SPARQL Query Parser
                SparqlQueryParser parser = new SparqlQueryParser();
                parser.DefaultBaseUri = manifest.NamespaceMap.GetNamespaceUri(String.Empty);

                //Find all the Positive Syntax Tests
                foreach (Triple t in manifest.Triples.WithPredicateObject(rdfType, positiveSyntaxTest))
                {
                    //Test ID
                    INode testID = t.Subject;

                    //See whether the Test is approved
                    if (manifest.Triples.Contains(new Triple(testID, approval, approvedTest)))
                    {
                        tests++;
                        testsSyntax++;

                        //Find the Test Query
                        Triple queryDef = manifest.Triples.WithSubjectPredicate(testID, action).FirstOrDefault();
                        if (queryDef != null)
                        {
                            this.ProcessSyntaxTest(parser, queryDef.Object.ToString(), true);
                        }
                        else
                        {
                            Console.WriteLine("Unable to find the Test Query for Test ID '" + testID.ToString() + "' in '" + dir + "'");
                        }

                        Debug.WriteLine(tests + " Tests Completed");
                    }
                }

                //Find all the Negative Syntax Tests
                foreach (Triple t in manifest.Triples.WithPredicateObject(rdfType, negativeSyntaxTest))
                {
                    //Test ID
                    INode testID = t.Subject;

                    //See whether the Test is approved
                    if (manifest.Triples.Contains(new Triple(testID, approval, approvedTest)))
                    {
                        tests++;
                        testsSyntax++;

                        //Find the Test Query
                        Triple queryDef = manifest.Triples.WithSubjectPredicate(testID, action).FirstOrDefault();
                        if (queryDef != null)
                        {
                            this.ProcessSyntaxTest(parser, queryDef.Object.ToString(), false);
                        }
                        else
                        {
                            Console.WriteLine("Unable to find the Test Query for Test ID '" + testID.ToString() + "' in '" + dir + "'");
                            testsIndeterminate++;
                            testsEvaluationIndeterminate++;
                        }

                        Debug.WriteLine(tests + " Tests Completed");
                    }
                }

                //Find all the Query Evaluation Tests
                foreach (Triple t in manifest.Triples.WithPredicateObject(rdfType, evaluationTest))
                {
                    //Test ID
                    INode testID = t.Subject;

                    //See whether the Test is approved
                    if (manifest.Triples.Contains(new Triple(testID, approval, approvedTest)))
                    {
                        tests++;
                        testsEvaluation++;

                        //Find the Action ID
                        Triple actionDef = manifest.Triples.WithSubjectPredicate(testID, action).FirstOrDefault();
                        if (actionDef != null)
                        {
                            INode actionID = actionDef.Object;

                            //Get the Query
                            Triple queryDef = manifest.Triples.WithSubjectPredicate(actionID, query).FirstOrDefault();
                            if (queryDef != null)
                            {
                                //Get the Default Graph
                                Triple defaultGraphDef = manifest.Triples.WithSubjectPredicate(actionID, data).FirstOrDefault();
                                String defGraph        = (defaultGraphDef == null) ? null : defaultGraphDef.Object.ToString();

                                //Get the Named Graphs if any
                                List <String> namedGraphs = manifest.Triples.WithSubjectPredicate(actionID, graphData).Select(gdef => gdef.Object.ToString()).ToList();

                                //Get the expected Result
                                Triple resultDef = manifest.Triples.WithSubjectPredicate(testID, result).FirstOrDefault();
                                if (resultDef != null)
                                {
                                    //Try to get the comments on the Test
                                    Triple commentDef = manifest.Triples.WithSubjectPredicate(testID, rdfsComment).FirstOrDefault();

                                    //Run the Evaluation Test
                                    int eval = this.ProcessEvaluationTest(parser, commentDef, queryDef.Object.ToString(), defGraph, namedGraphs, resultDef.Object.ToString());
                                }
                                else
                                {
                                    Console.WriteLine("Unable to find the Expected Result file for Test ID '" + testID.ToString() + "' in '" + dir + "'");
                                    testsIndeterminate++;
                                    testsEvaluationIndeterminate++;
                                }
                            }
                            else
                            {
                                Console.WriteLine("Unable to find the Test Query for Test ID '" + testID.ToString() + "' in '" + dir + "'");
                                testsIndeterminate++;
                                testsEvaluationIndeterminate++;
                            }
                        }
                        else
                        {
                            Console.WriteLine("Unable to find the Action for Test ID '" + testID.ToString() + "' + in + '" + dir + "'");
                            testsIndeterminate++;
                            testsEvaluationIndeterminate++;
                        }

                        Console.WriteLine();
                        Console.WriteLine(new String('-', 150));
                    }

                    Debug.WriteLine(tests + " Tests Completed");
                }
            }

            Console.WriteLine();
            Console.WriteLine("## Finished processing directory '" + dir + "'");
            Console.WriteLine(new String('=', 150));
            Console.WriteLine();

            //if (dir.EndsWith("il8n\\"))
            //{
            //    Options.UriNormalization = true;
            //}
        }
Пример #50
0
        public static Dictionary <string, object> WonkyCubes(int X = 21, int Y = 21, int Z = 2)
        {
            Triple[,,] points = new Triple[X, Y, Z];
            List <Point> pointsLinear = new List <Point>();

            for (int i = 0; i < X; i++)
            {
                for (int j = 0; j < Y; j++)
                {
                    for (int k = 0; k < Z; k++)
                    {
                        points[i, j, k] = new Triple(i, j, k + 5f);
                        pointsLinear.Add(Point.ByCoordinates(i, j, k + 5f));
                    }
                }
            }


            List <Goal> anchorGoals = new List <Goal>();

            anchorGoals.Add(new AnchorGoal(points[0, 0, Z - 1]));
            anchorGoals.Add(new AnchorGoal(points[X - 1, 0, Z - 1]));
            anchorGoals.Add(new AnchorGoal(points[X - 1, Y - 1, Z - 1]));
            anchorGoals.Add(new AnchorGoal(points[0, Y - 1, Z - 1]));

            List <Goal> goals = new List <Goal>();

            goals.AddRange(anchorGoals);


            List <GeometryBinder> geometryBinders = new List <GeometryBinder>();

            List <Triple> vertices = new List <Triple>();

            vertices.Clear();
            for (int i = 0; i < X; i++)
            {
                for (int j = 0; j < Y; j++)
                {
                    vertices.Add(points[i, i % 2 == 0 ? j : Y - 1 - j, 0]);
                }
            }
            geometryBinders.Add(new PolylineBinder(vertices));

            vertices.Clear();
            for (int j = 0; j < X; j++)
            {
                for (int i = 0; i < Y; i++)
                {
                    vertices.Add(points[j % 2 == 0 ? i : X - 1 - i, j, 0]);
                }
            }
            geometryBinders.Add(new PolylineBinder(vertices));

            vertices.Clear();
            for (int i = 0; i < X; i++)
            {
                for (int j = 0; j < Y; j++)
                {
                    vertices.Add(points[i, i % 2 == 0 ? j : Y - 1 - j, Z - 1]);
                }
            }
            geometryBinders.Add(new PolylineBinder(vertices));

            vertices.Clear();
            for (int j = 0; j < X; j++)
            {
                for (int i = 0; i < Y; i++)
                {
                    vertices.Add(points[j % 2 == 0 ? i : X - 1 - i, j, Z - 1]);
                }
            }
            geometryBinders.Add(new PolylineBinder(vertices));



            vertices.Clear();
            for (int j = 0; j < Y; j++)
            {
                for (int k = 0; k < Z; k++)
                {
                    vertices.Add(points[0, j, j % 2 == 0 ? k : Z - 1 - k]);
                }
            }
            geometryBinders.Add(new PolylineBinder(vertices));

            vertices.Clear();
            for (int k = 0; k < Z; k++)
            {
                for (int j = 0; j < Y; j++)
                {
                    vertices.Add(points[0, k % 2 == 0 ? j : Y - 1 - j, k]);
                }
            }
            geometryBinders.Add(new PolylineBinder(vertices));

            vertices.Clear();
            for (int j = 0; j < Y; j++)
            {
                for (int k = 0; k < Z; k++)
                {
                    vertices.Add(points[X - 1, j, j % 2 == 0 ? k : Z - 1 - k]);
                }
            }
            geometryBinders.Add(new PolylineBinder(vertices));

            vertices.Clear();
            for (int k = 0; k < Z; k++)
            {
                for (int j = 0; j < Y; j++)
                {
                    vertices.Add(points[X - 1, k % 2 == 0 ? j : Y - 1 - j, k]);
                }
            }
            geometryBinders.Add(new PolylineBinder(vertices));



            vertices.Clear();
            for (int k = 0; k < Z; k++)
            {
                for (int i = 0; i < Y; i++)
                {
                    vertices.Add(points[k % 2 == 0 ? i : X - 1 - i, 0, k]);
                }
            }
            geometryBinders.Add(new PolylineBinder(vertices));

            vertices.Clear();
            for (int i = 0; i < Y; i++)
            {
                for (int k = 0; k < Z; k++)
                {
                    vertices.Add(points[i, 0, i % 2 == 0 ? k : Z - 1 - k]);
                }
            }
            geometryBinders.Add(new PolylineBinder(vertices));

            vertices.Clear();
            for (int k = 0; k < Z; k++)
            {
                for (int i = 0; i < Y; i++)
                {
                    vertices.Add(points[k % 2 == 0 ? i : X - 1 - i, Y - 1, k]);
                }
            }
            geometryBinders.Add(new PolylineBinder(vertices));

            vertices.Clear();
            for (int i = 0; i < Y; i++)
            {
                for (int k = 0; k < Z; k++)
                {
                    vertices.Add(points[i, Y - 1, i % 2 == 0 ? k : Z - 1 - k]);
                }
            }
            geometryBinders.Add(new PolylineBinder(vertices));


            for (int i = 0; i < X - 1; i++)
            {
                for (int j = 0; j < Y - 1; j++)
                {
                    for (int k = 0; k < Z - 1; k++)
                    {
                        var voxelPoints = new List <Triple>()
                        {
                            points[i + 0, j + 0, k + 0],
                            points[i + 1, j + 0, k + 0],
                            points[i + 1, j + 1, k + 0],
                            points[i + 0, j + 1, k + 0],
                            points[i + 0, j + 0, k + 1],
                            points[i + 1, j + 0, k + 1],
                            points[i + 1, j + 1, k + 1],
                            points[i + 0, j + 1, k + 1],
                        };


                        goals.Add(new ShapeMatchingGoal(voxelPoints, voxelPoints));
                    }
                }
            }

            //goals.Add(new FloorGoal(pointsLinear));
            //goals.Add(new ConstantGoal(pointsLinear, Triple.BasisZ * -0.1f));

            return(new Dictionary <string, object>
            {
                { "goals", goals },
                { "geometryBinders", geometryBinders },
                { "anchorGoals", anchorGoals },
                { "points", pointsLinear }
            });
        }
Пример #51
0
        /// <summary>
        /// Initializes this StructureLayoutHolder object, which sets up all the structures the AI has at its disposal.
        /// </summary>
        /// <param name="director"></param>
        public static void Initialize(ref Director director)
        {
            sAllStructures =
                new Dictionary <EaiDifficulty, Triple <CommandCenter, List <PlatformBlank>, List <Road> >[]>
            {
                [EaiDifficulty.Easy] =
                    new Triple <CommandCenter, List <PlatformBlank>, List <Road> > [EasyStructureCount],
                [EaiDifficulty.Medium] =
                    new Triple <CommandCenter, List <PlatformBlank>, List <Road> > [MediumStructureCount],
                [EaiDifficulty.Hard] =
                    new Triple <CommandCenter, List <PlatformBlank>, List <Road> > [HardStructureCount]
            };


            #region 1. Easy Structure
            // 1 CC, 1 spawner, 1 sentinal : traingle formation

            var struct1CommandCenter = (CommandCenter)PlatformFactory.Get(EStructureType.Command, ref director, 0f, 0f, null, false, false);

            var struct1Platforms = new List <PlatformBlank>();
            var struct1Plat1     = (Spawner)PlatformFactory.Get(EStructureType.Spawner, ref director, -200, -110);
            var struct1Plat2     = (Sentinel)PlatformFactory.Get(EStructureType.Sentinel, ref director, 70, -180);

            struct1Platforms.Add(struct1Plat1);
            struct1Platforms.Add(struct1Plat2);


            var struct1Roads = new List <Road>
            {
                new Road(struct1CommandCenter, struct1Plat2, ref director),
                new Road(struct1CommandCenter, struct1Plat1, ref director),
                new Road(struct1Plat1, struct1Plat2, ref director)
            };

            var struct1 = new Triple <CommandCenter, List <PlatformBlank>, List <Road> >(struct1CommandCenter, struct1Platforms, struct1Roads);

            sAllStructures[EaiDifficulty.Easy][0] = struct1;

            #endregion

            #region 2. Easy Structure
            // 1 CC, 1 spawner, 1 sentinal, 3 blank : a samll tree like strucutre

            var struct2CommandCenter = (CommandCenter)PlatformFactory.Get(EStructureType.Command, ref director, 0f, 0f, null, false, false);

            var struct2Platforms = new List <PlatformBlank>();
            var struct2Plat1     = PlatformFactory.Get(EStructureType.Blank, ref director, -200, -110, friendly: false);
            var struct2Plat2     = PlatformFactory.Get(EStructureType.Sentinel, ref director, 200, -30);
            var struct2Plat3     = PlatformFactory.Get(EStructureType.Blank, ref director, -150, -250, friendly: false);
            var struct2Plat4     = PlatformFactory.Get(EStructureType.Spawner, ref director, 70, -240);
            var struct2Plat5     = PlatformFactory.Get(EStructureType.Blank, ref director, -150, 200, friendly: false);


            struct2Platforms.Add(struct2Plat1);
            struct2Platforms.Add(struct2Plat2);
            struct2Platforms.Add(struct2Plat3);
            struct2Platforms.Add(struct2Plat4);
            struct2Platforms.Add(struct2Plat5);


            var struct2Roads = new List <Road>
            {
                new Road(struct2CommandCenter, struct2Plat5, ref director),
                new Road(struct2CommandCenter, struct2Plat1, ref director),
                new Road(struct2CommandCenter, struct2Plat2, ref director),
                new Road(struct2CommandCenter, struct2Plat3, ref director),
                new Road(struct2CommandCenter, struct2Plat5, ref director),
                new Road(struct2Plat4, struct2Plat3, ref director)
            };

            var struct2 = new Triple <CommandCenter, List <PlatformBlank>, List <Road> >(struct2CommandCenter, struct2Platforms, struct2Roads);

            sAllStructures[EaiDifficulty.Easy][1] = struct2;

            #endregion

            #region 3. Easy Structure
            // 1 CC, 2 sentinal, 1 spawner, 2 blank : random constellation

            var struct3ECommandCenter = (CommandCenter)PlatformFactory.Get(EStructureType.Command, ref director, 0f, 0f, null, false, false);

            var struct3EPlatforms = new List <PlatformBlank>();
            var struct3EPlat1     = PlatformFactory.Get(EStructureType.Blank, ref director, -300, 150, friendly: false);
            var struct3EPlat2     = PlatformFactory.Get(EStructureType.Blank, ref director, 200, 200, friendly: false);
            var struct3EPlat3     = PlatformFactory.Get(EStructureType.Sentinel, ref director, 400, 300);
            var struct3EPlat4     = PlatformFactory.Get(EStructureType.Spawner, ref director, -450, 350);
            var struct3EPlat5     = PlatformFactory.Get(EStructureType.Sentinel, ref director, -200, -200);


            struct3EPlatforms.Add(struct3EPlat1);
            struct3EPlatforms.Add(struct3EPlat2);
            struct3EPlatforms.Add(struct3EPlat3);
            struct3EPlatforms.Add(struct3EPlat4);
            struct3EPlatforms.Add(struct3EPlat5);


            var struct3ERoads = new List <Road>
            {
                new Road(struct3ECommandCenter, struct3EPlat1, ref director),
                new Road(struct3ECommandCenter, struct3EPlat2, ref director),
                new Road(struct3ECommandCenter, struct3EPlat5, ref director),
                new Road(struct3EPlat1, struct3EPlat4, ref director),
                new Road(struct3EPlat2, struct3EPlat3, ref director),
                new Road(struct3EPlat4, struct3EPlat2, ref director),
                new Road(struct3EPlat1, struct3EPlat2, ref director)
            };

            var struct3E = new Triple <CommandCenter, List <PlatformBlank>, List <Road> >(struct3ECommandCenter, struct3EPlatforms, struct3ERoads);

            sAllStructures[EaiDifficulty.Easy][2] = struct3E;

            #endregion

            #region 1. Medium Structure
            // 1 CC, 1 spawner, 3 sentinal, 3 blank : cc center point with 3 arms

            var struct1MCommandCenter = (CommandCenter)PlatformFactory.Get(EStructureType.Command, ref director, 0f, 0f, null, false, false);

            var struct1MPlatforms = new List <PlatformBlank>();
            var struct1MPlat1     = PlatformFactory.Get(EStructureType.Spawner, ref director, -200, -110);
            var struct1MPlat2     = PlatformFactory.Get(EStructureType.Blank, ref director, -100, -200, friendly: false);
            var struct1MPlat3     = PlatformFactory.Get(EStructureType.Sentinel, ref director, -170, 200);
            var struct1MPlat4     = PlatformFactory.Get(EStructureType.Sentinel, ref director, -600, -440);
            var struct1MPlat5     = PlatformFactory.Get(EStructureType.Blank, ref director, -400, 100, friendly: false);
            var struct1MPlat6     = PlatformFactory.Get(EStructureType.Sentinel, ref director, 400, -300);
            var struct1MPlat7     = PlatformFactory.Get(EStructureType.Blank, ref director, 200, 150, friendly: false);

            struct1MPlatforms.Add(struct1MPlat1);
            struct1MPlatforms.Add(struct1MPlat2);
            struct1MPlatforms.Add(struct1MPlat3);
            struct1MPlatforms.Add(struct1MPlat4);
            struct1MPlatforms.Add(struct1MPlat5);
            struct1MPlatforms.Add(struct1MPlat6);
            struct1MPlatforms.Add(struct1MPlat7);

            var struct1MRoads = new List <Road>
            {
                new Road(struct1MCommandCenter, struct1MPlat1, ref director),
                new Road(struct1MCommandCenter, struct1MPlat2, ref director),
                new Road(struct1MCommandCenter, struct1MPlat3, ref director),
                new Road(struct1MCommandCenter, struct1MPlat6, ref director),
                new Road(struct1MCommandCenter, struct1MPlat7, ref director),
                new Road(struct1MPlat1, struct1MPlat2, ref director),
                new Road(struct1MPlat1, struct1MPlat3, ref director),
                new Road(struct1MPlat1, struct1MPlat4, ref director),
                new Road(struct1MPlat1, struct1MPlat5, ref director)
            };


            var struct1M = new Triple <CommandCenter, List <PlatformBlank>, List <Road> >(struct1MCommandCenter, struct1MPlatforms, struct1MRoads);

            sAllStructures[EaiDifficulty.Medium][0] = struct1M;


            #endregion

            #region 2. Medium Structure
            // 1 CC, 2 spawner, 3 sentinal, 2 blank : random constellation

            var struct2MCommandCenter = (CommandCenter)PlatformFactory.Get(EStructureType.Command, ref director, 0f, 0f, null, false, false);

            var struct2MPlatforms = new List <PlatformBlank>();
            var struct2MPlat1     = PlatformFactory.Get(EStructureType.Spawner, ref director, -200, 110);
            var struct2MPlat2     = PlatformFactory.Get(EStructureType.Spawner, ref director, 60, -260);
            var struct2MPlat3     = PlatformFactory.Get(EStructureType.Sentinel, ref director, 200, -400);
            var struct2MPlat4     = PlatformFactory.Get(EStructureType.Sentinel, ref director, y: 300);
            var struct2MPlat5     = PlatformFactory.Get(EStructureType.Sentinel, ref director, -230, -70);
            var struct2MPlat6     = PlatformFactory.Get(EStructureType.Blank, ref director, 220, 80, friendly: false);
            var struct2MPlat7     = PlatformFactory.Get(EStructureType.Blank, ref director, -300, -120, friendly: false);

            struct2MPlatforms.Add(struct2MPlat1);
            struct2MPlatforms.Add(struct2MPlat2);
            struct2MPlatforms.Add(struct2MPlat3);
            struct2MPlatforms.Add(struct2MPlat4);
            struct2MPlatforms.Add(struct2MPlat5);
            struct2MPlatforms.Add(struct2MPlat6);
            struct2MPlatforms.Add(struct2MPlat7);


            var struct2MRoads = new List <Road>
            {
                new Road(struct2MCommandCenter, struct2MPlat1, ref director),
                new Road(struct2MCommandCenter, struct2MPlat2, ref director),
                new Road(struct2MCommandCenter, struct2MPlat5, ref director),
                new Road(struct2MCommandCenter, struct2MPlat6, ref director),
                new Road(struct2MPlat1, struct2MPlat4, ref director),
                new Road(struct2MPlat5, struct2MPlat7, ref director),
                new Road(struct2MPlat2, struct2MPlat3, ref director),
                new Road(struct2MPlat4, struct2MPlat6, ref director),
                new Road(struct2MPlat6, struct2MPlat2, ref director),
                new Road(struct2MPlat7, struct2MPlat2, ref director)
            };

            var struct2M = new Triple <CommandCenter, List <PlatformBlank>, List <Road> >(struct2MCommandCenter, struct2MPlatforms, struct2MRoads);

            sAllStructures[EaiDifficulty.Medium][1] = struct2M;


            #endregion

            #region 3. Medium Structure



            #endregion

            #region 1. Hard Structure
            // 1 CC, 4 sentinal, 1 spawner : circular constellation around spawner and CC

            var struct1HCommandCenter = (CommandCenter)PlatformFactory.Get(EStructureType.Command, ref director, 0f, 0f, null, false, false);

            var struct1HPlatforms = new List <PlatformBlank>();
            var struct1HPlat1     = PlatformFactory.Get(EStructureType.Spawner, ref director, -200);
            var struct1HPlat2     = PlatformFactory.Get(EStructureType.Blank, ref director, -100, -200, friendly: false);
            var struct1HPlat3     = PlatformFactory.Get(EStructureType.Blank, ref director, -100, 200, friendly: false);
            var struct1HPlat4     = PlatformFactory.Get(EStructureType.Sentinel, ref director, -400, -100);
            var struct1HPlat5     = PlatformFactory.Get(EStructureType.Sentinel, ref director, -400, 100);
            var struct1HPlat6     = PlatformFactory.Get(EStructureType.Sentinel, ref director, 200, -100);
            var struct1HPlat7     = PlatformFactory.Get(EStructureType.Sentinel, ref director, 200, 100);

            struct1HPlatforms.Add(struct1HPlat1);
            struct1HPlatforms.Add(struct1HPlat2);
            struct1HPlatforms.Add(struct1HPlat3);
            struct1HPlatforms.Add(struct1HPlat4);
            struct1HPlatforms.Add(struct1HPlat5);
            struct1HPlatforms.Add(struct1HPlat6);
            struct1HPlatforms.Add(struct1HPlat7);

            var struct1HRoads = new List <Road>
            {
                new Road(struct1HCommandCenter, struct1HPlat1, ref director),
                new Road(struct1HCommandCenter, struct1HPlat2, ref director),
                new Road(struct1HCommandCenter, struct1HPlat3, ref director),
                new Road(struct1HCommandCenter, struct1HPlat6, ref director),
                new Road(struct1HCommandCenter, struct1HPlat7, ref director),
                new Road(struct1HPlat1, struct1HPlat2, ref director),
                new Road(struct1HPlat1, struct1HPlat3, ref director),
                new Road(struct1HPlat1, struct1HPlat4, ref director),
                new Road(struct1HPlat1, struct1HPlat5, ref director)
            };


            var struct1H = new Triple <CommandCenter, List <PlatformBlank>, List <Road> >(struct1HCommandCenter, struct1HPlatforms, struct1HRoads);

            sAllStructures[EaiDifficulty.Hard][0] = struct1H;
            #endregion

            #region 2. Hard Structure
            // 1 CC, 2 spawner, 3 sentinal : star of death

            var struct2HCommandCenter = (CommandCenter)PlatformFactory.Get(EStructureType.Command, ref director, 0f, 0f, null, false, false);

            var struct2HPlatforms = new List <PlatformBlank>();
            var struct2HPlat1     = PlatformFactory.Get(EStructureType.Spawner, ref director, -340, -120);
            var struct2HPlat2     = PlatformFactory.Get(EStructureType.Spawner, ref director, 300, 110);
            var struct2HPlat3     = PlatformFactory.Get(EStructureType.Sentinel, ref director, 200, -200);
            var struct2HPlat4     = PlatformFactory.Get(EStructureType.Sentinel, ref director, -400, 180);
            var struct2HPlat5     = PlatformFactory.Get(EStructureType.Sentinel, ref director, -100, 300);
            var struct2HPlat6     = PlatformFactory.Get(EStructureType.Blank, ref director, -200, 100, friendly: false);
            var struct2HPlat7     = PlatformFactory.Get(EStructureType.Blank, ref director, -120, 190, friendly: false);
            var struct2HPlat8     = PlatformFactory.Get(EStructureType.Blank, ref director, 60, 210, friendly: false);


            var struct2HPlat9  = PlatformFactory.Get(EStructureType.Blank, ref director, 170, 50, friendly: false);
            var struct2HPlat10 = PlatformFactory.Get(EStructureType.Blank, ref director, -60, -20, friendly: false);

            struct2HPlatforms.Add(struct2HPlat1);
            struct2HPlatforms.Add(struct2HPlat2);
            struct2HPlatforms.Add(struct2HPlat3);
            struct2HPlatforms.Add(struct2HPlat4);
            struct2HPlatforms.Add(struct2HPlat5);
            struct2HPlatforms.Add(struct2HPlat6);
            struct2HPlatforms.Add(struct2HPlat7);
            struct2HPlatforms.Add(struct2HPlat8);
            struct2HPlatforms.Add(struct2HPlat9);
            struct2HPlatforms.Add(struct2HPlat10);


            var struct2HRoads = new List <Road>
            {
                new Road(struct2HCommandCenter, struct2HPlat1, ref director),
                new Road(struct2HCommandCenter, struct2HPlat2, ref director),
                new Road(struct2HCommandCenter, struct2HPlat3, ref director),
                new Road(struct2HCommandCenter, struct2HPlat4, ref director),
                new Road(struct2HCommandCenter, struct2HPlat5, ref director),
                new Road(struct2HPlat1, struct2HPlat6, ref director),
                new Road(struct2HPlat4, struct2HPlat6, ref director),
                new Road(struct2HPlat4, struct2HPlat7, ref director),
                new Road(struct2HPlat5, struct2HPlat7, ref director),
                new Road(struct2HPlat5, struct2HPlat8, ref director),
                new Road(struct2HPlat2, struct2HPlat8, ref director),
                new Road(struct2HPlat2, struct2HPlat9, ref director),
                new Road(struct2HPlat3, struct2HPlat9, ref director),
                new Road(struct2HPlat3, struct2HPlat10, ref director),
                new Road(struct2HPlat1, struct2HPlat10, ref director)
            };



            var struct2H = new Triple <CommandCenter, List <PlatformBlank>, List <Road> >(struct2HCommandCenter, struct2HPlatforms, struct2HRoads);

            sAllStructures[EaiDifficulty.Hard][1] = struct2H;

            #endregion

            #region 3. Hard Structure
            #endregion
        }
Пример #52
0
 public override string SelectTripleValue(Triple triple)
 {
     return(triple.Predicate.GetId());
 }
Пример #53
0
        public Triple <int> cellLabel; //Cells are labelled via the scheme: (row,column, cell contents).


        public SudokuRowHeader(Triple <int> label)
        {
            cellLabel = label;
        }
Пример #54
0
        /// <summary>
        /// Internal method which generates the RDF/Json Output for a Graph
        /// </summary>
        /// <param name="g">Graph to save</param>
        /// <param name="output">Stream to save to</param>
        private void GenerateOutput(IGraph g, TextWriter output)
        {
            //Always force RDF Namespace to be correctly defined
            g.NamespaceMap.Import(this._defaultNamespaces);
            g.NamespaceMap.AddNamespace("rdf", UriFactory.Create(NamespaceMapper.RDF));

            //Create our Writer Context and start the XML Document
            RdfXmlWriterContext context = new RdfXmlWriterContext(g, output);

            context.CompressionLevel = this._compressionLevel;
            context.UseDtd           = this._useDTD;
            context.Writer.WriteStartDocument();

            if (context.UseDtd)
            {
                //Create the DOCTYPE declaration
                StringBuilder entities = new StringBuilder();
                String        uri;
                entities.Append('\n');
                foreach (String prefix in context.NamespaceMap.Prefixes)
                {
                    uri = context.NamespaceMap.GetNamespaceUri(prefix).AbsoluteUri;
                    if (!uri.Equals(context.NamespaceMap.GetNamespaceUri(prefix).ToString()))
                    {
                        context.UseDtd = false;
                        break;
                    }
                    if (!prefix.Equals(String.Empty))
                    {
                        entities.AppendLine("\t<!ENTITY " + prefix + " '" + uri + "'>");
                    }
                }
                if (context.UseDtd)
                {
                    context.Writer.WriteDocType("rdf:RDF", null, null, entities.ToString());
                }
            }

            //Create the rdf:RDF element
            context.Writer.WriteStartElement("rdf", "RDF", NamespaceMapper.RDF);
            if (context.Graph.BaseUri != null)
            {
                context.Writer.WriteAttributeString("xml", "base", null, context.Graph.BaseUri.AbsoluteUri);//Uri.EscapeUriString(context.Graph.BaseUri.ToString()));
            }
            context.NamespaceMap.IncrementNesting();
            foreach (String prefix in context.NamespaceMap.Prefixes)
            {
                if (prefix.Equals("rdf"))
                {
                    continue;
                }

                if (!prefix.Equals(String.Empty))
                {
                    context.Writer.WriteStartAttribute("xmlns", prefix, null);
                    //String nsRef = "&" + prefix + ";";
                    //context.Writer.WriteRaw(nsRef);
                    //context.Writer.WriteEntityRef(prefix);
                    context.Writer.WriteRaw(WriterHelper.EncodeForXml(context.NamespaceMap.GetNamespaceUri(prefix).AbsoluteUri));//Uri.EscapeUriString(WriterHelper.EncodeForXml(context.NamespaceMap.GetNamespaceUri(prefix).AbsoluteUri)));
                    context.Writer.WriteEndAttribute();
                }
                else
                {
                    context.Writer.WriteStartAttribute("xmlns");
                    context.Writer.WriteRaw(WriterHelper.EncodeForXml(context.NamespaceMap.GetNamespaceUri(prefix).AbsoluteUri));//Uri.EscapeUriString(WriterHelper.EncodeForXml(context.NamespaceMap.GetNamespaceUri(prefix).AbsoluteUri)));
                    context.Writer.WriteEndAttribute();
                }
            }

            //Find the Collections and Type References
            if (context.CompressionLevel >= WriterCompressionLevel.More)
            {
                WriterHelper.FindCollections(context, CollectionSearchMode.ImplicitOnly);
                //WriterHelper.FindCollections(context, CollectionSearchMode.All);
            }
            Dictionary <INode, String> typerefs = this.FindTypeReferences(context);

            //Get the Triples as a Sorted List
            List <Triple> ts = context.Graph.Triples.Where(t => !context.TriplesDone.Contains(t)).ToList();

            ts.Sort(new RdfXmlTripleComparer());

            //Variables we need to track our writing
            INode lastSubj, lastPred, lastObj;

            lastSubj = lastPred = lastObj = null;

            for (int i = 0; i < ts.Count; i++)
            {
                Triple t = ts[i];
                if (context.TriplesDone.Contains(t))
                {
                    continue;                                  //Skip if already done
                }
                if (lastSubj == null || !t.Subject.Equals(lastSubj))
                {
                    //Start a new set of Triples
                    if (lastSubj != null)
                    {
                        context.NamespaceMap.DecrementNesting();
                        context.Writer.WriteEndElement();
                    }
                    if (lastPred != null)
                    {
                        context.NamespaceMap.DecrementNesting();
                        context.Writer.WriteEndElement();
                    }

                    //Write out the Subject
                    //Validate Subject
                    //Use a Type Reference if applicable
                    context.NamespaceMap.IncrementNesting();
                    if (typerefs.ContainsKey(t.Subject))
                    {
                        String tref = typerefs[t.Subject];
                        if (tref.StartsWith(":"))
                        {
                            context.Writer.WriteStartElement(tref.Substring(1));
                        }
                        else if (tref.Contains(":"))
                        {
                            context.Writer.WriteStartElement(tref.Substring(0, tref.IndexOf(':')), tref.Substring(tref.IndexOf(':') + 1), null);
                        }
                        else
                        {
                            context.Writer.WriteStartElement(tref);
                        }
                    }
                    else
                    {
                        context.Writer.WriteStartElement("rdf", "Description", NamespaceMapper.RDF);
                    }
                    lastSubj = t.Subject;

                    //Apply appropriate attributes
                    switch (t.Subject.NodeType)
                    {
                    case NodeType.GraphLiteral:
                        throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("RDF/XML"));

                    case NodeType.Literal:
                        throw new RdfOutputException(WriterErrorMessages.LiteralSubjectsUnserializable("RDF/XML"));

                    case NodeType.Blank:
                        if (context.Collections.ContainsKey(t.Subject))
                        {
                            this.GenerateCollectionOutput(context, t.Subject);
                        }
                        else
                        {
                            context.Writer.WriteAttributeString("rdf", "nodeID", null, context.BlankNodeMapper.GetOutputID(((IBlankNode)t.Subject).InternalID));
                        }
                        break;

                    case NodeType.Uri:
                        this.GenerateUriOutput(context, (IUriNode)t.Subject, "rdf:about");
                        break;

                    default:
                        throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("RDF/XML"));
                    }

                    //Write the Predicate
                    context.NamespaceMap.IncrementNesting();
                    this.GeneratePredicateNode(context, t.Predicate);
                    lastPred = t.Predicate;
                    lastObj  = null;
                }
                else if (lastPred == null || !t.Predicate.Equals(lastPred))
                {
                    if (lastPred != null)
                    {
                        context.NamespaceMap.DecrementNesting();
                        context.Writer.WriteEndElement();
                    }

                    //Write the Predicate
                    context.NamespaceMap.IncrementNesting();
                    this.GeneratePredicateNode(context, t.Predicate);
                    lastPred = t.Predicate;
                    lastObj  = null;
                }

                //Write the Object
                if (lastObj != null)
                {
                    //Terminate the previous Predicate Node
                    context.NamespaceMap.DecrementNesting();
                    context.Writer.WriteEndElement();

                    //Start a new Predicate Node
                    context.NamespaceMap.DecrementNesting();
                    context.Writer.WriteEndElement();
                    context.NamespaceMap.IncrementNesting();
                    this.GeneratePredicateNode(context, t.Predicate);
                }
                //Create an Object for the Object
                switch (t.Object.NodeType)
                {
                case NodeType.Blank:
                    if (context.Collections.ContainsKey(t.Object))
                    {
                        //Output a Collection
                        this.GenerateCollectionOutput(context, t.Object);
                    }
                    else
                    {
                        //Terminate the Blank Node triple by adding a rdf:nodeID attribute
                        context.Writer.WriteAttributeString("rdf", "nodeID", null, context.BlankNodeMapper.GetOutputID(((IBlankNode)t.Object).InternalID));
                    }

                    break;

                case NodeType.GraphLiteral:
                    throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("RDF/XML"));

                case NodeType.Literal:
                    ILiteralNode lit = (ILiteralNode)t.Object;
                    this.GenerateLiteralOutput(context, lit);

                    break;

                case NodeType.Uri:
                    this.GenerateUriOutput(context, (IUriNode)t.Object, "rdf:resource");
                    break;

                default:
                    throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("RDF/XML"));
                }
                lastObj = t.Object;

                //Force a new Predicate Node
                context.NamespaceMap.DecrementNesting();
                context.Writer.WriteEndElement();
                lastPred = null;

                context.TriplesDone.Add(t);
            }

            //Check we haven't failed to output any collections
            foreach (KeyValuePair <INode, OutputRdfCollection> pair in context.Collections)
            {
                if (pair.Value.Triples.Count > 0)
                {
                    if (typerefs.ContainsKey(pair.Key))
                    {
                        String tref = typerefs[pair.Key];
                        context.NamespaceMap.IncrementNesting();
                        if (tref.StartsWith(":"))
                        {
                            context.Writer.WriteStartElement(tref.Substring(1));
                        }
                        else if (tref.Contains(":"))
                        {
                            context.Writer.WriteStartElement(tref.Substring(0, tref.IndexOf(':')), tref.Substring(tref.IndexOf(':') + 1), null);
                        }
                        else
                        {
                            context.Writer.WriteStartElement(tref);
                        }

                        this.GenerateCollectionOutput(context, pair.Key);

                        context.Writer.WriteEndElement();
                    }
                    else
                    {
                        context.Writer.WriteStartElement("rdf", "Description", NamespaceMapper.RDF);
                        context.Writer.WriteAttributeString("rdf", "nodeID", NamespaceMapper.RDF, context.BlankNodeMapper.GetOutputID(((IBlankNode)pair.Key).InternalID));
                        this.GenerateCollectionOutput(context, pair.Key);
                        context.Writer.WriteEndElement();
                        //throw new RdfOutputException("Failed to output a Collection due to an unknown error");
                    }
                }
            }

            context.NamespaceMap.DecrementNesting();
            context.Writer.WriteEndDocument();

            //Save to the Output Stream
            context.Writer.Close();
        }
Пример #55
0
        public bool hasStatement(org.openrdf.model.Statement s, bool b, params org.openrdf.model.Resource[] rarr)
        {
            Triple t = SesameConverter.FromSesame(s, this._mapping);

            return(HasTripleInternal(t));
        }
Пример #56
0
 protected internal override bool Add(Triple t)
 {
     return(_dataset.AddQuad(_graphUri, t));
 }
Пример #57
0
        /// <summary>
        /// Parses the page for food
        /// </summary>
        /// <param name="pageTitle"></param>
        /// <param name="pageContent"></param>
        /// <param name="graphContainer"></param>
        /// <returns></returns>
        private async Task <Food> ParseFood(string pageTitle, string pageContent, RdfGraphContainer graphContainer)
        {
            Food food = null;
            int  id;

            try
            {
                Triple tripleNourishmentBonus = graphContainer.GetGraph().Triples.Where(x => x.Nodes.Any(y => y.NodeType == NodeType.Uri && ((UriNode)y).Uri.ToString().EndsWith("Property-3AHas_nourishment_bonus"))).FirstOrDefault();
                Triple tripleId = graphContainer.GetGraph().Triples.Where(x => x.Nodes.Any(y => y.NodeType == NodeType.Uri && ((UriNode)y).Uri.ToString().EndsWith("Property-3AHas_game_id"))).FirstOrDefault();

                //Page RDF information has Nourishment Bonus and ID
                if (tripleId != null &&
                    tripleId.Object is LiteralNode &&
                    int.TryParse(((LiteralNode)tripleId.Object).Value, out id))
                {
                    if (tripleNourishmentBonus != null &&
                        tripleNourishmentBonus.Object is LiteralNode)
                    {
                        string[] nourishmentBonusLines = ((LiteralNode)tripleNourishmentBonus.Object).Value.Split("<br>", StringSplitOptions.RemoveEmptyEntries);
                        File.AppendAllLines(_allEffectsFile, nourishmentBonusLines, Encoding.UTF8);
                        food = new Food()
                        {
                            Id              = id,
                            Name            = pageTitle,
                            DurationSeconds = GetDuration(graphContainer, pageTitle),
                            IsFeast         = GetFeastStatus(graphContainer, pageTitle)
                        };

                        foreach (string line in nourishmentBonusLines)
                        {
                            FoodEffect effect = FoodEffect.GetEffect(line);
                            food.Effects.Add(effect);
                        }
                    }
                    else
                    {
                        _log.Warn($"{pageTitle}: RDF does not contain Nourishment");

                        Food feastIngredient = await ResolveFeast(pageTitle, graphContainer);

                        if (feastIngredient != null)
                        {
                            food = new Food()
                            {
                                Id              = id,
                                Name            = pageTitle,
                                Effects         = feastIngredient.Effects,
                                IsFeast         = true,
                                DurationSeconds = (int)TimeSpan.FromHours(1).TotalSeconds
                            };
                        }
                        else
                        {
                            _log.Warn($"Feast {pageTitle} could not be resolved");
                            food = null;
                        }
                    }
                }
                else
                {
                    _log.Error($"{pageTitle} does not have ID");
                    food = null;
                }
            }
            catch (InvalidFoodDurationException ex)
            {
                _log.Warn(ex);
                food = null;
            }
            catch (UnmatchedFoodEffectException ex)
            {
                _log.Warn(ex);
                File.AppendAllText(_errorFile, ex.Line + Environment.NewLine, Encoding.UTF8);
                food = null;
            }

            return(food);
        }
Пример #58
0
 public override bool FilterValidTriples(Triple triple)
 {
     return(triple.Predicate.IsReverseProperty());
 }
Пример #59
0
 /// <summary>
 /// Must be overridden by derived handlers to take appropriate Triple handling action.
 /// </summary>
 /// <param name="t">Triple.</param>
 /// <returns></returns>
 protected abstract bool HandleTripleInternal(Triple t);
Пример #60
0
        private void GenerateCollectionOutput(RdfXmlWriterContext context, INode key)
        {
            OutputRdfCollection c = context.Collections[key];

            if (!c.IsExplicit)
            {
                if (context.NamespaceMap.NestingLevel > 2)
                {
                    //Need to set the Predicate to have a rdf:parseType of Resource
                    context.Writer.WriteAttributeString("rdf", "parseType", NamespaceMapper.RDF, "Resource");
                }

                int length = c.Triples.Count;
                while (c.Triples.Count > 0)
                {
                    //Get the Next Item and generate the rdf:first element
                    INode next = c.Triples.First().Object;
                    c.Triples.RemoveAt(0);
                    context.NamespaceMap.IncrementNesting();
                    context.Writer.WriteStartElement("rdf", "first", NamespaceMapper.RDF);

                    //Set the value of the rdf:first Item
                    switch (next.NodeType)
                    {
                    case NodeType.Blank:
                        context.Writer.WriteAttributeString("rdf", "nodeID", NamespaceMapper.RDF, context.BlankNodeMapper.GetOutputID(((IBlankNode)next).InternalID));
                        break;

                    case NodeType.GraphLiteral:
                        throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("RDF/XML"));

                    case NodeType.Literal:
                        this.GenerateLiteralOutput(context, (ILiteralNode)next);
                        break;

                    case NodeType.Uri:
                        this.GenerateUriOutput(context, (IUriNode)next, "rdf:resource");
                        break;

                    default:
                        throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("RDF/XML"));
                    }

                    //Now generate the rdf:rest element
                    context.NamespaceMap.DecrementNesting();
                    context.Writer.WriteEndElement();
                    context.NamespaceMap.IncrementNesting();
                    context.Writer.WriteStartElement("rdf", "rest", NamespaceMapper.RDF);

                    if (c.Triples.Count >= 1)
                    {
                        //Set Parse Type to resource
                        context.Writer.WriteAttributeString("rdf", "parseType", NamespaceMapper.RDF, "Resource");
                    }
                    else
                    {
                        //Terminate list with an rdf:nil
                        context.Writer.WriteStartAttribute("rdf", "resource", NamespaceMapper.RDF);
                        context.Writer.WriteRaw("&rdf;nil");
                        context.Writer.WriteEndAttribute();
                    }
                }
                for (int i = 0; i < length; i++)
                {
                    context.NamespaceMap.DecrementNesting();
                    context.Writer.WriteEndElement();
                }
            }
            else
            {
                if (c.Triples.Count == 0)
                {
                    //Terminate the Blank Node triple by adding a rdf:nodeID attribute
                    context.Writer.WriteAttributeString("rdf", "nodeID", NamespaceMapper.RDF, context.BlankNodeMapper.GetOutputID(((IBlankNode)key).InternalID));
                }
                else
                {
                    //Need to set the Predicate to have a rdf:parseType of Resource
                    if (context.NamespaceMap.NestingLevel > 2)
                    {
                        //Need to set the Predicate to have a rdf:parseType of Resource
                        context.Writer.WriteAttributeString("rdf", "parseType", NamespaceMapper.RDF, "Resource");
                    }

                    //Output the Predicate Object list
                    while (c.Triples.Count > 0)
                    {
                        Triple t = c.Triples[0];
                        c.Triples.RemoveAt(0);
                        INode nextPred = t.Predicate;
                        INode nextObj  = t.Object;

                        //Generate the predicate
                        this.GeneratePredicateNode(context, nextPred);

                        //Output the Object
                        switch (nextObj.NodeType)
                        {
                        case NodeType.Blank:
                            if (context.Collections.ContainsKey(nextObj))
                            {
                                //Output a Collection
                                this.GenerateCollectionOutput(context, nextObj);
                            }
                            else
                            {
                                context.Writer.WriteAttributeString("rdf", "nodeID", NamespaceMapper.RDF, context.BlankNodeMapper.GetOutputID(((IBlankNode)key).InternalID));
                            }
                            break;

                        case NodeType.GraphLiteral:
                            throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("RDF/XML"));

                        case NodeType.Literal:
                            this.GenerateLiteralOutput(context, (ILiteralNode)nextObj);
                            break;

                        case NodeType.Uri:
                            this.GenerateUriOutput(context, (IUriNode)nextObj, "rdf:resource");
                            break;

                        default:
                            throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("RDF/XML"));
                        }

                        context.Writer.WriteEndElement();
                    }
                }
            }
        }