Пример #1
0
        public void GetShortestRoute_should_consider_routes_in_order_from_small_distance()
        {
            using (new IndirectionsContext())
            {
                // Arrange
                var slot = 0;
                var numAndDistances = new[] { 4, 2, 4, 3, 1, 6, 7 };
                PRandom.NextInt32().Body = (@this, maxValue) => numAndDistances[slot++];

                var vil = new Village();

                var considerations = new List<RicePaddy>();
                PList<RicePaddy>.AddT().Body = (@this, item) =>
                {
                    IndirectionsContext.ExecuteOriginal(() =>
                    {
                        considerations.Add(item);
                        @this.Add(item);
                    });
                };


                // Act
                var result = vil.GetShortestRoute(vil.RicePaddies.ElementAt(2), vil.RicePaddies.ElementAt(0));


                // Assert
                Assert.AreEqual(3, result.TotalDistance);
                Assert.AreEqual(4, considerations.Count);
                Assert.AreEqual(2, considerations[0].Identifier);
                Assert.AreEqual(1, considerations[1].Identifier);
                Assert.AreEqual(0, considerations[2].Identifier);
                Assert.AreEqual(3, considerations[3].Identifier);
            }
        }
Пример #2
0
        /// <summary>Main method of mention detection.</summary>
        /// <remarks>
        /// Main method of mention detection.
        /// Extract all NP, PRP or NE, and filter out by manually written patterns.
        /// </remarks>
        public override IList <IList <Mention> > FindMentions(Annotation doc, Dictionaries dict, Properties props)
        {
            IList <IList <Mention> >       predictedMentions  = new List <IList <Mention> >();
            ICollection <string>           neStrings          = Generics.NewHashSet();
            IList <ICollection <IntPair> > mentionSpanSetList = Generics.NewArrayList();
            IList <ICoreMap> sentences = doc.Get(typeof(CoreAnnotations.SentencesAnnotation));

            // extract premarked mentions, NP/PRP, named entity, enumerations
            foreach (ICoreMap s in sentences)
            {
                IList <Mention> mentions = new List <Mention>();
                predictedMentions.Add(mentions);
                ICollection <IntPair> mentionSpanSet     = Generics.NewHashSet();
                ICollection <IntPair> namedEntitySpanSet = Generics.NewHashSet();
                ExtractPremarkedEntityMentions(s, mentions, mentionSpanSet, namedEntitySpanSet);
                ExtractNamedEntityMentions(s, mentions, mentionSpanSet, namedEntitySpanSet);
                ExtractNPorPRP(s, mentions, mentionSpanSet, namedEntitySpanSet);
                ExtractEnumerations(s, mentions, mentionSpanSet, namedEntitySpanSet);
                AddNamedEntityStrings(s, neStrings, namedEntitySpanSet);
                mentionSpanSetList.Add(mentionSpanSet);
            }
            if (CorefProperties.LiberalMD(props))
            {
                ExtractNamedEntityModifiers(sentences, mentionSpanSetList, predictedMentions, neStrings);
            }
            // find head
            for (int i = 0; i < sz; i++)
            {
                FindHead(sentences[i], predictedMentions[i]);
                SetBarePlural(predictedMentions[i]);
            }
            // mention selection based on document-wise info
            if (lang == Locale.English && !CorefProperties.LiberalMD(props))
            {
                RemoveSpuriousMentionsEn(doc, predictedMentions, dict);
            }
            else
            {
                if (lang == Locale.Chinese)
                {
                    if (CorefProperties.LiberalMD(props))
                    {
                        RemoveSpuriousMentionsZhSimple(doc, predictedMentions, dict);
                    }
                    else
                    {
                        RemoveSpuriousMentionsZh(doc, predictedMentions, dict, CorefProperties.RemoveNestedMentions(props));
                    }
                }
            }
            return(predictedMentions);
        }
        /// <summary>Reads an annotation from the given filename using the requested input.</summary>
        public static IList <Annotation> GetAnnotations(StanfordCoreNLP tokenizer, SentimentPipeline.Input inputFormat, string filename, bool filterUnknown)
        {
            switch (inputFormat)
            {
            case SentimentPipeline.Input.Text:
            {
                string     text       = IOUtils.SlurpFileNoExceptions(filename);
                Annotation annotation = new Annotation(text);
                tokenizer.Annotate(annotation);
                IList <Annotation> annotations = Generics.NewArrayList();
                foreach (ICoreMap sentence in annotation.Get(typeof(CoreAnnotations.SentencesAnnotation)))
                {
                    Annotation nextAnnotation = new Annotation(sentence.Get(typeof(CoreAnnotations.TextAnnotation)));
                    nextAnnotation.Set(typeof(CoreAnnotations.SentencesAnnotation), Java.Util.Collections.SingletonList(sentence));
                    annotations.Add(nextAnnotation);
                }
                return(annotations);
            }

            case SentimentPipeline.Input.Trees:
            {
                IList <Tree> trees;
                if (filterUnknown)
                {
                    trees = SentimentUtils.ReadTreesWithGoldLabels(filename);
                    trees = SentimentUtils.FilterUnknownRoots(trees);
                }
                else
                {
                    MemoryTreebank treebank = new MemoryTreebank("utf-8");
                    treebank.LoadPath(filename, null);
                    trees = new List <Tree>(treebank);
                }
                IList <Annotation> annotations = Generics.NewArrayList();
                foreach (Tree tree in trees)
                {
                    ICoreMap sentence = new Annotation(SentenceUtils.ListToString(tree.Yield()));
                    sentence.Set(typeof(TreeCoreAnnotations.TreeAnnotation), tree);
                    IList <ICoreMap> sentences  = Java.Util.Collections.SingletonList(sentence);
                    Annotation       annotation = new Annotation(string.Empty);
                    annotation.Set(typeof(CoreAnnotations.SentencesAnnotation), sentences);
                    annotations.Add(annotation);
                }
                return(annotations);
            }

            default:
            {
                throw new ArgumentException("Unknown format " + inputFormat);
            }
            }
        }
Пример #4
0
        private static IDictionary <string, int> ArgOptionDefs()
        {
            IDictionary <string, int> argOptionDefs = Generics.NewHashMap();

            argOptionDefs["help"]      = 0;
            argOptionDefs["ftb"]       = 0;
            argOptionDefs["ancora"]    = 0;
            argOptionDefs["lowerCase"] = 0;
            argOptionDefs["encoding"]  = 1;
            argOptionDefs["options"]   = 1;
            argOptionDefs["tokens"]    = 0;
            return(argOptionDefs);
        }
Пример #5
0
        /// <summary>
        /// Rotates the given Vector around the zero point.
        /// </summary>
        /// <param name="vector">The vector to rotate.</param>
        /// <returns>The rotated vector.</returns>
        public Vector RotateVector(Vector vector)
        {
            double tolerance = Generics.GetTolerance(this, vector);

            if (Radians.IsZeroSign(tolerance))
            {
                return(vector);
            }

            Angle completeAngle = CreateFromVector(vector) + Radians;

            return(completeAngle.GetDirectionVector() * vector.Magnitude());
        }
Пример #6
0
            private static IDictionary <string, TokenizerAnnotator.TokenizerType> InitializeClassMap()
            {
                IDictionary <string, TokenizerAnnotator.TokenizerType> map = Generics.NewHashMap();

                foreach (TokenizerAnnotator.TokenizerType type in TokenizerAnnotator.TokenizerType.Values())
                {
                    if (type.className != null)
                    {
                        map[type.className.ToUpper()] = type;
                    }
                }
                return(Java.Util.Collections.UnmodifiableMap(map));
            }
Пример #7
0
        static IOBUtils()
        {
            // Training token types.
            // Label inventory
            // Patterns for tokens that should not be segmented.
            // Sets of known clitics for tagging when reconstructing the segmented sequences.
            string arabicPrefixString = "ل ف و م ما ح حا ه ها ك ب س";

            arPrefixSet = Java.Util.Collections.UnmodifiableSet(Generics.NewHashSet(Arrays.AsList(arabicPrefixString.Split("\\s+"))));
            string arabicSuffixString = "ل و ما ه ها هم هن نا كم تن تم ى ي هما ك ب ش";

            arSuffixSet = Java.Util.Collections.UnmodifiableSet(Generics.NewHashSet(Arrays.AsList(arabicSuffixString.Split("\\s+"))));
        }
Пример #8
0
        public static ICollection <string> GetUnaryMatrixNames(IList <IDictionary <string, SimpleMatrix> > maps)
        {
            ICollection <string> matrixNames = Generics.NewHashSet();

            foreach (IDictionary <string, SimpleMatrix> map in maps)
            {
                foreach (KeyValuePair <string, SimpleMatrix> entry in map)
                {
                    matrixNames.Add(entry.Key);
                }
            }
            return(matrixNames);
        }
Пример #9
0
 public void ToString(StringBuilder sb)
 {
     ReturnType.ToString(sb);
     sb.Append(" ");
     if (ExplicitInterface != null)
     {
         sb.Append(ExplicitInterface);
         sb.Append('.');
     }
     sb.Append(Name);
     Generics.ToString(sb);
     Parameters.ToString(sb);
 }
Пример #10
0
        /// <summary>Get all of the states which *only* occur at the root.</summary>
        /// <remarks>
        /// Get all of the states which *only* occur at the root.  Useful for
        /// knowing which transitions can't be done internal to the tree
        /// </remarks>
        private static ICollection <string> FindRootOnlyStates(IList <Tree> trees, ICollection <string> rootStates)
        {
            ICollection <string> rootOnlyStates = Generics.NewHashSet(rootStates);

            foreach (Tree tree in trees)
            {
                foreach (Tree child in tree.Children())
                {
                    FindRootOnlyStatesHelper(child, rootStates, rootOnlyStates);
                }
            }
            return(Java.Util.Collections.UnmodifiableSet(rootOnlyStates));
        }
        /// <summary>Returns the set of keys that have exactly the given count.</summary>
        /// <remarks>
        /// Returns the set of keys that have exactly the given count.
        /// This set may have 0 elements but will not be null.
        /// </remarks>
        public virtual ICollection <E> KeysAt(int count)
        {
            ICollection <E> keys = Generics.NewHashSet();

            foreach (E key in map.Keys)
            {
                if (GetIntCount(key) == count)
                {
                    keys.Add(key);
                }
            }
            return(keys);
        }
Пример #12
0
        private Type GetSubTypeAsModelType(ParseContext context)
        {
            Type returnType = GetReturnType(context);

            try
            {
                return(Generics.GetParameterType(returnType));
            }
            catch (ArgumentException)
            {
                return(returnType);
            }
        }
        public virtual ICollection <K2> SecondKeySet()
        {
            ICollection <K2> result = Generics.NewHashSet();

            foreach (K1 k1 in FirstKeySet())
            {
                foreach (K2 k2 in GetCounter(k1).KeySet())
                {
                    result.Add(k2);
                }
            }
            return(result);
        }
Пример #14
0
        private static IDictionary <string, int> OptionArgDefs()
        {
            IDictionary <string, int> optionArgDefs = Generics.NewHashMap();

            optionArgDefs["v"] = 0;
            optionArgDefs["l"] = 1;
            optionArgDefs["y"] = 1;
            optionArgDefs["s"] = 1;
            optionArgDefs["c"] = 0;
            optionArgDefs["e"] = 0;
            optionArgDefs["f"] = 1;
            return(optionArgDefs);
        }
Пример #15
0
 public CorefCluster(int Id)
 {
     clusterID      = Id;
     corefMentions  = Generics.NewHashSet();
     numbers        = EnumSet.NoneOf <Dictionaries.Number>();
     genders        = EnumSet.NoneOf <Dictionaries.Gender>();
     animacies      = EnumSet.NoneOf <Dictionaries.Animacy>();
     nerStrings     = Generics.NewHashSet();
     heads          = Generics.NewHashSet();
     words          = Generics.NewHashSet();
     firstMention   = null;
     representative = null;
 }
Пример #16
0
 /// <summary>Constructor.</summary>
 /// <param name="r"/>
 /// <param name="tf"/>
 /// <param name="lexerProperties"/>
 /// <param name="splitCompounds"/>
 public FrenchTokenizer(Reader r, ILexedTokenFactory <T> tf, Properties lexerProperties, bool splitCompounds, bool splitContractions)
 {
     // The underlying JFlex lexer
     // Internal fields compound splitting
     // Produces the tokenization for parsing used by Green, de Marneffe, and Manning (2011)
     lexer = new FrenchLexer(r, tf, lexerProperties);
     this.splitCompounds    = splitCompounds;
     this.splitContractions = splitContractions;
     if (splitCompounds || splitContractions)
     {
         compoundBuffer = Generics.NewLinkedList();
     }
 }
Пример #17
0
        /// <summary>Given a file name, reads in those trees and returns them as a List</summary>
        public static IList <Tree> ReadTreesWithLabels(string path, Type annotationClass)
        {
            IList <Tree>   trees    = Generics.NewArrayList();
            MemoryTreebank treebank = new MemoryTreebank("utf-8");

            treebank.LoadPath(path, null);
            foreach (Tree tree in treebank)
            {
                AttachLabels(tree, annotationClass);
                trees.Add(tree);
            }
            return(trees);
        }
        protected internal static ICollection <TransducerGraph.Arc> Difference(ICollection <TransducerGraph.Arc> block, ICollection <TransducerGraph.Arc> members)
        {
            ICollection <TransducerGraph.Arc> difference = Generics.NewHashSet();

            foreach (TransducerGraph.Arc member in block)
            {
                if (!members.Contains(member))
                {
                    difference.Add(member);
                }
            }
            return(difference);
        }
 public AbishekFrenchHeadFinder(FrenchTreebankLanguagePack tlp)
     : base(tlp)
 {
     //French POS:
     // A (adjective), ADV (adverb), C (conjunction and subordinating conjunction), CL (clitics),
     // CS (subordinating conjunction) but occurs only once!,
     // D (determiner), ET (foreign word), I (interjection), N (noun),
     // P (preposition), PREF (prefix), PRO (strong pronoun -- very confusing), V (verb), PUNC (punctuation)
     nonTerminalInfo = Generics.NewHashMap();
     // "sentence"
     nonTerminalInfo[tlp.StartSymbol()] = new string[][] { new string[] { "left", "VN", "V", "NP", "Srel", "Ssub", "Sint" } };
     nonTerminalInfo["SENT"]            = new string[][] { new string[] { "left", "VN", "V", "NP", "Srel", "Ssub", "Sint" } };
     // adjectival phrases
     nonTerminalInfo["AP"] = new string[][] { new string[] { "right", "A", "N", "V" } };
     // adverbial phrases
     nonTerminalInfo["AdP"] = new string[][] { new string[] { "right", "ADV" }, new string[] { "left", "P", "D", "C" } };
     // coordinated phrases
     nonTerminalInfo["COORD"] = new string[][] { new string[] { "left", "C" }, new string[] { "right" } };
     // noun phrases
     nonTerminalInfo["NP"] = new string[][] { new string[] { "right", "N", "PRO", "A", "ADV" }, new string[] { "left", "NP" }, new string[] { "right" } };
     // prepositional phrases
     nonTerminalInfo["PP"] = new string[][] { new string[] { "right", "P", "CL", "A", "ADV", "V", "N" } };
     // verbal nucleus
     nonTerminalInfo["VN"] = new string[][] { new string[] { "right", "V" } };
     // infinitive clauses
     nonTerminalInfo["VPinf"] = new string[][] { new string[] { "left", "VN", "V" }, new string[] { "right" } };
     // nonfinite clauses
     nonTerminalInfo["VPpart"] = new string[][] { new string[] { "left", "VN", "V" }, new string[] { "right" } };
     // relative clauses
     nonTerminalInfo["Srel"] = new string[][] { new string[] { "left", "VN", "V" } };
     // subordinate clauses
     nonTerminalInfo["Ssub"] = new string[][] { new string[] { "left", "VN", "V" }, new string[] { "right" } };
     // parenthetical clauses
     nonTerminalInfo["Sint"] = new string[][] { new string[] { "left", "VN", "V" }, new string[] { "right" } };
     // adverbes
     //nonTerminalInfo.put("ADV", new String[][] {{"left", "ADV", "PP", "P"}});
     // compound categories: start with MW: D, A, C, N, ADV, V, P, PRO, CL
     nonTerminalInfo["MWD"]   = new string[][] { new string[] { "left", "D" }, new string[] { "left" } };
     nonTerminalInfo["MWA"]   = new string[][] { new string[] { "left", "P" }, new string[] { "left", "N" }, new string[] { "right", "A" }, new string[] { "right" } };
     nonTerminalInfo["MWC"]   = new string[][] { new string[] { "left", "C", "CS" }, new string[] { "left" } };
     nonTerminalInfo["MWN"]   = new string[][] { new string[] { "right", "N", "ET" }, new string[] { "right" } };
     nonTerminalInfo["MWV"]   = new string[][] { new string[] { "left", "V" }, new string[] { "left" } };
     nonTerminalInfo["MWP"]   = new string[][] { new string[] { "left", "P", "ADV", "PRO" }, new string[] { "left" } };
     nonTerminalInfo["MWPRO"] = new string[][] { new string[] { "left", "PRO", "CL", "N", "A" }, new string[] { "left" } };
     nonTerminalInfo["MWCL"]  = new string[][] { new string[] { "left", "CL" }, new string[] { "right" } };
     nonTerminalInfo["MWADV"] = new string[][] { new string[] { "left", "P", "ADV" }, new string[] { "left" } };
     nonTerminalInfo["MWI"]   = new string[][] { new string[] { "left", "N", "ADV", "P" }, new string[] { "left" } };
     nonTerminalInfo["MWET"]  = new string[][] { new string[] { "left", "ET", "N" }, new string[] { "left" } };
     //TODO: wsg2011: For phrasal nodes that lacked a label.
     nonTerminalInfo[FrenchXMLTreeReader.MissingPhrasal] = new string[][] { new string[] { "left" } };
 }
Пример #20
0
        private void ComputeEmpiricalStatistics(IList <F> geFeatures)
        {
            //allocate memory to the containers and initialize them
            geFeature2EmpiricalDist = new double[][] {  };
            geFeature2DatumList     = new List <IList <int> >(geFeatures.Count);
            IDictionary <F, int> geFeatureMap            = Generics.NewHashMap();
            ICollection <int>    activeUnlabeledExamples = Generics.NewHashSet();

            for (int n = 0; n < geFeatures.Count; n++)
            {
                F geFeature = geFeatures[n];
                geFeature2DatumList.Add(new List <int>());
                Arrays.Fill(geFeature2EmpiricalDist[n], 0);
                geFeatureMap[geFeature] = n;
            }
            //compute the empirical label distribution for each GE feature
            for (int i = 0; i < labeledDataset.Size(); i++)
            {
                IDatum <L, F> datum   = labeledDataset.GetDatum(i);
                int           labelID = labeledDataset.labelIndex.IndexOf(datum.Label());
                foreach (F feature in datum.AsFeatures())
                {
                    if (geFeatureMap.Contains(feature))
                    {
                        int geFnum = geFeatureMap[feature];
                        geFeature2EmpiricalDist[geFnum][labelID]++;
                    }
                }
            }
            //now normalize and smooth the label distribution for each feature.
            for (int n_1 = 0; n_1 < geFeatures.Count; n_1++)
            {
                ArrayMath.Normalize(geFeature2EmpiricalDist[n_1]);
                SmoothDistribution(geFeature2EmpiricalDist[n_1]);
            }
            //now build the inverted index from each GE feature to unlabeled datums that contain it.
            for (int i_1 = 0; i_1 < unlabeledDataList.Count; i_1++)
            {
                IDatum <L, F> datum = unlabeledDataList[i_1];
                foreach (F feature in datum.AsFeatures())
                {
                    if (geFeatureMap.Contains(feature))
                    {
                        int geFnum = geFeatureMap[feature];
                        geFeature2DatumList[geFnum].Add(i_1);
                        activeUnlabeledExamples.Add(i_1);
                    }
                }
            }
            System.Console.Out.WriteLine("Number of active unlabeled examples:" + activeUnlabeledExamples.Count);
        }
 public virtual void Run(bool pathsAreFiles, bool displayWords, bool displayOOV)
 {
     if (useSplit)
     {
         IList <TreebankStats.ObservedCorpusStats> allSplitStats = new List <TreebankStats.ObservedCorpusStats>();
         makeVocab = true;
         foreach (KeyValuePair <TreebankStats.Split, ICollection <string> > split in splitFileLists)
         {
             DiskTreebank tb          = tlpp.DiskTreebank();
             IFileFilter  splitFilter = new TreebankStats.SplitFilter(split.Value);
             foreach (string path in pathNames)
             {
                 tb.LoadPath(path, splitFilter);
             }
             TreebankStats.ObservedCorpusStats splitStats = GatherStats(tb, languageName.ToString() + "." + split.Key.ToString());
             allSplitStats.Add(splitStats);
             makeVocab = false;
         }
         Display(AggregateStats(allSplitStats), displayWords, displayOOV);
         foreach (TreebankStats.ObservedCorpusStats ocs in allSplitStats)
         {
             Display(ocs, displayWords, displayOOV);
         }
     }
     else
     {
         if (pathsAreFiles)
         {
             makeVocab = true;
             foreach (string path in pathNames)
             {
                 DiskTreebank tb = tlpp.DiskTreebank();
                 tb.LoadPath(path, null);
                 TreebankStats.ObservedCorpusStats stats = GatherStats(tb, languageName.ToString() + "  " + path);
                 Display(stats, displayWords, displayOOV);
                 makeVocab = false;
             }
         }
         else
         {
             trainVocab = Generics.NewHashSet();
             DiskTreebank tb = tlpp.DiskTreebank();
             foreach (string path in pathNames)
             {
                 tb.LoadPath(path, null);
             }
             TreebankStats.ObservedCorpusStats allStats = GatherStats(tb, languageName.ToString());
             Display(allStats, displayWords, displayOOV);
         }
     }
 }
Пример #22
0
        internal bool RegisterGeneric(TypeSig t)
        {
            Debug.Assert(t != null, $"{nameof(t)} != null");

            // This is a temporary fix.
            // Type visibility should be handled in a much better way which would involved some analysis.
            var typeDef = t.ToTypeDefOrRef().ResolveTypeDef();

            if (typeDef != null && !typeDef.IsVisibleOutside())
            {
                return(false);
            }

            // Get proper type.
            t = SignatureUtils.GetLeaf(t);

            if (!Generics.ContainsKey(t))
            {
                GenericParam newGenericParam;
                if (t.IsGenericMethodParameter)
                {
                    var mVar = t.ToGenericMVar();
                    Debug.Assert(mVar != null, $"{nameof(mVar)} != null");
                    newGenericParam = new GenericParamUser(GenericCount, mVar.GenericParam.Flags, $"T{GenericCount}")
                    {
                        Rid = mVar.Rid
                    };
                }
                else if (t.IsGenericTypeParameter)
                {
                    var tVar = t.ToGenericVar();
                    Debug.Assert(tVar != null, $"{nameof(tVar)} != null");
                    newGenericParam = new GenericParamUser(GenericCount, tVar.GenericParam.Flags, $"T{GenericCount}")
                    {
                        Rid = tVar.Rid
                    };
                }
                else
                {
                    newGenericParam = new GenericParamUser(GenericCount, GenericParamAttributes.NoSpecialConstraint, $"T{GenericCount}");
                }
                Generics.Add(t, newGenericParam);
                GenericCount++;
                _trueTypes.Add(t);
                return(true);
            }
            else
            {
                return(false);
            }
        }
 protected void btnUpdateItem_Click(object sender, CommandEventArgs e)
 {
     try
     {
         byte quantity = 1;
         quantity = byte.Parse(Generics.IfNullString(((DropDownList)((LinkButton)sender).NamingContainer.FindControl("ddlQuantity")).SelectedValue));
         Mediator.doUpdateCartItemQuantity(int.Parse(Generics.IfNullString(e.CommandArgument)), quantity);
         Response.Redirect(Request.RawUrl);
     }
     catch
     {
         ;
     }
 }
 public SpanishHeadFinder(ITreebankLanguagePack tlp)
     : base(tlp)
 {
     nonTerminalInfo = Generics.NewHashMap();
     // "sentence"
     string[][] rootRules = new string[][] { new string[] { "right", "grup.verb", "s.a", "sn" }, new string[] { "left", "S" }, new string[] { "right", "sadv", "grup.adv", "neg", "interjeccio", "i", "sp", "grup.prep" }, InsertVerbs(new string[] {
             "rightdis"
         }, new string[] { "nc0s000", "nc0p000", "nc00000", "np00000", "rg", "rn" }) };
     nonTerminalInfo[tlp.StartSymbol()] = rootRules;
     nonTerminalInfo["S"]        = rootRules;
     nonTerminalInfo["sentence"] = rootRules;
     nonTerminalInfo["inc"]      = rootRules;
     // adjectival phrases
     string[][] adjectivePhraseRules = new string[][] { new string[] { "leftdis", "grup.a", "s.a", "spec" } };
     nonTerminalInfo["s.a"]    = adjectivePhraseRules;
     nonTerminalInfo["sa"]     = adjectivePhraseRules;
     nonTerminalInfo["grup.a"] = new string[][] { new string[] { "rightdis", "aq0000", "ao0000" }, InsertVerbs(new string[] { "right" }, new string[] {  }), new string[] { "right", "rg", "rn" } };
     // adverbial phrases
     nonTerminalInfo["sadv"]     = new string[][] { new string[] { "left", "grup.adv", "sadv" } };
     nonTerminalInfo["grup.adv"] = new string[][] { new string[] { "left", "conj" }, new string[] { "rightdis", "rg", "rn", "neg", "grup.adv" }, new string[] { "rightdis", "pr000000", "pi000000", "nc0s000", "nc0p000", "nc00000", "np00000" } };
     nonTerminalInfo["neg"]      = new string[][] { new string[] { "leftdis", "rg", "rn" } };
     // noun phrases
     nonTerminalInfo["sn"]       = new string[][] { new string[] { "leftdis", "nc0s000", "nc0p000", "nc00000" }, new string[] { "left", "grup.nom", "grup.w", "grup.z", "sn" }, new string[] { "leftdis", "spec" } };
     nonTerminalInfo["grup.nom"] = new string[][] { new string[] { "leftdis", "nc0s000", "nc0p000", "nc00000", "np00000", "w", "grup.w" }, new string[] { "leftdis", "pi000000", "pd000000" }, new string[] { "left", "grup.nom", "sp" }, new string[]
                                                    { "leftdis", "pn000000", "aq0000", "ao0000" }, new string[] { "left", "grup.a", "i", "grup.verb" }, new string[] { "leftdis", "grup.adv" } };
     // verb phrases
     nonTerminalInfo["grup.verb"] = new string[][] { InsertVerbs(new string[] { "left" }, new string[] {  }) };
     nonTerminalInfo["infinitiu"] = new string[][] { InsertVerbs(new string[] { "left" }, new string[] { "infinitiu" }) };
     nonTerminalInfo["gerundi"]   = new string[][] { new string[] { "left", "vmg0000", "vag0000", "vsg0000", "gerundi" } };
     nonTerminalInfo["participi"] = new string[][] { new string[] { "left", "aq", "vmp0000", "vap0000", "vsp0000", "grup.a" } };
     // specifiers
     nonTerminalInfo["spec"] = new string[][] { new string[] { "left", "conj", "spec" }, new string[] { "leftdis", "da0000", "de0000", "di0000", "dd0000", "dp0000", "dn0000", "dt0000" }, new string[] { "leftdis", "z0", "grup.z" }, new string[] {
                                                    "left", "rg", "rn"
                                                }, new string[] { "leftdis", "pt000000", "pe000000", "pd000000", "pp000000", "pi000000", "pn000000", "pr000000" }, new string[] { "left", "grup.adv", "w" } };
     // entre A y B
     // etc.
     nonTerminalInfo["conj"]        = new string[][] { new string[] { "leftdis", "cs", "cc" }, new string[] { "leftdis", "grup.cc", "grup.cs" }, new string[] { "left", "sp" } };
     nonTerminalInfo["interjeccio"] = new string[][] { new string[] { "leftdis", "i", "nc0s000", "nc0p000", "nc00000", "np00000", "pi000000" }, new string[] { "left", "interjeccio" } };
     nonTerminalInfo["relatiu"]     = new string[][] { new string[] { "left", "pr000000" } };
     // prepositional phrases
     nonTerminalInfo["sp"]   = new string[][] { new string[] { "left", "prep", "sp" } };
     nonTerminalInfo["prep"] = new string[][] { new string[] { "leftdis", "sp000", "prep", "grup.prep" } };
     // custom categories
     nonTerminalInfo["grup.cc"]   = new string[][] { new string[] { "left", "cs" } };
     nonTerminalInfo["grup.cs"]   = new string[][] { new string[] { "left", "cs" } };
     nonTerminalInfo["grup.prep"] = new string[][] { new string[] { "left", "prep", "grup.prep", "s" } };
     nonTerminalInfo["grup.pron"] = new string[][] { new string[] { "rightdis", "px000000" } };
     nonTerminalInfo["grup.w"]    = new string[][] { new string[] { "right", "w" }, new string[] { "leftdis", "z0" }, new string[] { "left" } };
     nonTerminalInfo["grup.z"]    = new string[][] { new string[] { "leftdis", "z0", "zu", "zp", "zd", "zm" }, new string[] { "right", "nc0s000", "nc0p000", "nc00000", "np00000" } };
 }
Пример #25
0
 public override void Display(bool verbose, PrintWriter pw)
 {
     base.Display(verbose, pw);
     if (doCatLevelEval)
     {
         NumberFormat         nf   = new DecimalFormat("0.00");
         ICollection <string> cats = Generics.NewHashSet();
         Random rand = new Random();
         Sharpen.Collections.AddAll(cats, precisions.KeySet());
         Sharpen.Collections.AddAll(cats, recalls.KeySet());
         IDictionary <double, string> f1Map = new SortedDictionary <double, string>();
         foreach (string cat in cats)
         {
             double pnum2 = pnums2.GetCount(cat);
             double rnum2 = rnums2.GetCount(cat);
             double prec  = precisions2.GetCount(cat) / pnum2;
             double rec   = recalls2.GetCount(cat) / rnum2;
             double f1    = 2.0 / (1.0 / prec + 1.0 / rec);
             if (f1.Equals(double.NaN))
             {
                 f1 = -1.0;
             }
             if (f1Map.Contains(f1))
             {
                 f1Map[f1 + (rand.NextDouble() / 1000.0)] = cat;
             }
             else
             {
                 f1Map[f1] = cat;
             }
         }
         pw.Println("============================================================");
         pw.Println("Tagging Performance by Category -- final statistics");
         pw.Println("============================================================");
         foreach (string cat_1 in f1Map.Values)
         {
             double pnum2 = pnums2.GetCount(cat_1);
             double rnum2 = rnums2.GetCount(cat_1);
             double prec  = precisions2.GetCount(cat_1) / pnum2;
             prec *= 100.0;
             double rec = recalls2.GetCount(cat_1) / rnum2;
             rec *= 100.0;
             double f1      = 2.0 / (1.0 / prec + 1.0 / rec);
             double oovRate = (lex == null) ? -1.0 : percentOOV.GetCount(cat_1) / percentOOV2.GetCount(cat_1);
             pw.Println(cat_1 + "\tLP: " + ((pnum2 == 0.0) ? " N/A" : nf.Format(prec)) + "\tguessed: " + (int)pnum2 + "\tLR: " + ((rnum2 == 0.0) ? " N/A" : nf.Format(rec)) + "\tgold:  " + (int)rnum2 + "\tF1: " + ((pnum2 == 0.0 || rnum2 == 0.0) ? " N/A" :
                                                                                                                                                                                                                     nf.Format(f1)) + "\tOOV: " + ((lex == null) ? " N/A" : nf.Format(oovRate)));
         }
         pw.Println("============================================================");
     }
 }
Пример #26
0
        /// <summary>
        /// Imports script results
        /// </summary>
        /// <param name="result">RScriptResults object</param>
        /// <returns>Script results</returns>
        public override object ImportResults(RScriptResult result)
        {
            IEnumerable <double> authorities = Generics.ImportDoubles(_authorityFile, false);
            IEnumerable <double> hubs        = Generics.ImportDoubles(_hubFile, false);
            IEnumerable <string> map         = Generics.ImportStrings(_mappingFile);
            HITSResult           results     = new HITSResult();

            for (int i = 0; i < map.Count(); i++)
            {
                results.Hubs.AddLink(_traceID, map.ElementAt(i), hubs.ElementAt(i));
                results.Authorities.AddLink(_traceID, map.ElementAt(i), authorities.ElementAt(i));
            }
            return(results);
        }
 public GaleP4LexMapper()
 {
     //Buckwalter patterns
     //U+0627
     //TODO Extend coverage to entire Arabic code chart
     //Obviously Buckwalter is a lossful conversion, but no assumptions should be made about
     //UTF-8 input from "the wild"
     //Patterns to fix segmentation issues observed in the ATB
     //Tags for the canChangeEncoding() method
     parentTagsToEscape = Generics.NewHashSet();
     parentTagsToEscape.Add("PUNC");
     parentTagsToEscape.Add("LATIN");
     parentTagsToEscape.Add("-NONE-");
 }
        /// <summary>
        /// Construct a new
        /// <c>CollocationFinder</c>
        /// over the
        /// <c>Tree</c>
        /// t.
        /// </summary>
        /// <param name="t">parse tree</param>
        /// <param name="w">wordnet connection</param>
        /// <param name="hf">
        ///
        /// <see cref="IHeadFinder"/>
        /// to use
        /// </param>
        public CollocationFinder(Tree t, IWordNetConnection w, IHeadFinder hf)
        {
            CoordinationTransformer transformer = new CoordinationTransformer(hf);

            this.wnConnect            = w;
            this.qTree                = transformer.TransformTree(t);
            this.collocationCollector = Generics.NewArrayList();
            this.hf = hf;
            this.GetCollocationsList();
            if (Debug)
            {
                log.Info("Collected collocations: " + collocationCollector);
            }
        }
        // static method only
        public static IList <V> GetShortestPath <V, E>(IGraph <V, E> graph, V node1, V node2, bool directionSensitive)
        {
            if (node1.Equals(node2))
            {
                return(Java.Util.Collections.SingletonList(node2));
            }
            ICollection <V>             visited        = Generics.NewHashSet();
            IDictionary <V, V>          previous       = Generics.NewHashMap();
            BinaryHeapPriorityQueue <V> unsettledNodes = new BinaryHeapPriorityQueue <V>();

            unsettledNodes.Add(node1, 0);
            while (unsettledNodes.Count > 0)
            {
                double distance = unsettledNodes.GetPriority();
                V      u        = unsettledNodes.RemoveFirst();
                visited.Add(u);
                if (u.Equals(node2))
                {
                    break;
                }
                unsettledNodes.Remove(u);
                ICollection <V> candidates = ((directionSensitive) ? graph.GetChildren(u) : graph.GetNeighbors(u));
                foreach (V candidate in candidates)
                {
                    double alt = distance - 1;
                    // nodes not already present will have a priority of -inf
                    if (alt > unsettledNodes.GetPriority(candidate) && !visited.Contains(candidate))
                    {
                        unsettledNodes.RelaxPriority(candidate, alt);
                        previous[candidate] = u;
                    }
                }
            }
            if (!previous.Contains(node2))
            {
                return(null);
            }
            List <V> path = new List <V>();

            path.Add(node2);
            V n = node2;

            while (previous.Contains(n))
            {
                path.Add(previous[n]);
                n = previous[n];
            }
            Java.Util.Collections.Reverse(path);
            return(path);
        }
        protected internal virtual void MakeInitialBlocks()
        {
            // sink block (for if the automaton isn't complete
            MakeBlock(Java.Util.Collections.Singleton(SinkNode));
            // accepting block
            ICollection <TransducerGraph.Arc> endNodes = GetUnminimizedFA().GetEndNodes();

            MakeBlock(endNodes);
            // main block
            ICollection <TransducerGraph.Arc> nonFinalNodes = Generics.NewHashSet(GetUnminimizedFA().GetNodes());

            nonFinalNodes.RemoveAll(endNodes);
            MakeBlock(nonFinalNodes);
        }
        /// <summary>Copies the Auxiliary tree.</summary>
        /// <remarks>
        /// Copies the Auxiliary tree.  Also, puts the new names-&gt;nodes map in the TsurgeonMatcher that called copy.
        /// <br />
        /// The trees and labels to use when making the copy are specified
        /// with treeFactory and labelFactory.  This lets the tsurgeon script
        /// produce trees which are of the same type as the input trees.
        /// Each of the tsurgeon relations which copies a tree should include
        /// pass in the correct factories.
        /// </remarks>
        public virtual Edu.Stanford.Nlp.Trees.Tregex.Tsurgeon.AuxiliaryTree Copy(TsurgeonMatcher matcher, ITreeFactory treeFactory, ILabelFactory labelFactory)
        {
            if (labelFactory == null)
            {
                labelFactory = CoreLabel.Factory();
            }
            IDictionary <string, Tree> newNamesToNodes = Generics.NewHashMap();
            Pair <Tree, Tree>          result          = CopyHelper(tree, newNamesToNodes, treeFactory, labelFactory);

            //if(! result.first().dominates(result.second()))
            //log.info("Error -- aux tree copy doesn't dominate foot copy.");
            matcher.newNodeNames.PutAll(newNamesToNodes);
            return(new Edu.Stanford.Nlp.Trees.Tregex.Tsurgeon.AuxiliaryTree(result.First(), result.Second(), newNamesToNodes, originalTreeString));
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        intSite = Convert.ToInt32(HttpContext.Current.Session["siteId"].ToString());
        if (HttpContext.Current.Session["contId"] != null)
        {
            intCont = Convert.ToInt32(HttpContext.Current.Session["contId"].ToString());
        }
        else
        {
            intCont = 1;
        }

        System.Text.StringBuilder sbUser = new System.Text.StringBuilder();
        if (Convert.ToInt32(Session["userType"]) == 1)
        {
            sbUser.AppendLine("<div class=\"LoginName\">");
            sbUser.AppendLine("<a href=mnt_administrator.aspx style=\"border:0px\"><img src=\"imagesCss/user-icon.gif\" style=\"border:0px\" alt=\"user\" align=\"absmiddle\" /></a> Administrator ");
            sbUser.AppendLine("</div>");
        }
        else
        {
            sbUser.AppendLine("<div class=\"LoginName\">");
            sbUser.AppendLine("<img src=\"imagesCss/user-icon.gif\"  style=\"border:0\" alt=\"user\" align=\"absmiddle\" />&nbsp;" + Convert.ToString(Session["userfullname"]) + "");
            sbUser.AppendLine("</div>");
        }
        sbUser.AppendLine("<div class=\"LoginName\" id=\"cms_documentation\"><a class=\"linkHeader\" href=\"documents/ER-CMSUserManual.doc\" target=\"_blank\"><img align=\"absmiddle\" alt=\"user\" style=\"border: 0px none;\" src=\"imagesCss/Word.gif\"> CMS Documentation</a></div>");
        admin_name.InnerHtml = sbUser.ToString();

        #region Aut ifs
        if (Convert.ToBoolean(Session["authenticated"]) != true)
        {
            Response.Redirect("CMS_Login.aspx");
        }
        if (Request["Generic"] != null)
        {
            Session["CurrentPage"] = "mnt_Generics.aspx?Generic=" + Convert.ToInt32(Request["Generic"]);

        }
        if (Request["ContentGroupId"] != null)
        {
            Session["contId"] = Convert.ToInt32(Request["ContentGroupId"]);
            Session["CurrentPage"] = "mnt_Generics.aspx?Generic=" + Convert.ToInt32(Request["Generic"]);
            Response.Redirect("mnt_Generics.aspx?Generic=" + Convert.ToInt32(Request["Generic"]));
        }
        #endregion

        #region Ifs
        if (Convert.ToBoolean(Session["TemplateChose"]) == false)
        {
            Session["GeneType"] = 0;
            if ((Request["Generic"]) != null)
            {
                if (Convert.ToInt32(Request["Generic"]) == 2)
                {
                    Session["About"] = true;
                }
                else
                {
                    Session["About"] = false;
                }
            }

            if ((Request["Generic"]) != null)
            {
                Session["GeneType"] = Convert.ToInt32(Request["Generic"]);
            }

        }
        else {
            loadDDL();
        }

        if (Convert.ToString(Session["PageTitle"]) != "")
        {
            tamplates = true;
            txt_NewPageTitle.Value = Convert.ToString(Session["PageTitle"]);
        }

        #endregion

        #region Content group
        if (Convert.ToBoolean(Session["authenticated"]) != true)
        {
            Response.Redirect("CMS_Login.aspx");
        }
        System.Text.StringBuilder sbcont = new System.Text.StringBuilder();
        //if (Session["contId"] != null)
        //{
        ContentNavigation content = new ContentNavigation();
        DataSet data = new DataSet();
        string[] Vector = new string[6 + 1];
        data = content.getAllContent(intSite);
        foreach (DataTable table in data.Tables)
        {
            foreach (DataRow row in table.Rows)
            {
                string link = "<a class=\"SelectAudience2\"  href=" + Convert.ToString(Session["CurrentPage"]) + "&ContentGroupId=" + Convert.ToInt32(row["ContId"]) + ">" + Convert.ToString(row["ContTitle"]) + "</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                Vector[Convert.ToInt32(row["ContOrdPos"])] = link;
            }

        }
        for (int i = 1; i < Vector.Length; i++)
        {
            sbcont.AppendLine(Convert.ToString(Vector[i]));
        }

        sbcont.AppendLine("<br/>");
        div_TopNavigation.InnerHtml = sbcont.ToString();
        //}
        #endregion

        #region FirstLoad
        if (((Request["Generic"]) != null) || (Convert.ToInt32(Session["GeneType"]) != 0) || (Convert.ToBoolean(Session["NewPageTemplate"]) == true))
        {

            bool fila = true;
            Generics gen = new Generics();
            //DataSet data = new DataSet();
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            if (Session["GeneType"] != null)
            {
                if (Convert.ToInt32(Session["GeneType"]) == 1)
                {
                    RCAbout = "Resource Center";
                    data = gen.Get_All_GenericByType(intSite, intCont, Convert.ToInt32(Session["GeneType"]));
                }
                else
                {
                    if (Convert.ToInt32(Session["GeneType"]) == 2)
                    {
                        RCAbout = "About Us";
                        data = gen.Get_All_GenericByType(intSite, 0, Convert.ToInt32(Session["GeneType"]));
                    }
                }

                sb.AppendLine("<TABLE  border=\"0\" cellspacing=\"0\" cellpadding=\"2\">");
                sb.AppendLine("<tr>");
                sb.AppendLine("<td width=\"9\" height=\"10\">&nbsp;</td> ");
                sb.AppendLine("<td width=\"44\">&nbsp;</td>");
                sb.AppendLine("<td width=\"150\" class=\"class_LineaVTabla\">&nbsp;</td>");
                sb.AppendLine("<td width=\"80\" align=\"center\">&nbsp;</td> ");
                sb.AppendLine("<td width=\"100\" align=\"center\">&nbsp;</td>  ");
                sb.AppendLine("<td width=\"58\">&nbsp;</td>");
                sb.AppendLine("</tr>");
                sb.AppendLine("<tr>");
                sb.AppendLine("<td>&nbsp;</td> ");
                sb.AppendLine("<td>Id</td>");
                sb.AppendLine("<td class=\"class_LineaVTabla\">Name</td> ");
                sb.AppendLine("<td align=\"center\">&nbsp;</td><td align=\"center\">&nbsp;</td> ");
                sb.AppendLine("<td>&nbsp;</td>");
                sb.AppendLine("</tr>");
                foreach (DataTable table in data.Tables)
                {
                    foreach (DataRow row in table.Rows)
                    {
                        if(fila == true)
                        {sb.AppendLine("<tr class=\"fila\"> ");}else{sb.AppendLine("<tr> ");}
                        sb.AppendLine("<td>&nbsp;</td>");
                        sb.AppendLine("<TD align=\"center\">");
                        sb.AppendLine("" + row["GeneId"].ToString() + "");
                        sb.AppendLine("</TD>");
                        sb.AppendLine("<TD align=\"left\" class=\"class_LineaVTabla\">");
                        sb.AppendLine("" + row["GeneTitle"].ToString() + "");
                        sb.AppendLine("</TD>");
                        sb.AppendLine("<td align=\"center\"><a class=\"enlace\" href= mnt_Generics.aspx?RenameId=" + row["GeneId"] + "&Type=" + Session["GeneType"] + "><img src=\"images/edit.jpg\" border=\"0\"> Rename</A></td>");
                        sb.AppendLine("<TD align=\"center\"><a href=" + row["tempmntpage"].ToString() + "?GenericId=" + row["GeneId"] + " class=\"enlace\"><img src=\"images/btn_Edit.png\" border=\"0\" /> Edit Content</a></TD>");
                        sb.AppendLine("<td align=\"center\"><a class=\"enlace\" href= mnt_Generics.aspx?DeleteId=" + row["GeneId"] + "&Type=" + Session["GeneType"] + "><img src=\"images/btn_delete.png\" border=\"0\" onclick=\"return confirm('Do you want to continue?  ');\"> Delete</A></td>");
                        sb.AppendLine(" <td align=\"left\">&nbsp;</td></tr>");
                        if (fila == true)
                        { fila = false; }
                        else { fila = true; }
                    }
                }
                if (Convert.ToBoolean(Session["About"]) == false)
                {
                    if (fila == true)
                    { sb.AppendLine("<tr class=\"fila\"> "); }
                    else { sb.AppendLine("<tr> "); }
                    sb.AppendLine("<td>&nbsp;</td>");
                    sb.AppendLine("<TD align=\"center\">");
                    sb.AppendLine("</TD>");
                    sb.AppendLine("<TD align=\"left\" class=\"class_LineaVTabla\">Free Tools</TD>");
                    sb.AppendLine("<td align=\"center\"></td>");
                    sb.AppendLine("<TD align=\"center\"><a href=\"mnt_FreeTools.aspx\" class=\"enlace\"><img src=\"images/btn_Edit.png\" border=\"0\" /> Edit Content</a></TD>");
                    sb.AppendLine("<td align=\"center\"></td>");
                    sb.AppendLine(" <td align=\"left\">&nbsp;</td></tr>");
                }
                sb.AppendLine("<tr><td>&nbsp;</td><td align=\"center\">&nbsp;</td>");
                sb.AppendLine("<td align=\"left\"class=\"class_LineaVTabla\">&nbsp;</td>");
                sb.AppendLine("<td align=\"center\">&nbsp;</td>");
                sb.AppendLine("<td align=\"center\">&nbsp;</td>");
                sb.AppendLine("<td align=\"left\">&nbsp;</td></tr>");

                sb.AppendLine("</TABLE>");
                div_Generic.InnerHtml = sb.ToString();
                btn_New.Visible = true;
            }
            else
            {
                Session["NewPageTemplate"] = true;
                div_templates.Visible = true;
            }
            if ((Request["GenericId"] != null) || (Request["ContentGroupId"] != null))
            {
                div_templates.Visible = false;
            }
            if (Convert.ToBoolean(Session["NewPageTemplate"]) == true)
            {
                div_templates.Visible = true;
            }

        }
        #endregion

        if (Request["Rename"] != null)
        {
            nameGene = Request["Rename"].ToString();
            Rename = true;
        }
    }
Пример #33
0
 public DataSet Get_LeftMenu_All_AboutUs(int SiteId)
 {
     Generics generics = new Generics();
     return generics.Get_Site_All_GenericByType(SiteId, 0, 2);//Loading  About Us only in Site Level
     generics.Dispose();
 }
Пример #34
0
 public DataSet Get_LeftMenu_All_AboutUs()
 {
     Generics generics = new Generics();
     return generics.Get_Site_All_GenericByType(SiteId, 0, 2);
        // generics.Dispose();
 }
 //Extrae tipo de menú
 public DataSet getGeneTypeId(string _gentype)
 {
     Generics generics = new Generics();
     return generics.Get_GeneDefault_By_Id(_gentype);
 }
 //Get Id Generic by Default Id
 public DataSet Get_Id_Generic(int genDefaId)
 {
     Generics generics = new Generics();
     return generics.Get_Id_Generic(SiteId, ContId, genDefaId);
 }
 protected void loadDDL()
 {
     DataSet datanew = new DataSet();
     Generics genew = new Generics();
     SelectGeneric.Items.Add(new ListItem("None", "0"));
     datanew = genew.Get_GeneDefault_By_Type(Convert.ToInt32(Session["GeneType"]));
     foreach (DataTable table in datanew.Tables)
     {
         foreach (DataRow row in table.Rows)
         {
             SelectGeneric.Items.Add(new ListItem(Convert.ToString(row["GeneDefaDescription"]), Convert.ToString(row["GeneDefaId"])));
         }
     }
 }
 //-----------------------------------------------------
 public DataSet Get_LeftMenu_All_ResourceCenter(int siteid,int contid)
 {
     Generics generics = new Generics();
     return generics.Get_Site_All_GenericByType(siteid, contid, 1);
 }
Пример #39
0
 public DataSet Get_LeftMenu_All_ResourceCenter(int SiteId, int ContId)
 {
     Generics generics = new Generics();
     return generics.Get_Site_All_GenericByType(SiteId, ContId, 1);
     generics.Dispose();
 }