proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/DynamicHunspellLanguage.java
DynamicHunspellLanguage
getRelevantRules
class DynamicHunspellLanguage extends DynamicLanguage { DynamicHunspellLanguage(String name, String code, File dictPath) { super(name, code, dictPath); } @Override public List<Rule> getRelevantRules(ResourceBundle messages, UserConfig userConfig, Language motherTongue, List<Language> altLanguages) throws IOException {<FILL_FUNCTION_BODY>} }
HunspellRule r = new HunspellRule(JLanguageTool.getMessageBundle(Languages.getLanguageForShortCode("en-US")), this, userConfig) { @Override public String getId() { return code.toUpperCase() + "_SPELLER_RULE"; } @NotNull @Override protected String getDictFilenameInResources(String langCountry) { return dictPath.getAbsolutePath().replaceAll(".dic$", ""); } @Override public String getSpellingFileName() { return null; } }; return Collections.singletonList(r);
111
165
276
<methods>public java.lang.String getCommonWordsPath() ,public java.lang.String[] getCountries() ,public org.languagetool.language.Contributor[] getMaintainers() ,public java.lang.String getName() ,public List<java.lang.String> getRuleFileNames() ,public java.lang.String getShortCode() ,public boolean isSpellcheckOnlyLanguage() <variables>private static final java.util.regex.Pattern DASH,protected final non-sealed java.lang.String code,protected final non-sealed java.io.File dictPath,protected final non-sealed java.lang.String name
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/DynamicMorfologikLanguage.java
DynamicMorfologikLanguage
getRelevantRules
class DynamicMorfologikLanguage extends DynamicLanguage { DynamicMorfologikLanguage(String name, String code, File dictPath) { super(name, code, dictPath); } @Override public List<Rule> getRelevantRules(ResourceBundle messages, UserConfig userConfig, Language motherTongue, List<Language> altLanguages) throws IOException {<FILL_FUNCTION_BODY>} }
MorfologikSpellerRule r = new MorfologikSpellerRule(JLanguageTool.getMessageBundle(Languages.getLanguageForShortCode("en-US")), this) { @Override public String getFileName() { return dictPath.getAbsolutePath(); } @Override public String getId() { return code.toUpperCase() + "_SPELLER_RULE"; } @Override public String getSpellingFileName() { return null; } }; return Collections.singletonList(r);
112
145
257
<methods>public java.lang.String getCommonWordsPath() ,public java.lang.String[] getCountries() ,public org.languagetool.language.Contributor[] getMaintainers() ,public java.lang.String getName() ,public List<java.lang.String> getRuleFileNames() ,public java.lang.String getShortCode() ,public boolean isSpellcheckOnlyLanguage() <variables>private static final java.util.regex.Pattern DASH,protected final non-sealed java.lang.String code,protected final non-sealed java.io.File dictPath,protected final non-sealed java.lang.String name
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/ExtendedSentenceRange.java
ExtendedSentenceRange
equals
class ExtendedSentenceRange implements Comparable<ExtendedSentenceRange> { @Getter private final int fromPos; @Getter private final int toPos; @Getter private final Map<String, Float> languageConfidenceRates; //languageCode;0-1 confidenceRate from LanguageDetectionService ExtendedSentenceRange(int fromPos, int toPos, String languageCode) { this(fromPos, toPos, Collections.singletonMap(languageCode, 1.0f)); } ExtendedSentenceRange(int fromPos, int toPos, @NotNull Map<String, Float> languageConfidenceRates) { this.fromPos = fromPos; this.toPos = toPos; this.languageConfidenceRates = new LinkedHashMap<>(languageConfidenceRates); } public void updateLanguageConfidenceRates(@NotNull Map<String, Float> languageConfidenceRates) { this.languageConfidenceRates.clear(); this.languageConfidenceRates.putAll(languageConfidenceRates); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { int result = fromPos; result = 31 * result + toPos; return result; } @Override public String toString() { return fromPos + "-" + toPos + ":" + languageConfidenceRates; } @Override public int compareTo(@NotNull ExtendedSentenceRange o) { return Integer.compare(this.fromPos, o.fromPos); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ExtendedSentenceRange extendedSentenceRange = (ExtendedSentenceRange) o; return fromPos == extendedSentenceRange.fromPos && toPos == extendedSentenceRange.toPos;
420
81
501
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/FragmentWithLanguage.java
FragmentWithLanguage
toString
class FragmentWithLanguage { private final String langCode; private final String fragment; FragmentWithLanguage(String langCode, String fragment) { this.langCode = Objects.requireNonNull(langCode); this.fragment = Objects.requireNonNull(fragment); } public String getLangCode() { return langCode; } public String getFragment() { return fragment; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "| " + langCode + ": " + fragment + " |";
143
22
165
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/GlobalConfig.java
GlobalConfig
equals
class GlobalConfig { private String grammalecteServer; private String grammalecteUser; private String grammalectePassword; private File beolingusFile; private String nerUrl; private static boolean verbose = false; /** * @return whether we need to track additional information like e.g. the disambiguation log to show in verbose mode */ public static boolean isVerbose() { return verbose; } public static void setVerbose(boolean verbose) { GlobalConfig.verbose = verbose; } public void setGrammalecteServer(String serverUrl) { grammalecteServer = serverUrl; } public void setGrammalecteUser(String user) { grammalecteUser = user; } public void setGrammalectePassword(String password) { grammalectePassword = password; } public void setBeolingusFile(File beolingusFile) { this.beolingusFile = beolingusFile; } /** External named entity recognizer service. */ public void setNERUrl(String nerUrl) { this.nerUrl = nerUrl; } @Nullable public String getGrammalecteServer() { return grammalecteServer; } @Nullable public String getGrammalecteUser() { return grammalecteUser; } @Nullable public String getGrammalectePassword() { return grammalectePassword; } public File getBeolingusFile() { return beolingusFile; } @Nullable public String getNerUrl() { return nerUrl; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(grammalecteServer, beolingusFile, nerUrl); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GlobalConfig that = (GlobalConfig) o; return Objects.equals(grammalecteServer, that.grammalecteServer) && Objects.equals(grammalecteUser, that.grammalecteUser) && Objects.equals(grammalectePassword, that.grammalectePassword) && Objects.equals(beolingusFile, that.beolingusFile) && Objects.equals(nerUrl, that.nerUrl);
534
149
683
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/InputSentence.java
InputSentence
equals
class InputSentence { private final String text; private final Language lang; private final Language motherTongue; private final Set<String> disabledRules; private final Set<CategoryId> disabledRuleCategories; private final Set<String> enabledRules; private final Set<CategoryId> enabledRuleCategories; private final UserConfig userConfig; private final List<Language> altLanguages; private final JLanguageTool.Mode mode; private final JLanguageTool.Level level; private final Long textSessionID; private final Set<ToneTag> toneTags; InputSentence(String text, Language lang, Language motherTongue, Set<String> disabledRules, Set<CategoryId> disabledRuleCategories, Set<String> enabledRules, Set<CategoryId> enabledRuleCategories, UserConfig userConfig, List<Language> altLanguages, JLanguageTool.Mode mode, JLanguageTool.Level level, Long textSessionID, Set<ToneTag> toneTags) { this.text = Objects.requireNonNull(text); this.lang = Objects.requireNonNull(lang); this.motherTongue = motherTongue; this.disabledRules = disabledRules; this.disabledRuleCategories = disabledRuleCategories; this.enabledRules = enabledRules; this.enabledRuleCategories = enabledRuleCategories; this.userConfig = userConfig; this.textSessionID = textSessionID; this.altLanguages = altLanguages; this.mode = Objects.requireNonNull(mode); this.level = Objects.requireNonNull(level); this.toneTags = toneTags != null ? toneTags : Collections.emptySet(); } InputSentence(String text, Language lang, Language motherTongue, Set<String> disabledRules, Set<CategoryId> disabledRuleCategories, Set<String> enabledRules, Set<CategoryId> enabledRuleCategories, UserConfig userConfig, List<Language> altLanguages, JLanguageTool.Mode mode, JLanguageTool.Level level, Set<ToneTag> toneTags) { this(text, lang, motherTongue, disabledRules, disabledRuleCategories, enabledRules, enabledRuleCategories, userConfig, altLanguages, mode, level, userConfig != null ? userConfig.getTextSessionId() : null, toneTags); } InputSentence(String text, Language lang, Language motherTongue, Set<String> disabledRules, Set<CategoryId> disabledRuleCategories, Set<String> enabledRules, Set<CategoryId> enabledRuleCategories, UserConfig userConfig, List<Language> altLanguages, JLanguageTool.Mode mode, JLanguageTool.Level level) { this(text, lang, motherTongue, disabledRules, disabledRuleCategories, enabledRules, enabledRuleCategories, userConfig, altLanguages, mode, level, userConfig != null ? userConfig.getTextSessionId() : null, null); } /** @since 4.1 */ public String getText() { return text; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(text, lang, motherTongue, disabledRules, disabledRuleCategories, enabledRules, enabledRuleCategories, userConfig, textSessionID, altLanguages, mode, level, toneTags); } @Override public String toString() { return text; } }
if (o == null) return false; if (o == this) return true; if (o.getClass() != getClass()) return false; InputSentence other = (InputSentence) o; return Objects.equals(text, other.text) && Objects.equals(lang, other.lang) && Objects.equals(motherTongue, other.motherTongue) && Objects.equals(disabledRules, other.disabledRules) && Objects.equals(disabledRuleCategories, other.disabledRuleCategories) && Objects.equals(enabledRules, other.enabledRules) && Objects.equals(enabledRuleCategories, other.enabledRuleCategories) && Objects.equals(userConfig, other.userConfig) && Objects.equals(textSessionID, other.textSessionID) && Objects.equals(altLanguages, other.altLanguages) && mode == other.mode && level == other.level && Objects.equals(toneTags, other.toneTags);
908
265
1,173
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/LanguageAnnotator.java
TokenWithLanguages
equals
class TokenWithLanguages { private final String token; private final List<Language> langs; TokenWithLanguages(String token, Language... langs) { this.token = Objects.requireNonNull(token); this.langs = new ArrayList<>(Arrays.asList(Objects.requireNonNull(langs))); } TokenWithLanguages(String token, List<Language> langs) { this.token = Objects.requireNonNull(token); this.langs = Objects.requireNonNull(langs); } boolean ambiguous() { return langs.size() != 1; } @Override public String toString() { //return token + "/" + langs.stream().map(k -> k.getShortCodeWithCountryAndVariant()).collect(Collectors.joining("/")); if (isWord(token)) { return token + "/" + langs.stream().map(k -> k.getShortCodeWithCountryAndVariant()).collect(Collectors.joining("/")); } else { return token; } } String getToken() { return token; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(token, langs); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TokenWithLanguages that = (TokenWithLanguages) o; return token.equals(that.token) && langs.equals(that.langs);
350
74
424
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/LevelToneTagCacheKey.java
LevelToneTagCacheKey
equals
class LevelToneTagCacheKey { private final JLanguageTool.Level level; private final Set<ToneTag> toneTags; public LevelToneTagCacheKey(@NotNull JLanguageTool.Level level, @NotNull Set<ToneTag> toneTags) { this.level = level; this.toneTags = new TreeSet<>(toneTags); //sorted by default } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { int result = getLevel().hashCode(); result = 31 * result + getToneTags().hashCode(); return result; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LevelToneTagCacheKey that = (LevelToneTagCacheKey) o; if (getLevel() != that.getLevel()) return false; if (!getToneTags().equals(that.getToneTags())) return false; return true;
174
101
275
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/MultiThreadedJLanguageTool.java
MultiThreadedJLanguageTool
performCheck
class MultiThreadedJLanguageTool extends JLanguageTool { private final int threadPoolSize; private final ExecutorService threadPool; public MultiThreadedJLanguageTool(Language language) { this(language, null); } /** * @see #shutdown() * @param threadPoolSize the number of concurrent threads (use 0 or negative value for a default) * @since 2.9 */ public MultiThreadedJLanguageTool(Language language, int threadPoolSize) { this(language, null, threadPoolSize, null); } /** * @see #shutdown() */ public MultiThreadedJLanguageTool(Language language, Language motherTongue) { this(language, motherTongue, getDefaultThreadCount(), null); } /** * @since 4.2 */ public MultiThreadedJLanguageTool(Language language, Language motherTongue, UserConfig userConfig) { this(language, motherTongue, getDefaultThreadCount(), userConfig); } /** * @see #shutdown() * @param threadPoolSize the number of concurrent threads * @since 4.2 */ public MultiThreadedJLanguageTool(Language language, Language motherTongue, int threadPoolSize, UserConfig userConfig) { this(language, motherTongue, threadPoolSize, null, userConfig); } /** * @see #shutdown() * @param threadPoolSize the number of concurrent threads * @since 4.2 */ public MultiThreadedJLanguageTool(Language language, Language motherTongue, int threadPoolSize, GlobalConfig globalConfig, UserConfig userConfig) { super(language, Collections.emptyList(), motherTongue, null, globalConfig, userConfig); this.threadPoolSize = threadPoolSize <= 0 ? getDefaultThreadCount() : threadPoolSize; threadPool = new ForkJoinPool(this.threadPoolSize, ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, false); } /** * Call this to shut down the internally used thread pool. * @since 3.0 */ public void shutdown() { threadPool.shutdownNow(); } /** * Call this to shut down the internally used thread pool after all running tasks are finished. * @since 3.1 */ public void shutdownWhenDone() { threadPool.shutdown(); } private static int getDefaultThreadCount() { return Runtime.getRuntime().availableProcessors(); } /** * When no thread pool size is configured, the number of available processors is returned. */ protected int getThreadPoolSize() { return threadPoolSize; } /** * @return a fixed size executor with the given number of threads */ protected ExecutorService getExecutorService() { return threadPool; } @Override protected List<AnalyzedSentence> analyzeSentences(List<String> sentences) throws IOException { if (sentences.size() < 2) { return super.analyzeSentences(sentences); } List<AnalyzedSentence> analyzedSentences = new ArrayList<>(); ExecutorService executorService = getExecutorService(); int j = 0; List<Callable<AnalyzedSentence>> callables = new ArrayList<>(); for (String sentence : sentences) { AnalyzeSentenceCallable analyzeSentenceCallable = ++j < sentences.size() ? new AnalyzeSentenceCallable(sentence) : new ParagraphEndAnalyzeSentenceCallable(sentence); callables.add(analyzeSentenceCallable); } try { List<Future<AnalyzedSentence>> futures = executorService.invokeAll(callables); for (Future<AnalyzedSentence> future : futures) { AnalyzedSentence analyzedSentence = future.get(); rememberUnknownWords(analyzedSentence); printSentenceInfo(analyzedSentence); analyzedSentences.add(analyzedSentence); } } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } return analyzedSentences; } @Override protected CheckResults performCheck(List<AnalyzedSentence> analyzedSentences, List<String> sentenceTexts, RuleSet ruleSet, ParagraphHandling paraMode, AnnotatedText annotatedText, RuleMatchListener listener, Mode mode, Level level, boolean checkRemoteRules, Set<ToneTag> toneTags) {<FILL_FUNCTION_BODY>} private class AnalyzeSentenceCallable implements Callable<AnalyzedSentence> { private final String sentence; private AnalyzeSentenceCallable(String sentence) { this.sentence = sentence; } @Override public AnalyzedSentence call() throws Exception { return getAnalyzedSentence(sentence); } } private final class ParagraphEndAnalyzeSentenceCallable extends AnalyzeSentenceCallable { private ParagraphEndAnalyzeSentenceCallable(String sentence) { super(sentence); } @Override public AnalyzedSentence call() throws Exception { return markAsParagraphEnd(super.call()); } } }
List<Rule> allRules = ruleSet.allRules(); List<SentenceData> sentences = computeSentenceData(analyzedSentences, sentenceTexts); Map<Rule, BitSet> map = new HashMap<>(); for (int i = 0; i < sentences.size(); i++) { for (Rule rule : ruleSet.rulesForSentence(sentences.get(i).analyzed)) { map.computeIfAbsent(rule, __ -> new BitSet()).set(i); } } AtomicInteger ruleIndex = new AtomicInteger(); Map<Integer, List<RuleMatch>> ruleMatches = new TreeMap<>(); List<Range> ignoreRanges = new ArrayList<>(); List<Future<?>> futures = IntStream.range(0, getThreadPoolSize()).mapToObj(__ -> getExecutorService().submit(() -> { while (true) { int index = ruleIndex.getAndIncrement(); if (index >= allRules.size()) return null; Rule rule = allRules.get(index); BitSet applicable = map.get(rule); if (applicable == null) continue; // less need for special treatment of remote rules when execution is already parallel CheckResults res = new TextCheckCallable(RuleSet.plain(Collections.singletonList(rule)), RuleSet.filterList(applicable, sentences), paraMode, annotatedText, listener, mode, level, true, toneTags).call(); if (!res.getRuleMatches().isEmpty()) { synchronized (ruleMatches) { ruleMatches.put(index, res.getRuleMatches()); } synchronized (ignoreRanges) { ignoreRanges.addAll(res.getIgnoredRanges()); } } } })).collect(Collectors.toList()); try { for (Future<?> future : futures) { future.get(); } } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } List<RuleMatch> rm = applyCustomFilters(Lists.newArrayList(Iterables.concat(ruleMatches.values())), annotatedText); return new CheckResults(rm, ignoreRanges);
1,369
569
1,938
<methods>public void <init>(org.languagetool.Language, org.languagetool.Language) ,public void <init>(org.languagetool.Language) ,public void <init>(org.languagetool.Language, org.languagetool.Language, org.languagetool.ResultCache) ,public void <init>(org.languagetool.Language, org.languagetool.ResultCache, org.languagetool.UserConfig) ,public void <init>(org.languagetool.Language, List<org.languagetool.Language>, org.languagetool.Language, org.languagetool.ResultCache, org.languagetool.GlobalConfig, org.languagetool.UserConfig) ,public void <init>(org.languagetool.Language, List<org.languagetool.Language>, org.languagetool.Language, org.languagetool.ResultCache, org.languagetool.GlobalConfig, org.languagetool.UserConfig, boolean) ,public void <init>(org.languagetool.Language, org.languagetool.Language, org.languagetool.ResultCache, org.languagetool.UserConfig) ,public void activateLanguageModelRules(java.io.File) throws java.io.IOException,public void activateRemoteRules(java.io.File) throws java.io.IOException,public void activateRemoteRules(List<org.languagetool.rules.RemoteRuleConfig>) throws java.io.IOException,public void addMatchFilter(org.languagetool.rules.RuleMatchFilter) ,public void addRule(org.languagetool.rules.Rule) ,public static void addTemporaryFile(java.io.File) ,public org.languagetool.rules.RuleMatch adjustRuleMatchPos(org.languagetool.rules.RuleMatch, int, int, int, java.lang.String, org.languagetool.markup.AnnotatedText) ,public List<org.languagetool.AnalyzedSentence> analyzeText(java.lang.String) throws java.io.IOException,public List<org.languagetool.rules.RuleMatch> check(java.lang.String) throws java.io.IOException,public List<org.languagetool.rules.RuleMatch> check(java.lang.String, org.languagetool.JLanguageTool.Level) throws java.io.IOException,public List<org.languagetool.rules.RuleMatch> check(java.lang.String, org.languagetool.RuleMatchListener) throws java.io.IOException,public List<org.languagetool.rules.RuleMatch> check(java.lang.String, boolean, org.languagetool.JLanguageTool.ParagraphHandling) throws java.io.IOException,public List<org.languagetool.rules.RuleMatch> check(java.lang.String, boolean, org.languagetool.JLanguageTool.ParagraphHandling, org.languagetool.RuleMatchListener) throws java.io.IOException,public List<org.languagetool.rules.RuleMatch> check(org.languagetool.markup.AnnotatedText) throws java.io.IOException,public List<org.languagetool.rules.RuleMatch> check(org.languagetool.markup.AnnotatedText, org.languagetool.RuleMatchListener) throws java.io.IOException,public List<org.languagetool.rules.RuleMatch> check(org.languagetool.markup.AnnotatedText, boolean, org.languagetool.JLanguageTool.ParagraphHandling) throws java.io.IOException,public List<org.languagetool.rules.RuleMatch> check(org.languagetool.markup.AnnotatedText, boolean, org.languagetool.JLanguageTool.ParagraphHandling, org.languagetool.RuleMatchListener) throws java.io.IOException,public List<org.languagetool.rules.RuleMatch> check(org.languagetool.markup.AnnotatedText, boolean, org.languagetool.JLanguageTool.ParagraphHandling, org.languagetool.RuleMatchListener, org.languagetool.JLanguageTool.Level) throws java.io.IOException,public List<org.languagetool.rules.RuleMatch> check(org.languagetool.markup.AnnotatedText, boolean, org.languagetool.JLanguageTool.ParagraphHandling, org.languagetool.RuleMatchListener, org.languagetool.JLanguageTool.Mode, org.languagetool.JLanguageTool.Level) throws java.io.IOException,public List<org.languagetool.rules.RuleMatch> check(org.languagetool.markup.AnnotatedText, boolean, org.languagetool.JLanguageTool.ParagraphHandling, org.languagetool.RuleMatchListener, org.languagetool.JLanguageTool.Mode, org.languagetool.JLanguageTool.Level, java.lang.Long) throws java.io.IOException,public org.languagetool.CheckResults check2(org.languagetool.markup.AnnotatedText, boolean, org.languagetool.JLanguageTool.ParagraphHandling, org.languagetool.RuleMatchListener, org.languagetool.JLanguageTool.Mode, org.languagetool.JLanguageTool.Level, java.lang.Long) throws java.io.IOException,public org.languagetool.CheckResults check2(org.languagetool.markup.AnnotatedText, boolean, org.languagetool.JLanguageTool.ParagraphHandling, org.languagetool.RuleMatchListener, org.languagetool.JLanguageTool.Mode, org.languagetool.JLanguageTool.Level, Set<org.languagetool.ToneTag>, java.lang.Long) throws java.io.IOException,public List<org.languagetool.rules.RuleMatch> checkAnalyzedSentence(org.languagetool.JLanguageTool.ParagraphHandling, List<org.languagetool.rules.Rule>, org.languagetool.AnalyzedSentence) throws java.io.IOException,public List<org.languagetool.rules.RuleMatch> checkAnalyzedSentence(org.languagetool.JLanguageTool.ParagraphHandling, List<org.languagetool.rules.Rule>, org.languagetool.AnalyzedSentence, boolean) throws java.io.IOException,public void disableCategory(org.languagetool.rules.CategoryId) ,public void disableRule(java.lang.String) ,public void disableRules(List<java.lang.String>) ,public void enableRule(java.lang.String) ,public void enableRuleCategory(org.languagetool.rules.CategoryId) ,public List<org.languagetool.rules.Rule> getAllActiveOfficeRules() ,public List<org.languagetool.rules.Rule> getAllActiveRules() ,public List<org.languagetool.rules.Rule> getAllRules() ,public List<org.languagetool.rules.spelling.SpellingCheckRule> getAllSpellingCheckRules() ,public org.languagetool.AnalyzedSentence getAnalyzedSentence(java.lang.String) throws java.io.IOException,public Map<org.languagetool.rules.CategoryId,org.languagetool.rules.Category> getCategories() ,public static synchronized org.languagetool.broker.ClassBroker getClassBroker() ,public static synchronized org.languagetool.broker.ResourceDataBroker getDataBroker() ,public Set<java.lang.String> getDisabledRules() ,public org.languagetool.Language getLanguage() ,public static java.util.ResourceBundle getMessageBundle() ,public static java.util.ResourceBundle getMessageBundle(org.languagetool.Language) ,public List<org.languagetool.rules.patterns.AbstractPatternRule> getPatternRulesByIdAndSubId(java.lang.String, java.lang.String) ,public org.languagetool.AnalyzedSentence getRawAnalyzedSentence(java.lang.String) throws java.io.IOException,public List<java.lang.String> getUnknownWords() ,public boolean isCategoryDisabled(org.languagetool.rules.CategoryId) ,public static boolean isCustomPasswordAuthenticatorUsed() ,public List<org.languagetool.rules.patterns.AbstractPatternRule> loadFalseFriendRules(java.lang.String) throws javax.xml.parsers.ParserConfigurationException, org.xml.sax.SAXException, java.io.IOException,public List<org.languagetool.rules.patterns.AbstractPatternRule> loadPatternRules(java.lang.String) throws java.io.IOException,public static void removeTemporaryFiles() ,public List<java.lang.String> sentenceTokenize(java.lang.String) ,public void setCheckCancelledCallback(org.languagetool.JLanguageTool.CheckCancelledCallback) ,public static synchronized void setClassBrokerBroker(org.languagetool.broker.ClassBroker) ,public void setCleanOverlappingMatches(boolean) ,public void setConfigValues(Map<java.lang.String,java.lang.Integer>) ,public static synchronized void setDataBroker(org.languagetool.broker.ResourceDataBroker) ,public void setListUnknownWords(boolean) ,public void setMaxErrorsPerWordRate(float) ,public void setOutput(java.io.PrintStream) ,public static void useCustomPasswordAuthenticator(boolean) <variables>public static final java.lang.String BUILD_DATE,public static final java.lang.String CUSTOM_PATTERN_FILE,public static final java.lang.String DICTIONARY_FILENAME_EXTENSION,public static final java.lang.String FALSE_FRIEND_FILE,public static final java.lang.String GIT_SHORT_ID,public static final java.lang.String MESSAGE_BUNDLE,public static final java.lang.String PARAGRAPH_END_TAGNAME,public static final java.lang.String PATTERN_FILE,public static final java.lang.String SENTENCE_END_TAGNAME,public static final java.lang.String SENTENCE_START_TAGNAME,public static final java.lang.String STYLE_FILE,public static final java.lang.String VERSION,private static final java.util.regex.Pattern ZERO_WIDTH_NBSP,private final non-sealed List<org.languagetool.Language> altLanguages,private final non-sealed List<org.languagetool.rules.Rule> builtinRules,private final non-sealed org.languagetool.ResultCache cache,private org.languagetool.JLanguageTool.CheckCancelledCallback checkCancelledCallback,private static org.languagetool.broker.ClassBroker classBroker,private boolean cleanOverlappingMatches,private static org.languagetool.broker.ResourceDataBroker dataBroker,private final non-sealed org.languagetool.ShortDescriptionProvider descProvider,private final Set<org.languagetool.rules.CategoryId> disabledRuleCategories,private final Set<java.lang.String> disabledRules,private final Set<org.languagetool.rules.CategoryId> enabledRuleCategories,private final Set<java.lang.String> enabledRules,private final non-sealed org.languagetool.GlobalConfig globalConfig,private final non-sealed boolean inputLogging,private final non-sealed org.languagetool.Language language,private boolean listUnknownWords,private static final Logger logger,private final List<org.languagetool.rules.RuleMatchFilter> matchFilters,private float maxErrorsPerWordRate,private final non-sealed org.languagetool.Language motherTongue,private final Set<java.lang.String> optionalLanguageModelRules,private java.io.PrintStream printStream,private final Map<org.languagetool.LevelToneTagCacheKey,org.languagetool.rules.patterns.RuleSet> ruleSetCache,private static final List<java.io.File> temporaryFiles,private Set<java.lang.String> unknownWords,private static volatile boolean useCustomPasswordAuthenticator,private final non-sealed org.languagetool.UserConfig userConfig,private final List<org.languagetool.rules.Rule> userRules
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/Premium.java
Premium
isPremiumVersion
class Premium { private static final List<String> tempNotPremiumRules = Arrays.asList(); public static boolean isTempNotPremium(Rule rule) { return tempNotPremiumRules.contains(rule.getId()); } public static boolean isPremiumStatusCheck(AnnotatedText text) { final String testRuleText = "languagetool testrule 8634756"; final String testRuleText2 = "The languagetool testrule 8634756."; return testRuleText2.equals(text.getOriginalText()) || testRuleText.equals(text.getOriginalText()); } public static Premium get() { String className = "org.languagetool.PremiumOn"; try { Class<?> aClass = JLanguageTool.getClassBroker().forName(className); Constructor<?> constructor = aClass.getConstructor(); return (Premium)constructor.newInstance(); } catch (ClassNotFoundException e) { // 'PremiumOn' doesn't exist, thus this is the non-premium version return new PremiumOff(); } catch (Exception e) { throw new RuntimeException("Object for class '" + className + "' could not be created", e); } } public static boolean isPremiumVersion() {<FILL_FUNCTION_BODY>} public abstract boolean isPremiumRule(Rule rule); /** * @deprecated Please use LtBuildInfo.PREMIUM.getBuildDate() instead. * @return premium build date */ @Deprecated public String getBuildDate() { return LtBuildInfo.PREMIUM.getBuildDate(); } /** * @deprecated Please use LtBuildInfo.PREMIUM.getShortGitId() instead. * @return short git ID */ @Deprecated public String getShortGitId() { return LtBuildInfo.PREMIUM.getShortGitId(); } /** * @deprecated Please use LtBuildInfo.PREMIUM.getVersion() instead. * @return premium version */ @Deprecated public String getVersion() { return LtBuildInfo.PREMIUM.getVersion(); } }
String className = "org.languagetool.PremiumOn"; try { Class<?> aClass = JLanguageTool.getClassBroker().forName(className); Constructor<?> constructor = aClass.getConstructor(); constructor.newInstance(); return true; } catch (ClassNotFoundException e) { // doesn't exist, thus this is the non-premium version return false; } catch (Exception e) { throw new RuntimeException("Object for class '" + className + "' could not be created", e); }
582
143
725
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/Range.java
Range
equals
class Range { private final int fromPos; private final int toPos; private final String lang; Range(int fromPos, int toPos, String lang) { this.fromPos = fromPos; this.toPos = toPos; this.lang = Objects.requireNonNull(lang); } public int getFromPos() { return fromPos; } public int getToPos() { return toPos; } public String getLang() { return lang; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(fromPos, toPos, lang); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Range range = (Range) o; return fromPos == range.fromPos && toPos == range.toPos && lang.equals(range.lang);
201
72
273
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/ResourceBundleTools.java
ResourceBundleTools
getMessageBundle
class ResourceBundleTools { private ResourceBundleTools() { } /** * Gets the ResourceBundle (i18n strings) for the default language of the user's system. */ public static ResourceBundle getMessageBundle() {<FILL_FUNCTION_BODY>} /** * Gets the ResourceBundle (i18n strings) for the given user interface language. */ public static ResourceBundle getMessageBundle(Language lang) { try { ResourceBundle bundle = JLanguageTool.getDataBroker().getResourceBundle(MESSAGE_BUNDLE, lang.getLocaleWithCountryAndVariant()); if (!isValidBundleFor(lang, bundle)) { bundle = JLanguageTool.getDataBroker().getResourceBundle(MESSAGE_BUNDLE, lang.getLocale()); if (!isValidBundleFor(lang, bundle)) { // happens if 'xx' is requested but only a MessagesBundle_xx_YY.properties exists: Language defaultVariant = lang.getDefaultLanguageVariant(); if (defaultVariant != null && defaultVariant.getCountries().length > 0) { Locale locale = new Locale(defaultVariant.getShortCode(), defaultVariant.getCountries()[0]); bundle = JLanguageTool.getDataBroker().getResourceBundle(MESSAGE_BUNDLE, locale); } } } ResourceBundle fallbackBundle = JLanguageTool.getDataBroker().getResourceBundle(MESSAGE_BUNDLE, Locale.ENGLISH); return new ResourceBundleWithFallback(bundle, fallbackBundle); } catch (MissingResourceException e) { return JLanguageTool.getDataBroker().getResourceBundle(MESSAGE_BUNDLE, Locale.ENGLISH); } } private static boolean isValidBundleFor(Language lang, ResourceBundle bundle) { return lang.getLocale().getLanguage().equals(bundle.getLocale().getLanguage()); } }
try { ResourceBundle bundle = JLanguageTool.getDataBroker().getResourceBundle(MESSAGE_BUNDLE, Locale.getDefault()); ResourceBundle fallbackBundle = JLanguageTool.getDataBroker().getResourceBundle(MESSAGE_BUNDLE, Locale.ENGLISH); return new ResourceBundleWithFallback(bundle, fallbackBundle); } catch (MissingResourceException e) { return JLanguageTool.getDataBroker().getResourceBundle(MESSAGE_BUNDLE, Locale.ENGLISH); }
492
138
630
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/ResourceBundleWithFallback.java
ResourceBundleWithFallback
handleGetObject
class ResourceBundleWithFallback extends ResourceBundle { private final ResourceBundle bundle; private final ResourceBundle fallbackBundle; public ResourceBundleWithFallback(ResourceBundle bundle, ResourceBundle fallbackBundle) { this.bundle = bundle; this.fallbackBundle = fallbackBundle; } @Override public Object handleGetObject(String key) {<FILL_FUNCTION_BODY>} @Override public Enumeration<String> getKeys() { return bundle.getKeys(); } }
String s = bundle.getString(key); if (s.trim().isEmpty()) { return fallbackBundle.getString(key); } return s;
137
44
181
<methods>public void <init>() ,public static final void clearCache() ,public static final void clearCache(java.lang.ClassLoader) ,public boolean containsKey(java.lang.String) ,public java.lang.String getBaseBundleName() ,public static final java.util.ResourceBundle getBundle(java.lang.String) ,public static final java.util.ResourceBundle getBundle(java.lang.String, java.util.ResourceBundle.Control) ,public static final java.util.ResourceBundle getBundle(java.lang.String, java.util.Locale) ,public static java.util.ResourceBundle getBundle(java.lang.String, java.lang.Module) ,public static java.util.ResourceBundle getBundle(java.lang.String, java.util.Locale, java.lang.Module) ,public static final java.util.ResourceBundle getBundle(java.lang.String, java.util.Locale, java.util.ResourceBundle.Control) ,public static java.util.ResourceBundle getBundle(java.lang.String, java.util.Locale, java.lang.ClassLoader) ,public static java.util.ResourceBundle getBundle(java.lang.String, java.util.Locale, java.lang.ClassLoader, java.util.ResourceBundle.Control) ,public abstract Enumeration<java.lang.String> getKeys() ,public java.util.Locale getLocale() ,public final java.lang.Object getObject(java.lang.String) ,public final java.lang.String getString(java.lang.String) ,public final java.lang.String[] getStringArray(java.lang.String) ,public Set<java.lang.String> keySet() <variables>static final boolean $assertionsDisabled,private static final int INITIAL_CACHE_SIZE,private static final java.util.ResourceBundle NONEXISTENT_BUNDLE,private static final boolean TRACE_ON,private static final java.lang.String UNKNOWN_FORMAT,private volatile java.util.ResourceBundle.CacheKey cacheKey,private static final ConcurrentMap<java.util.ResourceBundle.CacheKey,java.util.ResourceBundle.BundleReference> cacheList,private volatile boolean expired,private volatile Set<java.lang.String> keySet,private java.util.Locale locale,private java.lang.String name,protected java.util.ResourceBundle parent,private static final ReferenceQueue<java.lang.Object> referenceQueue
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/ResultCache.java
MatchesWeigher
weigh
class MatchesWeigher implements Weigher<InputSentence, List<RuleMatch>> { @Override public int weigh(InputSentence sentence, List<RuleMatch> matches) {<FILL_FUNCTION_BODY>} }
// this is just a rough guesstimate so that the cacheSize given by the user // is very roughly the number of average sentences the cache can keep: return sentence.getText().length() / 75 + matches.size();
60
58
118
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/SentenceRange.java
SentenceRange
getRangesFromSentences
class SentenceRange implements Comparable<SentenceRange>{ private static final Pattern BEGINS_WITH_SPACE = Pattern.compile("^\\s*"); private static final Pattern ENDS_WITH_SPACE = Pattern.compile("\\s+$"); private final int fromPos; private final int toPos; SentenceRange(int fromPos, int toPos) { this.fromPos = fromPos; this.toPos = toPos; } public static List<SentenceRange> getRangesFromSentences(AnnotatedText annotatedText, List<String> sentences) {<FILL_FUNCTION_BODY>} public int getFromPos() { return fromPos; } public int getToPos() { return toPos; } @Override public String toString() { return fromPos + "-" + toPos; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SentenceRange range = (SentenceRange) o; return fromPos == range.fromPos && toPos == range.toPos; } @Override public int hashCode() { return Objects.hash(fromPos, toPos); } @Override public int compareTo(@NotNull SentenceRange o) { return Integer.compare(this.fromPos, o.fromPos); } }
List<SentenceRange> sentenceRanges = new ArrayList<>(); int pos = 0; int markupTextLength = annotatedText.getTextWithMarkup().length(); int diff = markupTextLength - annotatedText.getPlainText().length(); for (String sentence : sentences) { if (sentence.trim().isEmpty()) { //No content no sentence pos += sentence.length(); continue; } //trim whitespaces String sentenceNoBeginWhitespace = BEGINS_WITH_SPACE.matcher(sentence).replaceFirst(""); String sentenceNoEndWhitespace = ENDS_WITH_SPACE.matcher(sentence).replaceFirst(""); //Get position without tailing and leading whitespace int fromPos = pos + (sentence.length() - sentenceNoBeginWhitespace.length()); int toPos = pos + sentenceNoEndWhitespace.length(); int fromPosOrig = fromPos + diff; int toPosOrig = toPos + diff; if (fromPosOrig != markupTextLength) { fromPosOrig = annotatedText.getOriginalTextPositionFor(fromPos, false); } if (toPosOrig != markupTextLength) { toPosOrig = annotatedText.getOriginalTextPositionFor(toPos, true); } sentenceRanges.add(new SentenceRange(fromPosOrig, toPosOrig)); pos += sentence.length(); } return sentenceRanges;
387
368
755
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/ShortDescriptionProvider.java
ShortDescriptionProvider
init
class ShortDescriptionProvider { private final static Map<Language, Map<String, String>> descriptions = new ConcurrentHashMap<>(); @Nullable public String getShortDescription(String word, Language lang) { return getAllDescriptions(lang).get(word); } @VisibleForTesting static Map<String, String> getAllDescriptions(Language lang) { return descriptions.computeIfAbsent(lang, ShortDescriptionProvider::init); } private static Map<String, String> init(Language lang) {<FILL_FUNCTION_BODY>} }
ResourceDataBroker dataBroker = JLanguageTool.getDataBroker(); String path = "/" + lang.getShortCode() + "/word_definitions.txt"; if (!dataBroker.resourceExists(path)) { return Collections.emptyMap(); } Map<String, String> wordToDef = new HashMap<>(); List<String> lines = dataBroker.getFromResourceDirAsLines(path); for (String line : lines) { if (line.startsWith("#") || line.trim().isEmpty()) { continue; } String[] parts = line.split("\t"); if (parts.length != 2) { throw new RuntimeException("Format in " + path + " not expected, expected 2 tab-separated columns: '" + line + "'"); } wordToDef.put(parts[0], parts[1]); } return wordToDef;
148
231
379
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/SimpleInputSentence.java
SimpleInputSentence
equals
class SimpleInputSentence { private final String text; private final Language lang; SimpleInputSentence(String text, Language lang) { this.text = Objects.requireNonNull(text); this.lang = Objects.requireNonNull(lang); } /** @since 4.1 */ public String getText() { return text; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(text, lang); } @Override public String toString() { return text; } }
if (o == null) return false; if (o == this) return true; if (o.getClass() != getClass()) return false; SimpleInputSentence other = (SimpleInputSentence) o; return Objects.equals(text, other.text) && Objects.equals(lang, other.lang);
176
87
263
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/bitext/TabBitextReader.java
TabReader
next
class TabReader implements Iterator<StringPair> { @Override public boolean hasNext() { return nextLine != null; } @Override public StringPair next() {<FILL_FUNCTION_BODY>} // The file is read-only. @Override public void remove() { throw new UnsupportedOperationException(); } }
try { StringPair result = nextPair; sentencePos = nextPair.getSource().length() + 1; if (nextLine != null) { prevLine = nextLine; nextLine = in.readLine(); nextPair = tab2StringPair(nextLine); lineCount++; if (nextLine == null) { in.close(); } } return result; } catch (IOException e) { throw new RuntimeException(e); }
102
130
232
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/bitext/WordFastTMReader.java
WordFastTMReader
tab2StringPair
class WordFastTMReader extends TabBitextReader { public WordFastTMReader(String filename, String encoding) throws IOException { super(filename, encoding); //skip the header (first line) if (nextLine != null) { nextLine = in.readLine(); nextPair = tab2StringPair(nextLine); } } @Nullable @Override public final StringPair tab2StringPair(String line) {<FILL_FUNCTION_BODY>} @Override public Iterator<StringPair> iterator() { return new TabReader(); } class TabReader implements Iterator<StringPair> { @Override public boolean hasNext() { return nextLine != null; } @Override public StringPair next() { try { StringPair result = nextPair; if (nextLine != null) { nextLine = in.readLine(); nextPair = tab2StringPair(nextLine); if (nextLine == null) { in.close(); } } return result; } catch (IOException e) { throw new RuntimeException(e); } } // The file is read-only. @Override public void remove() { throw new UnsupportedOperationException(); } } }
if (line == null) { return null; } String[] fields = line.split("\t"); sentencePos = fields[4].length() + 1; return new StringPair(fields[4], fields[6]);
350
61
411
<methods>public void <init>(java.lang.String, java.lang.String) ,public int getColumnCount() ,public java.lang.String getCurrentLine() ,public int getLineCount() ,public int getSentencePosition() ,public int getTargetColumnCount() ,public Iterator<org.languagetool.bitext.StringPair> iterator() <variables>protected java.io.BufferedReader in,private int lineCount,protected java.lang.String nextLine,protected org.languagetool.bitext.StringPair nextPair,private java.lang.String prevLine,protected int sentencePos
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/chunking/ChunkTag.java
ChunkTag
equals
class ChunkTag { private final String chunkTag; private final boolean isRegexp; public ChunkTag(String chunkTag) { this(chunkTag, false); } /** @since 5.1 */ public ChunkTag(String chunkTag, boolean isRegexp) { if (chunkTag == null || chunkTag.trim().isEmpty()) { throw new IllegalArgumentException("chunkTag cannot be null or empty: '" + chunkTag + "'"); } this.chunkTag = chunkTag; this.isRegexp = isRegexp; } public String getChunkTag() { return chunkTag; } /** @since 5.1 */ public boolean isRegexp() { return isRegexp; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return chunkTag.hashCode(); } @Override public String toString() { return chunkTag + (isRegexp ? "[regex]" : ""); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ChunkTag other = (ChunkTag) o; return chunkTag.equals(other.chunkTag);
292
63
355
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/chunking/TokenExpressionFactory.java
TokenExpressionFactory
create
class TokenExpressionFactory extends ExpressionFactory<ChunkTaggedToken> { private final boolean caseSensitive; /** * @param caseSensitive whether word tokens should be compared case-sensitively - also used for regular expressions */ public TokenExpressionFactory(boolean caseSensitive) { this.caseSensitive = caseSensitive; } @Override public Expression.BaseExpression<ChunkTaggedToken> create(String expr) {<FILL_FUNCTION_BODY>} }
LogicExpression<ChunkTaggedToken> logicExpression = LogicExpression.compile(expr, input -> new TokenPredicate(input, caseSensitive)); return new Expression.BaseExpression<ChunkTaggedToken>(expr) { @Override public boolean apply(ChunkTaggedToken token) { return logicExpression.apply(token); } };
131
95
226
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/chunking/TokenPredicate.java
TokenPredicate
compile
class TokenPredicate extends Expression.Arg.Pred<ChunkTaggedToken> { private final Predicate<ChunkTaggedToken> predicate; TokenPredicate(String description, boolean caseSensitive) { super(description); predicate = compile(description, caseSensitive); } private Predicate<ChunkTaggedToken> compile(String description, boolean caseSensitive) {<FILL_FUNCTION_BODY>} private static String unquote(String s) { return s.startsWith("'") && s.endsWith("'") ? s.substring(1, s.length() - 1) : s; } @Override public boolean apply(ChunkTaggedToken analyzedToken) { return predicate.test(analyzedToken); } }
String[] parts = description.split("="); String exprType; String exprValue; if (parts.length == 1) { exprType = "string"; exprValue = unquote(parts[0]); } else if (parts.length == 2) { exprType = parts[0]; exprValue = unquote(parts[1]); } else { throw new RuntimeException("Could not parse expression: " + getDescription()); } switch (exprType) { case "string": case "regex": case "regexCS": StringMatcher matcher = StringMatcher.create(exprValue, !"string".equals(exprType), caseSensitive || "regexCS".equals(exprType)); return analyzedToken -> matcher.matches(analyzedToken.getToken()); case "chunk": StringMatcher chunkPattern = StringMatcher.regexp(exprValue); return analyzedToken -> { for (ChunkTag chunkTag : analyzedToken.getChunkTags()) { if (chunkPattern.matches(chunkTag.getChunkTag())) { return true; } } return false; }; case "pos": return analyzedToken -> { AnalyzedTokenReadings readings = analyzedToken.getReadings(); if (readings != null) { for (AnalyzedToken token : readings) { if (token.getPOSTag() != null && token.getPOSTag().contains(exprValue)) { return true; } } } return false; }; case "posre": case "posregex": StringMatcher posPattern = StringMatcher.regexp(exprValue); return analyzedToken -> { AnalyzedTokenReadings readings = analyzedToken.getReadings(); if (readings != null) { for (AnalyzedToken token : readings) { if (token.getPOSTag() != null && posPattern.matches(token.getPOSTag())) { return true; } } } return false; }; default: throw new RuntimeException("Expression type not supported: '" + exprType + "'"); }
200
567
767
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/language/LanguageBuilder.java
LanguageBuilder
makeLanguage
class LanguageBuilder { private LanguageBuilder() { } public static Language makeAdditionalLanguage(File file) throws InstantiationException, IllegalAccessException { return makeLanguage(file, true); } /** * Takes an XML file named <tt>rules-xx-language.xml</tt>, * e.g. <tt>rules-de-German.xml</tt> and builds * a Language object for that language. */ private static Language makeLanguage(File file, boolean isAdditional) throws IllegalAccessException, InstantiationException {<FILL_FUNCTION_BODY>} static class ExtendedLanguage extends Language { private final Language baseLanguage; private final String name; private final File ruleFile; ExtendedLanguage(Language baseLanguage, String name, File ruleFile) { this.baseLanguage = baseLanguage; this.name = name; this.ruleFile = ruleFile; } @Override public String getName() { return name; } @Override public List<String> getRuleFileNames() { List<String> ruleFiles = new ArrayList<>(); ruleFiles.addAll(baseLanguage.getRuleFileNames()); ruleFiles.add(ruleFile.getAbsolutePath()); return ruleFiles; } @Override public boolean isExternal() { return true; } @Override public Locale getLocale() { return baseLanguage.getLocale(); } @Override public Contributor[] getMaintainers() { return baseLanguage.getMaintainers(); } @Override public String getShortCode() { return baseLanguage.getShortCode(); } @Override public String[] getCountries() { return baseLanguage.getCountries(); } @Override public List<Rule> getRelevantRules(ResourceBundle messages, UserConfig userConfig, Language motherTongue, List<Language> altLanguages) throws IOException { return baseLanguage.getRelevantRules(messages, null, motherTongue, altLanguages); } @Nullable @Override public String getVariant() { return baseLanguage.getVariant(); } @Override public List<String> getDefaultEnabledRulesForVariant() { return baseLanguage.getDefaultEnabledRulesForVariant(); } @Override public List<String> getDefaultDisabledRulesForVariant() { return baseLanguage.getDefaultDisabledRulesForVariant(); } @Nullable @Override public LanguageModel getLanguageModel(File indexDir) throws IOException { return baseLanguage.getLanguageModel(indexDir); } @Override public List<Rule> getRelevantLanguageModelRules(ResourceBundle messages, LanguageModel languageModel, UserConfig userConfig) throws IOException { return baseLanguage.getRelevantLanguageModelRules(messages, languageModel, userConfig); } @Override public Locale getLocaleWithCountryAndVariant() { return baseLanguage.getLocaleWithCountryAndVariant(); } @Nullable @Override public Language getDefaultLanguageVariant() { return baseLanguage.getDefaultLanguageVariant(); } @Override public Disambiguator createDefaultDisambiguator() { return baseLanguage.createDefaultDisambiguator(); } @NotNull @Override public Tagger createDefaultTagger() { return baseLanguage.createDefaultTagger(); } @Override public SentenceTokenizer createDefaultSentenceTokenizer() { return baseLanguage.createDefaultSentenceTokenizer(); } @Override public Tokenizer createDefaultWordTokenizer() { return baseLanguage.createDefaultWordTokenizer(); } @Nullable @Override public Chunker createDefaultChunker() { return baseLanguage.createDefaultChunker(); } @Nullable @Override public Chunker createDefaultPostDisambiguationChunker() { return baseLanguage.createDefaultPostDisambiguationChunker(); } @Nullable @Override public Synthesizer createDefaultSynthesizer() { return baseLanguage.createDefaultSynthesizer(); } } }
Objects.requireNonNull(file, "file cannot be null"); if (!file.getName().endsWith(".xml")) { throw new RuleFilenameException(file); } String[] parts = file.getName().split("-"); boolean startsWithRules = parts[0].equals("rules"); boolean secondPartHasCorrectLength = parts.length == 3 && (parts[1].length() == "en".length() || parts[1].length() == "ast".length() || parts[1].length() == "en_US".length()); if (!startsWithRules || !secondPartHasCorrectLength) { throw new RuleFilenameException(file); } //TODO: when the XML file is mergeable with // other rules (check this in the XML Rule Loader by using rules[@integrate='add']?), // subclass the existing language, //and adjust the settings if any are set in the rule file default configuration set Language newLanguage; if (Languages.isLanguageSupported(parts[1])) { Language baseLanguage = Languages.getLanguageForShortCode(parts[1]).getClass().newInstance(); newLanguage = new ExtendedLanguage(baseLanguage, parts[2].replace(".xml", ""), file); } else { newLanguage = new Language() { @Override public Locale getLocale() { return new Locale(getShortCode()); } @Override public Contributor[] getMaintainers() { return null; } @Override public String getShortCode() { if (parts[1].length() == 2) { return parts[1]; } return parts[1].split("_")[0]; //en as in en_US } @Override public String[] getCountries() { if (parts[1].length() == 2) { return new String[]{""}; } return new String[]{parts[1].split("_")[1]}; //US as in en_US } @Override public String getName() { return parts[2].replace(".xml", ""); } @Override public List<Rule> getRelevantRules(ResourceBundle messages, UserConfig userConfig, Language motherTongue, List<Language> altLanguages) { return Collections.emptyList(); } @Override public List<String> getRuleFileNames() { List<String> ruleFiles = new ArrayList<>(); ruleFiles.add(file.getAbsolutePath()); return ruleFiles; } @Override public boolean isExternal() { return isAdditional; } }; } return newLanguage;
1,103
684
1,787
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/language/identifier/detector/CommonWordsDetector.java
CommonWordsDetector
getKnownWordsPerLanguage
class CommonWordsDetector { private final static Map<String, List<Language>> word2langs = Collections.synchronizedMap(new HashMap<>()); private final static Pattern numberPattern = Pattern.compile("[0-9.,%-]+"); private final static Language esLang = Languages.getLanguageForShortCode("es"); private final static Language caLang = Languages.getLanguageForShortCode("ca"); private final static Language ptLang = Languages.getLanguageForShortCode("pt"); // but -cion can be Esperanto; ía(n) can be Galician private final static Pattern spanishPattern = Pattern.compile("^[a-zñ]+(ón|cion|aban|ábamos|ábais|íamos|íais|[úí]a[sn]?|úe[ns]?)$"); private final static Pattern notSpanishPattern = Pattern.compile("^[lmndts]['’].*$|^.*(ns|[áéó].i[oa]s?)$|^.*(ss|[çàèòïâêôãõìù]|l·l).*$"); private final static Pattern notCatalanPattern = Pattern.compile("^.*([áéó].i[oa]s?|d[oa]s)$|^.*[áâêôãõìùñ].*$"); private final static Pattern portuguesePattern = Pattern.compile("^.*([áó]ri[oa]|ério)s?$"); // éria can be French private static final Pattern PUNCT_PATTERN = Pattern.compile("[(),.:;!?„“\"¡¿\\s\\[\\]{}-«»”]"); private static final Pattern CHARS_PATTERN = Pattern.compile("\\p{L}+$"); private static final Pattern SPACE_OR_HYPHEN_PATTERN = Pattern.compile("[ -]"); public CommonWordsDetector() throws IOException { synchronized (word2langs) { if (word2langs.isEmpty()) { for (Language lang : Languages.get()) { if (lang.isVariant() && !lang.getShortCode().equals("no")) { // ugly hack to quick fix https://github.com/languagetooler-gmbh/languagetool-premium/issues/822 continue; } ResourceDataBroker dataBroker = JLanguageTool.getDataBroker(); String path = lang.getCommonWordsPath(); InputStream stream = null; try { if (path != null) { if (dataBroker.resourceExists(path)) { stream = dataBroker.getFromResourceDirAsStream(path); } else if (new File(path).exists()) { stream = new FileInputStream(path); } else { throw new IOException("Common words file not found for " + lang + ": " + path); } } else { if (!lang.getShortCode().matches("ja|km")) { System.out.println("WARN: no common words file defined for " + lang + " - this language might not be correctly auto-detected"); } continue; } try (Scanner scanner = new Scanner(stream, "utf-8")) { while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.isEmpty() || line.startsWith("#")) { continue; } String key = line.toLowerCase(); if (key.length() == 1 && Character.isSpaceChar(key.charAt(0))) { continue; } List<Language> languages = word2langs.get(key); if (languages == null) { // word2langs is static, so this can be accessed from multiple threads concurrently -> prevent exceptions List<Language> l = Collections.synchronizedList(new LinkedList<>()); l.add(lang); word2langs.put(key, l); } else { if (!languages.contains(lang)) { languages.add(lang); } } } } } finally { if (stream != null) { stream.close(); } } } } } } public Map<Language, Integer> getKnownWordsPerLanguage(String text) {<FILL_FUNCTION_BODY>} }
Map<Language,Integer> result = new HashMap<>(); String auxText = PUNCT_PATTERN.matcher(text).replaceAll(" "); if (!auxText.endsWith(" ") && StringUtils.countMatches(auxText, " ") > 0) { // last word might not be finished yet, so ignore auxText = CHARS_PATTERN.matcher(auxText).replaceFirst(""); } // Proper per-language tokenizing might help, but then the common_words.txt // will also need to be tokenized the same way. Also, this is quite fast. String[] words = SPACE_OR_HYPHEN_PATTERN.split(auxText); for (String word : words) { if (numberPattern.matcher(word).matches()) { continue; } String lcWord = word.toLowerCase(); List<Language> languages = word2langs.get(lcWord); if (languages != null) { for (Language lang : languages) { //System.out.println(lcWord + " -> " + lang); result.put(lang, result.getOrDefault(lang, 0) + 1); } } //Portuguese if ((languages == null || !languages.contains(ptLang)) && portuguesePattern.matcher(lcWord).matches()) { result.put(ptLang, result.getOrDefault(ptLang, 0) + 1); } //Spanish if ((languages == null || !languages.contains(esLang)) && spanishPattern.matcher(lcWord).matches()) { result.put(esLang, result.getOrDefault(esLang, 0) + 1); } if ((languages == null || !languages.contains(esLang)) && notSpanishPattern.matcher(lcWord).matches()) { result.put(esLang, result.getOrDefault(esLang, 0) - 1); } //Catalan if ((languages == null || !languages.contains(caLang)) && notCatalanPattern.matcher(lcWord).matches()) { result.put(caLang, result.getOrDefault(caLang, 0) - 1); } } //System.out.println("==> " + result); return result;
1,133
604
1,737
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/language/identifier/detector/FastTextDetector.java
FastTextException
parseBuffer
class FastTextException extends RuntimeException { private final boolean disabled; public FastTextException(String message, boolean disabled) { super(message); this.disabled = disabled; } /** * Should {@link FastTextDetector} be disable after this exception */ public boolean isDisabled() { return disabled; } } public FastTextDetector(File modelPath, File binaryPath) throws IOException { this.modelPath = modelPath; this.binaryPath = binaryPath; init(); } private void init() throws IOException{ fasttextProcess = new ProcessBuilder(binaryPath.getPath(), "predict-prob", modelPath.getPath(), "-", "" + K_HIGHEST_SCORES).start(); // avoid buffering, we want to flush/read all data immediately // might cause mixup fasttextIn = new InputStreamReader(fasttextProcess.getInputStream(), StandardCharsets.UTF_8); fasttextOut = new OutputStreamWriter(fasttextProcess.getOutputStream(), StandardCharsets.UTF_8); } // for tests only FastTextDetector() { fasttextProcess = null; fasttextIn = null; fasttextOut = null; } public Map<String, Double> runFasttext(String text, List<String> additionalLanguageCodes) throws IOException { String joined = text.replace('\n', ' ').toLowerCase(Locale.ROOT); char[] cbuf = new char[BUFFER_SIZE]; synchronized (this) { fasttextOut.write(joined + System.lineSeparator()); fasttextOut.flush(); long read = fasttextIn.read(cbuf); if (read <= 0) { // hack to see if this helps us debug the rare case of readLine() returning null: try { logger.warn("fasttextIn.read() returned no data, trying again after short delay"); Thread.sleep(10); read = fasttextIn.read(cbuf); if (read == -1) { logger.warn("fasttextIn.read() returned no data again"); } } catch (InterruptedException e) { throw new RuntimeException(e); } } if (fasttextIn.ready()) { logger.warn("More input to read from Fasttext, this should not happen; language detection results might be mixed up"); } } return parseBuffer(new String(cbuf), additionalLanguageCodes); } @NotNull Map<String, Double> parseBuffer(String buffer, List<String> additionalLanguageCodes) {<FILL_FUNCTION_BODY>
String[] values = WHITESPACE.split(buffer.trim()); if (!buffer.startsWith("__label__")) { throw new FastTextException("FastText output is expected to start with '__label__': ''" + buffer + "'", true); } if (values.length % 2 != 0) { throw new FastTextException("Error while parsing fasttext output, expected pairs of '__label_xx' and float: '" + buffer + "'", true); } if (buffer.trim().contains("\n")) { logger.warn("Got multiple lines to read from Fasttext, this should not happen: '" + buffer + "'" ); } Map<String, Double> probabilities = new HashMap<>(); for (int i = 0; i < values.length; i += 2) { String lang = values[i]; String langCode = lang.substring(lang.lastIndexOf("__") + 2); String prob = values[i + 1]; Double probValue = Double.parseDouble(prob); if (LanguageIdentifierService.INSTANCE.canLanguageBeDetected(langCode, additionalLanguageCodes)) { probabilities.put(langCode, probValue); } } return probabilities;
667
306
973
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/language/identifier/detector/UnicodeBasedDetector.java
UnicodeBasedDetector
getDominantLangCodes
class UnicodeBasedDetector { private static final int DEFAULT_MAX_CHECK_LENGTH = 50; private static final float THRESHOLD = 0.5f; private final int maxCheckLength; public UnicodeBasedDetector() { this(DEFAULT_MAX_CHECK_LENGTH); } public UnicodeBasedDetector(int maxCheckLength) { this.maxCheckLength = maxCheckLength; } public List<String> getDominantLangCodes(String str) {<FILL_FUNCTION_BODY>} }
// For a more complete list of script/language relations, // see https://unicode-org.github.io/cldr-staging/charts/37/supplemental/scripts_and_languages.html // Another more complete approach might be to use Character.UnicodeScript.of() for each character. int arabicChars = 0; int cyrillicChars = 0; int cjkChars = 0; int khmerChars = 0; int tamilChars = 0; int greekChars = 0; int devanagariChars = 0; int thaiChars = 0; int hebrewChars = 0; int hangulChars = 0; int significantChars = 0; for (int i = 0; i < Math.min(str.length(), maxCheckLength); i++) { int val = str.charAt(i); if (!Character.isWhitespace(val) && !Character.isDigit(val) && val != '.') { significantChars++; } if (val >= 0x0600 && val <= 0x06FF) { arabicChars++; } if (val >= 0x0400 && val <= 0x04FF) { cyrillicChars++; } if (val >= 0x4E00 && val <= 0x9FFF || val >= 0x3040 && val <= 0x309F || val >= 0x30A0 && val <= 0x30FF) { // https://de.wikipedia.org/wiki/Japanische_Schrift // there might be a better way to tell Chinese from Japanese, but we rely // on the actual language identifier in a later step, so finding candidates is enough here cjkChars++; } if (val >= 0x1780 && val <= 0x17FF) { khmerChars++; } if (val >= 0xB82 && val <= 0xBFA) { tamilChars++; } if (val >= 0x0370 && val <= 0x03FF || val >= 0x1F00 && val <= 0x1FFF) { greekChars++; } if (val >= 0x0900 && val <= 0x097F) { devanagariChars++; } if (val >= 0x0E00 && val <= 0x0E7F) { thaiChars++; } if (val >= 0x0590 && val <= 0x05FF || val >= 0xFB1D && val <= 0xFB40) { hebrewChars++; } if (val >= 0xAC00 && val <= 0xD7AF || // https://en.wikipedia.org/wiki/Hangul val >= 0x1100 && val <= 0x11FF || val >= 0x3130 && val <= 0x318F || val >= 0xA960 && val <= 0xA97F || val >= 0xD7B0 && val <= 0xD7FF) { hangulChars++; } } List<String> langCodes = new ArrayList<>(); if ((float) arabicChars / significantChars >= THRESHOLD) { langCodes.add("ar"); langCodes.add("fa"); } if ((float) cyrillicChars / significantChars >= THRESHOLD) { langCodes.add("ru"); langCodes.add("uk"); langCodes.add("be"); } if ((float) cjkChars / significantChars >= THRESHOLD) { langCodes.add("zh"); langCodes.add("ja"); // Korean: see hangulChars } if ((float) khmerChars / significantChars >= THRESHOLD) { langCodes.add("km"); } if ((float) tamilChars / significantChars >= THRESHOLD) { langCodes.add("ta"); } if ((float) greekChars / significantChars >= THRESHOLD) { langCodes.add("el"); } if ((float) devanagariChars / significantChars >= THRESHOLD) { langCodes.add("hi"); langCodes.add("mr"); } if ((float) thaiChars / significantChars >= THRESHOLD) { langCodes.add("th"); } if ((float) hebrewChars / significantChars >= THRESHOLD) { langCodes.add("he"); } if ((float) hangulChars / significantChars >= THRESHOLD) { langCodes.add("ko"); } //System.out.println("CJK: " + cjkChars); //System.out.println("Hangul: " + hangulChars); // // NOTE: if you add languages here that LT doesn't support, also update LanguageIdentifier.detectLanguage() // so it makes use of the fact that we have safely detected a language by its character set // (we can then directly assume it's not supported) // return langCodes;
145
1,377
1,522
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/languagemodel/LuceneLanguageModel.java
LuceneLanguageModel
validateDirectory
class LuceneLanguageModel extends BaseLanguageModel { private final List<LuceneSingleIndexLanguageModel> lms = new ArrayList<>(); public static void validateDirectory(File topIndexDir) {<FILL_FUNCTION_BODY>} @Nullable private static File[] getSubDirectoriesOrNull(File topIndexDir) { return topIndexDir.listFiles((file, name) -> name.matches("index-\\d+")); } /** * @param topIndexDir a directory which contains either: * 1) sub directories called {@code 1grams}, {@code 2grams}, {@code 3grams}, * which are Lucene indexes with ngram occurrences as created by * {@code org.languagetool.dev.FrequencyIndexCreator} * or 2) sub directories {@code index-1}, {@code index-2} etc that contain * the sub directories described under 1) */ public LuceneLanguageModel(File topIndexDir) { File[] subDirs = getSubDirectoriesOrNull(topIndexDir); if (subDirs != null && subDirs.length > 0) { System.out.println("Running in multi-index mode with " + subDirs.length + " indexes: " + topIndexDir); for (File subDir : subDirs) { lms.add(new LuceneSingleIndexLanguageModel(subDir)); } } else { lms.add(new LuceneSingleIndexLanguageModel(topIndexDir)); } } @Override public long getCount(List<String> tokens) { return lms.stream().mapToLong(lm -> lm.getCount(tokens)).sum(); } @Override public long getCount(String token) { return getCount(Arrays.asList(token)); } @Override public long getTotalTokenCount() { return lms.stream().mapToLong(lm -> lm.getTotalTokenCount()).sum(); } @Override public void close() { lms.forEach(lm -> lm.close()); } @Override public String toString() { return lms.toString(); } }
File[] subDirs = getSubDirectoriesOrNull(topIndexDir); if (subDirs == null || subDirs.length == 0) { LuceneSingleIndexLanguageModel.validateDirectory(topIndexDir); }
572
60
632
<methods>public void <init>() ,public abstract long getCount(java.lang.String) ,public abstract long getCount(List<java.lang.String>) ,public org.languagetool.rules.ngrams.Probability getPseudoProbability(List<java.lang.String>) ,public org.languagetool.rules.ngrams.Probability getPseudoProbabilityStupidBackoff(List<java.lang.String>) ,public abstract long getTotalTokenCount() <variables>private static final boolean DEBUG,private java.lang.Long totalTokenCount
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/languagemodel/MultiLanguageModel.java
MultiLanguageModel
getPseudoProbability
class MultiLanguageModel implements LanguageModel { private final List<LanguageModel> lms; public MultiLanguageModel(List<LanguageModel> lms) { if (lms.isEmpty()) { throw new IllegalArgumentException("List of language models is empty"); } this.lms = lms; } @Override public Probability getPseudoProbability(List<String> context) {<FILL_FUNCTION_BODY>} @Override public void close() { lms.stream().forEach(LanguageModel::close); } @Override public String toString() { return lms.toString(); } }
double prob = 0; float coverage = 0; long occurrences = 0; for (LanguageModel lm : lms) { Probability pProb = lm.getPseudoProbability(context); //System.out.println(i + ". " + pProb.getProb() + " (" + pProb.getCoverage() + ")"); // TODO: decide what's the proper way to combine the probabilities prob += pProb.getProb(); coverage += pProb.getCoverage(); occurrences += pProb.getOccurrences(); } return new Probability(prob, coverage/lms.size(), occurrences);
170
169
339
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/languagemodel/bert/RemoteLanguageModel.java
Request
getChannel
class Request { public String text; public int start; public int end; public List<String> candidates; public Request(String text, int start, int end, List<String> candidates) { this.text = text; this.start = start; this.end = end; this.candidates = candidates; } public ScoreRequest convert() { List<Mask> masks = Arrays.asList(Mask.newBuilder() .setStart(start) .setEnd(end) .addAllCandidates(candidates) .build()); return ScoreRequest.newBuilder().setText(text).addAllMask(masks).build(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Request request = (Request) o; return start == request.start && end == request.end && text.equals(request.text) && candidates.equals(request.candidates); } @Override public int hashCode() { return Objects.hash(text, start, end, candidates); } } public RemoteLanguageModel(String host, int port, boolean useSSL, @Nullable String clientPrivateKey, @Nullable String clientCertificate, @Nullable String rootCertificate) throws SSLException { // TODO configure deadline/retries/... here? channel = getChannel(host, port, useSSL, clientPrivateKey, clientCertificate, rootCertificate); model = BertLmGrpc.newBlockingStub(channel); } private ManagedChannel getChannel(String host, int port, boolean useSSL, @Nullable String clientPrivateKey, @Nullable String clientCertificate, @Nullable String rootCertificate) throws SSLException {<FILL_FUNCTION_BODY>
NettyChannelBuilder channelBuilder = NettyChannelBuilder.forAddress(host, port); if (useSSL) { SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient(); if (rootCertificate != null) { sslContextBuilder.trustManager(new File(rootCertificate)); } if (clientCertificate != null && clientPrivateKey != null) { sslContextBuilder.keyManager(new File(clientCertificate), new File(clientPrivateKey)); } channelBuilder = channelBuilder.negotiationType(NegotiationType.TLS).sslContext(sslContextBuilder.build()); } else { channelBuilder = channelBuilder.usePlaintext(); } return channelBuilder.build();
486
190
676
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/languagemodel/bert/grpc/BertLmGrpc.java
MethodHandlers
invoke
class MethodHandlers<Req, Resp> implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>, io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> { private final BertLmImplBase serviceImpl; private final int methodId; MethodHandlers(BertLmImplBase serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {<FILL_FUNCTION_BODY>} @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver<Req> invoke( io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { default: throw new AssertionError(); } } }
switch (methodId) { case METHODID_SCORE: serviceImpl.score((org.languagetool.languagemodel.bert.grpc.BertLmProto.ScoreRequest) request, (io.grpc.stub.StreamObserver<org.languagetool.languagemodel.bert.grpc.BertLmProto.BertLmResponse>) responseObserver); break; case METHODID_BATCH_SCORE: serviceImpl.batchScore((org.languagetool.languagemodel.bert.grpc.BertLmProto.BatchScoreRequest) request, (io.grpc.stub.StreamObserver<org.languagetool.languagemodel.bert.grpc.BertLmProto.BatchBertLmResponse>) responseObserver); break; default: throw new AssertionError(); }
340
234
574
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/markup/AnnotatedText.java
AnnotatedText
getOriginalTextPositionFor
class AnnotatedText { /** * @since 3.9 */ public enum MetaDataKey { DocumentTitle, EmailToAddress, FullName, EmailNumberOfAttachments } private final List<TextPart> parts; private final Map<Integer, MappingValue> mapping; // plain text position to original text (with markup) position private final Map<MetaDataKey, String> metaData; private final Map<String, String> customMetaData; AnnotatedText(List<TextPart> parts, Map<Integer, MappingValue> mapping, Map<MetaDataKey, String> metaData, Map<String, String> customMetaData) { this.parts = Objects.requireNonNull(parts); this.mapping = Objects.requireNonNull(mapping); this.metaData = Objects.requireNonNull(metaData); this.customMetaData = Objects.requireNonNull(customMetaData); } /** * @since 5.4 */ public List<TextPart> getParts() { return parts; } /** * Get the plain text, without markup and content from {@code interpretAs}. * @since 4.3 */ public String getOriginalText() { StringBuilder sb = new StringBuilder(); for (TextPart part : parts) { if (part.getType() == TextPart.Type.TEXT) { sb.append(part.getPart()); } } return sb.toString(); } /** * Get the plain text, without markup but with content from {@code interpretAs}. */ public String getPlainText() { StringBuilder sb = new StringBuilder(); for (TextPart part : parts) { if (part.getType() == TextPart.Type.TEXT || part.getType() == TextPart.Type.FAKE_CONTENT) { sb.append(part.getPart()); } } return sb.toString(); } /** * @since 4.3 */ public String getTextWithMarkup() { StringBuilder sb = new StringBuilder(); for (TextPart part : parts) { if (part.getType() != TextPart.Type.FAKE_CONTENT) { sb.append(part.getPart()); } } return sb.toString(); } /** * Internally used by LanguageTool to adjust error positions to point to the * original location with markup, even though markup was ignored during text checking. * @param plainTextPosition the position in the plain text (no markup) that was checked * @param isToPos the from/to position needed * @return an adjusted position of the same location in the text with markup */ public int getOriginalTextPositionFor(int plainTextPosition, boolean isToPos) {<FILL_FUNCTION_BODY>} /** * @since 3.9 */ public String getGlobalMetaData(String key, String defaultValue) { return customMetaData.getOrDefault(key, defaultValue); } /** * @since 3.9 */ public String getGlobalMetaData(MetaDataKey key, String defaultValue) { return metaData.getOrDefault(key, defaultValue); } /** @since 5.4 */ public Map<MetaDataKey, String> getGlobalMetaData() { return metaData; } /** @since 5.4 */ public Map<String, String> getCustomMetaData() { return customMetaData; } @Override public String toString() { return StringUtils.join(parts, ""); } }
if (plainTextPosition < 0) { throw new IllegalArgumentException("plainTextPosition must be >= 0: " + plainTextPosition); } if (mapping.isEmpty()) { return 0; } int minDiff = Integer.MAX_VALUE; MappingValue bestMatch = null; // algorithm: find the closest lower position for (Map.Entry<Integer, MappingValue> entry : mapping.entrySet()) { int maybeClosePosition = entry.getKey(); if (plainTextPosition < maybeClosePosition) { int diff = maybeClosePosition - plainTextPosition; if (diff > 0 && diff < minDiff) { bestMatch = entry.getValue(); minDiff = diff; } } } if (bestMatch == null) { String msg = "mappings: " + (mapping.size() < 5 ? mapping : mapping.size()); throw new RuntimeException("Could not map " + plainTextPosition + " to original position. isToPos: " + isToPos + ", " + msg); } // we remove markup total length if usage of fake markup and need from position if (!isToPos && bestMatch.getFakeMarkupLength() > 0) { minDiff = bestMatch.getFakeMarkupLength(); } // We assume that when we have found the closest match there's a one-to-one mapping // in this region, thus we can subtract 'minDiff' to get the exact position. // If the bestMatch is a fakeMarkup, subtract it: return bestMatch.getTotalPosition() - minDiff;
949
396
1,345
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/markup/AnnotatedTextBuilder.java
AnnotatedTextBuilder
addText
class AnnotatedTextBuilder { private final static String hiddenChars = "\u00AD\u202D\u202c"; private final List<TextPart> parts = new ArrayList<>(); private final Map<AnnotatedText.MetaDataKey, String> metaData = new HashMap<>(); private final Map<String, String> customMetaData = new HashMap<>(); public AnnotatedTextBuilder() { } /** * Add global meta data like document title or receiver name (when writing an email). * Some rules may use this information. * @since 3.9 */ public AnnotatedTextBuilder addGlobalMetaData(AnnotatedText.MetaDataKey key, String value) { metaData.put(key, value); return this; } /** * Add any global meta data about the document to be checked. Some rules may use this information. * Unless you're using your own rules for which you know useful keys, you probably want to * use {@link #addGlobalMetaData(AnnotatedText.MetaDataKey, String)}. * @since 3.9 */ public AnnotatedTextBuilder addGlobalMetaData(String key, String value) { customMetaData.put(key, value); return this; } /** * Add a plain text snippet, to be checked by LanguageTool when using * {@link org.languagetool.JLanguageTool#check(AnnotatedText)}. */ public AnnotatedTextBuilder addText(String text) {<FILL_FUNCTION_BODY>} /** * Add a markup text snippet like {@code <b attr='something'>} or {@code <div>}. These * parts will be ignored by LanguageTool when using {@link org.languagetool.JLanguageTool#check(AnnotatedText)}. */ public AnnotatedTextBuilder addMarkup(String markup) { parts.add(new TextPart(markup, TextPart.Type.MARKUP)); return this; } /** * Add a markup text snippet like {@code <b attr='something'>} or {@code <div>}. These * parts will be ignored by LanguageTool when using {@link org.languagetool.JLanguageTool#check(AnnotatedText)}. * @param interpretAs A string that will be used by the checker instead of the markup. This is usually * whitespace, e.g. {@code \n\n} for {@code <p>} */ public AnnotatedTextBuilder addMarkup(String markup, String interpretAs) { parts.add(new TextPart(markup, TextPart.Type.MARKUP)); parts.add(new TextPart(interpretAs, TextPart.Type.FAKE_CONTENT)); return this; } /** @since 5.4 */ public void add(TextPart part) { parts.add(part); } /** * Create the annotated text to be passed into {@link org.languagetool.JLanguageTool#check(AnnotatedText)}. */ public AnnotatedText build() { int plainTextPosition = 0; int totalPosition = 0; Map<Integer, MappingValue> mapping = new HashMap<>(); for (int i = 0; i < parts.size(); i++) { TextPart part = parts.get(i); if (part.getType() == TextPart.Type.TEXT) { plainTextPosition += part.getPart().length(); totalPosition += part.getPart().length(); MappingValue mappingValue = new MappingValue(totalPosition); mapping.put(plainTextPosition, mappingValue); } else if (part.getType() == TextPart.Type.MARKUP) { totalPosition += part.getPart().length(); if (hasFakeContent(i, parts)) { plainTextPosition += parts.get(i + 1).getPart().length(); i++; if (mapping.get(plainTextPosition) == null) { MappingValue mappingValue = new MappingValue(totalPosition, part.getPart().length()); mapping.put(plainTextPosition, mappingValue); } } } } return new AnnotatedText(parts, mapping, metaData, customMetaData); } private boolean hasFakeContent(int i, List<TextPart> parts) { int nextPartIndex = i + 1; if (nextPartIndex < parts.size()) { if (parts.get(nextPartIndex).getType().equals(TextPart.Type.FAKE_CONTENT)) { return true; } } return false; } }
StringTokenizer st = new StringTokenizer(text, hiddenChars, true); while (st.hasMoreElements()) { String token = (String) st.nextElement(); if (!hiddenChars.contains(token)) { parts.add(new TextPart(token, TextPart.Type.TEXT)); } else { parts.add(new TextPart(token, TextPart.Type.MARKUP)); } } return this;
1,192
116
1,308
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/noop/NoopLanguage.java
NoopLanguage
createDefaultSentenceTokenizer
class NoopLanguage extends Language { public static final String SHORT_CODE = "zz"; @Override public Locale getLocale() { return new Locale("en"); } @Override public Disambiguator createDefaultDisambiguator() { return new NoopDisambiguator(); } @Override public String getName() { return "NoopLanguage"; } @Override public String getShortCode() { return SHORT_CODE; } @Override public String[] getCountries() { return new String[] {}; } @NotNull @Override public Tagger createDefaultTagger() { return new DemoTagger(); } @Nullable @Override public Chunker createDefaultChunker() { return new NoopChunker(); } @Override public Contributor[] getMaintainers() { return null; } @Override public List<Rule> getRelevantRules(ResourceBundle messages, UserConfig userConfig, Language motherTongue, List<Language> altLanguages) { return Collections.emptyList(); } @Override protected synchronized List<AbstractPatternRule> getPatternRules() { return Collections.emptyList(); } public SentenceTokenizer createDefaultSentenceTokenizer() {<FILL_FUNCTION_BODY>} @Override public Tokenizer createDefaultWordTokenizer() { // result needs to be modifiable (see JLanguageTool.replaceSoftHyphens()) return text -> new ArrayList<>(); } }
return new SentenceTokenizer() { @Override public List<String> tokenize(String text) { return Collections.singletonList(text); } @Override public void setSingleLineBreaksMarksParagraph(boolean lineBreakParagraphs) {} @Override public boolean singleLineBreaksMarksPara() { return false; } };
424
100
524
<methods>public java.lang.String adaptSuggestion(java.lang.String) ,public List<org.languagetool.rules.RuleMatch> adaptSuggestions(List<org.languagetool.rules.RuleMatch>, Set<java.lang.String>) ,public org.languagetool.rules.RuleMatch adjustMatch(org.languagetool.rules.RuleMatch, List<java.lang.String>) ,public org.languagetool.chunking.Chunker createDefaultChunker() ,public org.languagetool.tagging.disambiguation.Disambiguator createDefaultDisambiguator() ,public org.languagetool.JLanguageTool createDefaultJLanguageTool() ,public org.languagetool.chunking.Chunker createDefaultPostDisambiguationChunker() ,public org.languagetool.tokenizers.SentenceTokenizer createDefaultSentenceTokenizer() ,public org.languagetool.synthesis.Synthesizer createDefaultSynthesizer() ,public org.languagetool.tagging.Tagger createDefaultTagger() ,public org.languagetool.tokenizers.Tokenizer createDefaultWordTokenizer() ,public boolean equals(java.lang.Object) ,public boolean equalsConsiderVariantsIfSpecified(org.languagetool.Language) ,public synchronized org.languagetool.chunking.Chunker getChunker() ,public java.lang.String getClosingDoubleQuote() ,public java.lang.String getClosingSingleQuote() ,public java.lang.String getCommonWordsPath() ,public java.lang.String getConsistencyRulePrefix() ,public abstract java.lang.String[] getCountries() ,public List<java.lang.String> getDefaultDisabledRulesForVariant() ,public List<java.lang.String> getDefaultEnabledRulesForVariant() ,public org.languagetool.Language getDefaultLanguageVariant() ,public org.languagetool.rules.spelling.SpellingCheckRule getDefaultSpellingRule() ,public org.languagetool.rules.spelling.SpellingCheckRule getDefaultSpellingRule(java.util.ResourceBundle) ,public org.languagetool.rules.patterns.Unifier getDisambiguationUnifier() ,public org.languagetool.rules.patterns.UnifierConfiguration getDisambiguationUnifierConfiguration() ,public synchronized org.languagetool.tagging.disambiguation.Disambiguator getDisambiguator() ,public java.util.regex.Pattern getIgnoredCharactersRegex() ,public org.languagetool.languagemodel.LanguageModel getLanguageModel(java.io.File) throws java.io.IOException,public java.util.Locale getLocale() ,public java.util.Locale getLocaleWithCountryAndVariant() ,public org.languagetool.LanguageMaintainedState getMaintainedState() ,public abstract org.languagetool.language.Contributor[] getMaintainers() ,public org.languagetool.rules.spelling.multitoken.MultitokenSpeller getMultitokenSpeller() ,public abstract java.lang.String getName() ,public java.lang.String getOpeningDoubleQuote() ,public java.lang.String getOpeningSingleQuote() ,public synchronized org.languagetool.chunking.Chunker getPostDisambiguationChunker() ,public Map<java.lang.String,java.lang.Integer> getPriorityMap() ,public List<org.languagetool.rules.Rule> getRelevantLanguageModelCapableRules(java.util.ResourceBundle, org.languagetool.languagemodel.LanguageModel, org.languagetool.GlobalConfig, org.languagetool.UserConfig, org.languagetool.Language, List<org.languagetool.Language>) throws java.io.IOException,public List<org.languagetool.rules.Rule> getRelevantLanguageModelRules(java.util.ResourceBundle, org.languagetool.languagemodel.LanguageModel, org.languagetool.UserConfig) throws java.io.IOException,public List<org.languagetool.rules.Rule> getRelevantRemoteRules(java.util.ResourceBundle, List<org.languagetool.rules.RemoteRuleConfig>, org.languagetool.GlobalConfig, org.languagetool.UserConfig, org.languagetool.Language, List<org.languagetool.Language>, boolean) throws java.io.IOException,public abstract List<org.languagetool.rules.Rule> getRelevantRules(java.util.ResourceBundle, org.languagetool.UserConfig, org.languagetool.Language, List<org.languagetool.Language>) throws java.io.IOException,public List<org.languagetool.rules.Rule> getRelevantRulesGlobalConfig(java.util.ResourceBundle, org.languagetool.GlobalConfig, org.languagetool.UserConfig, org.languagetool.Language, List<org.languagetool.Language>) throws java.io.IOException,public Function<org.languagetool.rules.Rule,org.languagetool.rules.Rule> getRemoteEnhancedRules(java.util.ResourceBundle, List<org.languagetool.rules.RemoteRuleConfig>, org.languagetool.UserConfig, org.languagetool.Language, List<org.languagetool.Language>, boolean) throws java.io.IOException,public List<java.lang.String> getRuleFileNames() ,public int getRulePriority(org.languagetool.rules.Rule) ,public synchronized org.languagetool.tokenizers.SentenceTokenizer getSentenceTokenizer() ,public abstract java.lang.String getShortCode() ,public final java.lang.String getShortCodeWithCountryAndVariant() ,public synchronized org.languagetool.synthesis.Synthesizer getSynthesizer() ,public synchronized org.languagetool.tagging.Tagger getTagger() ,public final java.lang.String getTranslatedName(java.util.ResourceBundle) ,public org.languagetool.rules.patterns.Unifier getUnifier() ,public org.languagetool.rules.patterns.UnifierConfiguration getUnifierConfiguration() ,public java.lang.String getVariant() ,public synchronized org.languagetool.tokenizers.Tokenizer getWordTokenizer() ,public boolean hasMinMatchesRules() ,public boolean hasNGramFalseFriendRule(org.languagetool.Language) ,public final boolean hasVariant() ,public int hashCode() ,public boolean isAdvancedTypographyEnabled() ,public boolean isExternal() ,public boolean isHiddenFromGui() ,public boolean isSpellcheckOnlyLanguage() ,public boolean isVariant() ,public List<org.languagetool.rules.RuleMatch> mergeSuggestions(List<org.languagetool.rules.RuleMatch>, org.languagetool.markup.AnnotatedText, Set<java.lang.String>) ,public List<java.lang.String> prepareLineForSpeller(java.lang.String) ,public void setChunker(org.languagetool.chunking.Chunker) ,public void setDisambiguator(org.languagetool.tagging.disambiguation.Disambiguator) ,public void setPostDisambiguationChunker(org.languagetool.chunking.Chunker) ,public void setSentenceTokenizer(org.languagetool.tokenizers.SentenceTokenizer) ,public void setSynthesizer(org.languagetool.synthesis.Synthesizer) ,public void setTagger(org.languagetool.tagging.Tagger) ,public void setWordTokenizer(org.languagetool.tokenizers.Tokenizer) ,public java.lang.String toAdvancedTypography(java.lang.String) ,public final java.lang.String toString() <variables>private static final java.util.regex.Pattern APOSTROPHE,private static final org.languagetool.tagging.disambiguation.Disambiguator DEMO_DISAMBIGUATOR,private static final org.languagetool.tagging.Tagger DEMO_TAGGER,private static final java.util.regex.Pattern DOUBLE_QUOTE_PATTERN,private static final java.util.regex.Pattern ELLIPSIS,private static final java.util.regex.Pattern INSIDE_SUGGESTION,private static final java.util.regex.Pattern NBSPACE1,private static final java.util.regex.Pattern NBSPACE2,private static final java.util.regex.Pattern QUOTED_CHAR_PATTERN,private static final org.languagetool.tokenizers.SentenceTokenizer SENTENCE_TOKENIZER,private static final java.util.regex.Pattern SINGLE_QUOTE_PATTERN,private static final java.util.regex.Pattern SUGGESTION_CLOSE_TAG,private static final java.util.regex.Pattern SUGGESTION_OPEN_TAG,private static final java.util.regex.Pattern TYPOGRAPHY_PATTERN_1,private static final java.util.regex.Pattern TYPOGRAPHY_PATTERN_2,private static final java.util.regex.Pattern TYPOGRAPHY_PATTERN_3,private static final java.util.regex.Pattern TYPOGRAPHY_PATTERN_4,private static final java.util.regex.Pattern TYPOGRAPHY_PATTERN_5,private static final org.languagetool.tokenizers.WordTokenizer WORD_TOKENIZER,private org.languagetool.chunking.Chunker chunker,private final org.languagetool.rules.patterns.UnifierConfiguration disambiguationUnifierConfig,private org.languagetool.tagging.disambiguation.Disambiguator disambiguator,private final java.util.regex.Pattern ignoredCharactersRegex,private static final Map<Class<org.languagetool.Language>,org.languagetool.JLanguageTool> languagetoolInstances,private static final Logger logger,private final java.util.concurrent.atomic.AtomicBoolean noLmWarningPrinted,private List<org.languagetool.rules.patterns.AbstractPatternRule> patternRules,private org.languagetool.chunking.Chunker postDisambiguationChunker,private org.languagetool.tokenizers.SentenceTokenizer sentenceTokenizer,private java.lang.String shortCodeWithCountryAndVariant,private static final Map<Class<? extends org.languagetool.Language>,org.languagetool.rules.spelling.SpellingCheckRule> spellingRules,private org.languagetool.synthesis.Synthesizer synthesizer,private org.languagetool.tagging.Tagger tagger,private final org.languagetool.rules.patterns.UnifierConfiguration unifierConfig,private org.languagetool.tokenizers.Tokenizer wordTokenizer
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/AbstractDashRule.java
AbstractDashRule
match
class AbstractDashRule extends Rule { public AbstractDashRule(ResourceBundle messages) { super(messages); setCategory(Categories.TYPOGRAPHY.getCategory(messages)); setTags(Collections.singletonList(Tag.picky)); } @Override public String getId() { return "DASH_RULE"; } @Override public abstract String getDescription(); public abstract String getMessage(); protected abstract AhoCorasickDoubleArrayTrie<String> getCompoundsData(); @Override public int estimateContextForSureMatch() { return 2; } @Override public RuleMatch[] match(AnalyzedSentence sentence) throws IOException {<FILL_FUNCTION_BODY>} protected boolean isBoundary(String s) { return !s.matches("[a-zA-Z]"); } protected static AhoCorasickDoubleArrayTrie<String> loadCompoundFile(String path) { List<String> words = new ArrayList<>(); List<String> lines = JLanguageTool.getDataBroker().getFromResourceDirAsLines(path); for (String line : lines) { if (line.isEmpty() || line.charAt(0) == '#') { continue; // ignore comments } if (line.endsWith("+") || line.endsWith("?")) { continue; // skip non-hyphenated suggestions } else if (line.endsWith("*") || line.endsWith("$")) { line = removeLastCharacter(line); } words.add(line); } Map<String,String> map = new HashMap<>(); for (String word : words) { String variant1 = word.replace("-", "–"); map.put(variant1, variant1); String variant2 = word.replace("-", "—"); map.put(variant2, variant2); String variant3 = word.replace("-", " – "); map.put(variant3, variant3); String variant4 = word.replace("-", " — "); map.put(variant4, variant4); } AhoCorasickDoubleArrayTrie<String> trie = new AhoCorasickDoubleArrayTrie<>(); trie.build(map); return trie; } private static String removeLastCharacter(String str) { return str.substring(0, str.length() - 1); } }
List<RuleMatch> matches = new ArrayList<>(); String text = sentence.getText(); List<AhoCorasickDoubleArrayTrie.Hit<String>> hits = getCompoundsData().parseText(text); Set<Integer> startPositions = new HashSet<>(); Collections.reverse(hits); // work on longest matches first for (AhoCorasickDoubleArrayTrie.Hit<String> hit : hits) { if (startPositions.contains(hit.begin)) { continue; // avoid overlapping matches } if (hit.begin > 0 && !isBoundary(text.substring(hit.begin-1, hit.begin))) { // prevent substring matches continue; } if (hit.end < text.length() && !isBoundary(text.substring(hit.end, hit.end+1))) { // prevent substring matches, e.g. "Foto" for "Photons" continue; } RuleMatch match = new RuleMatch(this, sentence, hit.begin, hit.end, hit.begin, hit.end, getMessage(), null, false, ""); String covered = text.substring(hit.begin, hit.end); match.setSuggestedReplacement(covered.replaceAll(" ?[–—] ?", "-")); matches.add(match); startPositions.add(hit.begin); } return matches.toArray(new RuleMatch[0]);
638
376
1,014
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public void addTags(List<java.lang.String>) ,public void addToneTags(List<java.lang.String>) ,public int estimateContextForSureMatch() ,public List<org.languagetool.tagging.disambiguation.rules.DisambiguationPatternRule> getAntiPatterns() ,public org.languagetool.rules.Category getCategory() ,public java.lang.String getConfigureText() ,public final List<org.languagetool.rules.CorrectExample> getCorrectExamples() ,public int getDefaultValue() ,public abstract java.lang.String getDescription() ,public int getDistanceTokens() ,public final List<org.languagetool.rules.ErrorTriggeringExample> getErrorTriggeringExamples() ,public java.lang.String getFullId() ,public abstract java.lang.String getId() ,public final List<org.languagetool.rules.IncorrectExample> getIncorrectExamples() ,public org.languagetool.rules.ITSIssueType getLocQualityIssueType() ,public int getMaxConfigurableValue() ,public int getMinConfigurableValue() ,public int getMinPrevMatches() ,public int getPriority() ,public java.lang.String getSourceFile() ,public java.lang.String getSubId() ,public List<org.languagetool.Tag> getTags() ,public List<org.languagetool.ToneTag> getToneTags() ,public java.net.URL getUrl() ,public boolean hasConfigurableValue() ,public boolean hasTag(org.languagetool.Tag) ,public boolean hasToneTag(org.languagetool.ToneTag) ,public final boolean isDefaultOff() ,public final boolean isDefaultTempOff() ,public boolean isDictionaryBasedSpellingRule() ,public boolean isGoalSpecific() ,public final boolean isOfficeDefaultOff() ,public final boolean isOfficeDefaultOn() ,public boolean isPremium() ,public abstract org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public final void setCategory(org.languagetool.rules.Category) ,public final void setCorrectExamples(List<org.languagetool.rules.CorrectExample>) ,public final void setDefaultOff() ,public final void setDefaultOn() ,public final void setDefaultTempOff() ,public void setDistanceTokens(int) ,public final void setErrorTriggeringExamples(List<org.languagetool.rules.ErrorTriggeringExample>) ,public void setGoalSpecific(boolean) ,public final void setIncorrectExamples(List<org.languagetool.rules.IncorrectExample>) ,public void setLocQualityIssueType(org.languagetool.rules.ITSIssueType) ,public void setMinPrevMatches(int) ,public final void setOfficeDefaultOff() ,public final void setOfficeDefaultOn() ,public void setPremium(boolean) ,public void setPriority(int) ,public void setTags(List<org.languagetool.Tag>) ,public void setToneTags(List<org.languagetool.ToneTag>) ,public void setUrl(java.net.URL) ,public boolean supportsLanguage(org.languagetool.Language) ,public boolean useInOffice() <variables>private static final org.languagetool.rules.Category MISC,private org.languagetool.rules.Category category,private List<org.languagetool.rules.CorrectExample> correctExamples,private boolean defaultOff,private boolean defaultTempOff,private int distanceTokens,private List<org.languagetool.rules.ErrorTriggeringExample> errorTriggeringExamples,private List<org.languagetool.rules.IncorrectExample> incorrectExamples,private boolean isGoalSpecific,private boolean isPremium,private org.languagetool.rules.ITSIssueType locQualityIssueType,protected final non-sealed java.util.ResourceBundle messages,private int minPrevMatches,private boolean officeDefaultOff,private boolean officeDefaultOn,private int priority,private List<org.languagetool.Tag> tags,private List<org.languagetool.ToneTag> toneTags,private java.net.URL url
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/AbstractDateCheckFilter.java
AbstractDateCheckFilter
acceptRuleMatch
class AbstractDateCheckFilter extends RuleFilter { private static final Logger logger = LoggerFactory.getLogger(AbstractDateCheckFilter.class); // The day of the month may contain not only digits but also extra letters // such as"22nd" in English or "22-an" in Esperanto. The regexp extracts // the numerical part. protected static final Pattern DAY_OF_MONTH_PATTERN = Pattern.compile("(\\d+).*"); /** * Implement so that Sunday returns {@code 1}, Monday {@code 2} etc. * @param localizedWeekDayString a week day name or abbreviation thereof */ protected abstract int getDayOfWeek(String localizedWeekDayString); /** * Get the localized name of the day of week for the given date. */ protected abstract String getDayOfWeek(Calendar date); /** * Implement so that "first" returns {@code 1}, second returns {@code 2} etc. * @param localizedDayOfMonth name of day of the month or abbreviation thereof */ protected int getDayOfMonth(String localizedDayOfMonth) { return 0; } /** * Implement so that January returns {@code 1}, February {@code 2} etc. * @param localizedMonth name of a month or abbreviation thereof */ protected abstract int getMonth(String localizedMonth); protected abstract Calendar getCalendar(); /** * @param args a map with values for {@code year}, {@code month}, {@code day} (day of month), {@code weekDay} */ @Override public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> args, int patternTokenPos, AnalyzedTokenReadings[] patternTokens, List<Integer> tokenPositions) {<FILL_FUNCTION_BODY>} private Calendar getDate(Map<String, String> args) { String yearArg = args.get("year"); int year; if (yearArg == null && TestHackHelper.isJUnitTest()) { // Volkswagen-style testing // Hack for tests of date - weekday match with missing year // in production, we assume the current year // For xml tests, we use weekdays of the year 2014 year = 2014; } else if (yearArg == null) { // assume current year for rule DATUM_WOCHENTAG_OHNE_JAHR etc. year = getCalendar().get(Calendar.YEAR); } else { year = Integer.parseInt(yearArg); } int month = getMonthFromArguments(args); int dayOfMonth = getDayOfMonthFromArguments(args); Calendar calendar = getCalendar(); calendar.setLenient(false); // be strict about validity of dates //noinspection MagicConstant calendar.set(year, month, dayOfMonth, 0, 0, 0); return calendar; } private int getDayOfMonthFromArguments(Map<String, String> args) { String dayOfMonthString = getRequired("day", args); int dayOfMonth; Matcher matcherDayOfMonth = DAY_OF_MONTH_PATTERN.matcher(dayOfMonthString); if (matcherDayOfMonth.matches()) { // The day of the month is a number, possibly with a suffix such // as "22nd" for example. dayOfMonth = Integer.parseInt(matcherDayOfMonth.group(1)); } else { // In some languages, the day of the month can also be written with // letters rather than with digits, so parse localized numbers. dayOfMonth = getDayOfMonth(dayOfMonthString); } return dayOfMonth; } private int getMonthFromArguments(Map<String, String> args) { String monthStr = getRequired("month", args); int month; if (StringUtils.isNumeric(monthStr)) { month = Integer.parseInt(monthStr); } else { month = getMonth(StringTools.trimSpecialCharacters(monthStr)); } return month - 1; } }
try { int dayOfWeekFromString = getDayOfWeek(getRequired("weekDay", args).replace("\u00AD", "")); // replace soft hyphen Calendar dateFromDate = getDate(args); int dayOfWeekFromDate; try { dayOfWeekFromDate = dateFromDate.get(Calendar.DAY_OF_WEEK); } catch (IllegalArgumentException ignore) { // happens with 'dates' like '32.8.2014' - those should be caught by a different rule return null; } if (dayOfWeekFromString != dayOfWeekFromDate) { Calendar calFromDateString = Calendar.getInstance(); calFromDateString.set(Calendar.DAY_OF_WEEK, dayOfWeekFromString); String message = match.getMessage() .replace("{realDay}", getDayOfWeek(dateFromDate)) .replace("{day}", getDayOfWeek(calFromDateString)) .replace("{currentYear}", Integer.toString(Calendar.getInstance().get(Calendar.YEAR))); RuleMatch ruleMatch = new RuleMatch(match.getRule(), match.getSentence(), match.getFromPos(), match.getToPos(), message, match.getShortMessage()); ruleMatch.setType(match.getType()); ruleMatch.setUrl(Tools.getUrl("https://www.timeanddate.com/calendar/?year=" + dateFromDate.get(Calendar.YEAR))); return ruleMatch; } else { return null; } } catch (IllegalArgumentException e) { throw e; } catch (RuntimeException e) { // this can happen with some special characters which the Java regex matches but which the Java code // cannot map to days, e.g. German "Dıenstag" vs "Dienstag" (note the difference on the second character - // the first word is not valid, but it should not crash LT): logger.warn("Skipping potential match for " + match.getRule().getFullId(), e); return null; }
1,055
519
1,574
<methods>public non-sealed void <init>() ,public abstract org.languagetool.rules.RuleMatch acceptRuleMatch(org.languagetool.rules.RuleMatch, Map<java.lang.String,java.lang.String>, int, org.languagetool.AnalyzedTokenReadings[], List<java.lang.Integer>) throws java.io.IOException,public boolean matches(Map<java.lang.String,java.lang.String>, org.languagetool.AnalyzedTokenReadings[], int, List<java.lang.Integer>) throws java.io.IOException<variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/AbstractFillerWordsRule.java
AbstractFillerWordsRule
match
class AbstractFillerWordsRule extends TextLevelRule { public static final String RULE_ID = "FILLER_WORDS"; private static final int DEFAULT_MIN_PERCENT = 8; private static final Pattern OPENING_QUOTES = Pattern.compile("[\"“„”»«]"); private static final Pattern ENDING_QUOTES = Pattern.compile("[\"“”»«]"); private static final boolean DEFAULT_ACTIVATION = false; private int minPercent = DEFAULT_MIN_PERCENT; private final Language lang; /* * Override this to detect filler words in the specified language */ protected abstract boolean isFillerWord(String token); public AbstractFillerWordsRule(ResourceBundle messages, Language lang, UserConfig userConfig, boolean defaultActive) { super(messages); super.setCategory(new Category(new CategoryId("CREATIVE_WRITING"), messages.getString("category_creative_writing"), Location.INTERNAL, false)); this.lang = lang; if (!defaultActive) { setDefaultOff(); } if (userConfig != null) { int confPercent = userConfig.getConfigValueByID(getId()); if(confPercent >= 0) { this.minPercent = confPercent; } } setLocQualityIssueType(ITSIssueType.Style); } public AbstractFillerWordsRule(ResourceBundle messages, Language lang, UserConfig userConfig) { this(messages, lang, userConfig, DEFAULT_ACTIVATION); } @Override public String getDescription() { return messages.getString("filler_words_rule_desc"); } @Override public String getId() { return RULE_ID; } @Override public int getDefaultValue() { return minPercent; } @Override public boolean hasConfigurableValue() { return true; } @Override public int getMinConfigurableValue() { return 0; } @Override public int getMaxConfigurableValue() { return 100; } /* (non-Javadoc) * @see org.languagetool.rules.Rule#getConfigureText() */ @Override public String getConfigureText() { return messages.getString("filler_words_rule_opt_text"); } public String getMessage() { return messages.getString("filler_words_rule_msg"); } protected boolean isException(AnalyzedTokenReadings[] tokens, int num) { return false; } /* (non-Javadoc) * @see org.languagetool.rules.TextLevelRule#match(java.util.List) */ @Override public RuleMatch[] match(List<AnalyzedSentence> sentences) throws IOException {<FILL_FUNCTION_BODY>} @Override public int minToCheckParagraph() { return 0; } }
List<RuleMatch> ruleMatches = new ArrayList<>(); String msg = getMessage(); List<Integer> startPos = new ArrayList<>(); List<Integer> endPos = new ArrayList<>(); List<AnalyzedSentence> relevantSentences = new ArrayList<>(); double percent; int pos = 0; int wordCount = 0; boolean isDirectSpeech = false; for (int nSentence = 0; nSentence < sentences.size(); nSentence++) { AnalyzedSentence sentence = sentences.get(nSentence); AnalyzedTokenReadings[] tokens = sentence.getTokensWithoutWhitespace(); for (int n = 1; n < tokens.length; n++) { AnalyzedTokenReadings token = tokens[n]; String sToken = token.getToken(); if (!isDirectSpeech && OPENING_QUOTES.matcher(sToken).matches() && n < tokens.length -1 && !tokens[n + 1].isWhitespaceBefore()) { isDirectSpeech = true; } else if (isDirectSpeech && ENDING_QUOTES.matcher(sToken).matches() && n > 1 && !tokens[n].isWhitespaceBefore()) { isDirectSpeech = false; } else if ((!isDirectSpeech || minPercent == 0) && !token.isWhitespace() && !token.isNonWord()) { wordCount++; if (isFillerWord(sToken) && !isException(tokens, n)) { startPos.add(token.getStartPos() + pos); endPos.add(token.getEndPos() + pos); relevantSentences.add(sentence); } } } if (Tools.isParagraphEnd(sentences, nSentence, lang)) { if(wordCount > 0) { percent = startPos.size() * 100.0 / wordCount; } else { percent = 0; } if (percent > minPercent) { for (int i = 0; i < startPos.size(); i++) { RuleMatch ruleMatch = new RuleMatch(this, relevantSentences.get(i), startPos.get(i), endPos.get(i), msg); ruleMatches.add(ruleMatch); } } wordCount = 0; startPos = new ArrayList<>(); endPos = new ArrayList<>(); relevantSentences = new ArrayList<>(); } pos += sentence.getCorrectedTextLength(); } if (wordCount > 0) { percent = startPos.size() * 100.0 / wordCount; } else { percent = 0; } if (percent > minPercent) { for (int i = 0; i < startPos.size(); i++) { RuleMatch ruleMatch = new RuleMatch(this, relevantSentences.get(i), startPos.get(i), endPos.get(i), msg); ruleMatches.add(ruleMatch); } } return toRuleMatchArray(ruleMatches);
798
782
1,580
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public int estimateContextForSureMatch() ,public org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>, org.languagetool.markup.AnnotatedText) throws java.io.IOException,public abstract org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>) throws java.io.IOException,public final org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public abstract int minToCheckParagraph() <variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/AbstractFutureDateFilter.java
AbstractFutureDateFilter
acceptRuleMatch
class AbstractFutureDateFilter extends RuleFilter { private static final Pattern DAY_OF_MONTH_PATTERN = Pattern.compile("(\\d+).*"); /** * Implement so that "first" returns {@code 1}, second returns {@code 2} etc. * @param localizedDayOfMonth name of day of the month or abbreviation thereof */ protected int getDayOfMonth(String localizedDayOfMonth) { return 0; } /** * Implement so that January returns {@code 1}, February {@code 2} etc. * @param localizedMonth name of a month or abbreviation thereof */ protected abstract int getMonth(String localizedMonth); protected abstract Calendar getCalendar(); /** * @param args a map with values for {@code year}, {@code month}, {@code day} (day of month), {@code weekDay} */ @Override public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> args, int patternTokenPos, AnalyzedTokenReadings[] patternTokens, List<Integer> tokenPositions) {<FILL_FUNCTION_BODY>} private Calendar getDate(Map<String, String> args) { int year = Integer.parseInt(getRequired("year", args)); int month = getMonthFromArguments(args); int dayOfMonth = getDayOfMonthFromArguments(args); Calendar calendar = getCalendar(); calendar.setLenient(false); // be strict about validity of dates //noinspection MagicConstant calendar.set(year, month, dayOfMonth, 0, 0, 0); return calendar; } private int getDayOfMonthFromArguments(Map<String, String> args) { String dayOfMonthString = getRequired("day", args); int dayOfMonth; Matcher matcherDayOfMonth = DAY_OF_MONTH_PATTERN.matcher(dayOfMonthString); if (matcherDayOfMonth.matches()) { // The day of the month is a number, possibly with a suffix such // as "22nd" for example. dayOfMonth = Integer.parseInt(matcherDayOfMonth.group(1)); } else { // In some languages, the day of the month can also be written with // letters rather than with digits, so parse localized numbers. dayOfMonth = getDayOfMonth(dayOfMonthString); } return dayOfMonth; } private int getMonthFromArguments(Map<String, String> args) { String monthStr = getRequired("month", args); int month; if (StringUtils.isNumeric(monthStr)) { month = Integer.parseInt(monthStr); } else { month = getMonth(monthStr); } return month - 1; } }
Calendar dateFromDate = getDate(args); Calendar currentDate = getCalendar(); if (TestHackHelper.isJUnitTest()) { currentDate = new Calendar.Builder().setDate(2014, 0, 1).build(); } try { if (dateFromDate.after(currentDate)) { return match; } else { return null; } } catch (IllegalArgumentException ignore) { // happens with 'dates' like '32.8.2014' - those should be caught by a different rule return null; }
710
152
862
<methods>public non-sealed void <init>() ,public abstract org.languagetool.rules.RuleMatch acceptRuleMatch(org.languagetool.rules.RuleMatch, Map<java.lang.String,java.lang.String>, int, org.languagetool.AnalyzedTokenReadings[], List<java.lang.Integer>) throws java.io.IOException,public boolean matches(Map<java.lang.String,java.lang.String>, org.languagetool.AnalyzedTokenReadings[], int, List<java.lang.Integer>) throws java.io.IOException<variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/AbstractMakeContractionsFilter.java
AbstractMakeContractionsFilter
acceptRuleMatch
class AbstractMakeContractionsFilter extends RuleFilter { @Override public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> arguments, int patternTokenPos, AnalyzedTokenReadings[] patternTokens, List<Integer> tokenPositions) throws IOException {<FILL_FUNCTION_BODY>} protected abstract String fixContractions(String suggestion); }
RuleMatch newMatch = match; List<String> newSugestions = new ArrayList<>(); for (String suggestion: match.getSuggestedReplacements()) { newSugestions.add(fixContractions(suggestion)); } newMatch.setSuggestedReplacements(newSugestions); return newMatch;
94
90
184
<methods>public non-sealed void <init>() ,public abstract org.languagetool.rules.RuleMatch acceptRuleMatch(org.languagetool.rules.RuleMatch, Map<java.lang.String,java.lang.String>, int, org.languagetool.AnalyzedTokenReadings[], List<java.lang.Integer>) throws java.io.IOException,public boolean matches(Map<java.lang.String,java.lang.String>, org.languagetool.AnalyzedTokenReadings[], int, List<java.lang.Integer>) throws java.io.IOException<variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/AbstractNewYearDateFilter.java
AbstractNewYearDateFilter
getDate
class AbstractNewYearDateFilter extends RuleFilter { // The day of the month may contain not only digits but also extra letters // such as "22nd" in English or "22-an" in Esperanto. The regexp extracts // the numerical part. private static final Pattern DAY_OF_MONTH_PATTERN = Pattern.compile("(\\d+).*"); /** * Return true if the year recently changed (= it is January) */ protected boolean isJanuary() { if (TestHackHelper.isJUnitTest()) { return true; } return getCalendar().get(Calendar.MONTH) == Calendar.JANUARY; } protected int getCurrentYear() { if (TestHackHelper.isJUnitTest()) { return 2014; } return getCalendar().get(Calendar.YEAR); } /** * Implement so that January returns {@code 1}, February {@code 2} etc. * @param localizedMonth name of a month or abbreviation thereof */ protected abstract int getMonth(String localizedMonth); protected abstract Calendar getCalendar(); /** * Implement so that "first" returns {@code 1}, second returns {@code 2} etc. * @param localizedDayOfMonth name of day of the month or abbreviation thereof */ protected int getDayOfMonth(String localizedDayOfMonth) { return 0; } /** * @param args a map with values for {@code year}, {@code month}, {@code day} (day of month) */ @Override public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> args, int patternTokenPos, AnalyzedTokenReadings[] patternTokens, List<Integer> tokenPositions) { Calendar dateFromText = getDate(args); int monthFromText; int yearFromText; try { monthFromText = dateFromText.get(Calendar.MONTH); yearFromText = dateFromText.get(Calendar.YEAR); } catch (IllegalArgumentException e) { return null; // date is not valid; another rule is responsible } int currentYear = getCurrentYear(); if (isJanuary() && monthFromText != 11 /*December*/ && yearFromText + 1 == currentYear) { String message = match.getMessage() .replace("{year}", Integer.toString(yearFromText)) .replace("{realYear}", Integer.toString(currentYear)); RuleMatch ruleMatch = new RuleMatch(match.getRule(), match.getSentence(), match.getFromPos(), match.getToPos(), message, match.getShortMessage()); ruleMatch.setType(match.getType()); return ruleMatch; } else { return null; } } private Calendar getDate(Map<String, String> args) {<FILL_FUNCTION_BODY>} private int getDayOfMonthFromArguments(Map<String, String> args) { String dayOfMonthString = getRequired("day", args).replace("\u00AD", ""); // replace soft hyphen int dayOfMonth; Matcher matcherDayOfMonth = DAY_OF_MONTH_PATTERN.matcher(dayOfMonthString); if (matcherDayOfMonth.matches()) { // The day of the month is a number, possibly with a suffix such // as "22nd" for example. dayOfMonth = Integer.parseInt(matcherDayOfMonth.group(1)); } else { // In some languages, the day of the month can also be written with // letters rather than with digits, so parse localized numbers. dayOfMonth = getDayOfMonth(dayOfMonthString); } return dayOfMonth; } private int getMonthFromArguments(Map<String, String> args) { String monthStr = getRequired("month", args).replace("\u00AD", ""); // replace soft hyphen int month; if (StringUtils.isNumeric(monthStr)) { month = Integer.parseInt(monthStr); } else { month = getMonth(monthStr); } return month - 1; } }
int year = Integer.parseInt(getRequired("year", args)); int month = getMonthFromArguments(args); int dayOfMonth = getDayOfMonthFromArguments(args); Calendar calendar = getCalendar(); calendar.setLenient(false); // be strict about validity of dates //noinspection MagicConstant calendar.set(year, month, dayOfMonth, 0, 0, 0); return calendar;
1,066
111
1,177
<methods>public non-sealed void <init>() ,public abstract org.languagetool.rules.RuleMatch acceptRuleMatch(org.languagetool.rules.RuleMatch, Map<java.lang.String,java.lang.String>, int, org.languagetool.AnalyzedTokenReadings[], List<java.lang.Integer>) throws java.io.IOException,public boolean matches(Map<java.lang.String,java.lang.String>, org.languagetool.AnalyzedTokenReadings[], int, List<java.lang.Integer>) throws java.io.IOException<variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/AbstractNumberInWordFilter.java
AbstractNumberInWordFilter
acceptRuleMatch
class AbstractNumberInWordFilter extends RuleFilter { protected final Language language; public static final Pattern typoPattern = Pattern.compile("[0-9]"); protected AbstractNumberInWordFilter(Language language) { this.language = language; } @Nullable @Override public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> arguments, int patternTokenPos, AnalyzedTokenReadings[] patternTokens, List<Integer> tokenPositions) throws IOException {<FILL_FUNCTION_BODY>} protected abstract boolean isMisspelled(String word) throws IOException; protected abstract List<String> getSuggestions(String word) throws IOException; }
String word = arguments.get("word"); String wordReplacingZeroO = word.replaceAll("0","o"); String wordWithoutNumberCharacter = typoPattern.matcher(word).replaceAll(""); List<String> replacements = new ArrayList<>(); if (!isMisspelled(wordReplacingZeroO) && !word.equals(wordReplacingZeroO) ) { replacements.add(wordReplacingZeroO); } if (!isMisspelled(wordWithoutNumberCharacter)) { replacements.add(wordWithoutNumberCharacter); } if (replacements.isEmpty()){ List<String> suggestions = getSuggestions(wordWithoutNumberCharacter); replacements.addAll(suggestions); } if (!replacements.isEmpty()) { RuleMatch ruleMatch = new RuleMatch(match); ruleMatch.setSuggestedReplacements(replacements); return ruleMatch; } return null;
176
256
432
<methods>public non-sealed void <init>() ,public abstract org.languagetool.rules.RuleMatch acceptRuleMatch(org.languagetool.rules.RuleMatch, Map<java.lang.String,java.lang.String>, int, org.languagetool.AnalyzedTokenReadings[], List<java.lang.Integer>) throws java.io.IOException,public boolean matches(Map<java.lang.String,java.lang.String>, org.languagetool.AnalyzedTokenReadings[], int, List<java.lang.Integer>) throws java.io.IOException<variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/AbstractSpaceBeforeRule.java
AbstractSpaceBeforeRule
match
class AbstractSpaceBeforeRule extends Rule { protected abstract Pattern getConjunctions(); public AbstractSpaceBeforeRule(ResourceBundle messages, Language language) { super.setCategory(Categories.MISC.getCategory(messages)); } @Override public String getId() { return "SPACE_BEFORE_CONJUNCTION"; } @Override public String getDescription() { return "Checks for missing space before some conjunctions"; } protected String getShort() { return "Missing white space"; } protected String getSuggestion() { return "Missing white space before conjunction"; } @Override public final RuleMatch[] match(AnalyzedSentence sentence) {<FILL_FUNCTION_BODY>} }
List<RuleMatch> ruleMatches = new ArrayList<>(); AnalyzedTokenReadings[] tokens = sentence.getTokens(); for (int i = 1; i < tokens.length; i++) { String token = tokens[i].getToken(); Matcher matcher = getConjunctions().matcher(token); if (matcher.matches()) { String previousToken = tokens[i - 1].getToken(); if (!(previousToken.equals(" ") || previousToken.equals("("))) { String replacement = " " + token; String msg = getSuggestion(); int pos = tokens[i].getStartPos(); RuleMatch potentialRuleMatch = new RuleMatch(this, sentence, pos, pos + token.length(), msg, getShort()); potentialRuleMatch.setSuggestedReplacement(replacement); ruleMatches.add(potentialRuleMatch); } } } return toRuleMatchArray(ruleMatches);
204
245
449
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public void addTags(List<java.lang.String>) ,public void addToneTags(List<java.lang.String>) ,public int estimateContextForSureMatch() ,public List<org.languagetool.tagging.disambiguation.rules.DisambiguationPatternRule> getAntiPatterns() ,public org.languagetool.rules.Category getCategory() ,public java.lang.String getConfigureText() ,public final List<org.languagetool.rules.CorrectExample> getCorrectExamples() ,public int getDefaultValue() ,public abstract java.lang.String getDescription() ,public int getDistanceTokens() ,public final List<org.languagetool.rules.ErrorTriggeringExample> getErrorTriggeringExamples() ,public java.lang.String getFullId() ,public abstract java.lang.String getId() ,public final List<org.languagetool.rules.IncorrectExample> getIncorrectExamples() ,public org.languagetool.rules.ITSIssueType getLocQualityIssueType() ,public int getMaxConfigurableValue() ,public int getMinConfigurableValue() ,public int getMinPrevMatches() ,public int getPriority() ,public java.lang.String getSourceFile() ,public java.lang.String getSubId() ,public List<org.languagetool.Tag> getTags() ,public List<org.languagetool.ToneTag> getToneTags() ,public java.net.URL getUrl() ,public boolean hasConfigurableValue() ,public boolean hasTag(org.languagetool.Tag) ,public boolean hasToneTag(org.languagetool.ToneTag) ,public final boolean isDefaultOff() ,public final boolean isDefaultTempOff() ,public boolean isDictionaryBasedSpellingRule() ,public boolean isGoalSpecific() ,public final boolean isOfficeDefaultOff() ,public final boolean isOfficeDefaultOn() ,public boolean isPremium() ,public abstract org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public final void setCategory(org.languagetool.rules.Category) ,public final void setCorrectExamples(List<org.languagetool.rules.CorrectExample>) ,public final void setDefaultOff() ,public final void setDefaultOn() ,public final void setDefaultTempOff() ,public void setDistanceTokens(int) ,public final void setErrorTriggeringExamples(List<org.languagetool.rules.ErrorTriggeringExample>) ,public void setGoalSpecific(boolean) ,public final void setIncorrectExamples(List<org.languagetool.rules.IncorrectExample>) ,public void setLocQualityIssueType(org.languagetool.rules.ITSIssueType) ,public void setMinPrevMatches(int) ,public final void setOfficeDefaultOff() ,public final void setOfficeDefaultOn() ,public void setPremium(boolean) ,public void setPriority(int) ,public void setTags(List<org.languagetool.Tag>) ,public void setToneTags(List<org.languagetool.ToneTag>) ,public void setUrl(java.net.URL) ,public boolean supportsLanguage(org.languagetool.Language) ,public boolean useInOffice() <variables>private static final org.languagetool.rules.Category MISC,private org.languagetool.rules.Category category,private List<org.languagetool.rules.CorrectExample> correctExamples,private boolean defaultOff,private boolean defaultTempOff,private int distanceTokens,private List<org.languagetool.rules.ErrorTriggeringExample> errorTriggeringExamples,private List<org.languagetool.rules.IncorrectExample> incorrectExamples,private boolean isGoalSpecific,private boolean isPremium,private org.languagetool.rules.ITSIssueType locQualityIssueType,protected final non-sealed java.util.ResourceBundle messages,private int minPrevMatches,private boolean officeDefaultOff,private boolean officeDefaultOn,private int priority,private List<org.languagetool.Tag> tags,private List<org.languagetool.ToneTag> toneTags,private java.net.URL url
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/AbstractSpecificCaseRule.java
AbstractSpecificCaseRule
loadPhrases
class AbstractSpecificCaseRule extends Rule { // a map that has as keys the special case phrases into lowercase // and as values the special case phrases properly spelled: // one for each subclass private static final ConcurrentMap<Class, Map<String,String>> lcToProperSpelling = new ConcurrentHashMap<>(); private static int maxLen; // used to speed up the server as the phrases are loaded in every initialization: protected final CachingWordListLoader phrasesListLoader = new CachingWordListLoader(); /** * The constructor of the abstract class AbstractSpecificCaseRule * @param messages the messages to apply the rule */ public AbstractSpecificCaseRule(ResourceBundle messages) { super(messages); super.setCategory(Categories.CASING.getCategory(messages)); setLocQualityIssueType(ITSIssueType.Misspelling); loadPhrases(); } /** * @return the path to the txt file that contains the phrases for the rule */ public abstract String getPhrasesPath(); /** * @return the message that will be shown if the words of the * wrongly capitalized phrase must begin with capital */ public String getInitialCapitalMessage() { return "The initials of the particular phrase must be capitals."; } /** * @return the message that will be shown if the wrongly capitalized phrase * must not be written with capital initials * (another special kind of capitalization) */ public String getOtherCapitalizationMessage() { return "The particular expression should follow the suggested capitalization."; } public String getShortMessage() { return "Special capitalization"; } /** * Initializes the phrases that will be detected from the rule by the given path */ private synchronized void loadPhrases() {<FILL_FUNCTION_BODY>} @Override public String getId() { return "SPECIFIC_CASE"; } @Override public String getDescription() { return "Checks upper/lower case expressions."; } @Override public RuleMatch[] match(AnalyzedSentence sentence) { List<RuleMatch> matches = new ArrayList<>(); AnalyzedTokenReadings[] tokens = sentence.getTokensWithoutWhitespace(); Map<String, String> properSpellingMap = lcToProperSpelling.get(this.getClass()); for (int i = 0; i < tokens.length; i++) { List<String> l = new ArrayList<>(); int j = 0; while (l.size() < maxLen && i+j < tokens.length) { l.add(tokens[i+j].getToken()); j++; String phrase = String.join(" ", l); String lcPhrase = phrase.toLowerCase(); String properSpelling = properSpellingMap.get(lcPhrase); if (properSpelling != null && !StringTools.isAllUppercase(phrase) && !phrase.equals(properSpelling)) { if (i > 0 && tokens[i-1].isSentenceStart() && !StringTools.startsWithUppercase(properSpelling)) { // avoid suggesting e.g. "vitamin C" at sentence start: continue; } String msg; if (allWordsUppercase(properSpelling)) { msg = getInitialCapitalMessage(); } else { msg = getOtherCapitalizationMessage(); } RuleMatch match = new RuleMatch(this, sentence, tokens[i].getStartPos(), tokens[i+j-1].getEndPos(), msg, getShortMessage()); match.setSuggestedReplacement(properSpelling); matches.add(match); } } } return toRuleMatchArray(matches); } /** * Checks if all the words in the given string begin with a capital letter * @param s the string to check * @return <code>true</code> if all the words within the given string * begin with capital letter, else <code>false</code> */ private boolean allWordsUppercase(String s) { return Arrays.stream(s.split(" ")).allMatch(StringTools::startsWithUppercase); } }
lcToProperSpelling.computeIfAbsent(this.getClass(), (clazz) -> { Map<String, String> properSpelling = new Object2ObjectOpenHashMap<>(); List<String> lines = phrasesListLoader.loadWords(getPhrasesPath()); for (String line : lines) { int parts = line.split(" ").length; maxLen = Math.max(parts, maxLen); String phrase = line.trim(); properSpelling.put(phrase.toLowerCase(), phrase); } return properSpelling; });
1,108
148
1,256
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public void addTags(List<java.lang.String>) ,public void addToneTags(List<java.lang.String>) ,public int estimateContextForSureMatch() ,public List<org.languagetool.tagging.disambiguation.rules.DisambiguationPatternRule> getAntiPatterns() ,public org.languagetool.rules.Category getCategory() ,public java.lang.String getConfigureText() ,public final List<org.languagetool.rules.CorrectExample> getCorrectExamples() ,public int getDefaultValue() ,public abstract java.lang.String getDescription() ,public int getDistanceTokens() ,public final List<org.languagetool.rules.ErrorTriggeringExample> getErrorTriggeringExamples() ,public java.lang.String getFullId() ,public abstract java.lang.String getId() ,public final List<org.languagetool.rules.IncorrectExample> getIncorrectExamples() ,public org.languagetool.rules.ITSIssueType getLocQualityIssueType() ,public int getMaxConfigurableValue() ,public int getMinConfigurableValue() ,public int getMinPrevMatches() ,public int getPriority() ,public java.lang.String getSourceFile() ,public java.lang.String getSubId() ,public List<org.languagetool.Tag> getTags() ,public List<org.languagetool.ToneTag> getToneTags() ,public java.net.URL getUrl() ,public boolean hasConfigurableValue() ,public boolean hasTag(org.languagetool.Tag) ,public boolean hasToneTag(org.languagetool.ToneTag) ,public final boolean isDefaultOff() ,public final boolean isDefaultTempOff() ,public boolean isDictionaryBasedSpellingRule() ,public boolean isGoalSpecific() ,public final boolean isOfficeDefaultOff() ,public final boolean isOfficeDefaultOn() ,public boolean isPremium() ,public abstract org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public final void setCategory(org.languagetool.rules.Category) ,public final void setCorrectExamples(List<org.languagetool.rules.CorrectExample>) ,public final void setDefaultOff() ,public final void setDefaultOn() ,public final void setDefaultTempOff() ,public void setDistanceTokens(int) ,public final void setErrorTriggeringExamples(List<org.languagetool.rules.ErrorTriggeringExample>) ,public void setGoalSpecific(boolean) ,public final void setIncorrectExamples(List<org.languagetool.rules.IncorrectExample>) ,public void setLocQualityIssueType(org.languagetool.rules.ITSIssueType) ,public void setMinPrevMatches(int) ,public final void setOfficeDefaultOff() ,public final void setOfficeDefaultOn() ,public void setPremium(boolean) ,public void setPriority(int) ,public void setTags(List<org.languagetool.Tag>) ,public void setToneTags(List<org.languagetool.ToneTag>) ,public void setUrl(java.net.URL) ,public boolean supportsLanguage(org.languagetool.Language) ,public boolean useInOffice() <variables>private static final org.languagetool.rules.Category MISC,private org.languagetool.rules.Category category,private List<org.languagetool.rules.CorrectExample> correctExamples,private boolean defaultOff,private boolean defaultTempOff,private int distanceTokens,private List<org.languagetool.rules.ErrorTriggeringExample> errorTriggeringExamples,private List<org.languagetool.rules.IncorrectExample> incorrectExamples,private boolean isGoalSpecific,private boolean isPremium,private org.languagetool.rules.ITSIssueType locQualityIssueType,protected final non-sealed java.util.ResourceBundle messages,private int minPrevMatches,private boolean officeDefaultOff,private boolean officeDefaultOn,private int priority,private List<org.languagetool.Tag> tags,private List<org.languagetool.ToneTag> toneTags,private java.net.URL url
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/AbstractStatisticSentenceStyleRule.java
AbstractStatisticSentenceStyleRule
match
class AbstractStatisticSentenceStyleRule extends TextLevelRule { private static final Pattern OPENING_QUOTES = Pattern.compile("[\"“„»«]"); private static final Pattern ENDING_QUOTES = Pattern.compile("[\"“”»«]"); private static final Pattern MARKS_REGEX = Pattern.compile("[,;.:?•!-–—]"); private static final boolean DEFAULT_ACTIVATION = false; private final int minPercent; private final int defaultMinPercent; private int sentenceCount = 0; private int numMatches = 0; private boolean withoutDirectSpeech = false; /** * Condition to generate a hint (possibly including all exceptions) * Returns: * &lt; nAnalysedToken, if condition is not fulfilled * &gt;= nAnalysedToken, if condition is not fulfilled; integer is number of token which is the end hint */ protected abstract AnalyzedTokenReadings conditionFulfilled(List<AnalyzedTokenReadings> tokens); /** * Condition to generate a hint related to the sentence (possibly including all exceptions) */ protected abstract boolean excludeDirectSpeech(); /** * Defines the message for hints which exceed the limit */ protected abstract String getLimitMessage(int limit, double percent); @Override public abstract String getConfigureText(); public AbstractStatisticSentenceStyleRule(ResourceBundle messages, Language lang, UserConfig userConfig, int minPercent, boolean defaultActive) { super(messages); super.setCategory(new Category(new CategoryId("CREATIVE_WRITING"), messages.getString("category_creative_writing"), Location.INTERNAL, false)); if (!defaultActive) { setDefaultOff(); } defaultMinPercent = minPercent; this.minPercent = getMinPercent(userConfig, minPercent); setLocQualityIssueType(ITSIssueType.Style); } private int getMinPercent(UserConfig userConfig, int minPercentDefault) { if (userConfig != null) { int confPercent = userConfig.getConfigValueByID(getId()); if (confPercent >= 0) { return confPercent; } } return minPercentDefault; } protected boolean isMark(AnalyzedTokenReadings token) { return MARKS_REGEX.matcher(token.getToken()).matches(); } protected boolean isOpeningQuote(AnalyzedTokenReadings token) { return OPENING_QUOTES.matcher(token.getToken()).matches(); } public AbstractStatisticSentenceStyleRule(ResourceBundle messages, Language lang, UserConfig userConfig, int minPercent) { this(messages, lang, userConfig, minPercent, DEFAULT_ACTIVATION); } /** * Override, if value should be given in an other unity than percent */ public double denominator() { return 100.0; } @Override public boolean hasConfigurableValue() { return true; } @Override public int getDefaultValue() { return defaultMinPercent; } @Override public int getMinConfigurableValue() { return 0; } @Override public int getMaxConfigurableValue() { return 100; } public int getSentenceCount() { return sentenceCount; } public int getNumberOfMatches() { return numMatches; } public void setWithoutDirectSpeech(boolean withoutDirectSpeech) { this.withoutDirectSpeech = withoutDirectSpeech; } /* (non-Javadoc) * @see org.languagetool.rules.TextLevelRule#match(java.util.List) */ @Override public RuleMatch[] match(List<AnalyzedSentence> sentences) throws IOException {<FILL_FUNCTION_BODY>} @Override public int minToCheckParagraph() { return -1; } }
List<RuleMatch> ruleMatches = new ArrayList<>(); List<Integer> startPos = new ArrayList<>(); List<Integer> endPos = new ArrayList<>(); List<AnalyzedSentence> relevantSentences = new ArrayList<>(); double percent; int pos = 0; sentenceCount = 0; boolean excludeDirectSpeech = excludeDirectSpeech(); boolean isDirectSpeech = false; for (AnalyzedSentence sentence : sentences) { AnalyzedTokenReadings[] tokens = sentence.getTokensWithoutWhitespace(); List<AnalyzedTokenReadings> relevantSentencePart = new ArrayList<AnalyzedTokenReadings>(); boolean isSentenceCount = false; AnalyzedTokenReadings foundToken = null; for (int n = 1; n < tokens.length; n++) { AnalyzedTokenReadings token = tokens[n]; String sToken = token.getToken(); if (excludeDirectSpeech && !isDirectSpeech && OPENING_QUOTES.matcher(sToken).matches() && n < tokens.length - 1 && !tokens[n + 1].isWhitespaceBefore()) { isDirectSpeech = true; if (!relevantSentencePart.isEmpty()) { isSentenceCount = true; foundToken = conditionFulfilled(relevantSentencePart); if (foundToken != null) { break; } } } else if (excludeDirectSpeech && isDirectSpeech && ENDING_QUOTES.matcher(sToken).matches() && n > 1 && !tokens[n].isWhitespaceBefore()) { isDirectSpeech = false; relevantSentencePart = new ArrayList<AnalyzedTokenReadings>(); } else if ((!isDirectSpeech || (minPercent == 0 && !withoutDirectSpeech)) && !token.isWhitespace()) { relevantSentencePart.add(token); } if (n == tokens.length - 1 && !relevantSentencePart.isEmpty()) { isSentenceCount = true; foundToken = conditionFulfilled(relevantSentencePart); } } if (isSentenceCount) { sentenceCount++; } if (foundToken != null) { startPos.add(foundToken.getStartPos() + pos); endPos.add(foundToken.getEndPos() + pos); relevantSentences.add(sentence); } pos += sentence.getCorrectedTextLength(); } numMatches = startPos.size(); if (sentenceCount > 0) { percent = (numMatches * denominator()) / sentenceCount; } else { percent = 0; } if (percent > minPercent) { for (int i = 0; i < startPos.size(); i++) { RuleMatch ruleMatch = new RuleMatch(this, relevantSentences.get(i), startPos.get(i), endPos.get(i), getLimitMessage(minPercent, percent)); ruleMatches.add(ruleMatch); } } return toRuleMatchArray(ruleMatches);
1,062
786
1,848
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public int estimateContextForSureMatch() ,public org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>, org.languagetool.markup.AnnotatedText) throws java.io.IOException,public abstract org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>) throws java.io.IOException,public final org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public abstract int minToCheckParagraph() <variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/AbstractStatisticStyleRule.java
AbstractStatisticStyleRule
match
class AbstractStatisticStyleRule extends TextLevelRule { private static final Pattern OPENING_QUOTES = Pattern.compile("[\"“„»«]"); private static final Pattern ENDING_QUOTES = Pattern.compile("[\"“”»«]"); private static final boolean DEFAULT_ACTIVATION = false; private final int minPercent; private final int defaultMinPercent; private int wordCount = 0; private int numMatches = 0; private boolean withoutDirectSpeech = false; /** * Condition to generate a hint (possibly including all exceptions) * Returns: * &lt; nAnalysedToken, if condition is not fulfilled * &gt;= nAnalysedToken, if condition is not fulfilled; integer is number of token which is the end hint */ protected abstract int conditionFulfilled(AnalyzedTokenReadings[] tokens, int nAnalysedToken); /** * Condition to generate a hint related to the sentence (possibly including all exceptions) */ protected abstract boolean sentenceConditionFulfilled(AnalyzedTokenReadings[] tokens, int nAnalysedToken); /** * Condition to generate a hint related to the sentence (possibly including all exceptions) */ protected abstract boolean excludeDirectSpeech(); /** * Defines the message for hints which exceed the limit */ protected abstract String getLimitMessage(int limit, double percent); /** * Defines the message for sentence related hints */ protected abstract String getSentenceMessage(); /* (non-Javadoc) * @see org.languagetool.rules.Rule#getConfigureText() */ @Override public abstract String getConfigureText(); public AbstractStatisticStyleRule(ResourceBundle messages, Language lang, UserConfig userConfig, int minPercent, boolean defaultActive) { super(messages); super.setCategory(new Category(new CategoryId("CREATIVE_WRITING"), messages.getString("category_creative_writing"), Location.INTERNAL, false)); if (!defaultActive) { setDefaultOff(); } defaultMinPercent = minPercent; this.minPercent = getMinPercent(userConfig, minPercent); setLocQualityIssueType(ITSIssueType.Style); } private int getMinPercent(UserConfig userConfig, int minPercentDefault) { if (userConfig != null) { int confPercent = userConfig.getConfigValueByID(getId()); if (confPercent >= 0) { return confPercent; } } return minPercentDefault; } public AbstractStatisticStyleRule(ResourceBundle messages, Language lang, UserConfig userConfig, int minPercent) { this(messages, lang, userConfig, minPercent, DEFAULT_ACTIVATION); } /** * Override, if value should be given in an other unity than percent */ public double denominator() { return 100.0; } @Override public boolean hasConfigurableValue() { return true; } @Override public int getDefaultValue() { return defaultMinPercent; } @Override public int getMinConfigurableValue() { return 0; } @Override public int getMaxConfigurableValue() { return 100; } public int getWordCount() { return wordCount; } public int getNumberOfMatches() { return numMatches; } public void setWithoutDirectSpeech(boolean withoutDirectSpeech) { this.withoutDirectSpeech = withoutDirectSpeech; } /* (non-Javadoc) * @see org.languagetool.rules.TextLevelRule#match(java.util.List) */ @Override public RuleMatch[] match(List<AnalyzedSentence> sentences) throws IOException {<FILL_FUNCTION_BODY>} @Override public int minToCheckParagraph() { return -1; } }
List<RuleMatch> ruleMatches = new ArrayList<>(); List<Integer> startPos = new ArrayList<>(); List<Integer> endPos = new ArrayList<>(); List<AnalyzedSentence> relevantSentences = new ArrayList<>(); double percent; int pos = 0; wordCount = 0; boolean excludeDirectSpeech = excludeDirectSpeech(); boolean isDirectSpeech = false; for (AnalyzedSentence sentence : sentences) { AnalyzedTokenReadings[] tokens = sentence.getTokensWithoutWhitespace(); for (int n = 1; n < tokens.length; n++) { AnalyzedTokenReadings token = tokens[n]; String sToken = token.getToken(); if (excludeDirectSpeech && !isDirectSpeech && OPENING_QUOTES.matcher(sToken).matches() && n < tokens.length - 1 && !tokens[n + 1].isWhitespaceBefore()) { isDirectSpeech = true; } else if (excludeDirectSpeech && isDirectSpeech && ENDING_QUOTES.matcher(sToken).matches() && n > 1 && !tokens[n].isWhitespaceBefore()) { isDirectSpeech = false; } else if ((!isDirectSpeech || (minPercent == 0 && !withoutDirectSpeech)) && !token.isWhitespace() && !token.isNonWord()) { wordCount++; int nEnd = conditionFulfilled(tokens, n); if (nEnd >= n) { if (sentenceConditionFulfilled(tokens, n)) { RuleMatch ruleMatch = new RuleMatch(this, sentence, token.getStartPos() + pos, token.getEndPos() + pos, getSentenceMessage()); ruleMatches.add(ruleMatch); } else { startPos.add(token.getStartPos() + pos); endPos.add(tokens[nEnd].getEndPos() + pos); relevantSentences.add(sentence); } } } } pos += sentence.getCorrectedTextLength(); } numMatches = startPos.size() + ruleMatches.size(); if (wordCount > 0) { percent = (numMatches * denominator()) / wordCount; } else { percent = 0; } if (percent > minPercent) { for (int i = 0; i < startPos.size(); i++) { RuleMatch ruleMatch = new RuleMatch(this, relevantSentences.get(i), startPos.get(i), endPos.get(i), getLimitMessage(minPercent, percent)); ruleMatches.add(ruleMatch); } } return toRuleMatchArray(ruleMatches);
1,061
695
1,756
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public int estimateContextForSureMatch() ,public org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>, org.languagetool.markup.AnnotatedText) throws java.io.IOException,public abstract org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>) throws java.io.IOException,public final org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public abstract int minToCheckParagraph() <variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/AbstractSuppressMisspelledSuggestionsFilter.java
AbstractSuppressMisspelledSuggestionsFilter
acceptRuleMatch
class AbstractSuppressMisspelledSuggestionsFilter extends RuleFilter { protected AbstractSuppressMisspelledSuggestionsFilter() { } @Override public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> arguments, int patternTokenPos, AnalyzedTokenReadings[] patternTokens, List<Integer> tokenPositions) throws IOException {<FILL_FUNCTION_BODY>} public boolean isMisspelled(String s, Language language) throws IOException { SpellingCheckRule spellerRule = language.getDefaultSpellingRule(); if (spellerRule == null) { return false; } List<String> tokens = language.getWordTokenizer().tokenize(s); for (String token : tokens) { if (spellerRule.isMisspelled(token)) { return true; }; } return false; } }
RuleMatch ruleMatch = match; Language language = ((PatternRule) match.getRule()).getLanguage(); Tagger tagger = language.getTagger(); List<String> replacements = match.getSuggestedReplacements(); List<String> newReplacements = new ArrayList<>(); String suppressMatch = getRequired("suppressMatch", arguments); String suppressPostag = getOptional("SuppressPostag", arguments); List<AnalyzedTokenReadings> atrs = new ArrayList<>(); if (tagger != null && suppressPostag != null) { atrs = tagger.tag(replacements); } for (int i = 0; i < replacements.size(); i++) { if (!isMisspelled(replacements.get(i), language)) { if (tagger != null && suppressPostag != null) { if (!atrs.get(i).matchesPosTagRegex(suppressPostag)) { newReplacements.add(replacements.get(i)); } } else { newReplacements.add(replacements.get(i)); } } } boolean bSuppressMatch = true; if (suppressMatch != null && suppressMatch.equalsIgnoreCase("false")) { bSuppressMatch = false; } if (newReplacements.isEmpty() && bSuppressMatch) { return null; } else { ruleMatch.setSuggestedReplacements(newReplacements); return ruleMatch; }
230
405
635
<methods>public non-sealed void <init>() ,public abstract org.languagetool.rules.RuleMatch acceptRuleMatch(org.languagetool.rules.RuleMatch, Map<java.lang.String,java.lang.String>, int, org.languagetool.AnalyzedTokenReadings[], List<java.lang.Integer>) throws java.io.IOException,public boolean matches(Map<java.lang.String,java.lang.String>, org.languagetool.AnalyzedTokenReadings[], int, List<java.lang.Integer>) throws java.io.IOException<variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/AbstractTextToNumberFilter.java
AbstractTextToNumberFilter
format
class AbstractTextToNumberFilter extends RuleFilter { protected static Map<String, Float> numbers = new HashMap<>(); protected static Map<String, Float> multipliers = new HashMap<>(); @Override public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> arguments, int patternTokenPos, AnalyzedTokenReadings[] patternTokens, List<Integer> tokenPositions) throws IOException { int posWord = 0; float total = 0; float current = 0; float totalDecimal = 0; float currentDecimal = 0; int addedZeros = 0; boolean percentage = false; boolean decimal = false; while (posWord < patternTokens.length && patternTokens[posWord].getEndPos() <= match.getToPos()) { // inside <marker> if (patternTokens[posWord].getStartPos() >= match.getFromPos() && patternTokens[posWord].getEndPos() <= match.getToPos()) { String form = patternTokens[posWord].getToken().toLowerCase(); if (posWord > 0 && isPercentage(patternTokens, posWord)) { percentage = true; break; } if (isComma(form)) { decimal = true; posWord++; continue; } List<String> forms = tokenize(form); for (String subForm : forms) { if (!decimal) { if (numbers.containsKey(subForm)) { current += numbers.get(subForm); } else if (multipliers.containsKey(subForm)) { if (current == 0) {// mil current = 1; } total += current * multipliers.get(subForm); current = 0; } } else { if (numbers.containsKey(subForm)) { int zerosToAdd = format((numbers.get(subForm)), false).length(); currentDecimal += numbers.get(subForm) / Math.pow(10, addedZeros + zerosToAdd); addedZeros++; } /* else: multipliers after the decimal comma are not expected */ } } } posWord++; } total += current; totalDecimal += currentDecimal; total = total + totalDecimal /* / (Float.toString(totalDecimal).length() + addedZeros) */; RuleMatch ruleMatch = match; String sugg = format(total, percentage); ruleMatch.addSuggestedReplacement(sugg); return ruleMatch; } private String format(float d, boolean percentage) {<FILL_FUNCTION_BODY>} abstract protected boolean isComma(String s); abstract protected boolean isPercentage(AnalyzedTokenReadings[] patternTokens, int i); protected String formatResult(String s) { return s; }; protected List<String> tokenize(String s) { return Collections.singletonList(s); }; }
String result; if (d == (long) d) { result = String.format("%d", (long) d); } else { result = String.format("%s", d); } if (percentage) { result = result + "\u202F%"; // narrow non-breaking space + percentage } return formatResult(result);
780
96
876
<methods>public non-sealed void <init>() ,public abstract org.languagetool.rules.RuleMatch acceptRuleMatch(org.languagetool.rules.RuleMatch, Map<java.lang.String,java.lang.String>, int, org.languagetool.AnalyzedTokenReadings[], List<java.lang.Integer>) throws java.io.IOException,public boolean matches(Map<java.lang.String,java.lang.String>, org.languagetool.AnalyzedTokenReadings[], int, List<java.lang.Integer>) throws java.io.IOException<variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/AbstractWordCoherencyRule.java
AbstractWordCoherencyRule
match
class AbstractWordCoherencyRule extends TextLevelRule { /** * Maps words in both directions, e.g. "aufwendig -&gt; aufwändig" and "aufwändig -&gt; aufwendig". * @since 3.0 */ protected abstract Map<String, Set<String>> getWordMap(); /** * Get the message shown to the user if the rule matches. */ protected abstract String getMessage(String word1, String word2); protected String getShortMessage() { return null; }; public AbstractWordCoherencyRule(ResourceBundle messages) throws IOException { super.setCategory(Categories.MISC.getCategory(messages)); } @Override public RuleMatch[] match(List<AnalyzedSentence> sentences) {<FILL_FUNCTION_BODY>} @Override public int minToCheckParagraph() { return -1; } protected String createReplacement(String marked, String token, String otherSpelling, AnalyzedTokenReadings tmpToken) { return marked.replaceFirst("(?i)" + token, otherSpelling); } }
List<RuleMatch> ruleMatches = new ArrayList<>(); Map<String, String> shouldNotAppearWord = new HashMap<>(); // e.g. aufwändig -> aufwendig int pos = 0; for (AnalyzedSentence sentence : sentences) { AnalyzedTokenReadings[] tokens = sentence.getTokensWithoutWhitespace(); for (AnalyzedTokenReadings tmpToken : tokens) { String token = tmpToken.getToken(); List<AnalyzedToken> readings = tmpToken.getReadings(); if (!readings.isEmpty()) { Set<String> baseforms = readings.stream().map(AnalyzedToken::getLemma).collect(Collectors.toSet()); for (String baseform : baseforms) { if (baseform != null) { token = baseform; } int fromPos = pos + tmpToken.getStartPos(); int toPos = pos + tmpToken.getEndPos(); if (shouldNotAppearWord.containsKey(token)) { String otherSpelling = shouldNotAppearWord.get(token); String msg = getMessage(token, otherSpelling); RuleMatch ruleMatch = new RuleMatch(this, sentence, fromPos, toPos, msg); String marked = sentence.getText().substring(tmpToken.getStartPos(), tmpToken.getEndPos()); String replacement = createReplacement(marked, token, otherSpelling, tmpToken); if (StringTools.startsWithUppercase(tmpToken.getToken())) { replacement = StringTools.uppercaseFirstChar(replacement); } if (!marked.equalsIgnoreCase(replacement)) { // see https://github.com/languagetool-org/languagetool/issues/3493 ruleMatch.setSuggestedReplacement(replacement); ruleMatches.add(ruleMatch); } ruleMatch.setShortMessage(getShortMessage()); break; } else if (getWordMap().containsKey(token)) { Set<String> shouldNotAppearSet = getWordMap().get(token); for (String shouldNotAppear : shouldNotAppearSet) { shouldNotAppearWord.put(shouldNotAppear, token); } } } } } pos += sentence.getCorrectedTextLength(); } return toRuleMatchArray(ruleMatches);
305
611
916
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public int estimateContextForSureMatch() ,public org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>, org.languagetool.markup.AnnotatedText) throws java.io.IOException,public abstract org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>) throws java.io.IOException,public final org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public abstract int minToCheckParagraph() <variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/AdaptSuggestionsFilter.java
AdaptSuggestionsFilter
acceptRuleMatch
class AdaptSuggestionsFilter extends RuleFilter { @Override public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> arguments, int patternTokenPos, AnalyzedTokenReadings[] patternTokens, List<Integer> tokenPositions) throws IOException {<FILL_FUNCTION_BODY>} }
Rule rule = match.getRule(); if (rule instanceof AbstractPatternRule) { List<String> adjustedSuggestions = new ArrayList<>(); Language lang = ((AbstractPatternRule) rule).getLanguage(); for (String replacement : match.getSuggestedReplacements()) { adjustedSuggestions.add(lang.adaptSuggestion(replacement)); } match.setSuggestedReplacements(adjustedSuggestions); return match; } else { return match; }
82
134
216
<methods>public non-sealed void <init>() ,public abstract org.languagetool.rules.RuleMatch acceptRuleMatch(org.languagetool.rules.RuleMatch, Map<java.lang.String,java.lang.String>, int, org.languagetool.AnalyzedTokenReadings[], List<java.lang.Integer>) throws java.io.IOException,public boolean matches(Map<java.lang.String,java.lang.String>, org.languagetool.AnalyzedTokenReadings[], int, List<java.lang.Integer>) throws java.io.IOException<variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/AddCommasFilter.java
AddCommasFilter
acceptRuleMatch
class AddCommasFilter extends RuleFilter { private static final Pattern OPENING_QUOTES = Pattern.compile("[«“\"‘'„¿¡]", Pattern.DOTALL); @Override public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> arguments, int patternTokenPos, AnalyzedTokenReadings[] patternTokens, List<Integer> tokenPositions) throws IOException {<FILL_FUNCTION_BODY>} }
// for patterns ", aun así" suggest "; aun así," and ", aun así," String suggestSemicolon = getOptional("suggestSemicolon", arguments); boolean bSuggestSemicolon = false; if (suggestSemicolon != null && suggestSemicolon.equalsIgnoreCase("true")) { bSuggestSemicolon = true; } AnalyzedTokenReadings[] tokens = match.getSentence().getTokensWithoutWhitespace(); int postagFrom = 1; while (postagFrom < tokens.length && tokens[postagFrom].getStartPos() < match.getFromPos()) { postagFrom++; } int postagTo = postagFrom; while (postagTo < tokens.length && tokens[postagTo].getEndPos() < match.getToPos()) { postagTo++; } boolean beforeOK = (postagFrom == 1) || StringTools.isPunctuationMark(tokens[postagFrom - 1].getToken()) || StringTools.isCapitalizedWord(tokens[postagFrom].getToken()); boolean afterOK = !(postagTo + 1 > tokens.length - 1) && StringTools.isPunctuationMark(tokens[postagTo + 1].getToken()) && !(tokens[postagTo + 1].isWhitespaceBefore() && OPENING_QUOTES.matcher(tokens[postagTo + 1].getToken()).matches()); if (beforeOK && afterOK) { return null; } RuleMatch newMatch = null; if (bSuggestSemicolon && tokens[postagFrom - 1].getToken().equals(",") && !afterOK) { newMatch = new RuleMatch(match.getRule(), match.getSentence(), tokens[postagFrom - 1].getStartPos(), tokens[postagTo].getEndPos(), match.getMessage(), match.getShortMessage()); newMatch.addSuggestedReplacement( "; " + match.getSentence().getText().substring(match.getFromPos(), match.getToPos()) + ","); newMatch.addSuggestedReplacement( ", " + match.getSentence().getText().substring(match.getFromPos(), match.getToPos()) + ","); } else if (beforeOK && !afterOK) { newMatch = new RuleMatch(match.getRule(), match.getSentence(), tokens[postagTo].getStartPos(), match.getToPos(), match.getMessage(), match.getShortMessage()); newMatch.setSuggestedReplacement(tokens[postagTo].getToken() + ","); } else if (!beforeOK && afterOK) { int startPos = tokens[postagFrom].getStartPos(); if (tokens[postagFrom].isWhitespaceBefore()) { startPos--; } newMatch = new RuleMatch(match.getRule(), match.getSentence(), startPos, tokens[postagFrom].getEndPos(), match.getMessage(), match.getShortMessage()); newMatch.setSuggestedReplacement(", " + tokens[postagFrom].getToken()); } else if (!beforeOK && !afterOK) { int startPos = tokens[postagFrom].getStartPos(); if (tokens[postagFrom].isWhitespaceBefore()) { startPos--; } newMatch = new RuleMatch(match.getRule(), match.getSentence(), startPos, tokens[postagTo].getEndPos(), match.getMessage(), match.getShortMessage()); newMatch.setSuggestedReplacement( ", " + match.getSentence().getText().substring(match.getFromPos(), match.getToPos()) + ","); } return newMatch;
123
942
1,065
<methods>public non-sealed void <init>() ,public abstract org.languagetool.rules.RuleMatch acceptRuleMatch(org.languagetool.rules.RuleMatch, Map<java.lang.String,java.lang.String>, int, org.languagetool.AnalyzedTokenReadings[], List<java.lang.Integer>) throws java.io.IOException,public boolean matches(Map<java.lang.String,java.lang.String>, org.languagetool.AnalyzedTokenReadings[], int, List<java.lang.Integer>) throws java.io.IOException<variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/BERTSuggestionRanking.java
MatchesForReordering
buildRequest
class MatchesForReordering extends RemoteRequest { final List<AnalyzedSentence> sentences; final List<RuleMatch> matches; final List<RemoteLanguageModel.Request> requests; MatchesForReordering(List<AnalyzedSentence> sentences, List<RuleMatch> matches, List<RemoteLanguageModel.Request> requests) { this.sentences = sentences; this.matches = matches; this.requests = requests; } } /** * transform suggestions before resorting, e.g. limit resorting to top-n candidates * @return transformed suggestions */ protected List<SuggestedReplacement> prepareSuggestions(List<SuggestedReplacement> suggestions) { // include more suggestions for resorting if there are translations included as original order isn't that good if (suggestions.stream().anyMatch(s -> s.getType() == SuggestedReplacement.SuggestionType.Translation)) { suggestionLimit = 25; } else { suggestionLimit = 10; } return suggestions.subList(0, Math.min(suggestions.size(), suggestionLimit)); } private static final int MIN_WORDS = 8; private static final double MAX_ERROR_RATE = 0.5; @Override protected RemoteRequest prepareRequest(List<AnalyzedSentence> sentences, Long textSessionId) { List<RuleMatch> matches = new LinkedList<>(); int totalWords = 0; try { for (AnalyzedSentence sentence : sentences) { RuleMatch[] sentenceMatches = wrappedRule.match(sentence); Collections.addAll(matches, sentenceMatches); // computing many suggestions (e.g. for requests with the language incorrectly set, or with garbled input) is very expensive // having this as a RemoteRule circumvents the normal ErrorRateTooHighException // so build this logic again here int words = sentence.getTokensWithoutWhitespace().length; totalWords += words; if (words > MIN_WORDS && (double) sentenceMatches.length / words > MAX_ERROR_RATE) { for (RuleMatch m : sentenceMatches) { m.discardLazySuggestedReplacements(); } logger.info("Skipping suggestion generation for sentence, too many matches ({} matches in {} words)", sentenceMatches.length, words); } } } catch (IOException e) { logger.error("Error while executing rule " + wrappedRule.getId(), e); return new MatchesForReordering(sentences, Collections.emptyList(), Collections.emptyList()); } if (totalWords > MIN_WORDS && (double) matches.size() / totalWords > MAX_ERROR_RATE) { logger.info("Skipping suggestion generation for request, too many matches ({} matches in {} words)", matches.size(), totalWords); matches.forEach(RuleMatch::discardLazySuggestedReplacements); return new MatchesForReordering(sentences, matches, Collections.emptyList()); } List<RemoteLanguageModel.Request> requests = new LinkedList<>(); for (RuleMatch match : matches) { match.setSuggestedReplacementObjects(prepareSuggestions(match.getSuggestedReplacementObjects())); requests.add(buildRequest(match)); } return new MatchesForReordering(sentences, matches, requests); } @Override protected RemoteRuleResult fallbackResults(RemoteRequest request) { MatchesForReordering req = (MatchesForReordering) request; return new RemoteRuleResult(false, false, req.matches, req.sentences); } @Override protected Callable<RemoteRuleResult> executeRequest(RemoteRequest request, long timeoutMilliseconds) throws TimeoutException { return () -> { if (model == null) { return fallbackResults(request); } MatchesForReordering data = (MatchesForReordering) request; List<RuleMatch> matches = data.matches; List<RemoteLanguageModel.Request> requests = data.requests; Streams.FunctionWithIndex<RemoteLanguageModel.Request, Long> mapIndices = (req, index) -> req != null ? index : null; List<Long> indices = Streams.mapWithIndex(requests.stream(), mapIndices) .filter(Objects::nonNull).collect(Collectors.toList()); requests = requests.stream().filter(Objects::nonNull).collect(Collectors.toList()); if (requests.isEmpty()) { return new RemoteRuleResult(false, true, matches, data.sentences); } else { List<List<Double>> results = model.batchScore(requests, timeoutMilliseconds); // put curated at the top, then compare probabilities for (int i = 0; i < indices.size(); i++) { List<Double> scores = results.get(i); String userWord = requests.get(i).text.substring(requests.get(i).start, requests.get(i).end); RuleMatch match = matches.get(indices.get(i).intValue()); //RemoteLanguageModel.Request req = requests.get(i); //String error = req.text.substring(req.start, req.end); //logger.info("Scored suggestions for '{}': {} -> {}", error, match.getSuggestedReplacements(), Streams // .zip(match.getSuggestedReplacementObjects().stream(), scores.stream(), Pair::of) // .sorted(new CuratedAndSameCaseComparator(userWord)) // .map(scored -> String.format("%s (%e)", scored.getLeft().getReplacement(), scored.getRight())) // .collect(Collectors.toList())); List<SuggestedReplacement> ranked = Streams .zip(match.getSuggestedReplacementObjects().stream(), scores.stream(), Pair::of) .sorted(new CuratedAndSameCaseComparator(userWord)) .map(Pair::getLeft) .collect(Collectors.toList()); //logger.info("Reordered correction for '{}' from {} to {}", error, req.candidates, ranked); match.setSuggestedReplacementObjects(ranked); } return new RemoteRuleResult(true, true, matches, data.sentences); } }; } @Nullable private RemoteLanguageModel.Request buildRequest(RuleMatch match) {<FILL_FUNCTION_BODY>
List<String> suggestions = match.getSuggestedReplacements(); if (suggestions != null && suggestions.size() > 1) { return new RemoteLanguageModel.Request( match.getSentence().getText(), match.getFromPos(), match.getToPos(), suggestions); } else { return null; }
1,652
87
1,739
<methods>public void <init>(org.languagetool.Language, java.util.ResourceBundle, org.languagetool.rules.RemoteRuleConfig, boolean, java.lang.String) ,public void <init>(org.languagetool.Language, java.util.ResourceBundle, org.languagetool.rules.RemoteRuleConfig, boolean) ,public CircuitBreaker circuitBreaker() ,public static void fixMatchOffsets(org.languagetool.AnalyzedSentence, List<org.languagetool.rules.RuleMatch>) ,public java.lang.String getId() ,public org.languagetool.rules.RemoteRuleConfig getServiceConfiguration() ,public long getTimeout(long) ,public boolean isPremium() ,public org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public FutureTask<org.languagetool.rules.RemoteRuleResult> run(List<org.languagetool.AnalyzedSentence>) ,public FutureTask<org.languagetool.rules.RemoteRuleResult> run(List<org.languagetool.AnalyzedSentence>, java.lang.Long) ,public static void shutdown() <variables>protected static final ConcurrentMap<java.lang.String,CircuitBreaker> circuitBreakers,protected final non-sealed boolean filterMatches,protected final non-sealed boolean fixOffsets,protected final non-sealed boolean inputLogging,private static final Logger logger,protected final non-sealed org.languagetool.JLanguageTool lt,protected final non-sealed boolean premium,protected final non-sealed org.languagetool.Language ruleLanguage,protected final non-sealed org.languagetool.rules.RemoteRuleConfig serviceConfiguration,protected static final List<java.lang.Runnable> shutdownRoutines,protected final non-sealed java.util.regex.Pattern suppressMisspelledMatch,protected final non-sealed java.util.regex.Pattern suppressMisspelledSuggestions,protected final non-sealed boolean whitespaceNormalisation
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/CategoryId.java
CategoryId
equals
class CategoryId { private final String id; public CategoryId(String id) { Objects.requireNonNull(id, "Category id must not be null."); if (id.trim().isEmpty()) { throw new IllegalArgumentException("Category id must not be empty: '" + id + "'"); } this.id = id; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return id.hashCode(); } @Override public String toString() { return id; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CategoryId other = (CategoryId) o; return id.equals(other.id);
163
58
221
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/CleanOverlappingFilter.java
CleanOverlappingFilter
filter
class CleanOverlappingFilter implements RuleMatchFilter { private static final int negativeConstant = Integer.MIN_VALUE + 10000; private final Language language; private final boolean hidePremiumMatches; public CleanOverlappingFilter(Language lang, boolean hidePremiumMatches) { this.language = lang; this.hidePremiumMatches = hidePremiumMatches; } @Override public final List<RuleMatch> filter(List<RuleMatch> ruleMatches) {<FILL_FUNCTION_BODY>} protected boolean isPremiumRule(RuleMatch ruleMatch) { return Premium.get().isPremiumRule(ruleMatch.getRule()); } }
List<RuleMatch> cleanList = new ArrayList<>(); RuleMatch prevRuleMatch = null; for (RuleMatch ruleMatch: ruleMatches) { if (prevRuleMatch == null) { // first item prevRuleMatch = ruleMatch; continue; } if (ruleMatch.getFromPos() < prevRuleMatch.getFromPos()) { throw new IllegalArgumentException( "The list of rule matches is not ordered. Make sure it is sorted by start position."); } boolean isDuplicateSuggestion = false; if (ruleMatch.getSuggestedReplacements().size() > 0 && prevRuleMatch.getSuggestedReplacements().size() > 0) { String suggestion = ruleMatch.getSuggestedReplacements().get(0); String prevSuggestion = prevRuleMatch.getSuggestedReplacements().get(0); // juxtaposed errors adding a comma in the same place if (ruleMatch.getFromPos() == prevRuleMatch.getToPos()) { if (prevSuggestion.endsWith(",") && suggestion.startsWith(", ")) { isDuplicateSuggestion = true; } } // duplicate suggestion for the same position if (suggestion.indexOf(" ") > 0 && prevSuggestion.indexOf(" ") > 0 && ruleMatch.getFromPos() == prevRuleMatch.getToPos() + 1) { String parts[] = suggestion.split(" "); String partsPrev[] = prevSuggestion.split(" "); if (partsPrev.length > 1 && parts.length > 1 && partsPrev[1].equals(parts[0])) { isDuplicateSuggestion = true; } } } // no overlapping (juxtaposed errors are not removed) if (ruleMatch.getFromPos() >= prevRuleMatch.getToPos() && !isDuplicateSuggestion) { cleanList.add(prevRuleMatch); prevRuleMatch = ruleMatch; continue; } // overlapping int currentPriority = language.getRulePriority(ruleMatch.getRule()); if (isPremiumRule(ruleMatch) && hidePremiumMatches) { // non-premium match should win, so the premium match does *not* become a hidden match // (we'd show hidden matches for errors covered by an Open Source match) currentPriority = Integer.MIN_VALUE; } if (ruleMatch.getRule().getTags().contains(Tag.picky) && currentPriority != Integer.MIN_VALUE) { currentPriority += negativeConstant; } int prevPriority = language.getRulePriority(prevRuleMatch.getRule()); if (isPremiumRule(prevRuleMatch) && hidePremiumMatches) { prevPriority = Integer.MIN_VALUE; } if (prevRuleMatch.getRule().getTags().contains(Tag.picky) && prevPriority != Integer.MIN_VALUE) { prevPriority += negativeConstant; } if (currentPriority == prevPriority) { // take the longest error: currentPriority = ruleMatch.getToPos() - ruleMatch.getFromPos(); prevPriority = prevRuleMatch.getToPos() - prevRuleMatch.getFromPos(); } if (currentPriority == prevPriority) { currentPriority++; // take the last one (to keep the current results in the web UI) } if (currentPriority > prevPriority) { prevRuleMatch = ruleMatch; } } //last match if (prevRuleMatch != null) { cleanList.add(prevRuleMatch); } return cleanList;
181
912
1,093
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/CompoundRuleData.java
CompoundRuleData
loadCompoundFile
class CompoundRuleData { private final Set<String> incorrectCompounds = new ObjectOpenHashSet<>(); private final Set<String> joinedSuggestion = new ObjectOpenHashSet<>(); private final Set<String> joinedLowerCaseSuggestion = new ObjectOpenHashSet<>(); private final Set<String> dashSuggestion = new ObjectOpenHashSet<>(); private final LineExpander expander; public CompoundRuleData(String path) { this(new String[] {path}); } public CompoundRuleData(String... paths) { this(null, paths); } public CompoundRuleData(LineExpander expander, String... paths) { this.expander = expander; for (String path : paths) { try { loadCompoundFile(path); } catch (IOException e) { throw new RuntimeException("Could not load compound data from " + path, e); } } } public Set<String> getIncorrectCompounds() { return Collections.unmodifiableSet(incorrectCompounds); } public Set<String> getJoinedSuggestion() { return Collections.unmodifiableSet(joinedSuggestion); } public Set<String> getDashSuggestion() { return Collections.unmodifiableSet(dashSuggestion); } public Set<String> getJoinedLowerCaseSuggestion() { return Collections.unmodifiableSet(joinedLowerCaseSuggestion); } private void loadCompoundFile(String path) throws IOException {<FILL_FUNCTION_BODY>} private void validateLine(String path, String line) { String[] parts = line.split(" "); if (parts.length == 1) { throw new IllegalArgumentException("Not a compound in file " + path + ": " + line); } if (parts.length > AbstractCompoundRule.MAX_TERMS) { throw new IllegalArgumentException("Too many compound parts in file " + path + ": " + line + ", maximum allowed: " + AbstractCompoundRule.MAX_TERMS); } if (incorrectCompounds.contains(line.toLowerCase())) { throw new IllegalArgumentException("Duplicated word in file " + path + ": " + line); } } private String removeLastCharacter(String str) { return str.substring(0, str.length() - 1); } }
List<String> lines = JLanguageTool.getDataBroker().getFromResourceDirAsLines(path); for (String line : lines) { if (line.isEmpty() || line.startsWith("#")) { continue; // ignore comments } line = line.replaceFirst("#.*$", "").trim(); List<String> expandedLines = new ArrayList<>(); if (expander != null) { expandedLines = expander.expandLine(line); } else { expandedLines.add(line); } for (String expLine : expandedLines) { expLine = expLine.replace('-', ' '); // the set contains the incorrect spellings, i.e. the ones without hyphen validateLine(path, expLine); if (expLine.endsWith("+")) { expLine = removeLastCharacter(expLine); joinedSuggestion.add(expLine); } else if (expLine.endsWith("*")) { expLine = removeLastCharacter(expLine); dashSuggestion.add(expLine); } else if (expLine.endsWith("?")) { // github issue #779 expLine = removeLastCharacter(expLine); joinedSuggestion.add(expLine); joinedLowerCaseSuggestion.add(expLine); } else if (expLine.endsWith("$")) { // github issue #779 expLine = removeLastCharacter(expLine); joinedSuggestion.add(expLine); dashSuggestion.add(expLine); joinedLowerCaseSuggestion.add(expLine); } else { joinedSuggestion.add(expLine); dashSuggestion.add(expLine); } incorrectCompounds.add(expLine); } }
622
457
1,079
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/ConfusionPair.java
ConfusionPair
getUppercaseFirstCharTerms
class ConfusionPair { private final ConfusionString term1; private final ConfusionString term2; private final long factor; private final boolean bidirectional; public ConfusionPair(ConfusionString cs1, ConfusionString cs2, long factor, boolean bidirectional) { this.term1 = Objects.requireNonNull(cs1); this.term2 = Objects.requireNonNull(cs2); if (factor < 1) { throw new IllegalArgumentException("factor must be >= 1: " + factor); } this.factor = factor; this.bidirectional = bidirectional; } public ConfusionPair(String token1, String token2, Long factor, boolean bidirectional) { term1 = new ConfusionString(token1, null); term2 = new ConfusionString(token2, null); if (factor < 1) { throw new IllegalArgumentException("factor must be >= 1: " + factor); } this.factor = factor; this.bidirectional = bidirectional; } /* Alternative must be at least this much more probable to be considered correct. */ public long getFactor() { return factor; } /* If true, only direction term1 -> term2 is possible, i.e. if term1 is used incorrectly, term2 is suggested - not vice versa. */ public boolean isBidirectional() { return bidirectional; } public ConfusionString getTerm1() { return term1; } public ConfusionString getTerm2() { return term2; } public List<ConfusionString> getTerms() { return Collections.unmodifiableList(Arrays.asList(term1, term2)); } public List<ConfusionString> getUppercaseFirstCharTerms() {<FILL_FUNCTION_BODY>} @Override public String toString() { return term1 + (bidirectional ? "; " : " -> ") + term2; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ConfusionPair that = (ConfusionPair) o; return factor == that.factor && bidirectional == that.bidirectional && term1.equals(that.term1) && term2.equals(that.term2); } @Override public int hashCode() { return Objects.hash(term1, term2, factor, bidirectional); } }
List<ConfusionString> result = new ArrayList<>(); result.add(new ConfusionString(StringTools.uppercaseFirstChar(term1.getString()), term1.getDescription())); result.add(new ConfusionString(StringTools.uppercaseFirstChar(term2.getString()), term2.getDescription())); return Collections.unmodifiableList(result);
670
90
760
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/ConfusionSet.java
ConfusionSet
equals
class ConfusionSet { private final Set<ConfusionString> set = new HashSet<>(); private final long factor; /** * @param factor the factor that one string must be more probable than the other to be considered a correction, must be &gt;= 1 */ public ConfusionSet(long factor, List<ConfusionString> confusionStrings) { if (factor < 1) { throw new IllegalArgumentException("factor must be >= 1: " + factor); } this.factor = factor; set.addAll(Objects.requireNonNull(confusionStrings)); } /** * @param factor the factor that one string must be more probable than the other to be considered a correction, must be &gt;= 1 */ public ConfusionSet(long factor, String... words) { if (factor < 1) { throw new IllegalArgumentException("factor must be >= 1: " + factor); } Objects.requireNonNull(words); this.factor = factor; for (String word : words) { set.add(new ConfusionString(word, null)); } } /* Alternative must be at least this much more probable to be considered correct. */ public long getFactor() { return factor; } public Set<ConfusionString> getSet() { return Collections.unmodifiableSet(set); } public Set<ConfusionString> getUppercaseFirstCharSet() { Set<ConfusionString> result = new HashSet<>(); for (ConfusionString s : set) { ConfusionString newString = new ConfusionString(StringTools.uppercaseFirstChar(s.getString()), s.getDescription()); result.add(newString); } return Collections.unmodifiableSet(result); } @Override public String toString() { return set.toString(); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(set, factor); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ConfusionSet other = (ConfusionSet) o; return Objects.equals(set, other.set) && Objects.equals(factor, other.factor);
533
75
608
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/ConfusionSetLoader.java
ConfusionSetLoader
loadConfusionPairs
class ConfusionSetLoader { private static final String CHARSET = "utf-8"; private final ShortDescriptionProvider wordDefs; private final Language lang; public ConfusionSetLoader(Language lang) { wordDefs = new ShortDescriptionProvider(); this.lang = Objects.requireNonNull(lang); } public Map<String,List<ConfusionPair>> loadConfusionPairs(InputStream stream) throws IOException {<FILL_FUNCTION_BODY>} private void addToMap(Map<String, List<ConfusionPair>> map, List<ConfusionString> confusionStrings, ConfusionPair confusionSet) { for (ConfusionString confusionString : confusionStrings) { String key = confusionString.getString(); List<ConfusionPair> existingEntry = map.get(key); if (existingEntry != null) { existingEntry.add(confusionSet); } else { List<ConfusionPair> pairs = new ArrayList<>(); pairs.add(confusionSet); map.put(key, pairs); } } } }
Map<String,List<ConfusionPair>> map = new HashMap<>(); try ( InputStreamReader reader = new InputStreamReader(stream, CHARSET); BufferedReader br = new BufferedReader(reader) ) { String line; while ((line = br.readLine()) != null) { if (line.startsWith("#") || line.trim().isEmpty()) { continue; } String[] parts = line.replaceFirst("\\s*#.*", "").split("\\s*(;|->)\\s*"); if (parts.length != 3) { throw new RuntimeException("Unexpected format: '" + line + "' - expected three semicolon-separated values: word1; word2; factor"); } boolean bidirectional = !line.replaceFirst("#.*", "").contains(" -> "); List<ConfusionString> confusionStrings = new ArrayList<>(); Set<String> loadedForSet = new HashSet<>(); String prevWord = null; for (String part : Arrays.asList(parts).subList(0, parts.length - 1)) { String[] subParts = part.split("\\|"); String word = subParts[0]; if (bidirectional && prevWord != null && word.compareTo(prevWord) < 0) { // Quick hack for reordering lines //System.err.println("Delete: " + line); //String comment = line.substring(line.indexOf("#")); //String newLine = parts[1] + "; " + parts[0] + "; " + parts[2] + "; " + comment; //System.err.println("Add: " + newLine); throw new RuntimeException("Order words alphabetically per line in the confusion set file: " + line + ": found " + word + " after " + prevWord); } prevWord = word; String description = subParts.length == 2 ? subParts[1] : null; if (loadedForSet.contains(word)) { throw new RuntimeException("Word appears twice in same confusion set: '" + word + "'"); } if (description == null) { description = wordDefs.getShortDescription(word, lang); } confusionStrings.add(new ConfusionString(word, description)); loadedForSet.add(word); } long factor = Long.parseLong(parts[parts.length - 1]); if (bidirectional) { ConfusionPair confusionSet1 = new ConfusionPair(confusionStrings.get(0), confusionStrings.get(1), factor, false); addToMap(map, confusionStrings, confusionSet1); ConfusionPair confusionSet2 = new ConfusionPair(confusionStrings.get(1), confusionStrings.get(0), factor, false); addToMap(map, confusionStrings, confusionSet2); } else { ConfusionPair confusionSet = new ConfusionPair(confusionStrings.get(0), confusionStrings.get(1), factor, false); addToMap(map, confusionStrings, confusionSet); } } } return map;
276
785
1,061
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/ConfusionString.java
ConfusionString
equals
class ConfusionString { private final String str; private final String description; ConfusionString(String str, String description) { this.str = Objects.requireNonNull(str); this.description = description; } public String getString() { return str; } @Nullable public String getDescription() { return description; } @Override public String toString() { return str; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(str, description); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ConfusionString other = (ConfusionString) o; return Objects.equals(str, other.str) && Objects.equals(description, other.description);
177
75
252
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/ConvertToSentenceCaseFilter.java
ConvertToSentenceCaseFilter
normalizedCase
class ConvertToSentenceCaseFilter extends RuleFilter { @Override public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> arguments, int patternTokenPos, AnalyzedTokenReadings[] patternTokens, List<Integer> tokenPositions) throws IOException { RuleMatch ruleMatch = match; boolean firstDone = false; StringBuilder replacement = new StringBuilder(); StringBuilder originalStr = new StringBuilder(); for (int i = patternTokenPos; i < patternTokens.length; i++) { if (patternTokens[i].getStartPos() < match.getFromPos() || patternTokens[i].getEndPos() > match.getToPos()) { continue; } String normalizedCase = normalizedCase(patternTokens[i]); if (i + 1 < patternTokens.length && patternTokens[i + 1].getToken().equals(".")) { if (normalizedCase.length() == 1) { normalizedCase = normalizedCase.toUpperCase(); } else if (normalizedCase.equals("corp")) { normalizedCase = "Corp"; } } String tokenString = patternTokens[i].getToken(); String tokenCapitalized = StringTools.uppercaseFirstChar(normalizedCase); if (!firstDone & !isPunctuation(tokenString) && !tokenString.isEmpty()) { firstDone = true; replacement.append(tokenCapitalized); originalStr.append(tokenString); } else { if (patternTokens[i].isWhitespaceBefore()) { replacement.append(" "); originalStr.append(" "); } replacement.append(normalizedCase); originalStr.append(tokenString); } } if (replacement.toString().equals(originalStr.toString())) { return null; } ruleMatch.setSuggestedReplacement(replacement.toString()); return ruleMatch; } private boolean isPunctuation(String s) { return Pattern.matches("\\p{IsPunctuation}", s); } private String normalizedCase(AnalyzedTokenReadings atr) {<FILL_FUNCTION_BODY>} protected boolean tokenIsException(String s) { return false; } }
String tokenLowercase = atr.getToken().toLowerCase(); if (atr.hasTypographicApostrophe()) { tokenLowercase = tokenLowercase.replaceAll("'", "’"); } if (tokenIsException(tokenLowercase)) { // exception: the lemma is "I" return tokenLowercase; } String tokenCapitalized = StringTools.uppercaseFirstChar(tokenLowercase); //boolean lemmaIsAllUppercase = false; boolean lemmaIsCapitalized = false; boolean lemmaIsLowercase = false; for (AnalyzedToken at : atr) { if (at.hasNoTag() || at.getLemma() == null) { return tokenCapitalized; } // for multi-words lemmas, take the first word String lemma = at.getLemma().split(" ")[0]; //lemmaIsAllUppercase = lemmaIsAllUppercase || StringTools.isAllUppercase(lemma); lemmaIsCapitalized = lemmaIsCapitalized || StringTools.isCapitalizedWord(lemma); lemmaIsLowercase = lemmaIsLowercase || !StringTools.isNotAllLowercase(lemma); } if (lemmaIsLowercase) { return tokenLowercase; } if (lemmaIsCapitalized) { return tokenCapitalized; } return atr.getToken();
570
350
920
<methods>public non-sealed void <init>() ,public abstract org.languagetool.rules.RuleMatch acceptRuleMatch(org.languagetool.rules.RuleMatch, Map<java.lang.String,java.lang.String>, int, org.languagetool.AnalyzedTokenReadings[], List<java.lang.Integer>) throws java.io.IOException,public boolean matches(Map<java.lang.String,java.lang.String>, org.languagetool.AnalyzedTokenReadings[], int, List<java.lang.Integer>) throws java.io.IOException<variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/DateRangeChecker.java
DateRangeChecker
acceptRuleMatch
class DateRangeChecker extends RuleFilter { @Nullable @Override public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> arguments, int patternTokenPos, AnalyzedTokenReadings[] patternTokens, List<Integer> tokenPositions) {<FILL_FUNCTION_BODY>} }
try { int x = Integer.parseInt(arguments.get("x")); int y = Integer.parseInt(arguments.get("y")); if (x >= y) { return match; } } catch (IllegalArgumentException ignore) { // if something's fishy with the number – ignore it silently, // it's not a date range return null; } return null;
77
109
186
<methods>public non-sealed void <init>() ,public abstract org.languagetool.rules.RuleMatch acceptRuleMatch(org.languagetool.rules.RuleMatch, Map<java.lang.String,java.lang.String>, int, org.languagetool.AnalyzedTokenReadings[], List<java.lang.Integer>) throws java.io.IOException,public boolean matches(Map<java.lang.String,java.lang.String>, org.languagetool.AnalyzedTokenReadings[], int, List<java.lang.Integer>) throws java.io.IOException<variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/DemoRule.java
DemoRule
match
class DemoRule extends Rule { @Override public String getId() { return "DEMO_RULE"; // a unique id that doesn't change over time } @Override public String getDescription() { return "A demo rule that just prints the text analysis"; // shown in the configuration dialog } // This is the method with the error detection logic that you need to implement: @Override public RuleMatch[] match(AnalyzedSentence sentence) throws IOException {<FILL_FUNCTION_BODY>} }
List<RuleMatch> ruleMatches = new ArrayList<>(); // Let's get all the tokens (i.e. words) of this sentence, but not the spaces: AnalyzedTokenReadings[] tokens = sentence.getTokensWithoutWhitespace(); // No let's iterate over those - note that the first token will // be a special token that indicates the start of a sentence: for (AnalyzedTokenReadings token : tokens) { System.out.println("Token: " + token.getToken()); // the original word from the input text // A word can have more than one reading, e.g. 'dance' can be a verb or a noun, // so we iterate over the readings: for (AnalyzedToken analyzedToken : token.getReadings()) { System.out.println(" Lemma: " + analyzedToken.getLemma()); System.out.println(" POS: " + analyzedToken.getPOSTag()); } // You can add your own logic here to find errors. Here, we just consider // the word "demo" an error and create a rule match that LanguageTool will // then show to the user: if (token.getToken().equals("demo")) { RuleMatch ruleMatch = new RuleMatch(this, sentence, token.getStartPos(), token.getEndPos(), "The demo rule thinks this looks wrong"); ruleMatch.setSuggestedReplacement("blablah"); // the user will see this as a suggested correction ruleMatches.add(ruleMatch); } } return toRuleMatchArray(ruleMatches);
139
402
541
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public void addTags(List<java.lang.String>) ,public void addToneTags(List<java.lang.String>) ,public int estimateContextForSureMatch() ,public List<org.languagetool.tagging.disambiguation.rules.DisambiguationPatternRule> getAntiPatterns() ,public org.languagetool.rules.Category getCategory() ,public java.lang.String getConfigureText() ,public final List<org.languagetool.rules.CorrectExample> getCorrectExamples() ,public int getDefaultValue() ,public abstract java.lang.String getDescription() ,public int getDistanceTokens() ,public final List<org.languagetool.rules.ErrorTriggeringExample> getErrorTriggeringExamples() ,public java.lang.String getFullId() ,public abstract java.lang.String getId() ,public final List<org.languagetool.rules.IncorrectExample> getIncorrectExamples() ,public org.languagetool.rules.ITSIssueType getLocQualityIssueType() ,public int getMaxConfigurableValue() ,public int getMinConfigurableValue() ,public int getMinPrevMatches() ,public int getPriority() ,public java.lang.String getSourceFile() ,public java.lang.String getSubId() ,public List<org.languagetool.Tag> getTags() ,public List<org.languagetool.ToneTag> getToneTags() ,public java.net.URL getUrl() ,public boolean hasConfigurableValue() ,public boolean hasTag(org.languagetool.Tag) ,public boolean hasToneTag(org.languagetool.ToneTag) ,public final boolean isDefaultOff() ,public final boolean isDefaultTempOff() ,public boolean isDictionaryBasedSpellingRule() ,public boolean isGoalSpecific() ,public final boolean isOfficeDefaultOff() ,public final boolean isOfficeDefaultOn() ,public boolean isPremium() ,public abstract org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public final void setCategory(org.languagetool.rules.Category) ,public final void setCorrectExamples(List<org.languagetool.rules.CorrectExample>) ,public final void setDefaultOff() ,public final void setDefaultOn() ,public final void setDefaultTempOff() ,public void setDistanceTokens(int) ,public final void setErrorTriggeringExamples(List<org.languagetool.rules.ErrorTriggeringExample>) ,public void setGoalSpecific(boolean) ,public final void setIncorrectExamples(List<org.languagetool.rules.IncorrectExample>) ,public void setLocQualityIssueType(org.languagetool.rules.ITSIssueType) ,public void setMinPrevMatches(int) ,public final void setOfficeDefaultOff() ,public final void setOfficeDefaultOn() ,public void setPremium(boolean) ,public void setPriority(int) ,public void setTags(List<org.languagetool.Tag>) ,public void setToneTags(List<org.languagetool.ToneTag>) ,public void setUrl(java.net.URL) ,public boolean supportsLanguage(org.languagetool.Language) ,public boolean useInOffice() <variables>private static final org.languagetool.rules.Category MISC,private org.languagetool.rules.Category category,private List<org.languagetool.rules.CorrectExample> correctExamples,private boolean defaultOff,private boolean defaultTempOff,private int distanceTokens,private List<org.languagetool.rules.ErrorTriggeringExample> errorTriggeringExamples,private List<org.languagetool.rules.IncorrectExample> incorrectExamples,private boolean isGoalSpecific,private boolean isPremium,private org.languagetool.rules.ITSIssueType locQualityIssueType,protected final non-sealed java.util.ResourceBundle messages,private int minPrevMatches,private boolean officeDefaultOff,private boolean officeDefaultOn,private int priority,private List<org.languagetool.Tag> tags,private List<org.languagetool.ToneTag> toneTags,private java.net.URL url
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/DictionaryMatchFilter.java
DictionaryMatchFilter
filter
class DictionaryMatchFilter implements RuleMatchFilter { private final UserConfig userConfig; public DictionaryMatchFilter(UserConfig userConfig) { this.userConfig = userConfig; } @Override public List<RuleMatch> filter(List<RuleMatch> ruleMatches, AnnotatedText text) {<FILL_FUNCTION_BODY>} }
Set<String> dictionary = new HashSet<>(userConfig.getAcceptedWords()); return ruleMatches.stream().filter(match -> { // at this point, the offsets we get from match are already converted to be pointing to the text with markup // so we need to compute the substring based on that // using anything else leads to StringIndexOutOfBoundsErrors or getting the wrong text // if there's no markup, this is just equal to the original text String covered = text.getTextWithMarkup().substring(match.getFromPos(), match.getToPos()); return !dictionary.contains(covered); }).collect(Collectors.toList());
91
170
261
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/DictionarySpellMatchFilter.java
PhraseSearchLoader
getPhrases
class PhraseSearchLoader extends CacheLoader<UserConfig, AhoCorasickDoubleArrayTrie<String>> { @Override public AhoCorasickDoubleArrayTrie<String> load(UserConfig key) throws Exception { AhoCorasickDoubleArrayTrie<String> searcher = new AhoCorasickDoubleArrayTrie<>(); Map<String, String> phrases = new HashMap<>(); for (String phrase : key.getAcceptedPhrases()) { phrases.put(phrase, phrase); } searcher.build(phrases); return searcher; } } private static final LoadingCache<UserConfig, AhoCorasickDoubleArrayTrie<String>> phraseSearcher = CacheBuilder.newBuilder().recordStats() .maximumSize(CACHE_SIZE) .expireAfterAccess(CACHE_TTL_SECONDS, TimeUnit.SECONDS) .build(new PhraseSearchLoader()); public DictionarySpellMatchFilter(UserConfig userConfig) { this.userConfig = userConfig; } @Override public List<RuleMatch> filter(List<RuleMatch> ruleMatches, AnnotatedText text) { Set<String> dictionary = userConfig.getAcceptedPhrases(); if (dictionary.size() > 0) { List<RuleMatch> cleanMatches = new ArrayList<>(ruleMatches); try { AhoCorasickDoubleArrayTrie<String> searcher = phraseSearcher.get(userConfig); List<AhoCorasickDoubleArrayTrie.Hit<String>> phrases = searcher.parseText(text.getPlainText()); for (AhoCorasickDoubleArrayTrie.Hit<String> phrase : phrases) { Iterator<RuleMatch> iter = cleanMatches.iterator(); while (iter.hasNext()) { RuleMatch match = iter.next(); if (match.getRule().isDictionaryBasedSpellingRule() && match.getFromPos() >= phrase.begin && match.getToPos() <= phrase.end) { // remove all spelling matches that are (subsets) of accepted phrases iter.remove(); } } } return cleanMatches; } catch (ExecutionException e) { log.error("Couldn't set up phrase search, accepted phrases won't work.", e); return ruleMatches; } } return ruleMatches; } public Map<String, List<RuleMatch>> getPhrases(List<RuleMatch> ruleMatches, AnnotatedText text) {<FILL_FUNCTION_BODY>
Map<String, List<RuleMatch>> phraseToMatches = new HashMap<>(); int prevToPos = Integer.MIN_VALUE; List<RuleMatch> collectedMatches = new ArrayList<>(); List<String> collectedTerms = new ArrayList<>(); for (RuleMatch match : ruleMatches) { if (match.getRule().isDictionaryBasedSpellingRule()) { String covered = text.getPlainText().substring(match.getFromPos(), match.getToPos()); if (match.getFromPos() == prevToPos + 1) { String key = String.join(" ", collectedTerms) + " " + covered; ArrayList<RuleMatch> l = new ArrayList<>(collectedMatches); l.add(match); phraseToMatches.put(key, l); } else { collectedTerms.clear(); collectedMatches.clear(); } collectedTerms.add(covered); collectedMatches.add(match); prevToPos = match.getToPos(); } } return phraseToMatches;
662
271
933
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/DoublePunctuationRule.java
DoublePunctuationRule
match
class DoublePunctuationRule extends Rule { public DoublePunctuationRule(ResourceBundle messages) { this(messages, null); } /** @since 5.9 */ public DoublePunctuationRule(ResourceBundle messages, URL url) { super(messages); super.setCategory(Categories.PUNCTUATION.getCategory(messages)); setLocQualityIssueType(ITSIssueType.Typographical); if (url != null) { setUrl(url); } } @Override public String getId() { return "DOUBLE_PUNCTUATION"; } @Override public final String getDescription() { return messages.getString("desc_double_punct"); } public String getCommaCharacter() { return ","; } @Override public final RuleMatch[] match(AnalyzedSentence sentence) {<FILL_FUNCTION_BODY>} protected String getDotMessage() { return messages.getString("two_dots"); } protected String getCommaMessage() { return messages.getString("two_commas"); } }
List<RuleMatch> ruleMatches = new ArrayList<>(); AnalyzedTokenReadings[] tokens = sentence.getTokensWithoutWhitespace(); int startPos = 0; int dotCount = 0; int commaCount = 0; for (int i = 1; i < tokens.length; i++) { String token = tokens[i].getToken(); String nextToken = null; String prevPrevToken = null; if (i < tokens.length - 1) { nextToken = tokens[i + 1].getToken(); } if (i > 1) { prevPrevToken = tokens[i - 2].getToken(); } if (".".equals(token)) { dotCount++; commaCount = 0; startPos = tokens[i].getStartPos(); } else if (getCommaCharacter().equals(token)) { commaCount++; dotCount = 0; startPos = tokens[i].getStartPos(); } if (dotCount == 2 && !".".equals(nextToken) && !"…".equals(nextToken) && !"/".equals(token) && !"/".equals(nextToken) && /* Unix path */ !"\\".equals(token) && !"\\".equals(nextToken) && /* Windows path */ !"?".equals(prevPrevToken) && !"!".equals(prevPrevToken) && !"…".equals(prevPrevToken) && !".".equals(prevPrevToken)) { int fromPos = Math.max(0, startPos - 1); RuleMatch ruleMatch = new RuleMatch(this, sentence, fromPos, startPos + 1, getDotMessage(), messages.getString("double_dots_short")); ruleMatch.addSuggestedReplacement("."); ruleMatch.addSuggestedReplacement("…"); ruleMatches.add(ruleMatch); dotCount = 0; } else if (commaCount == 2 && !getCommaCharacter().equals(nextToken)) { int fromPos = Math.max(0, startPos - 1); RuleMatch ruleMatch = new RuleMatch(this, sentence, fromPos, startPos + 1, getCommaMessage(), messages.getString("double_commas_short")); ruleMatch.setSuggestedReplacement(getCommaCharacter()); ruleMatches.add(ruleMatch); commaCount = 0; } if (!".".equals(token) && !getCommaCharacter().equals(token)) { dotCount = 0; commaCount = 0; } } return toRuleMatchArray(ruleMatches);
303
661
964
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public void addTags(List<java.lang.String>) ,public void addToneTags(List<java.lang.String>) ,public int estimateContextForSureMatch() ,public List<org.languagetool.tagging.disambiguation.rules.DisambiguationPatternRule> getAntiPatterns() ,public org.languagetool.rules.Category getCategory() ,public java.lang.String getConfigureText() ,public final List<org.languagetool.rules.CorrectExample> getCorrectExamples() ,public int getDefaultValue() ,public abstract java.lang.String getDescription() ,public int getDistanceTokens() ,public final List<org.languagetool.rules.ErrorTriggeringExample> getErrorTriggeringExamples() ,public java.lang.String getFullId() ,public abstract java.lang.String getId() ,public final List<org.languagetool.rules.IncorrectExample> getIncorrectExamples() ,public org.languagetool.rules.ITSIssueType getLocQualityIssueType() ,public int getMaxConfigurableValue() ,public int getMinConfigurableValue() ,public int getMinPrevMatches() ,public int getPriority() ,public java.lang.String getSourceFile() ,public java.lang.String getSubId() ,public List<org.languagetool.Tag> getTags() ,public List<org.languagetool.ToneTag> getToneTags() ,public java.net.URL getUrl() ,public boolean hasConfigurableValue() ,public boolean hasTag(org.languagetool.Tag) ,public boolean hasToneTag(org.languagetool.ToneTag) ,public final boolean isDefaultOff() ,public final boolean isDefaultTempOff() ,public boolean isDictionaryBasedSpellingRule() ,public boolean isGoalSpecific() ,public final boolean isOfficeDefaultOff() ,public final boolean isOfficeDefaultOn() ,public boolean isPremium() ,public abstract org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public final void setCategory(org.languagetool.rules.Category) ,public final void setCorrectExamples(List<org.languagetool.rules.CorrectExample>) ,public final void setDefaultOff() ,public final void setDefaultOn() ,public final void setDefaultTempOff() ,public void setDistanceTokens(int) ,public final void setErrorTriggeringExamples(List<org.languagetool.rules.ErrorTriggeringExample>) ,public void setGoalSpecific(boolean) ,public final void setIncorrectExamples(List<org.languagetool.rules.IncorrectExample>) ,public void setLocQualityIssueType(org.languagetool.rules.ITSIssueType) ,public void setMinPrevMatches(int) ,public final void setOfficeDefaultOff() ,public final void setOfficeDefaultOn() ,public void setPremium(boolean) ,public void setPriority(int) ,public void setTags(List<org.languagetool.Tag>) ,public void setToneTags(List<org.languagetool.ToneTag>) ,public void setUrl(java.net.URL) ,public boolean supportsLanguage(org.languagetool.Language) ,public boolean useInOffice() <variables>private static final org.languagetool.rules.Category MISC,private org.languagetool.rules.Category category,private List<org.languagetool.rules.CorrectExample> correctExamples,private boolean defaultOff,private boolean defaultTempOff,private int distanceTokens,private List<org.languagetool.rules.ErrorTriggeringExample> errorTriggeringExamples,private List<org.languagetool.rules.IncorrectExample> incorrectExamples,private boolean isGoalSpecific,private boolean isPremium,private org.languagetool.rules.ITSIssueType locQualityIssueType,protected final non-sealed java.util.ResourceBundle messages,private int minPrevMatches,private boolean officeDefaultOff,private boolean officeDefaultOn,private int priority,private List<org.languagetool.Tag> tags,private List<org.languagetool.ToneTag> toneTags,private java.net.URL url
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/EmptyLineRule.java
EmptyLineRule
match
class EmptyLineRule extends TextLevelRule { private final Language lang; public EmptyLineRule(ResourceBundle messages, Language lang, boolean defaultActive) { super(messages); super.setCategory(Categories.STYLE.getCategory(messages)); this.lang = lang; if (!defaultActive) { setDefaultOff(); } setOfficeDefaultOn(); // Default for LO/OO is always On setLocQualityIssueType(ITSIssueType.Style); } public EmptyLineRule(ResourceBundle messages, Language lang) { this(messages, lang, false); } @Override public String getId() { return "EMPTY_LINE"; } @Override public String getDescription() { return messages.getString("empty_line_rule_desc"); } @Override public org.languagetool.rules.RuleMatch[] match(List<AnalyzedSentence> sentences) throws IOException {<FILL_FUNCTION_BODY>} private boolean isSecondParagraphEndMark(String sentence) { if (lang.getSentenceTokenizer().singleLineBreaksMarksPara()) { if (sentence.endsWith("\n\n") || sentence.endsWith("\n\r\n\r")) { return true; } } else { if (sentence.endsWith("\n\n\n\n") || sentence.endsWith("\n\r\n\r\n\r\n\r") || sentence.endsWith("\r\n\r\n\r\n\r\n")) { return true; } } return false; } @Override public int minToCheckParagraph() { return 1; } }
List<RuleMatch> ruleMatches = new ArrayList<>(); int pos = 0; for (int n = 0; n < sentences.size() - 1; n++) { AnalyzedSentence sentence = sentences.get(n); if(Tools.isParagraphEnd(sentences, n, lang)) { if(isSecondParagraphEndMark(sentence.getText())) { AnalyzedTokenReadings[] tokens = sentence.getTokensWithoutWhitespace(); if(tokens.length > 1) { int fromPos = pos + tokens[tokens.length - 1].getStartPos(); int toPos = pos + tokens[tokens.length - 1].getEndPos(); RuleMatch ruleMatch = new RuleMatch(this, sentence, fromPos, toPos, messages.getString("empty_line_rule_msg")); // Can't use SuggestedReplacement because of problems in LO/OO dialog with linebreaks ruleMatches.add(ruleMatch); } } } pos += sentence.getCorrectedTextLength(); } return toRuleMatchArray(ruleMatches);
454
279
733
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public int estimateContextForSureMatch() ,public org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>, org.languagetool.markup.AnnotatedText) throws java.io.IOException,public abstract org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>) throws java.io.IOException,public final org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public abstract int minToCheckParagraph() <variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/Example.java
Example
requireMarkup
class Example { private Example() { } /** * Create an example text (usually just one sentence) with an error - the error must be marked with {@code <marker>...</marker>}. * @throws IllegalArgumentException if the {@code <marker>...</marker>} is missing * @since 2.5 */ public static IncorrectExample wrong(String example) { requireMarkup(example); return new IncorrectExample(example); } /** * Create an example text (usually just one sentence) without an error - the fixed error (compared to the text created * with {@link #wrong(String)}) can be marked with {@code <marker>...</marker>}. * @since 2.5, return type modified in 3.5 */ public static CorrectExample fixed(String example) { return new CorrectExample(example); } private static void requireMarkup(String example) {<FILL_FUNCTION_BODY>} }
if (!example.contains("<marker>") || !example.contains("</marker>")) { throw new IllegalArgumentException("Example text must contain '<marker>...</marker>': " + example); }
260
59
319
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/GRPCRule.java
AnalyzedMLRuleRequest
prepareRequest
class AnalyzedMLRuleRequest extends RemoteRule.RemoteRequest { final List<MLServerProto.AnalyzedMatchRequest> requests; final List<AnalyzedSentence> sentences; public AnalyzedMLRuleRequest(List<MLServerProto.AnalyzedMatchRequest> requests, List<AnalyzedSentence> sentences) { this.requests = requests; this.sentences = sentences; } } @Override protected RemoteRule.RemoteRequest prepareRequest(List<AnalyzedSentence> sentences, @Nullable Long textSessionId) {<FILL_FUNCTION_BODY>
List<Long> ids = Collections.emptyList(); // TODO this is a temp fix to avoid sending too long sentences to the server List<AnalyzedSentence> filteredSentences = sentences.stream() .filter(s -> s.getText().length() <= maxSentenceLength) .collect(Collectors.toList()); if (textSessionId != null) { ids = Collections.nCopies(filteredSentences.size(), textSessionId); } if (sendAnalyzedData) { List<MLServerProto.AnalyzedMatchRequest> requests = new ArrayList<>(); for (int offset = 0; offset < filteredSentences.size(); offset += batchSize) { MLServerProto.AnalyzedMatchRequest req = MLServerProto.AnalyzedMatchRequest.newBuilder() .addAllSentences(filteredSentences .subList(offset, Math.min(filteredSentences.size(), offset + batchSize)) .stream().map(GRPCUtils::toGRPC).collect(Collectors.toList())) .setInputLogging(inputLogging) .addAllTextSessionID(textSessionId != null ? ids.subList(offset, Math.min(filteredSentences.size(), offset + batchSize)) : Collections.emptyList()) .build(); requests.add(req); } return new AnalyzedMLRuleRequest(requests, filteredSentences); } else { List<MLServerProto.MatchRequest> requests = new ArrayList<>(); for (int offset = 0; offset < filteredSentences.size(); offset += batchSize) { List<String> text = filteredSentences.stream().map(AnalyzedSentence::getText).map(s -> { if (whitespaceNormalisation) { // non-breaking space can be treated as normal space return WHITESPACE_REGEX.matcher(s).replaceAll(" "); } else { return s; } }).collect(Collectors.toList()); MLServerProto.MatchRequest req = MLServerProto.MatchRequest.newBuilder() .addAllSentences(text.subList(offset, Math.min(text.size(), offset + batchSize))) .setInputLogging(inputLogging) .addAllTextSessionID(textSessionId != null ? ids.subList(offset, Math.min(text.size(), offset + batchSize)) : Collections.emptyList()) .build(); requests.add(req); } if (requests.size() > 1) { logger.debug("Split {} sentences into {} requests for {}", filteredSentences.size(), requests.size(), getId()); } return new MLRuleRequest(requests, filteredSentences, textSessionId); }
143
691
834
<methods>public void <init>(org.languagetool.Language, java.util.ResourceBundle, org.languagetool.rules.RemoteRuleConfig, boolean, java.lang.String) ,public void <init>(org.languagetool.Language, java.util.ResourceBundle, org.languagetool.rules.RemoteRuleConfig, boolean) ,public CircuitBreaker circuitBreaker() ,public static void fixMatchOffsets(org.languagetool.AnalyzedSentence, List<org.languagetool.rules.RuleMatch>) ,public java.lang.String getId() ,public org.languagetool.rules.RemoteRuleConfig getServiceConfiguration() ,public long getTimeout(long) ,public boolean isPremium() ,public org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public FutureTask<org.languagetool.rules.RemoteRuleResult> run(List<org.languagetool.AnalyzedSentence>) ,public FutureTask<org.languagetool.rules.RemoteRuleResult> run(List<org.languagetool.AnalyzedSentence>, java.lang.Long) ,public static void shutdown() <variables>protected static final ConcurrentMap<java.lang.String,CircuitBreaker> circuitBreakers,protected final non-sealed boolean filterMatches,protected final non-sealed boolean fixOffsets,protected final non-sealed boolean inputLogging,private static final Logger logger,protected final non-sealed org.languagetool.JLanguageTool lt,protected final non-sealed boolean premium,protected final non-sealed org.languagetool.Language ruleLanguage,protected final non-sealed org.languagetool.rules.RemoteRuleConfig serviceConfiguration,protected static final List<java.lang.Runnable> shutdownRoutines,protected final non-sealed java.util.regex.Pattern suppressMisspelledMatch,protected final non-sealed java.util.regex.Pattern suppressMisspelledSuggestions,protected final non-sealed boolean whitespaceNormalisation
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/GRPCUtils.java
RuleData
toGRPC
class RuleData extends Rule { private final Match m; private final String sourceFile; RuleData(Match m) { this.m = m; this.sourceFile = m.getRule().getSourceFile(); // keep default values from Rule baseclass if (!m.getRule().getIssueType().isEmpty()) { setLocQualityIssueType(ITSIssueType.valueOf(m.getRule().getIssueType())); } if (m.getRule().getTempOff()) { setDefaultTempOff(); } if (m.getRule().hasCategory()) { Category c = new Category(new CategoryId(m.getRule().getCategory().getId()), m.getRule().getCategory().getName()); setCategory(c); } setPremium(m.getRule().getIsPremium()); setTags(m.getRule().getTagsList().stream().map(t -> Tag.valueOf(t.name())).collect(Collectors.toList())); } @Nullable @Override public String getSourceFile() { return emptyAsNull(sourceFile); } @Override public String getId() { return m.getId(); } @Override public String getSubId() { return emptyAsNull(m.getSubId()); } @Override public String getDescription() { return m.getRuleDescription(); } @Override public int estimateContextForSureMatch() { // 0 is okay as default value return m.getContextForSureMatch(); } @Override public RuleMatch[] match(AnalyzedSentence sentence) throws IOException { throw new UnsupportedOperationException( "Not implemented; internal class used for returning match" + " information from remote endpoint"); } } @NotNull private static String nullAsEmpty(@Nullable String s) { return s != null ? s : ""; } @Nullable private static String emptyAsNull(String s) { if (s != null && s.isEmpty()) { return null; } return s; } public static MLServerProto.AnalyzedToken toGRPC(AnalyzedToken token) { MLServerProto.AnalyzedToken.Builder t = MLServerProto.AnalyzedToken.newBuilder(); if (token.getLemma() != null) { t.setLemma(token.getLemma()); } if (token.getPOSTag() != null) { t.setPosTag(token.getPOSTag()); } t.setToken(token.getToken()); return t.build(); } public static MLServerProto.AnalyzedTokenReadings toGRPC(AnalyzedTokenReadings readings) { return MLServerProto.AnalyzedTokenReadings.newBuilder() .addAllChunkTags(readings.getChunkTags().stream().map(ChunkTag::getChunkTag).collect(Collectors.toList())) .addAllReadings(readings.getReadings().stream().map(GRPCUtils::toGRPC).collect(Collectors.toList())) .build(); } public static MLServerProto.AnalyzedSentence toGRPC(AnalyzedSentence sentence) { return MLServerProto.AnalyzedSentence.newBuilder() .setText(sentence.getText()) .addAllTokens(Arrays.stream(sentence.getTokens()).map(GRPCUtils::toGRPC).collect(Collectors.toList())) .build(); } public static AnalyzedTokenReadings fromGRPC(MLServerProto.AnalyzedTokenReadings tokenReadings) { return new AnalyzedTokenReadings(tokenReadings.getReadingsList().stream() .map(GRPCUtils::fromGRPC).collect(Collectors.toList()), tokenReadings.getStartPos()); } public static AnalyzedToken fromGRPC(MLServerProto.AnalyzedToken token) { return new AnalyzedToken(token.getToken(), token.getPosTag(), token.getLemma()); } public static AnalyzedSentence fromGRPC(MLServerProto.AnalyzedSentence sentence) { return new AnalyzedSentence(sentence.getTokensList().stream() .map(GRPCUtils::fromGRPC).toArray(AnalyzedTokenReadings[]::new)); } public static String getUrl(RuleMatch m) { // URL can be attached to Rule or RuleMatch (or both); in Protobuf, only to RuleMatch // prefer URL from RuleMatch, default to empty string if (m.getUrl() != null) { return m.getUrl().toString(); } if (m.getRule().getUrl() != null) { return m.getRule().getUrl().toString(); } return ""; } public static Match toGRPC(RuleMatch m) {<FILL_FUNCTION_BODY>
// could add better handling for conversion errors with enums return Match.newBuilder() .setOffset(m.getFromPos()) .setLength(m.getToPos() - m.getFromPos()) .setId(m.getSpecificRuleId()) .setSubId(nullAsEmpty(m.getRule().getSubId())) .addAllSuggestedReplacements(m.getSuggestedReplacementObjects().stream() .map(GRPCUtils::toGRPC).collect(Collectors.toList())) .setRuleDescription(nullAsEmpty(m.getRule().getDescription())) .setMatchDescription(nullAsEmpty(m.getMessage())) .setMatchShortDescription(nullAsEmpty(m.getShortMessage())) .setUrl(getUrl(m)) .setAutoCorrect(m.isAutoCorrect()) .setType(Match.MatchType.valueOf(m.getType().name())) .setContextForSureMatch(m.getRule().estimateContextForSureMatch()) .setRule(MLServerProto.Rule.newBuilder() .setSourceFile(nullAsEmpty(m.getRule().getSourceFile())) .setIssueType(m.getRule().getLocQualityIssueType().name()) .setTempOff(m.getRule().isDefaultTempOff()) .setCategory(MLServerProto.RuleCategory.newBuilder() .setId(m.getRule().getCategory().getId().toString()) .setName(m.getRule().getCategory().getName()) .build()) .setIsPremium(Premium.get().isPremiumRule(m.getRule())) .addAllTags(m.getRule().getTags().stream() .map(t -> MLServerProto.Rule.Tag.valueOf(t.name())) .collect(Collectors.toList())) .build() ).build();
1,240
469
1,709
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/IncorrectExample.java
IncorrectExample
getCorrections
class IncorrectExample extends ExampleSentence { private final Object corrections; public IncorrectExample(String example) { this(example, Collections.emptyList()); } /** * @since 2.9 */ public IncorrectExample(String example, List<String> corrections) { super(example); this.corrections = corrections.isEmpty() ? null : corrections.size() == 1 ? corrections.get(0) : corrections.toArray(new String[0]); } /** * Return the possible corrections. */ @NotNull public List<String> getCorrections() {<FILL_FUNCTION_BODY>} @Override public String toString() { return example + " " + getCorrections(); } }
return corrections == null ? Collections.emptyList() : corrections instanceof String ? Collections.singletonList((String) corrections) : Collections.unmodifiableList(Arrays.asList((String[])corrections));
208
58
266
<methods>public void <init>(java.lang.String) ,public static java.lang.String cleanMarkersInExample(java.lang.String) ,public java.lang.String getExample() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.String example
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/IsEnglishWordFilter.java
IsEnglishWordFilter
acceptRuleMatch
class IsEnglishWordFilter extends RuleFilter { private Language english = null; //private SpellingCheckRule spellingCheckRule = null; private Tagger tagger = null; public IsEnglishWordFilter() { try { english = Languages.getLanguageForShortCode("en-US"); } catch (Exception e) { } if (english != null) { //spellingCheckRule = english.getDefaultSpellingRule(); tagger = english.createDefaultTagger(); } } @Override public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> args, int patternTokenPos, AnalyzedTokenReadings[] patternTokens, List<Integer> tokenPositions) throws IOException {<FILL_FUNCTION_BODY>} private boolean wordIsTaggedWith(String word, String postag) throws IOException { return tagger.tag(Collections.singletonList(word)).get(0).matchesPosTagRegex(postag); } private boolean wordIsTagged(String word) throws IOException { return tagger.tag(Collections.singletonList(word)).get(0).isTagged(); } }
if (tagger == null) { return null; } String[] formPositions = getRequired("formPositions", args).split(","); List<String> forms = new ArrayList<>(); for (String formPosition : formPositions) { forms.add(patternTokens[getSkipCorrectedReference(tokenPositions, Integer.parseInt(formPosition))].getToken()); } boolean isEnglish = true; String postagsStr = getOptional("postags", args); if (postagsStr != null) { String [] postags = postagsStr.split(","); if (postags.length != forms.size()) { throw new RuntimeException("The number of forms and postags has to be the same in disambiguation rule with " + "filter IsEnglishWordFilter."); } for (int i = 0; i < postags.length; i++) { isEnglish = isEnglish && wordIsTaggedWith(forms.get(i), postags[i]); } } else { for (int i = 0; i < forms.size(); i++) { isEnglish = isEnglish && wordIsTagged(forms.get(i)); } } return (isEnglish ? match : null);
301
317
618
<methods>public non-sealed void <init>() ,public abstract org.languagetool.rules.RuleMatch acceptRuleMatch(org.languagetool.rules.RuleMatch, Map<java.lang.String,java.lang.String>, int, org.languagetool.AnalyzedTokenReadings[], List<java.lang.Integer>) throws java.io.IOException,public boolean matches(Map<java.lang.String,java.lang.String>, org.languagetool.AnalyzedTokenReadings[], int, List<java.lang.Integer>) throws java.io.IOException<variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/LongParagraphRule.java
LongParagraphRule
match
class LongParagraphRule extends TextLevelRule { public static final String RULE_ID = "TOO_LONG_PARAGRAPH"; private static final boolean DEFAULT_ACTIVATION = false; private static final int DEFAULT_MAX_WORDS = 220; private final Language lang; private int maxWords = DEFAULT_MAX_WORDS; public LongParagraphRule(ResourceBundle messages, Language lang, UserConfig userConfig, int defaultWords, boolean defaultActive) { super(messages); super.setCategory(Categories.STYLE.getCategory(messages)); this.lang = lang; setDefaultOff(); if (defaultWords > 0) { this.maxWords = defaultWords; } if (userConfig != null) { int confWords = userConfig.getConfigValueByID(getId()); if (confWords > 0) { this.maxWords = confWords; } } setLocQualityIssueType(ITSIssueType.Style); setTags(Arrays.asList(Tag.picky)); } /** Note: will be off by default. */ public LongParagraphRule(ResourceBundle messages, Language lang, UserConfig userConfig, int defaultWords) { this(messages, lang, userConfig, defaultWords, DEFAULT_ACTIVATION); } public LongParagraphRule(ResourceBundle messages, Language lang, UserConfig userConfig) { this(messages, lang, userConfig, -1, true); } @Override public String getDescription() { return MessageFormat.format(messages.getString("long_paragraph_rule_desc"), maxWords); } @Override public String getId() { return RULE_ID; } @Override public int getDefaultValue() { return maxWords; } @Override public boolean hasConfigurableValue() { return true; } @Override public int getMinConfigurableValue() { return 5; } @Override public int getMaxConfigurableValue() { return 300; } public String getConfigureText() { return messages.getString("guiLongParagraphsText"); } public String getMessage() { return MessageFormat.format(messages.getString("long_paragraph_rule_msg"), maxWords); } @Override public RuleMatch[] match(List<AnalyzedSentence> sentences) throws IOException {<FILL_FUNCTION_BODY>} @Override public int minToCheckParagraph() { return 0; } }
List<RuleMatch> ruleMatches = new ArrayList<>(); int pos = 0; int startPos = 0; int endPos = 0; int wordCount = 0; boolean paraHasLinebreaks = false; for (int n = 0; n < sentences.size(); n++) { AnalyzedSentence sentence = sentences.get(n); boolean paragraphEnd = Tools.isParagraphEnd(sentences, n, lang); if (!paragraphEnd && sentence.getText().replaceFirst("^\n+", "").contains("\n")) { // e.g. text with manually added line breaks (e.g. issues on github with "- [ ]" syntax) paraHasLinebreaks = true; } AnalyzedTokenReadings[] tokens = sentence.getTokensWithoutWhitespace(); for (AnalyzedTokenReadings token : tokens) { if (!token.isWhitespace() && !token.isSentenceStart() && !token.isNonWord()) { wordCount++; if (wordCount == maxWords) { startPos = token.getStartPos() + pos; endPos = token.getEndPos() + pos; } } } if (paragraphEnd) { if (wordCount > maxWords + 5 && !paraHasLinebreaks) { // + 5: don't show match almost at end of paragraph RuleMatch ruleMatch = new RuleMatch(this, sentence, startPos, endPos, getMessage()); ruleMatches.add(ruleMatch); } wordCount = 0; paraHasLinebreaks = false; } pos += sentence.getCorrectedTextLength(); } if (wordCount > maxWords) { RuleMatch ruleMatch = new RuleMatch(this, startPos, endPos, getMessage()); ruleMatches.add(ruleMatch); } return toRuleMatchArray(ruleMatches);
679
477
1,156
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public int estimateContextForSureMatch() ,public org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>, org.languagetool.markup.AnnotatedText) throws java.io.IOException,public abstract org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>) throws java.io.IOException,public final org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public abstract int minToCheckParagraph() <variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/LongSentenceRule.java
LongSentenceRule
match
class LongSentenceRule extends TextLevelRule { public static final String RULE_ID = "TOO_LONG_SENTENCE"; private static final Pattern QUOTED_SENT_END = Pattern.compile("[?!.][\"“”„»«]", Pattern.DOTALL); private static final Pattern SENT_END = Pattern.compile("[?!.]"); private static List<String> OPENING_QUOTES = Arrays.asList("\"", "“", "„", "«", "(", "[", "{", "—"); private static List<String> CLOSING_QUOTES = Arrays.asList("\"", "”", "“", "»", ")", "]", "}", "—"); private final ResourceBundle messages; private final int maxWords; public LongSentenceRule(ResourceBundle messages, UserConfig userConfig, int maxWords) { this.messages = messages; setCategory(Categories.STYLE.getCategory(messages)); setLocQualityIssueType(ITSIssueType.Style); setTags(Collections.singletonList(Tag.picky)); int tmpMaxWords = maxWords; if (userConfig != null) { int confWords = userConfig.getConfigValueByID(getId()); if (confWords > 0) { tmpMaxWords = confWords; } } this.maxWords = tmpMaxWords; } @Override public String getDescription() { return MessageFormat.format(messages.getString("long_sentence_rule_desc"), maxWords); } @Override public String getId() { return RULE_ID; } private boolean isWordCount(String tokenText) { if (tokenText.length() > 0) { return !StringTools.isNotWordCharacter(tokenText.substring(0,1)); } return false; } public String getMessage() { return MessageFormat.format(messages.getString("long_sentence_rule_msg2"), maxWords); } @Override public RuleMatch[] match(List<AnalyzedSentence> sentences) throws IOException {<FILL_FUNCTION_BODY>} @Override public int minToCheckParagraph() { return 0; } // next functions give the user the possibility to configure the function @Override public int getDefaultValue() { return maxWords; } @Override public boolean hasConfigurableValue() { return true; } @Override public int getMinConfigurableValue() { return 5; } @Override public int getMaxConfigurableValue() { return 100; } @Override public String getConfigureText() { return messages.getString("guiLongSentencesText"); } }
List<RuleMatch> ruleMatches = new ArrayList<>(); int pos = 0; for (AnalyzedSentence sentence : sentences) { AnalyzedTokenReadings[] tokens = sentence.getTokens(); if (tokens.length < maxWords) { // just a short-circuit pos += sentence.getCorrectedTextLength(); continue; } if (QUOTED_SENT_END.matcher(sentence.getText()).find()) { pos += sentence.getCorrectedTextLength(); continue; } String msg = getMessage(); int i = 0; List<Integer> fromPos = new ArrayList<>(); List<Integer> toPos = new ArrayList<>(); AnalyzedTokenReadings fromPosToken = null; AnalyzedTokenReadings toPosToken = null; int indexOfQuote = -1 ; while (i < tokens.length) { int numWords = 0; while (i < tokens.length && !tokens[i].getToken().equals(":") && !tokens[i].getToken().equals(";") && !tokens[i].getToken().equals("\n") && !tokens[i].getToken().equals("\r\n") && !tokens[i].getToken().equals("\n\r") ) { String token = tokens[i].getToken(); if (indexOfQuote == -1 && OPENING_QUOTES.indexOf(token) > -1) { indexOfQuote = OPENING_QUOTES.indexOf(token); } else if (indexOfQuote > -1 && CLOSING_QUOTES.indexOf(token) == indexOfQuote) { indexOfQuote = -1; } if (isWordCount(token) && indexOfQuote == -1) { //Get first word token if (fromPosToken == null) { fromPosToken = tokens[i]; } if (numWords == maxWords) { //Get last word token if (toPosToken == null) { for (int j = tokens.length - 1; j >= 0; j--) { if (isWordCount(tokens[j].getToken())) { if (tokens.length > j + 1 && SENT_END.matcher(tokens[j+1].getToken()).matches()) { toPosToken = tokens[j + 1]; } else { toPosToken = tokens[j]; } break; } } } if (fromPosToken != null && toPosToken != null) { fromPos.add(fromPosToken.getStartPos()); toPos.add(toPosToken.getEndPos()); } else { //keep old logic if we could not find word tokens fromPos.add(tokens[0].getStartPos()); toPos.add(tokens[tokens.length - 1].getEndPos()); } break; } numWords++; } i++; } i++; } for (int j = 0; j < fromPos.size(); j++) { RuleMatch ruleMatch = new RuleMatch(this, sentence, pos+fromPos.get(j), pos+toPos.get(j), msg); ruleMatches.add(ruleMatch); } pos += sentence.getCorrectedTextLength(); } return toRuleMatchArray(ruleMatches);
742
871
1,613
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public int estimateContextForSureMatch() ,public org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>, org.languagetool.markup.AnnotatedText) throws java.io.IOException,public abstract org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>) throws java.io.IOException,public final org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public abstract int minToCheckParagraph() <variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/MatchPosition.java
MatchPosition
equals
class MatchPosition { private final int start; private final int end; MatchPosition(int start, int end) { this.start = start; this.end = end; } int getStart() { return start; } int getEnd() { return end; } @Override public String toString() { return start + "-" + end; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(start, end); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MatchPosition other = (MatchPosition) o; return Objects.equals(start, other.start) && Objects.equals(end, other.end);
168
73
241
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/MultipleWhitespaceRule.java
MultipleWhitespaceRule
match
class MultipleWhitespaceRule extends TextLevelRule { public MultipleWhitespaceRule(ResourceBundle messages, Language language) { super(messages); super.setCategory(Categories.TYPOGRAPHY.getCategory(messages)); setLocQualityIssueType(ITSIssueType.Whitespace); } @Override public String getId() { return "WHITESPACE_RULE"; } @Override public String getDescription() { return messages.getString("desc_whitespacerepetition"); } // First White space is not a linebreak, function or footnote private static boolean isFirstWhite(AnalyzedTokenReadings token) { return (token.isWhitespace() || StringTools.isNonBreakingWhitespace(token.getToken())) && !token.isLinebreak() && !token.getToken().contains("\u200B") && !token.getToken().contains("\uFEFF") && !token.getToken().contains("\u2060"); } // Removable white space are not linebreaks, tabs, functions or footnotes private static boolean isRemovableWhite(AnalyzedTokenReadings token) { return (token.isWhitespace() || StringTools.isNonBreakingWhitespace(token.getToken())) && !token.isLinebreak() && !token.getToken().equals("\t") // exclude invisible spaces: && !token.getToken().contains("\u200B") && !token.getToken().contains("\uFEFF") && !token.getToken().contains("\u2060"); } @Override public RuleMatch[] match(List<AnalyzedSentence> sentences) {<FILL_FUNCTION_BODY>} @Override public int minToCheckParagraph() { return 0; } }
List<RuleMatch> ruleMatches = new ArrayList<>(); int pos = 0; for (AnalyzedSentence sentence : sentences) { AnalyzedTokenReadings[] tokens = sentence.getTokens(); //note: we start from token 1 //token no. 0 is guaranteed to be SENT_START for (int i = 1; i < tokens.length; i++) { if(isFirstWhite(tokens[i])) { int nFirst = i; for (i++; i < tokens.length && isRemovableWhite(tokens[i]); i++); i--; if (i > nFirst) { String message = messages.getString("whitespace_repetition"); RuleMatch ruleMatch = new RuleMatch(this, sentence, pos + tokens[nFirst].getStartPos(), pos + tokens[i].getEndPos(), message); ruleMatch.setSuggestedReplacement(tokens[nFirst].getToken()); ruleMatches.add(ruleMatch); } } else if (tokens[i].isLinebreak()) { for (i++; i < tokens.length && isRemovableWhite(tokens[i]); i++); } } pos += sentence.getCorrectedTextLength(); } return toRuleMatchArray(ruleMatches);
474
333
807
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public int estimateContextForSureMatch() ,public org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>, org.languagetool.markup.AnnotatedText) throws java.io.IOException,public abstract org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>) throws java.io.IOException,public final org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public abstract int minToCheckParagraph() <variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/ParagraphRepeatBeginningRule.java
ParagraphRepeatBeginningRule
match
class ParagraphRepeatBeginningRule extends TextLevelRule { private static final Pattern QUOTES_REGEX = Pattern.compile("[’'\"„“”»«‚‘›‹()\\[\\]]"); private final Language lang; public ParagraphRepeatBeginningRule(ResourceBundle messages, Language lang) { super(messages); super.setCategory(Categories.STYLE.getCategory(messages)); this.lang = lang; setLocQualityIssueType(ITSIssueType.Style); setDefaultOff(); } @Override public String getId() { return "PARAGRAPH_REPEAT_BEGINNING_RULE"; } @Override public String getDescription() { return messages.getString("repetition_paragraph_beginning_desc"); } public boolean isArticle(AnalyzedTokenReadings token) { return token.hasPosTagStartingWith("DT"); } private int numCharEqualBeginning(AnalyzedTokenReadings[] lastTokens, AnalyzedTokenReadings[] nextTokens) { if(lastTokens.length < 2 || nextTokens.length < 2 || lastTokens[1].isWhitespace() || nextTokens[1].isWhitespace()) { return 0; } int nToken = 1; String lastToken = lastTokens[nToken].getToken(); String nextToken = nextTokens[nToken].getToken(); if (QUOTES_REGEX.matcher(lastToken).matches() && lastToken.equals(nextToken)) { if(lastTokens.length <= nToken + 1 || nextTokens.length <= nToken + 1) { return 0; } nToken++; lastToken = lastTokens[nToken].getToken(); nextToken = nextTokens[nToken].getToken(); } if(!Character.isLetter(lastToken.charAt(0))) { return 0; } if (lastTokens.length > nToken + 1 && isArticle(lastTokens[nToken]) && lastToken.equals(nextToken)) { if (nextTokens.length <= nToken + 1) { return 0; } nToken++; lastToken = lastTokens[nToken].getToken(); nextToken = nextTokens[nToken].getToken(); } if (!Character.isLetter(lastToken.charAt(0))) { return 0; } if (lastToken.equals(nextToken)) { return lastTokens[nToken].getEndPos(); } return 0; } @Override public RuleMatch[] match(List<AnalyzedSentence> sentences) throws IOException {<FILL_FUNCTION_BODY>} @Override public int minToCheckParagraph() { return 1; } }
List<RuleMatch> ruleMatches = new ArrayList<>(); if (sentences.size() < 1) { return toRuleMatchArray(ruleMatches); } int nextPos = 0; int lastPos = 0; int endPos; AnalyzedSentence lastSentence = sentences.get(0); AnalyzedTokenReadings[] lastTokens = lastSentence.getTokensWithoutWhitespace(); AnalyzedSentence nextSentence; AnalyzedTokenReadings[] nextTokens; for (int n = 0; n < sentences.size() - 1; n++) { nextPos += sentences.get(n).getText().length(); if(Tools.isParagraphEnd(sentences, n, lang)) { nextSentence = sentences.get(n + 1); nextTokens = nextSentence.getTokensWithoutWhitespace(); endPos = numCharEqualBeginning(lastTokens, nextTokens); if (endPos > 0) { int startPos = lastPos + lastTokens[1].getStartPos(); if (startPos < lastPos+endPos) { String msg = messages.getString("repetition_paragraph_beginning_last_msg"); RuleMatch ruleMatch = new RuleMatch(this, lastSentence, startPos, lastPos+endPos, msg); ruleMatches.add(ruleMatch); startPos = nextPos + nextTokens[1].getStartPos(); msg = messages.getString("repetition_paragraph_beginning_last_msg"); ruleMatch = new RuleMatch(this, nextSentence, startPos, nextPos+endPos, msg); ruleMatches.add(ruleMatch); } } lastSentence = nextSentence; lastTokens = nextTokens; lastPos = nextPos; } } return toRuleMatchArray(ruleMatches);
744
477
1,221
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public int estimateContextForSureMatch() ,public org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>, org.languagetool.markup.AnnotatedText) throws java.io.IOException,public abstract org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>) throws java.io.IOException,public final org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public abstract int minToCheckParagraph() <variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/PartialPosTagFilter.java
PartialPosTagFilter
acceptRuleMatch
class PartialPosTagFilter extends RuleFilter { @Nullable protected abstract List<AnalyzedTokenReadings> tag(String token); @Override public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> args, int patternTokenPos, AnalyzedTokenReadings[] patternTokens, List<Integer> tokenPositions) {<FILL_FUNCTION_BODY>} private boolean partialTagHasRequiredTag(List<AnalyzedTokenReadings> tags, String requiredTagRegexp, boolean negatePos) { // Without negate_pos=yes: return true if any postag matches the regexp. // With negate_pos=yes: return true if there are postag and none them matches the regexp. int postagCount = 0; for (AnalyzedTokenReadings tag : tags) { for (AnalyzedToken analyzedToken : tag.getReadings()) { if (analyzedToken.getPOSTag() != null) { if (negatePos) { postagCount++; if (analyzedToken.getPOSTag().matches(requiredTagRegexp)) { return false; } } else { if (analyzedToken.getPOSTag().matches(requiredTagRegexp)) { return true; } } } } } return postagCount == 0 ? false : negatePos; } }
if (!(args.containsKey("no") && args.containsKey("regexp") && args.containsKey("postag_regexp"))) { throw new RuntimeException("Set 'no', 'regexp' and 'postag_regexp' for filter " + PartialPosTagFilter.class.getSimpleName()); } int tokenPos = Integer.parseInt(args.get("no")); Pattern pattern = Pattern.compile(args.get("regexp")); String requiredTagRegexp = args.get("postag_regexp"); boolean negatePos = args.containsKey("negate_pos"); boolean two_groups_regexp = args.containsKey("two_groups_regexp"); String prefix = ""; String suffix = ""; if (args.containsKey("prefix")) { prefix = args.get("prefix"); }; if (args.containsKey("suffix")) { suffix = args.get("suffix"); }; String token = prefix + patternTokens[tokenPos - 1].getToken() + suffix; Matcher matcher = pattern.matcher(token); if ((matcher.groupCount() != 1) && !(two_groups_regexp)) { throw new RuntimeException("Got " + matcher.groupCount() + " groups for regex '" + pattern.pattern() + "', expected 1"); } if ((matcher.groupCount() != 2) && (two_groups_regexp)) { throw new RuntimeException("Got " + matcher.groupCount() + " groups for regex '" + pattern.pattern() + "', expected 2"); } if (matcher.matches()) { String partialToken = matcher.group(1); if (matcher.groupCount() == 2) { partialToken += matcher.group(2); } List<AnalyzedTokenReadings> tags = tag(partialToken); if (tags != null && partialTagHasRequiredTag(tags, requiredTagRegexp, negatePos)) { return match; } return null; } return null;
348
527
875
<methods>public non-sealed void <init>() ,public abstract org.languagetool.rules.RuleMatch acceptRuleMatch(org.languagetool.rules.RuleMatch, Map<java.lang.String,java.lang.String>, int, org.languagetool.AnalyzedTokenReadings[], List<java.lang.Integer>) throws java.io.IOException,public boolean matches(Map<java.lang.String,java.lang.String>, org.languagetool.AnalyzedTokenReadings[], int, List<java.lang.Integer>) throws java.io.IOException<variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/PunctuationMarkAtParagraphEnd.java
PunctuationMarkAtParagraphEnd
match
class PunctuationMarkAtParagraphEnd extends TextLevelRule { private final static String[] PUNCTUATION_MARKS = {".", "!", "?", ":", ",", ";"}; private final static String[] QUOTATION_MARKS = {"„", "»", "«", "\"", "”", "″", "’", "‚", "‘", "›", "‹", "′", "'"}; private final static Pattern P_NUMERIC = Pattern.compile("[0-9.]+"); private final Language lang; /** * @since 4.5 */ public PunctuationMarkAtParagraphEnd(ResourceBundle messages, Language lang, boolean defaultActive) { super(messages); this.lang = Objects.requireNonNull(lang); super.setCategory(Categories.PUNCTUATION.getCategory(messages)); setLocQualityIssueType(ITSIssueType.Grammar); setTags(Collections.singletonList(Tag.picky)); if (!defaultActive) { setDefaultOff(); } } public PunctuationMarkAtParagraphEnd(ResourceBundle messages, Language lang) { this(messages, lang, true); } @Override public String getId() { return "PUNCTUATION_PARAGRAPH_END"; } @Override public String getDescription() { return messages.getString("punctuation_mark_paragraph_end_desc"); } private static boolean stringEqualsAny(String token, String[] any) { for (String s : any) { if (token.equals(s)) { return true; } } return false; } private static boolean isQuotationMark(AnalyzedTokenReadings tk) { return stringEqualsAny(tk.getToken(), QUOTATION_MARKS); } private static boolean isPunctuationMark(AnalyzedTokenReadings tk) { return stringEqualsAny(tk.getToken(), PUNCTUATION_MARKS); } private static boolean isWord(AnalyzedTokenReadings tk) { return Character.isLetter(tk.getToken().charAt(0)); } private static boolean isNumeric(String s) { return P_NUMERIC.matcher(s.trim()).matches(); } @Override public RuleMatch[] match(List<AnalyzedSentence> sentences) throws IOException {<FILL_FUNCTION_BODY>} @Override public int minToCheckParagraph() { return 0; } }
List<RuleMatch> ruleMatches = new ArrayList<>(); int lastPara = -1; int pos = 0; boolean isFirstWord; for (int n = 0; n < sentences.size(); n++) { AnalyzedSentence sentence = sentences.get(n); if (Tools.isParagraphEnd(sentences, n, lang)) { AnalyzedTokenReadings[] tokens = sentence.getTokensWithoutWhitespace(); if (tokens.length > 2) { isFirstWord = (isWord(tokens[1]) && !isPunctuationMark(tokens[2])) || (tokens.length > 3 && isQuotationMark(tokens[1]) && isWord(tokens[2]) && !isPunctuationMark(tokens[3])); // ignore sentences like "2.2.2. This is an item" (two sentences, first sentence only numbers) boolean ignoreSentence = false; if (n == 1 && isNumeric(sentences.get(0).getText())) { ignoreSentence = true; } if (n > 0 && isNumeric(sentences.get(n - 1).getText())) { ignoreSentence = true; } // paragraphs containing less than two sentences (e.g. headlines, listings) are excluded from rule if (n - lastPara > 1 && isFirstWord && !ignoreSentence) { int lastNWToken = tokens.length - 1; while (tokens[lastNWToken].isLinebreak()) { lastNWToken--; } if (tokens[tokens.length-2].getToken().equalsIgnoreCase(":") && WordTokenizer.isUrl(tokens[tokens.length-1].getToken())) { // e.g. "find it at: http://example.com" should not be an error lastPara = n; pos += sentence.getText().length(); continue; } if (isWord(tokens[lastNWToken]) || (isQuotationMark(tokens[lastNWToken]) && isWord(tokens[lastNWToken-1]))) { int fromPos = pos + tokens[lastNWToken].getStartPos(); int toPos = pos + tokens[lastNWToken].getEndPos(); RuleMatch ruleMatch = new RuleMatch(this, sentence, fromPos, toPos, messages.getString("punctuation_mark_paragraph_end_msg")); List<String> replacements = new ArrayList<>(); for (String mark : PUNCTUATION_MARKS) { replacements.add(tokens[lastNWToken].getToken() + mark); } ruleMatch.setSuggestedReplacements(replacements); ruleMatches.add(ruleMatch); } } } lastPara = n; } pos += sentence.getCorrectedTextLength(); } return toRuleMatchArray(ruleMatches);
669
746
1,415
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public int estimateContextForSureMatch() ,public org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>, org.languagetool.markup.AnnotatedText) throws java.io.IOException,public abstract org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>) throws java.io.IOException,public final org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public abstract int minToCheckParagraph() <variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/PunctuationMarkAtParagraphEnd2.java
PunctuationMarkAtParagraphEnd2
getLastNonSpaceToken
class PunctuationMarkAtParagraphEnd2 extends TextLevelRule { // more than this many word tokens needed for a "real" paragraph that requires a period (etc) at the end: private static final int TOKEN_THRESHOLD = 10; private final Language lang; public PunctuationMarkAtParagraphEnd2(ResourceBundle messages, Language lang) { super(messages); this.lang = Objects.requireNonNull(lang); super.setCategory(Categories.PUNCTUATION.getCategory(messages)); setLocQualityIssueType(ITSIssueType.Grammar); // setDefaultTempOff(); // TODO setDefaultOff(); } @Override public String getId() { return "PUNCTUATION_PARAGRAPH_END2"; } @Override public String getDescription() { return messages.getString("punctuation_mark_paragraph_end_desc"); } @Override public RuleMatch[] match(List<AnalyzedSentence> sentences) throws IOException { List<RuleMatch> ruleMatches = new ArrayList<>(); int pos = 0; int sentPos = 0; int tokenCount = 0; for (AnalyzedSentence sentence : sentences) { AnalyzedTokenReadings[] tokens = sentence.getTokens(); for (AnalyzedTokenReadings token : tokens) { if (!token.isNonWord() && !token.isWhitespace()) { tokenCount++; } } AnalyzedTokenReadings lastNonSpaceToken = getLastNonSpaceToken(tokens); boolean isParaEnd = Tools.isParagraphEnd(sentences, sentPos, lang); if (isParaEnd && tokenCount > TOKEN_THRESHOLD && lastNonSpaceToken != null && !lastNonSpaceToken.getToken().matches("[:.?!…]") && !lastNonSpaceToken.isNonWord()) { RuleMatch ruleMatch = new RuleMatch(this, sentence, pos + lastNonSpaceToken.getStartPos(), pos + lastNonSpaceToken.getEndPos(), messages.getString("punctuation_mark_paragraph_end_msg")); ruleMatch.setSuggestedReplacement(lastNonSpaceToken.getToken() + "."); ruleMatches.add(ruleMatch); } if (isParaEnd) { tokenCount = 0; } sentPos++; pos += sentence.getCorrectedTextLength(); } return toRuleMatchArray(ruleMatches); } private AnalyzedTokenReadings getLastNonSpaceToken(AnalyzedTokenReadings[] tokens) {<FILL_FUNCTION_BODY>} @Override public int minToCheckParagraph() { return 0; } }
for (int i = tokens.length-1; i >= 0; i--) { if (!tokens[i].isWhitespace()) { return tokens[i]; } } return null;
701
57
758
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public int estimateContextForSureMatch() ,public org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>, org.languagetool.markup.AnnotatedText) throws java.io.IOException,public abstract org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>) throws java.io.IOException,public final org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public abstract int minToCheckParagraph() <variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/RemoteRule.java
RemoteRequest
run
class RemoteRequest {} /** * run local preprocessing steps (or just store sentences) * @param sentences text to process * @param textSessionId session ID for caching, partial rollout, A/B testing * @return parameter for executeRequest/fallbackResults */ protected abstract RemoteRequest prepareRequest(List<AnalyzedSentence> sentences, @Nullable Long textSessionId); /** * @param request returned by prepareRequest * @param timeoutMilliseconds timeout for this operation, &lt;=0 -&gt; unlimited * @return callable that sends request, parses and returns result for this remote rule * @throws TimeoutException if timeout was exceeded */ protected abstract Callable<RemoteRuleResult> executeRequest(RemoteRequest request, long timeoutMilliseconds) throws TimeoutException; /** * fallback if executeRequest times out or throws an error * @param request returned by prepareRequest * @return local results for this rule */ protected abstract RemoteRuleResult fallbackResults(RemoteRequest request); protected CircuitBreaker createCircuitBreaker(String id) { CircuitBreakerConfig config = getCircuitBreakerConfig(serviceConfiguration, id); return CircuitBreakers.registry().circuitBreaker("remote-rule-" + id, config); } @NotNull static CircuitBreakerConfig getCircuitBreakerConfig(RemoteRuleConfig c, String id) { CircuitBreakerConfig.SlidingWindowType type; try { type = CircuitBreakerConfig.SlidingWindowType.valueOf(c.getSlidingWindowType()); } catch (IllegalArgumentException e) { type = CircuitBreakerConfig.SlidingWindowType.COUNT_BASED; logger.warn("Couldn't parse slidingWindowType value '{}' for rule '{}', use one of {}; defaulting to '{}'", c.getSlidingWindowType(), id, Arrays.asList(CircuitBreakerConfig.SlidingWindowType.values()), type); } CircuitBreakerConfig config = CircuitBreakerConfig .custom() .failureRateThreshold(c.getFailureRateThreshold()) .slidingWindow( c.getSlidingWindowSize(), c.getMinimumNumberOfCalls(), type) .waitDurationInOpenState(Duration.ofMillis(Math.max(1, c.getDownMilliseconds()))) .enableAutomaticTransitionFromOpenToHalfOpen() .build(); return config; } @Override public boolean isPremium() { return premium; } /** * @param sentences text to check * @param textSessionId ID for texts, should stay constant for a user session; used for A/B tests of experimental rules * @return Future with result */ public FutureTask<RemoteRuleResult> run(List<AnalyzedSentence> sentences, @Nullable Long textSessionId) {<FILL_FUNCTION_BODY>
if (sentences.isEmpty()) { return new FutureTask<>(() -> new RemoteRuleResult(false, true, Collections.emptyList(), sentences)); } Map<String, String> context = MDC.getCopyOfContextMap(); return new FutureTask<>(() -> { MDC.clear(); if (context != null) { MDC.setContextMap(context); } long characters = sentences.stream().mapToInt(sentence -> sentence.getText().length()).sum(); long timeout = getTimeout(characters); RemoteRequest req = prepareRequest(sentences, textSessionId); RemoteRuleResult result; result = executeRequest(req, timeout).call(); if (fixOffsets) { for (AnalyzedSentence sentence : sentences) { List<RuleMatch> toFix = result.matchesForSentence(sentence); if (toFix != null) { fixMatchOffsets(sentence, toFix); } } } if (filterMatches) { List<RuleMatch> filteredMatches = new ArrayList<>(); for (AnalyzedSentence sentence : sentences) { List<RuleMatch> sentenceMatches = result.matchesForSentence(sentence); if (sentenceMatches != null) { List<RuleMatch> filteredSentenceMatches = RemoteRuleFilters.filterMatches( ruleLanguage, sentence, sentenceMatches); filteredMatches.addAll(filteredSentenceMatches); } } result = new RemoteRuleResult(result.isRemote(), result.isSuccess(), filteredMatches, sentences); } List<RuleMatch> filteredMatches = new ArrayList<>(); for (AnalyzedSentence sentence : sentences) { List<RuleMatch> sentenceMatches = result.matchesForSentence(sentence); if (sentenceMatches != null) { List<RuleMatch> filteredSentenceMatches = suppressMisspelled(sentenceMatches); filteredMatches.addAll(filteredSentenceMatches); } } result = new RemoteRuleResult(result.isRemote(), result.isSuccess(), filteredMatches, sentences); return result; });
723
553
1,276
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public void addTags(List<java.lang.String>) ,public void addToneTags(List<java.lang.String>) ,public int estimateContextForSureMatch() ,public List<org.languagetool.tagging.disambiguation.rules.DisambiguationPatternRule> getAntiPatterns() ,public org.languagetool.rules.Category getCategory() ,public java.lang.String getConfigureText() ,public final List<org.languagetool.rules.CorrectExample> getCorrectExamples() ,public int getDefaultValue() ,public abstract java.lang.String getDescription() ,public int getDistanceTokens() ,public final List<org.languagetool.rules.ErrorTriggeringExample> getErrorTriggeringExamples() ,public java.lang.String getFullId() ,public abstract java.lang.String getId() ,public final List<org.languagetool.rules.IncorrectExample> getIncorrectExamples() ,public org.languagetool.rules.ITSIssueType getLocQualityIssueType() ,public int getMaxConfigurableValue() ,public int getMinConfigurableValue() ,public int getMinPrevMatches() ,public int getPriority() ,public java.lang.String getSourceFile() ,public java.lang.String getSubId() ,public List<org.languagetool.Tag> getTags() ,public List<org.languagetool.ToneTag> getToneTags() ,public java.net.URL getUrl() ,public boolean hasConfigurableValue() ,public boolean hasTag(org.languagetool.Tag) ,public boolean hasToneTag(org.languagetool.ToneTag) ,public final boolean isDefaultOff() ,public final boolean isDefaultTempOff() ,public boolean isDictionaryBasedSpellingRule() ,public boolean isGoalSpecific() ,public final boolean isOfficeDefaultOff() ,public final boolean isOfficeDefaultOn() ,public boolean isPremium() ,public abstract org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public final void setCategory(org.languagetool.rules.Category) ,public final void setCorrectExamples(List<org.languagetool.rules.CorrectExample>) ,public final void setDefaultOff() ,public final void setDefaultOn() ,public final void setDefaultTempOff() ,public void setDistanceTokens(int) ,public final void setErrorTriggeringExamples(List<org.languagetool.rules.ErrorTriggeringExample>) ,public void setGoalSpecific(boolean) ,public final void setIncorrectExamples(List<org.languagetool.rules.IncorrectExample>) ,public void setLocQualityIssueType(org.languagetool.rules.ITSIssueType) ,public void setMinPrevMatches(int) ,public final void setOfficeDefaultOff() ,public final void setOfficeDefaultOn() ,public void setPremium(boolean) ,public void setPriority(int) ,public void setTags(List<org.languagetool.Tag>) ,public void setToneTags(List<org.languagetool.ToneTag>) ,public void setUrl(java.net.URL) ,public boolean supportsLanguage(org.languagetool.Language) ,public boolean useInOffice() <variables>private static final org.languagetool.rules.Category MISC,private org.languagetool.rules.Category category,private List<org.languagetool.rules.CorrectExample> correctExamples,private boolean defaultOff,private boolean defaultTempOff,private int distanceTokens,private List<org.languagetool.rules.ErrorTriggeringExample> errorTriggeringExamples,private List<org.languagetool.rules.IncorrectExample> incorrectExamples,private boolean isGoalSpecific,private boolean isPremium,private org.languagetool.rules.ITSIssueType locQualityIssueType,protected final non-sealed java.util.ResourceBundle messages,private int minPrevMatches,private boolean officeDefaultOff,private boolean officeDefaultOn,private int priority,private List<org.languagetool.Tag> tags,private List<org.languagetool.ToneTag> toneTags,private java.net.URL url
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/RemoteRuleConfig.java
RemoteRuleConfig
isRelevantConfig
class RemoteRuleConfig { private static final int DEFAULT_PORT = 443; private static final long DEFAULT_BASE_TIMEOUT = 1000; private static final float DEFAULT_TIMEOUT_PER_CHAR = 0; private static final long DEFAULT_DOWN = 5000L; private static final float DEFAULT_FAILURE_RATE_THRESHOLD = 50f; private static final String DEFAULT_SLIDING_WINDOW_TYPE = CircuitBreakerConfig.SlidingWindowType.TIME_BASED.name(); private static final int DEFAULT_SLIDING_WINDOW_SIZE = 60; private static final int DEFAULT_MINIMUM_NUMBER_OF_CALLS = 10; private static final LoadingCache<File, List<RemoteRuleConfig>> configCache = CacheBuilder.newBuilder() .expireAfterWrite(15, TimeUnit.MINUTES) .build(new CacheLoader<File, List<RemoteRuleConfig>>() { @Override public List<RemoteRuleConfig> load(File path) throws Exception { try (FileInputStream in = new FileInputStream(path)) { return parse(in); } } }); public String ruleId; public String url; public Integer port = DEFAULT_PORT; public long baseTimeoutMilliseconds = DEFAULT_BASE_TIMEOUT; public float timeoutPerCharacterMilliseconds = DEFAULT_TIMEOUT_PER_CHAR; public long downMilliseconds = DEFAULT_DOWN; public float failureRateThreshold = DEFAULT_FAILURE_RATE_THRESHOLD; public String slidingWindowType = DEFAULT_SLIDING_WINDOW_TYPE; public int slidingWindowSize = DEFAULT_SLIDING_WINDOW_SIZE; public int minimumNumberOfCalls = DEFAULT_MINIMUM_NUMBER_OF_CALLS; public Map<String, String> options = new HashMap<>(); public String language; public String type; public RemoteRuleConfig() { } public RemoteRuleConfig(RemoteRuleConfig copy) { this.ruleId = copy.ruleId; this.url = copy.url; this.port = copy.port; this.baseTimeoutMilliseconds = copy.baseTimeoutMilliseconds; this.timeoutPerCharacterMilliseconds = copy.timeoutPerCharacterMilliseconds; this.downMilliseconds = copy.downMilliseconds; this.failureRateThreshold = copy.failureRateThreshold; this.slidingWindowType = copy.slidingWindowType; this.slidingWindowSize = copy.slidingWindowSize; this.minimumNumberOfCalls = copy.minimumNumberOfCalls; this.options = new HashMap<>(copy.options); this.language = copy.language; this.type = copy.type; } public static RemoteRuleConfig getRelevantConfig(String rule, List<RemoteRuleConfig> configs) { return configs.stream().filter(config -> config.getRuleId().equals(rule)).findFirst().orElse(null); } public static Predicate<RemoteRuleConfig> isRelevantConfig(String type, Language language) {<FILL_FUNCTION_BODY>} public static List<RemoteRuleConfig> parse(InputStream json) throws IOException { ObjectMapper mapper = new ObjectMapper(new JsonFactory().enable(JsonParser.Feature.ALLOW_COMMENTS)); return mapper.readValue(json, new TypeReference<List<RemoteRuleConfig>>() {}); } public static List<RemoteRuleConfig> load(File configFile) throws ExecutionException { return configCache.get(configFile); } public float getFailureRateThreshold() { return failureRateThreshold; } public String getSlidingWindowType() { return slidingWindowType; } public int getSlidingWindowSize() { return slidingWindowSize; } public String getRuleId() { return ruleId; } public String getUrl() { return url; } public int getPort() { return port != null ? port : DEFAULT_PORT; } public long getDownMilliseconds() { return downMilliseconds; } public long getBaseTimeoutMilliseconds() { return baseTimeoutMilliseconds; } public float getTimeoutPerCharacterMilliseconds() { return timeoutPerCharacterMilliseconds; } public int getMinimumNumberOfCalls() { return minimumNumberOfCalls; } /** * miscellaneous options for remote rules * allows implementing additional behavior in subclasses * some options defined in {@link RemoteRule}: * fixOffsets: boolean - adjust offsets of matches because of discrepancies in string length for some unicode characters between Java and Python * filterMatches: boolean - enable anti-patterns from remote-rule-filters.xml * suppressMisspelledMatch: regex - filter out matches with matching rule IDs that have misspelled suggestions * suppressMisspelledSuggestions: regex - filter out misspelled suggestions from matches with matching rule IDs * */ public Map<String, String> getOptions() { return options; } /** * Regex to match language codes for which this rule should be applied */ public String getLanguage() { return language; } /** * Identifier for the implementation of RemoteRule that this configuration is meant for */ public String getType() { return type; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RemoteRuleConfig that = (RemoteRuleConfig) o; return new EqualsBuilder().append(baseTimeoutMilliseconds, that.baseTimeoutMilliseconds).append(timeoutPerCharacterMilliseconds, that.timeoutPerCharacterMilliseconds).append(downMilliseconds, that.downMilliseconds).append(failureRateThreshold, that.failureRateThreshold).append(slidingWindowSize, that.slidingWindowSize).append(minimumNumberOfCalls, that.minimumNumberOfCalls).append(ruleId, that.ruleId).append(url, that.url).append(port, that.port).append(slidingWindowType, that.slidingWindowType).append(options, that.options).append(language, that.language).append(type, that.type).isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37).append(ruleId).append(url).append(port).append(baseTimeoutMilliseconds).append(timeoutPerCharacterMilliseconds).append(downMilliseconds).append(failureRateThreshold).append(slidingWindowType).append(slidingWindowSize).append(minimumNumberOfCalls).append(options).append(language).append(type).toHashCode(); } @Override public String toString() { return new ToStringBuilder(this) .append("ruleId", ruleId) .append("url", url) .append("port", port) .append("baseTimeoutMilliseconds", baseTimeoutMilliseconds) .append("timeoutPerCharacterMilliseconds", timeoutPerCharacterMilliseconds) .append("downMilliseconds", downMilliseconds) .append("failureRateThreshold", failureRateThreshold) .append("slidingWindowType", slidingWindowType) .append("slidingWindowSize", slidingWindowSize) .append("minimumNumberOfCalls", minimumNumberOfCalls) .append("options", options) .append("language", language) .append("type", type) .toString(); } }
return (r) -> type.equals(r.type) && (r.language == null || language.getShortCodeWithCountryAndVariant().matches(r.language));
1,959
47
2,006
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/RemoteRuleFilters.java
RemoteRuleFilters
filterMatches
class RemoteRuleFilters { public static final String RULE_FILE = "remote-rule-filters.xml"; private static final LoadingCache<Language, List<Map.Entry<Pattern, List<AbstractPatternRule>>>> rules = CacheBuilder.newBuilder() .build(CacheLoader.from((lang) -> compilePatterns(RemoteRuleFilters.load(lang)))); private RemoteRuleFilters() { } public static List<RuleMatch> filterMatches(@NotNull Language lang, @NotNull AnalyzedSentence sentence, @NotNull List<RuleMatch> matches) throws ExecutionException, IOException {<FILL_FUNCTION_BODY>} static class ExpectedMatches { public String sentence; public List<ExpectedMatch> matches; } static class ExpectedMatch { public int offset; public int length; public String rule_id; } static class ExpectedRule extends Rule{ private final String id; public ExpectedRule(String id) { this.id = id; } @Override public String getId() { return id; } @Override public String getDescription() { return null; } @Override public RuleMatch[] match(AnalyzedSentence sentence) throws IOException { throw new IllegalStateException(); } } /** * Print matches remaining after filtering; arguments are language code and JSON file with matches * e.g. java [...] org.languagetool.rules.RemoteRuleFilters en matches.json */ public static void main(String[] args) throws Exception { String langCode = args[0]; String matchesFile = args[1]; Language lang = Languages.getLanguageForShortCode(langCode); List<AbstractPatternRule> rules = RemoteRuleFilters.load(lang) .values().stream().flatMap(Collection::stream).collect(Collectors.toList()); Stream<String> lines = Files.lines(Paths.get(matchesFile), StandardCharsets.UTF_8); ObjectMapper mapper = new ObjectMapper(); JLanguageTool lt = new JLanguageTool(lang); Map<String, List<AbstractMap.SimpleEntry<Boolean, RuleMatch>>> result = lines.parallel() .map(s -> { try { return mapper.readValue(s, ExpectedMatches.class); } catch (JsonProcessingException e) { throw new RuntimeException(e); } }) .flatMap(matches -> { try { AnalyzedSentence s = lt.getAnalyzedSentence(matches.sentence); List<RuleMatch> ruleMatches = matches.matches.stream().map( m -> new RuleMatch(new ExpectedRule(m.rule_id), s, m.offset, m.offset + m.length, "") ).collect(Collectors.toList()); List<RuleMatch> remaining = RemoteRuleFilters.filterMatches(lang, s, ruleMatches); ruleMatches.removeAll(remaining); return Streams.concat( remaining.stream().map(m -> new AbstractMap.SimpleEntry<>(true, m)), ruleMatches.stream().map(m -> new AbstractMap.SimpleEntry<>(false, m))); } catch (IOException | ExecutionException e) { throw new RuntimeException(e); } }) .collect(Collectors.groupingBy(key -> (key.getKey() ? "Remaining" : "Removed" ) + " - " + key.getValue().getRule().getId())); result.forEach((section, matches) -> { System.out.println(section); System.out.println("---"); for (Map.Entry<Boolean, RuleMatch> entry : matches) { RuleMatch match = entry.getValue(); String s = match.getSentence().getText(); String marked = s.substring(0, match.getFromPos()) + "<marker>" + s.substring(match.getFromPos(), match.getToPos()) + "</marker>" + s.substring(match.getToPos()); System.out.println(marked); } System.out.println("---"); }); } static Map<String, List<AbstractPatternRule>> load(Language lang) { JLanguageTool lt = lang.createDefaultJLanguageTool(); ResourceDataBroker dataBroker = JLanguageTool.getDataBroker(); String filename = dataBroker.getRulesDir() + "/" + getFilename(lang); try { List<AbstractPatternRule> allRules = lt.loadPatternRules(filename); Map<String, List<AbstractPatternRule>> rules = new HashMap<>(); for (AbstractPatternRule rule : allRules) { rules.computeIfAbsent(rule.getId(), k -> new ArrayList<>()).add(rule); } return rules; } catch (IOException e) { throw new RuntimeException(e); } } static List<Map.Entry<Pattern, List<AbstractPatternRule>>> compilePatterns(Map<String, List<AbstractPatternRule>> rules) { List<Map.Entry<Pattern, List<AbstractPatternRule>>> result = new ArrayList<>(rules.size()); // we treat rule ids in this file as regexes over rule IDs of matches // compile them once here and then reuse rules.forEach((ruleId, ruleList) -> { Pattern key = Pattern.compile(ruleId); result.add(new AbstractMap.SimpleImmutableEntry<>(key, ruleList)); }); return result; } @NotNull static String getFilename(Language lang) { // we don't support language variants in AI rules / remote rule filters at the moment; // this is another kind of variant, treat it as German if (lang.getShortCode().equals("de-DE-x-simple-language")) { lang = Languages.getLanguageForShortCode("de-DE"); } return lang.getShortCode() + "/" + RULE_FILE; } }
if (matches.isEmpty()) { return matches; } // load all relevant filters for given matches Set<String> matchIds = matches.stream().map(m -> m.getRule().getId()).collect(Collectors.toSet()); List<AbstractPatternRule> filters = rules.get(lang).stream() .filter(e -> matchIds.stream().anyMatch(id -> e.getKey().matcher(id).matches())) .flatMap(e -> e.getValue().stream()) .collect(Collectors.toList()); // prepare for lookup of matches Map<MatchPosition, Set<AbstractPatternRule>> filterRulesByPosition = new HashMap<>(); for (AbstractPatternRule rule : filters) { RuleMatch[] filterMatches = rule.match(sentence); for (RuleMatch match : filterMatches) { MatchPosition pos = new MatchPosition(match.getFromPos(), match.getToPos()); filterRulesByPosition.computeIfAbsent(pos, k -> new HashSet<>()).add(rule); } } List<RuleMatch> filteredMatches = matches.stream() .filter(match -> { MatchPosition pos = new MatchPosition(match.getFromPos(), match.getToPos()); // is there a filter match with the right ID at this position? boolean matched = filterRulesByPosition.getOrDefault(pos, Collections.emptySet()) .stream().anyMatch(rule -> match.getRule().getId().matches(rule.getId())); return !matched; }) .collect(Collectors.toList()); return filteredMatches;
1,539
408
1,947
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/RemoteRuleMetrics.java
RemoteRuleMetrics
inCircuitBreaker
class RemoteRuleMetrics { private static final Logger logger = LoggerFactory.getLogger(RemoteRuleMetrics.class); private RemoteRuleMetrics() { throw new IllegalStateException("RemoteRuleMetrics should only be used via static methods."); } public enum RequestResult { SUCCESS, SKIPPED, TIMEOUT, INTERRUPTED, DOWN, ERROR } // TODO: provide configuration as info? private static final double[] WAIT_BUCKETS = { .05, .1, .2, .3, .4, .5, .75, 1., 2., 5., 7.5, 10., 15. }; private static final double[] LATENCY_BUCKETS = { 0.025, 0.05, .1, .25, .5, .75, 1., 2., 4., 6., 8., 10., 15. }; private static final double[] SIZE_BUCKETS = { 25, 100, 500, 1000, 2500, 5000, 10000, 20000, 40000 }; private static final Histogram wait = Histogram .build("languagetool_remote_rule_wait_seconds", "Time spent waiting on remote rule results/timeouts") .labelNames("language") .buckets(WAIT_BUCKETS) .register(); private static final Histogram requestLatency = Histogram .build("languagetool_remote_rule_request_latency_seconds", "Request duration summary") .labelNames("rule_id", "result") .buckets(LATENCY_BUCKETS) .register(); private static final Histogram requestThroughput = Histogram .build("languagetool_remote_rule_request_throughput_characters", "Request size summary") .labelNames("rule_id", "result") .buckets(SIZE_BUCKETS) .register(); public static void request(String rule, long startNanos, long characters, RequestResult result) { long delta = System.nanoTime() - startNanos; requestLatency.labels(rule, result.name().toLowerCase()).observe((double) delta / 1e9); requestThroughput.labels(rule, result.name().toLowerCase()).observe(characters); } public static void wait(String langCode, long milliseconds) { wait.labels(langCode).observe(milliseconds / 1000.0); } @ApiStatus.Internal @Nullable public static <T> T inCircuitBreaker(long deadlineStartNanos, CircuitBreaker circuitBreaker, String ruleKey, long chars, Callable<T> fetchResults) throws InterruptedException {<FILL_FUNCTION_BODY>} }
try { return circuitBreaker.executeCallable(fetchResults); } catch (InterruptedException e) { logger.info("Failed to fetch result from remote rule '{}' - interrupted.", ruleKey); request(ruleKey, deadlineStartNanos, chars, RequestResult.INTERRUPTED); throw e; } catch (CancellationException e) { logger.info("Failed to fetch result from remote rule '{}' - cancelled.", ruleKey); request(ruleKey, deadlineStartNanos, chars, RequestResult.INTERRUPTED); } catch (TimeoutException e) { long timeout = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - deadlineStartNanos); logger.info("Failed to fetch result from remote rule '{}' - timed out ({}ms, {} chars).", ruleKey, timeout, chars); request(ruleKey, deadlineStartNanos, chars, RequestResult.TIMEOUT); } catch (CallNotPermittedException e) { logger.info("Failed to fetch result from remote rule '{}' - circuitbreaker active, rule marked as down.", ruleKey); request(ruleKey, deadlineStartNanos, chars, RequestResult.DOWN); } catch (Exception e) { if (ExceptionUtils.indexOfThrowable(e, TimeoutException.class) != -1) { long timeout = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - deadlineStartNanos); logger.info("Failed to fetch result from remote rule '{}' - timed out with exception {} ({}ms, {} chars).", ruleKey, e, timeout, chars); request(ruleKey, deadlineStartNanos, chars, RequestResult.TIMEOUT); } else { logger.warn("Failed to fetch result from remote rule '" + ruleKey + "' - error while executing rule.", e); request(ruleKey, deadlineStartNanos, chars, RequestResult.ERROR); } } return null;
770
508
1,278
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/RemoteRuleResult.java
RemoteRuleResult
matchesForSentence
class RemoteRuleResult { private final boolean remote; // was remote needed/involved? rules may filter input sentences and only call remote on some; for metrics private final boolean success; // successful -> for caching, so that we can cache: remote not needed for this sentence private final List<RuleMatch> matches; private final Set<AnalyzedSentence> processedSentences; // which sentences were processed? to distinguish between no matches because not processed (e.g. cached) // and no errors/corrections found private final Map<AnalyzedSentence, List<RuleMatch>> sentenceMatches = new HashMap<>(); public RemoteRuleResult(boolean remote, boolean success, List<RuleMatch> matches, List<AnalyzedSentence> processedSentences) { this.remote = remote; this.success = success; this.matches = matches; this.processedSentences = Collections.unmodifiableSet(new HashSet<>(processedSentences)); for (RuleMatch match : matches) { sentenceMatches.compute(match.getSentence(), (sentence, ruleMatches) -> { if (ruleMatches == null) { return new ArrayList<>(Collections.singletonList(match)); } else { ruleMatches.add(match); return ruleMatches; } }); } } public boolean isRemote() { return remote; } public boolean isSuccess() { return success; } public List<RuleMatch> getMatches() { return matches; } public Set<AnalyzedSentence> matchedSentences() { return sentenceMatches.keySet(); } public Set<AnalyzedSentence> processedSentences() { return processedSentences; } /** * get matches for a specific sentence * @param sentence sentence to look up * @return null if sentence not processed, else returned matches */ @Nullable public List<RuleMatch> matchesForSentence(AnalyzedSentence sentence) {<FILL_FUNCTION_BODY>} }
List<RuleMatch> defaultValue = processedSentences.contains(sentence) ? Collections.emptyList() : null; return sentenceMatches.getOrDefault(sentence, defaultValue);
520
51
571
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/RuleWithMaxFilter.java
RuleWithMaxFilter
filter
class RuleWithMaxFilter implements RuleMatchFilter { @Override public final List<RuleMatch> filter(List<RuleMatch> ruleMatches) {<FILL_FUNCTION_BODY>} final boolean includes(RuleMatch match, RuleMatch nextMatch) { if (match.getFromPos() <= nextMatch.getFromPos() && match.getToPos() >= nextMatch.getToPos()) { return true; } return false; } private boolean haveSameRule(RuleMatch match, RuleMatch nextMatch) { if (!(match.getRule() instanceof AbstractPatternRule) || !(nextMatch.getRule() instanceof AbstractPatternRule)) { return false; } String id1 = match.getRule().getId(); String subId1 = ((AbstractPatternRule) match.getRule()).getSubId(); String subId2 = ((AbstractPatternRule) nextMatch.getRule()).getSubId(); if (subId1 == null && subId2 != null) { return false; } if (subId1 != null && subId2 == null) { return false; } return id1 != null && id1.equals(nextMatch.getRule().getId()) && (subId1 == null && subId2 == null || subId1 != null && subId1.equals(subId2)); } }
Collections.sort(ruleMatches); List<RuleMatch> filteredRules = new ArrayList<>(); for (int i = 0; i < ruleMatches.size(); i++) { RuleMatch match = ruleMatches.get(i); if (i < ruleMatches.size() - 1) { RuleMatch nextMatch = ruleMatches.get(i + 1); while (includes(match, nextMatch) && haveSameRule(match, nextMatch) && i < ruleMatches.size()) { i++; // skip next match if (i < ruleMatches.size() - 1) { nextMatch = ruleMatches.get(i + 1); } } } filteredRules.add(match); } return filteredRules;
343
202
545
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/SameRuleGroupFilter.java
SameRuleGroupFilter
filter
class SameRuleGroupFilter implements RuleMatchFilter { /** * @param ruleMatches list of matches */ @Override public List<RuleMatch> filter(List<RuleMatch> ruleMatches) {<FILL_FUNCTION_BODY>} private boolean overlapAndMatch(RuleMatch match, RuleMatch nextMatch) { return overlaps(match, nextMatch) && haveSameRuleGroup(match, nextMatch); } boolean overlaps(RuleMatch match, RuleMatch nextMatch) { if (match.getFromPos() <= nextMatch.getToPos() && match.getToPos() >= nextMatch.getFromPos()) { return true; } return false; } private boolean haveSameRuleGroup(RuleMatch match, RuleMatch nextMatch) { String id1 = match.getRule().getId(); return id1 != null && id1.equals(nextMatch.getRule().getId()); } }
Collections.sort(ruleMatches); List<RuleMatch> filteredRules = new ArrayList<>(); for (int i = 0; i < ruleMatches.size(); i++) { RuleMatch match = ruleMatches.get(i); while (i < ruleMatches.size() - 1 && overlapAndMatch(match, ruleMatches.get(i + 1))) { i++; // skip next match } filteredRules.add(match); } return filteredRules;
237
130
367
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/ScoredConfusionSet.java
ScoredConfusionSet
equals
class ScoredConfusionSet { private List<ConfusionString> confusionWords; private final float score; /** * @param score the score that a string must get at least to be considered a correction, must be &gt; 0 */ public ScoredConfusionSet(float score, List<ConfusionString> words) { if (score <= 0) { throw new IllegalArgumentException("factor must be > 0: " + score); } this.score = score; confusionWords = words; } /* Alternative must be at least this much more probable to be considered correct. */ public float getScore() { return score; } public List<String> getConfusionTokens() { return confusionWords.stream().map(ConfusionString::getString).collect(Collectors.toList()); } public List<Optional<String>> getTokenDescriptions() { return confusionWords.stream() .map(ConfusionString::getDescription) .map(Optional::ofNullable) .collect(Collectors.toList()); } @Override public String toString() { return confusionWords.toString(); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(confusionWords, score); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; org.languagetool.rules.ScoredConfusionSet other = (org.languagetool.rules.ScoredConfusionSet) o; return Objects.equals(confusionWords, other.confusionWords) && Objects.equals(score, other.score);
360
105
465
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/SentenceWhitespaceRule.java
SentenceWhitespaceRule
match
class SentenceWhitespaceRule extends TextLevelRule { public SentenceWhitespaceRule(ResourceBundle messages) { super(messages); super.setCategory(Categories.TYPOGRAPHY.getCategory(messages)); setLocQualityIssueType(ITSIssueType.Whitespace); } @Override public String getId() { return "SENTENCE_WHITESPACE"; } @Override public String getDescription() { return messages.getString("missing_space_between_sentences"); } public String getMessage(boolean prevSentenceEndsWithNumber) { return messages.getString("addSpaceBetweenSentences"); } @Override public RuleMatch[] match(List<AnalyzedSentence> sentences) throws IOException {<FILL_FUNCTION_BODY>} @Override public int minToCheckParagraph() { return 0; } }
boolean isFirstSentence = true; boolean prevSentenceEndsWithWhitespace = false; boolean prevSentenceEndsWithNumber = false; List<RuleMatch> ruleMatches = new ArrayList<>(); int pos = 0; for (AnalyzedSentence sentence : sentences) { AnalyzedTokenReadings[] tokens = sentence.getTokens(); if (isFirstSentence) { isFirstSentence = false; } else { if (!prevSentenceEndsWithWhitespace && tokens.length > 1) { String firstToken = tokens[1].getToken(); RuleMatch ruleMatch = new RuleMatch(this, sentence, pos, pos+firstToken.length(), getMessage(prevSentenceEndsWithNumber)); ruleMatch.setSuggestedReplacement(" " + firstToken); ruleMatches.add(ruleMatch); } } if (tokens.length > 0) { String lastToken = tokens[tokens.length-1].getToken(); prevSentenceEndsWithWhitespace = lastToken.replace('\u00A0',' ').trim().isEmpty() && lastToken.length() == 1; } if (tokens.length > 1) { String prevLastToken = tokens[tokens.length-2].getToken(); prevSentenceEndsWithNumber = StringUtils.isNumeric(prevLastToken); } pos += sentence.getCorrectedTextLength(); } return toRuleMatchArray(ruleMatches);
245
374
619
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public int estimateContextForSureMatch() ,public org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>, org.languagetool.markup.AnnotatedText) throws java.io.IOException,public abstract org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>) throws java.io.IOException,public final org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public abstract int minToCheckParagraph() <variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/ShortenedYearRangeChecker.java
ShortenedYearRangeChecker
acceptRuleMatch
class ShortenedYearRangeChecker extends RuleFilter { @Nullable @Override public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> arguments, int patternTokenPos, AnalyzedTokenReadings[] patternTokens, List<Integer> tokenPositions) {<FILL_FUNCTION_BODY>} }
try { int x = Integer.parseInt(arguments.get("x")); String centuryPrefix = arguments.get("x").substring(0, 2); int y = Integer.parseInt(centuryPrefix + arguments.get("y")); if (x >= y) { return match; } } catch (IllegalArgumentException ignore) { // if something's fishy with the number – ignore it silently, // it's not a date range return null; } return null;
81
132
213
<methods>public non-sealed void <init>() ,public abstract org.languagetool.rules.RuleMatch acceptRuleMatch(org.languagetool.rules.RuleMatch, Map<java.lang.String,java.lang.String>, int, org.languagetool.AnalyzedTokenReadings[], List<java.lang.Integer>) throws java.io.IOException,public boolean matches(Map<java.lang.String,java.lang.String>, org.languagetool.AnalyzedTokenReadings[], int, List<java.lang.Integer>) throws java.io.IOException<variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/SimpleReplaceDataLoader.java
SimpleReplaceDataLoader
loadWords
class SimpleReplaceDataLoader { /** * Load replacement rules from a utf-8 file in the classpath. */ public Map<String, List<String>> loadWords(String path) {<FILL_FUNCTION_BODY>} }
InputStream stream = JLanguageTool.getDataBroker().getFromRulesDirAsStream(path); Map<String, List<String>> map = new HashMap<>(); try (Scanner scanner = new Scanner(stream, "utf-8")) { while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.isEmpty() || line.charAt(0) == '#') { // # = comment continue; } String[] parts = line.split("="); if (parts.length != 2) { throw new RuntimeException("Could not load simple replacement data from: " + path + ". " + "Error in line '" + line + "', expected format 'word=replacement'"); } if (parts[1].trim().isEmpty()) { throw new RuntimeException("Could not load simple replacement data from: " + path + ". " + "Error in line '" + line + "', replacement cannot be empty"); } String[] wrongForms = parts[0].split("\\|"); List<String> replacements = Arrays.asList(parts[1].split("\\|")); for (String wrongForm : wrongForms) { map.put(wrongForm, replacements); } } } return Collections.unmodifiableMap(map);
65
334
399
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/SuggestedReplacement.java
SuggestedReplacement
equals
class SuggestedReplacement { private String replacement; private String shortDescription; private String suffix; private SortedMap<String, Float> features = Collections.emptySortedMap(); private Float confidence = null; private SuggestionType type = SuggestionType.Default; /** classify the type of the suggestion so that downstream tasks (e.g. resorting, as in {@link BERTSuggestionRanking}) can treat them accordingly Default - default, no special treatment Translation - offers to translate words from native language into text language; suggestion ranking extends size of list of candidates Curated - a manually curated suggestion / special case / ...; don't resort */ public enum SuggestionType { Default, Translation, Curated } public SuggestedReplacement(String replacement) { this(replacement, null, null); } public SuggestedReplacement(String replacement, String shortDescription) { this(replacement, shortDescription, null); } public SuggestedReplacement(String replacement, String shortDescription, String suffix) { this.replacement = Objects.requireNonNull(replacement); this.shortDescription = shortDescription; this.suffix = suffix; } public SuggestedReplacement(SuggestedReplacement repl) { this.replacement = repl.replacement; this.suffix = repl.suffix; setShortDescription(repl.getShortDescription()); setConfidence(repl.getConfidence()); setFeatures(repl.getFeatures()); setType(repl.getType()); } public String getReplacement() { return replacement; } public void setReplacement(String replacement) { this.replacement = Objects.requireNonNull(replacement); } @Nullable public String getShortDescription() { return shortDescription; } public void setShortDescription(String desc) { this.shortDescription = desc; } /** @since 4.9 */ public void setType(SuggestionType type) { this.type = Objects.requireNonNull(type); } /** @since 4.9 */ @NotNull public SuggestionType getType() { return type; } /** * Value shown in the UI after the replacement (but not part of it). */ @Nullable public String getSuffix() { return suffix; } public void setSuffix(String val) { this.suffix = val; } @Override public String toString() { return replacement + '(' + shortDescription + ')'; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(replacement, shortDescription); } @Nullable public Float getConfidence() { return confidence; } public void setConfidence(@Nullable Float confidence) { this.confidence = confidence; } @NotNull public SortedMap<String, Float> getFeatures() { return Collections.unmodifiableSortedMap(features); } public void setFeatures(@NotNull SortedMap<String, Float> features) { this.features = features; } public static List<SuggestedReplacement> convert(List<String> suggestions) { return suggestions.stream().map(SuggestedReplacement::new).collect(Collectors.toList()); } public static List<SuggestedReplacement> topMatch(String word) { return topMatch(word, null); } public static List<SuggestedReplacement> topMatch(String word, String shortDesc) { SuggestedReplacement sugg = new SuggestedReplacement(word, shortDesc); sugg.setConfidence(SpellingCheckRule.HIGH_CONFIDENCE); return singletonList(sugg); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SuggestedReplacement that = (SuggestedReplacement) o; return replacement.equals(that.replacement) && Objects.equals(shortDescription, that.shortDescription);
1,037
81
1,118
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/SuggestionFilter.java
SuggestionFilter
filter
class SuggestionFilter { private final Rule rule; private final JLanguageTool lt; public SuggestionFilter(Rule rule, Language lang) { this.rule = Objects.requireNonNull(rule); this.lt = lang.createDefaultJLanguageTool(); } public List<String> filter(List<String> replacements, String template) {<FILL_FUNCTION_BODY>} }
List<String> newReplacements = new ArrayList<>(); for (String repl : replacements) { try { List<AnalyzedSentence> analyzedSentences = lt.analyzeText(template.replace("{}", repl)); RuleMatch[] matches = rule.match(analyzedSentences.get(0)); if (matches.length == 0) { newReplacements.add(repl); } } catch (IOException e) { throw new RuntimeException(e); } } return newReplacements;
111
144
255
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/SuppressIfAnyRuleMatchesFilter.java
SuppressIfAnyRuleMatchesFilter
acceptRuleMatch
class SuppressIfAnyRuleMatchesFilter extends RuleFilter { /* * Suppress the match if the new suggestion creates any new match with the rule IDs provided */ @Override public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> arguments, int patternTokenPos, AnalyzedTokenReadings[] patternTokens, List<Integer> tokenPositions) throws IOException {<FILL_FUNCTION_BODY>} }
List<String> ruleIDs = Arrays.asList(getRequired("ruleIDs", arguments).split(",")); JLanguageTool lt = ((PatternRule) match.getRule()).getLanguage().createDefaultJLanguageTool(); String sentence = match.getSentence().getText(); for (String replacement : match.getSuggestedReplacements()) { String newSentence = sentence.substring(0, match.getFromPos()) + replacement + sentence.substring(match.getToPos()); AnalyzedSentence analyzedSentence = lt.analyzeText(newSentence).get(0); for (Rule r: lt.getAllActiveRules()) { if (ruleIDs.contains(r.getId())) { RuleMatch matches[] = r.match(analyzedSentence); for (RuleMatch m : matches) { if ((m.getToPos() >= match.getFromPos() && m.getToPos() <= match.getToPos()) || (match.getToPos() >= m.getFromPos() && match.getToPos() <= m.getToPos())) { return null; } } } } } return match;
110
298
408
<methods>public non-sealed void <init>() ,public abstract org.languagetool.rules.RuleMatch acceptRuleMatch(org.languagetool.rules.RuleMatch, Map<java.lang.String,java.lang.String>, int, org.languagetool.AnalyzedTokenReadings[], List<java.lang.Integer>) throws java.io.IOException,public boolean matches(Map<java.lang.String,java.lang.String>, org.languagetool.AnalyzedTokenReadings[], int, List<java.lang.Integer>) throws java.io.IOException<variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/TestHackHelper.java
TestHackHelper
isJUnitTest
class TestHackHelper { private TestHackHelper() { } public static boolean isJUnitTest() {<FILL_FUNCTION_BODY>} }
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); for (StackTraceElement element : stackTrace) { if (element.getClassName().startsWith("org.junit.") || element.getClassName().equals("org.languagetool.rules.patterns.PatternRuleTest")) { return true; } } return false;
46
97
143
<no_super_class>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/TestRemoteRule.java
TestRemoteRequest
executeRequest
class TestRemoteRequest extends RemoteRequest { private final List<AnalyzedSentence> sentences; TestRemoteRequest(List<AnalyzedSentence> sentences) { this.sentences = sentences; } } @Override protected RemoteRequest prepareRequest(List<AnalyzedSentence> sentences, Long textSessionId) { return new TestRemoteRequest(sentences); } private RuleMatch testMatch(AnalyzedSentence s) { return new RuleMatch(this, s, 0, 1, "Test match"); } @Override protected Callable<RemoteRuleResult> executeRequest(RemoteRequest request, long timeoutMilliseconds) throws TimeoutException {<FILL_FUNCTION_BODY>
return () -> { TestRemoteRequest req = (TestRemoteRequest) request; List<RuleMatch> matches = req.sentences.stream().map(this::testMatch).collect(Collectors.toList()); long deadline = System.currentTimeMillis() + waitTime; //noinspection StatementWithEmptyBody Thread.sleep(waitTime); // cancelling only works if implementations respect interrupts or timeouts //while(true); return new RemoteRuleResult(true, true, matches, req.sentences); };
180
137
317
<methods>public void <init>(org.languagetool.Language, java.util.ResourceBundle, org.languagetool.rules.RemoteRuleConfig, boolean, java.lang.String) ,public void <init>(org.languagetool.Language, java.util.ResourceBundle, org.languagetool.rules.RemoteRuleConfig, boolean) ,public CircuitBreaker circuitBreaker() ,public static void fixMatchOffsets(org.languagetool.AnalyzedSentence, List<org.languagetool.rules.RuleMatch>) ,public java.lang.String getId() ,public org.languagetool.rules.RemoteRuleConfig getServiceConfiguration() ,public long getTimeout(long) ,public boolean isPremium() ,public org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public FutureTask<org.languagetool.rules.RemoteRuleResult> run(List<org.languagetool.AnalyzedSentence>) ,public FutureTask<org.languagetool.rules.RemoteRuleResult> run(List<org.languagetool.AnalyzedSentence>, java.lang.Long) ,public static void shutdown() <variables>protected static final ConcurrentMap<java.lang.String,CircuitBreaker> circuitBreakers,protected final non-sealed boolean filterMatches,protected final non-sealed boolean fixOffsets,protected final non-sealed boolean inputLogging,private static final Logger logger,protected final non-sealed org.languagetool.JLanguageTool lt,protected final non-sealed boolean premium,protected final non-sealed org.languagetool.Language ruleLanguage,protected final non-sealed org.languagetool.rules.RemoteRuleConfig serviceConfiguration,protected static final List<java.lang.Runnable> shutdownRoutines,protected final non-sealed java.util.regex.Pattern suppressMisspelledMatch,protected final non-sealed java.util.regex.Pattern suppressMisspelledSuggestions,protected final non-sealed boolean whitespaceNormalisation
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/UnderlineSpacesFilter.java
UnderlineSpacesFilter
acceptRuleMatch
class UnderlineSpacesFilter extends RuleFilter { /* * Underline the whitespaces before and/or after the marker in the pattern */ public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> arguments, int patternTokenPos, AnalyzedTokenReadings[] patternTokens, List<Integer> tokenPositions) throws IOException {<FILL_FUNCTION_BODY>} }
String underlineSpaces = getRequired("underlineSpaces", arguments); // before/after/both String sentence = match.getSentence().getText(); if (underlineSpaces.equals("before") || underlineSpaces.equals("both")) { if (match.getFromPos() - 1 >= 0 && StringTools.isWhitespace(sentence.substring(match.getFromPos() - 1, match.getFromPos()))) { match.setOffsetPosition(match.getFromPos() - 1, match.getToPos()); } } if (underlineSpaces.equals("after") || underlineSpaces.equals("both")) { if (match.getToPos() + 1 < sentence.length() && StringTools.isWhitespace(sentence.substring(match.getToPos(), match.getToPos() + 1))) { match.setOffsetPosition(match.getFromPos(), match.getToPos() + 1); } } return match;
99
249
348
<methods>public non-sealed void <init>() ,public abstract org.languagetool.rules.RuleMatch acceptRuleMatch(org.languagetool.rules.RuleMatch, Map<java.lang.String,java.lang.String>, int, org.languagetool.AnalyzedTokenReadings[], List<java.lang.Integer>) throws java.io.IOException,public boolean matches(Map<java.lang.String,java.lang.String>, org.languagetool.AnalyzedTokenReadings[], int, List<java.lang.Integer>) throws java.io.IOException<variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/UnsyncStack.java
UnsyncStack
peek
class UnsyncStack<E> extends ArrayList<E> { /** Generated automatically. */ private static final long serialVersionUID = -4984830372178073605L; UnsyncStack() { } /** * Pushes an item onto the top of this stack. This has exactly the same effect * as: {@code add(item)} * * @param item the item to be pushed onto this stack. * @return the <code>item</code> argument. * @see ArrayList#add */ public E push(E item) { add(item); return item; } /** * Removes the object at the top of this stack and returns that object as the * value of this function. * * @return The object at the top of this stack (the last item of the * <tt>ArrayList</tt> object). * @exception EmptyStackException if this stack is empty. */ public E pop() { E obj; int len = size(); obj = peek(); remove(len - 1); return obj; } /** * Looks at the object at the top of this stack without removing it from the * stack. * * @return the object at the top of this stack (the last item of the * <tt>ArrayList</tt> object). * @exception EmptyStackException if this stack is empty. */ public E peek() {<FILL_FUNCTION_BODY>} /** * Tests if this stack is empty. * * @return <code>true</code> if and only if this stack contains no items; * <code>false</code> otherwise. */ public boolean empty() { return size() == 0; } /** * Returns the 1-based position where an object is on this stack. If the * object <tt>o</tt> occurs as an item in this stack, this method returns the * distance from the top of the stack of the occurrence nearest the top of the * stack; the topmost item on the stack is considered to be at distance * <tt>1</tt>. The <tt>equals</tt> method is used to compare <tt>o</tt> to the * items in this stack. * * @param o * the desired object. * @return the 1-based position from the top of the stack where the object is * located; the return value <code>-1</code> indicates that the object * is not on the stack. */ public int search(Object o) { int i = lastIndexOf(o); if (i >= 0) { return size() - i; } return -1; } }
int len = size(); if (len == 0) { throw new EmptyStackException(); } return get(len - 1);
734
41
775
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Collection<? extends E>) ,public boolean add(E) ,public void add(int, E) ,public boolean addAll(Collection<? extends E>) ,public boolean addAll(int, Collection<? extends E>) ,public void clear() ,public java.lang.Object clone() ,public boolean contains(java.lang.Object) ,public void ensureCapacity(int) ,public boolean equals(java.lang.Object) ,public void forEach(Consumer<? super E>) ,public E get(int) ,public int hashCode() ,public int indexOf(java.lang.Object) ,public boolean isEmpty() ,public Iterator<E> iterator() ,public int lastIndexOf(java.lang.Object) ,public ListIterator<E> listIterator() ,public ListIterator<E> listIterator(int) ,public E remove(int) ,public boolean remove(java.lang.Object) ,public boolean removeAll(Collection<?>) ,public boolean removeIf(Predicate<? super E>) ,public void replaceAll(UnaryOperator<E>) ,public boolean retainAll(Collection<?>) ,public E set(int, E) ,public int size() ,public void sort(Comparator<? super E>) ,public Spliterator<E> spliterator() ,public List<E> subList(int, int) ,public java.lang.Object[] toArray() ,public T[] toArray(T[]) ,public void trimToSize() <variables>private static final java.lang.Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA,private static final int DEFAULT_CAPACITY,private static final java.lang.Object[] EMPTY_ELEMENTDATA,transient java.lang.Object[] elementData,private static final long serialVersionUID,private int size
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/WhiteSpaceAtBeginOfParagraph.java
WhiteSpaceAtBeginOfParagraph
match
class WhiteSpaceAtBeginOfParagraph extends Rule { public WhiteSpaceAtBeginOfParagraph(ResourceBundle messages, boolean defaultActive) { super(messages); super.setCategory(Categories.STYLE.getCategory(messages)); if (!defaultActive) { setDefaultOff(); } setOfficeDefaultOn(); setLocQualityIssueType(ITSIssueType.Style); } public WhiteSpaceAtBeginOfParagraph(ResourceBundle messages) { this(messages, false); } @Override public String getId() { return "WHITESPACE_PARAGRAPH_BEGIN"; } @Override public String getDescription() { return messages.getString("whitespace_at_begin_parapgraph_desc"); } private boolean isWhitespaceDel (AnalyzedTokenReadings token) { // returns only whitespaces that may be deleted // "\u200B" is excluded to prevent function (e.g. page number, page count) in LO/OO return token.isWhitespace() && !token.getToken().equals("\u200B") && !token.isLinebreak(); } @Override public RuleMatch[] match(AnalyzedSentence sentence) throws IOException {<FILL_FUNCTION_BODY>} }
List<RuleMatch> ruleMatches = new ArrayList<>(); AnalyzedTokenReadings[] tokens = sentence.getTokens(); int i; for (i = 1; i < tokens.length && isWhitespaceDel(tokens[i]); i++); if (i > 1 && i < tokens.length && !tokens[i].isLinebreak()) { RuleMatch ruleMatch = new RuleMatch(this, sentence, tokens[1].getStartPos(), tokens[i].getEndPos(), messages.getString("whitespace_at_begin_parapgraph_msg")); ruleMatch.setSuggestedReplacement(tokens[i].getToken()); ruleMatches.add(ruleMatch); } return toRuleMatchArray(ruleMatches);
335
189
524
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public void addTags(List<java.lang.String>) ,public void addToneTags(List<java.lang.String>) ,public int estimateContextForSureMatch() ,public List<org.languagetool.tagging.disambiguation.rules.DisambiguationPatternRule> getAntiPatterns() ,public org.languagetool.rules.Category getCategory() ,public java.lang.String getConfigureText() ,public final List<org.languagetool.rules.CorrectExample> getCorrectExamples() ,public int getDefaultValue() ,public abstract java.lang.String getDescription() ,public int getDistanceTokens() ,public final List<org.languagetool.rules.ErrorTriggeringExample> getErrorTriggeringExamples() ,public java.lang.String getFullId() ,public abstract java.lang.String getId() ,public final List<org.languagetool.rules.IncorrectExample> getIncorrectExamples() ,public org.languagetool.rules.ITSIssueType getLocQualityIssueType() ,public int getMaxConfigurableValue() ,public int getMinConfigurableValue() ,public int getMinPrevMatches() ,public int getPriority() ,public java.lang.String getSourceFile() ,public java.lang.String getSubId() ,public List<org.languagetool.Tag> getTags() ,public List<org.languagetool.ToneTag> getToneTags() ,public java.net.URL getUrl() ,public boolean hasConfigurableValue() ,public boolean hasTag(org.languagetool.Tag) ,public boolean hasToneTag(org.languagetool.ToneTag) ,public final boolean isDefaultOff() ,public final boolean isDefaultTempOff() ,public boolean isDictionaryBasedSpellingRule() ,public boolean isGoalSpecific() ,public final boolean isOfficeDefaultOff() ,public final boolean isOfficeDefaultOn() ,public boolean isPremium() ,public abstract org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public final void setCategory(org.languagetool.rules.Category) ,public final void setCorrectExamples(List<org.languagetool.rules.CorrectExample>) ,public final void setDefaultOff() ,public final void setDefaultOn() ,public final void setDefaultTempOff() ,public void setDistanceTokens(int) ,public final void setErrorTriggeringExamples(List<org.languagetool.rules.ErrorTriggeringExample>) ,public void setGoalSpecific(boolean) ,public final void setIncorrectExamples(List<org.languagetool.rules.IncorrectExample>) ,public void setLocQualityIssueType(org.languagetool.rules.ITSIssueType) ,public void setMinPrevMatches(int) ,public final void setOfficeDefaultOff() ,public final void setOfficeDefaultOn() ,public void setPremium(boolean) ,public void setPriority(int) ,public void setTags(List<org.languagetool.Tag>) ,public void setToneTags(List<org.languagetool.ToneTag>) ,public void setUrl(java.net.URL) ,public boolean supportsLanguage(org.languagetool.Language) ,public boolean useInOffice() <variables>private static final org.languagetool.rules.Category MISC,private org.languagetool.rules.Category category,private List<org.languagetool.rules.CorrectExample> correctExamples,private boolean defaultOff,private boolean defaultTempOff,private int distanceTokens,private List<org.languagetool.rules.ErrorTriggeringExample> errorTriggeringExamples,private List<org.languagetool.rules.IncorrectExample> incorrectExamples,private boolean isGoalSpecific,private boolean isPremium,private org.languagetool.rules.ITSIssueType locQualityIssueType,protected final non-sealed java.util.ResourceBundle messages,private int minPrevMatches,private boolean officeDefaultOff,private boolean officeDefaultOn,private int priority,private List<org.languagetool.Tag> tags,private List<org.languagetool.ToneTag> toneTags,private java.net.URL url
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/WhiteSpaceBeforeParagraphEnd.java
WhiteSpaceBeforeParagraphEnd
match
class WhiteSpaceBeforeParagraphEnd extends TextLevelRule { private final Language lang; public WhiteSpaceBeforeParagraphEnd(ResourceBundle messages, Language lang, boolean defaultActive) { super(messages); super.setCategory(Categories.STYLE.getCategory(messages)); this.lang = lang; if (!defaultActive) { setDefaultOff(); } setOfficeDefaultOn(); setLocQualityIssueType(ITSIssueType.Style); } public WhiteSpaceBeforeParagraphEnd(ResourceBundle messages, Language lang) { this(messages, lang, false); } @Override public String getId() { return "WHITESPACE_PARAGRAPH"; } @Override public String getDescription() { return messages.getString("whitespace_before_parapgraph_end_desc"); } @Override public RuleMatch[] match(List<AnalyzedSentence> sentences) throws IOException {<FILL_FUNCTION_BODY>} @Override public int minToCheckParagraph() { return 0; } }
List<RuleMatch> ruleMatches = new ArrayList<>(); int pos = 0; for (int n = 0; n < sentences.size(); n++) { AnalyzedSentence sentence = sentences.get(n); if(Tools.isParagraphEnd(sentences, n, lang)) { AnalyzedTokenReadings[] tokens = sentence.getTokens(); int lb; int lw; for (lb = tokens.length - 1; lb > 0 && tokens[lb].isLinebreak(); lb--); for (lw = lb; lw > 0 && tokens[lw].isWhitespace() && !tokens[lw].getToken().equals("\u200B"); lw--); if(lw < lb) { int fromPos = tokens[lw].isWhitespace() ? pos + tokens[lw + 1].getStartPos() : pos + tokens[lw].getStartPos(); int toPos = pos + tokens[lb].getEndPos(); RuleMatch ruleMatch = new RuleMatch(this, sentence, fromPos, toPos, messages.getString("whitespace_before_parapgraph_end_msg")); if (lw > 0 && !tokens[lw].isWhitespace()) { ruleMatch.setSuggestedReplacement(tokens[lw].getToken()); } else { ruleMatch.setSuggestedReplacement(""); } ruleMatches.add(ruleMatch); } } pos += sentence.getCorrectedTextLength(); } return toRuleMatchArray(ruleMatches);
290
401
691
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public int estimateContextForSureMatch() ,public org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>, org.languagetool.markup.AnnotatedText) throws java.io.IOException,public abstract org.languagetool.rules.RuleMatch[] match(List<org.languagetool.AnalyzedSentence>) throws java.io.IOException,public final org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public abstract int minToCheckParagraph() <variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/WhitespaceBeforePunctuationRule.java
WhitespaceBeforePunctuationRule
match
class WhitespaceBeforePunctuationRule extends Rule { public WhitespaceBeforePunctuationRule(ResourceBundle messages) { super(messages); super.setCategory(Categories.TYPOGRAPHY.getCategory(messages)); setLocQualityIssueType(ITSIssueType.Whitespace); } @Override public final String getId() { return "WHITESPACE_PUNCTUATION"; } @Override public final String getDescription() { return messages.getString("desc_whitespace_before_punctuation"); } @Override public final RuleMatch[] match(AnalyzedSentence sentence) {<FILL_FUNCTION_BODY>} }
List<RuleMatch> ruleMatches = new ArrayList<>(); AnalyzedTokenReadings[] tokens = sentence.getTokens(); boolean prevWhite = false; int prevLen = 0; for (int i = 0; i < tokens.length; i++) { String token = tokens[i].getToken(); boolean isWhitespace = tokens[i].isWhitespace() || StringTools.isNonBreakingWhitespace(token) || tokens[i].isFieldCode(); String msg = null; String suggestionText = null; if (prevWhite) { if (token.equals(":")) { msg = messages.getString("no_space_before_colon"); suggestionText = ":"; // exception case for figures such as " : 0" if (i + 2 < tokens.length && tokens[i + 1].isWhitespace() && Character.isDigit(tokens[i + 2].getToken().charAt(0))) { msg = null; } } else if (token.equals(";")) { msg = messages.getString("no_space_before_semicolon"); suggestionText = ";"; } else if (i > 1 && token.equals("%")) { String prevPrevToken = tokens[i - 2].getToken(); if (prevPrevToken.length() > 0 && Character.isDigit(prevPrevToken.charAt(0))) { msg = messages.getString("no_space_before_percentage"); suggestionText = "%"; } } } if (msg != null) { int fromPos = tokens[i - 1].getStartPos(); int toPos = tokens[i - 1].getStartPos() + 1 + prevLen; RuleMatch ruleMatch = new RuleMatch(this, sentence, fromPos, toPos, msg); ruleMatch.setSuggestedReplacement(suggestionText); ruleMatches.add(ruleMatch); } prevWhite = isWhitespace && !tokens[i].isFieldCode(); //OOo code before comma/dot prevLen = tokens[i].getToken().length(); } return toRuleMatchArray(ruleMatches);
187
549
736
<methods>public void <init>() ,public void <init>(java.util.ResourceBundle) ,public void addTags(List<java.lang.String>) ,public void addToneTags(List<java.lang.String>) ,public int estimateContextForSureMatch() ,public List<org.languagetool.tagging.disambiguation.rules.DisambiguationPatternRule> getAntiPatterns() ,public org.languagetool.rules.Category getCategory() ,public java.lang.String getConfigureText() ,public final List<org.languagetool.rules.CorrectExample> getCorrectExamples() ,public int getDefaultValue() ,public abstract java.lang.String getDescription() ,public int getDistanceTokens() ,public final List<org.languagetool.rules.ErrorTriggeringExample> getErrorTriggeringExamples() ,public java.lang.String getFullId() ,public abstract java.lang.String getId() ,public final List<org.languagetool.rules.IncorrectExample> getIncorrectExamples() ,public org.languagetool.rules.ITSIssueType getLocQualityIssueType() ,public int getMaxConfigurableValue() ,public int getMinConfigurableValue() ,public int getMinPrevMatches() ,public int getPriority() ,public java.lang.String getSourceFile() ,public java.lang.String getSubId() ,public List<org.languagetool.Tag> getTags() ,public List<org.languagetool.ToneTag> getToneTags() ,public java.net.URL getUrl() ,public boolean hasConfigurableValue() ,public boolean hasTag(org.languagetool.Tag) ,public boolean hasToneTag(org.languagetool.ToneTag) ,public final boolean isDefaultOff() ,public final boolean isDefaultTempOff() ,public boolean isDictionaryBasedSpellingRule() ,public boolean isGoalSpecific() ,public final boolean isOfficeDefaultOff() ,public final boolean isOfficeDefaultOn() ,public boolean isPremium() ,public abstract org.languagetool.rules.RuleMatch[] match(org.languagetool.AnalyzedSentence) throws java.io.IOException,public final void setCategory(org.languagetool.rules.Category) ,public final void setCorrectExamples(List<org.languagetool.rules.CorrectExample>) ,public final void setDefaultOff() ,public final void setDefaultOn() ,public final void setDefaultTempOff() ,public void setDistanceTokens(int) ,public final void setErrorTriggeringExamples(List<org.languagetool.rules.ErrorTriggeringExample>) ,public void setGoalSpecific(boolean) ,public final void setIncorrectExamples(List<org.languagetool.rules.IncorrectExample>) ,public void setLocQualityIssueType(org.languagetool.rules.ITSIssueType) ,public void setMinPrevMatches(int) ,public final void setOfficeDefaultOff() ,public final void setOfficeDefaultOn() ,public void setPremium(boolean) ,public void setPriority(int) ,public void setTags(List<org.languagetool.Tag>) ,public void setToneTags(List<org.languagetool.ToneTag>) ,public void setUrl(java.net.URL) ,public boolean supportsLanguage(org.languagetool.Language) ,public boolean useInOffice() <variables>private static final org.languagetool.rules.Category MISC,private org.languagetool.rules.Category category,private List<org.languagetool.rules.CorrectExample> correctExamples,private boolean defaultOff,private boolean defaultTempOff,private int distanceTokens,private List<org.languagetool.rules.ErrorTriggeringExample> errorTriggeringExamples,private List<org.languagetool.rules.IncorrectExample> incorrectExamples,private boolean isGoalSpecific,private boolean isPremium,private org.languagetool.rules.ITSIssueType locQualityIssueType,protected final non-sealed java.util.ResourceBundle messages,private int minPrevMatches,private boolean officeDefaultOff,private boolean officeDefaultOn,private int priority,private List<org.languagetool.Tag> tags,private List<org.languagetool.ToneTag> toneTags,private java.net.URL url
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/WhitespaceCheckFilter.java
WhitespaceCheckFilter
acceptRuleMatch
class WhitespaceCheckFilter extends RuleFilter { @Override public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> arguments, int patternTokenPos, AnalyzedTokenReadings[] patternTokens, List<Integer> tokenPositions) {<FILL_FUNCTION_BODY>} }
String wsChar = getRequired("whitespaceChar", arguments); int pos = Integer.parseInt(getRequired("position", arguments)); if (pos < 1 || pos > patternTokens.length) { throw new IllegalArgumentException("Wrong position in WhitespaceCheckFilter: " + pos + ", must be 1 to " + patternTokens.length); } if (!patternTokens[pos - 1].getWhitespaceBefore().equals(wsChar)) { return match; } else { return null; }
79
135
214
<methods>public non-sealed void <init>() ,public abstract org.languagetool.rules.RuleMatch acceptRuleMatch(org.languagetool.rules.RuleMatch, Map<java.lang.String,java.lang.String>, int, org.languagetool.AnalyzedTokenReadings[], List<java.lang.Integer>) throws java.io.IOException,public boolean matches(Map<java.lang.String,java.lang.String>, org.languagetool.AnalyzedTokenReadings[], int, List<java.lang.Integer>) throws java.io.IOException<variables>
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/rules/WordCoherencyDataLoader.java
WordCoherencyDataLoader
loadWords
class WordCoherencyDataLoader { public Map<String, Set<String>> loadWords(String path) {<FILL_FUNCTION_BODY>} }
InputStream stream = JLanguageTool.getDataBroker().getFromRulesDirAsStream(path); Map<String, Set<String>> map = new Object2ObjectOpenHashMap<>(); try ( InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8); BufferedReader br = new BufferedReader(reader) ) { String line; while ((line = br.readLine()) != null) { if (line.isEmpty() || line.charAt(0) == '#') { // ignore comments continue; } String[] parts = line.split(";"); if (parts.length != 2) { throw new IOException("Format error in file " + path + ", line: " + line); } if(map.containsKey(parts[0])) { map.get(parts[0]).add(parts[1]); } else { map.put(parts[0], Stream.of(parts[1]).collect(Collectors.toCollection(ObjectOpenHashSet::new))); } if(map.containsKey(parts[1])) { map.get(parts[1]).add(parts[0]); } else { map.put(parts[1], Stream.of(parts[0]).collect(Collectors.toCollection(ObjectOpenHashSet::new))); } } } catch (IOException e) { throw new RuntimeException("Could not load coherency data from " + path, e); } return Collections.unmodifiableMap(map);
44
388
432
<no_super_class>