示例#1
0
  @Test
  public void testRuleRender() {
    final Rule rule = new Rule("myrule", new Integer(42), 1);
    rule.setComment("rule comments");

    final Condition cond = new Condition();
    cond.setComment("cond comment");
    cond.setSnippet("cond snippet");
    rule.addCondition(cond);

    final Consequence cons = new Consequence();
    cons.setComment("cons comment");
    cons.setSnippet("cons snippet;");
    rule.addConsequence(cons);
    rule.addConsequence(cons);

    final DRLOutput out = new DRLOutput();
    rule.renderDRL(out);
    final String drl = out.getDRL();
    assertNotNull(drl);

    assertTrue(drl.indexOf("cond snippet") != -1);
    assertTrue(drl.indexOf("cons snippet") != -1);
    assertTrue(drl.indexOf("salience 42") != -1);
    assertTrue(drl.indexOf("salience 42") < drl.indexOf("when"));
    assertTrue(drl.indexOf("cond snippet") < drl.indexOf("then"));
    assertTrue(drl.indexOf("cons snippet;") > drl.indexOf("then"));
    assertTrue(drl.indexOf("rule") != -1);
    assertTrue(drl.indexOf("end") > drl.indexOf("rule "));
    assertTrue(drl.indexOf("//rule comments") > -1);
  }
示例#2
0
  public Pack fromDefault(Pack pack) {
    Rule rule = pack.getRule();
    Target target = rule.getTarget();
    TuplePrototype targetPrototype = target.getPrototype();

    Function call = pack.getPriorCall();
    if (call == null) {
      throw new DefaultPackExpansionException("Cannot use implicit pack in a call-free chain.");
    }
    TuplePrototype callPrototype = target.getPrototype();

    if (callPrototype.size() != targetPrototype.size()) {
      throw new DefaultPackExpansionException(
          "Default pack cannot be created because tuple prototypes are of different lengths.");
    }

    Pack newPack = (Pack) adaptor.dupNode(pack);

    for (int i = 0; i < targetPrototype.size(); i++) {
      TupleRef ref = (TupleRef) adaptor.create(TUPLE_REF, "");
      adaptor.addChild(ref, adaptor.create(NUMBER, Integer.toString(i)));
      adaptor.addChild(newPack, ref);
    }

    return newPack;
  }
示例#3
0
  /** Returns the places of possible breaks between sentences. */
  private static List<BreakPosition> getBreaks(String paragraph, Rule rule) {
    List<BreakPosition> res = new ArrayList<BreakPosition>();

    Matcher bbm = null;
    if (rule.getBeforebreak() != null) bbm = rule.getCompiledBeforebreak().matcher(paragraph);
    Matcher abm = null;
    if (rule.getAfterbreak() != null) abm = rule.getCompiledAfterbreak().matcher(paragraph);

    if (bbm == null && abm == null) return res;

    if (abm != null) if (!abm.find()) return res;

    if (bbm == null) bbm = DEFAULT_BEFOREBREAK_PATTERN.matcher(paragraph);

    while (bbm.find()) {
      int bbe = bbm.end();
      if (abm == null) res.add(new BreakPosition(bbe, rule));
      else {
        int abs = abm.start();
        while (abs < bbe) {
          boolean found = abm.find();
          if (!found) return res;
          abs = abm.start();
        }
        if (abs == bbe) res.add(new BreakPosition(bbe, rule));
      }
    }

    return res;
  }
示例#4
0
 static {
   HashMap hashmap = MasterConfig.getMasterConfig();
   StringProperty astringproperty[] = new StringProperty[0];
   addProperties("COM.dragonflow.StandardMonitor.IPlanetWSMonitor", astringproperty);
   addClassElement(
       "COM.dragonflow.StandardMonitor.IPlanetWSMonitor",
       Rule.stringToClassifier("countersInError > 0\terror"));
   addClassElement(
       "COM.dragonflow.StandardMonitor.IPlanetWSMonitor", Rule.stringToClassifier("always\tgood"));
   setClassProperty(
       "COM.dragonflow.StandardMonitor.IPlanetWSMonitor",
       "description",
       "Monitors IPlanet Web servers using snmp.");
   setClassProperty("COM.dragonflow.StandardMonitor.IPlanetWSMonitor", "help", "IPWSMon.htm");
   setClassProperty(
       "COM.dragonflow.StandardMonitor.IPlanetWSMonitor", "title", "IPlanet Web Server");
   setClassProperty(
       "COM.dragonflow.StandardMonitor.IPlanetWSMonitor", "class", "IPlanetWSMonitor");
   setClassProperty("COM.dragonflow.StandardMonitor.IPlanetWSMonitor", "target", "_server");
   setClassProperty(
       "COM.dragonflow.StandardMonitor.IPlanetWSMonitor", "topazName", "IPlanet Web Server");
   setClassProperty("COM.dragonflow.StandardMonitor.IPlanetWSMonitor", "classType", "application");
   setClassProperty("COM.dragonflow.StandardMonitor.IPlanetWSMonitor", "topazType", "Web Server");
   if (TextUtils.getValue(hashmap, "_allowIPlanet").length() > 0) {
     setClassProperty("COM.dragonflow.StandardMonitor.IPlanetWSMonitor", "loadable", "true");
   } else {
     setClassProperty("COM.dragonflow.StandardMonitor.IPlanetWSMonitor", "loadable", "false");
   }
 }
 @Override
 public void visit(NodeTraversal t, Node n, Node parent) {
   for (int i = 0, len = rules.size(); i < len; i++) {
     Rule rule = rules.get(i);
     rule.check(t, n);
   }
 }
示例#6
0
 private void checkForWidgetTypeMismatch(Rules rs, Type declType, Integer lineNumber) {
   for (Rule r : rs) {
     if (!(r.isCompatibleWithType(declType))) {
       this.messages.add(StyleError.widgetTypeMismatch(declType.getTitle(), lineNumber));
     }
   }
 }
示例#7
0
文件: MetaK.java 项目: TomGebhardt/k
 public static boolean isAnywhere(Rule r) {
   if (null == r.getAttributes()) return false;
   for (Attribute any : anywheres) {
     if (any.getValue() == r.getAttribute(any.getKey())) return true;
   }
   return false;
 }
示例#8
0
  public void quitsIfInsufficientFunds() throws Exception {
    account = new Account(new BigDecimal(1), today.minusDays(6));
    Rule buyAndHold = new BuyAndHoldRule(account, asset, conditions);

    assertEquals(
        0, buyAndHold.generateSignals(today.minusDays(5), today.minusDays(4)).getTrades().size());
  }
示例#9
0
  /**
   * Return a string representation of the rules.
   *
   * @param databaseSize the number of transactions in the database where the rules were found.
   */
  public String toString(int databaseSize) {
    StringBuffer buffer = new StringBuffer(" ------- ");
    buffer.append(name);
    buffer.append(" -------\n");
    int i = 0;
    for (Rule rule : rules) {
      //			System.out.println("  L" + j + " ");
      buffer.append("   rule ");
      buffer.append(i);
      buffer.append(":  ");
      buffer.append(rule.toString());
      buffer.append("support :  ");
      buffer.append(rule.getRelativeSupport(databaseSize));

      buffer.append(" (");
      buffer.append(rule.getAbsoluteSupport());
      buffer.append("/");
      buffer.append(databaseSize);
      buffer.append(") ");
      buffer.append("confidence :  ");
      buffer.append(rule.getConfidence());
      buffer.append("\n");
      i++;
    }
    return buffer.toString();
  }
示例#10
0
  /**
   * Return a string representation of this list of rules
   *
   * @param databaseSize the number of transactions in the database where the rules were found.
   * @return a string
   */
  public String toString(int databaseSize) {
    // create a string buffer
    StringBuffer buffer = new StringBuffer(" ------- ");
    buffer.append(name);
    buffer.append(" -------\n");
    int i = 0;
    // for each rule
    for (Rule rule : rules) {
      // append the rule, its support and confidence.
      buffer.append("   rule ");
      buffer.append(i);
      buffer.append(":  ");
      buffer.append(rule.toString());
      buffer.append("support :  ");
      buffer.append(rule.getRelativeSupport(databaseSize));

      buffer.append(" (");
      buffer.append(rule.getAbsoluteSupport());
      buffer.append("/");
      buffer.append(databaseSize);
      buffer.append(") ");
      buffer.append("confidence :  ");
      buffer.append(rule.getConfidence());
      buffer.append("\n");
      i++;
    }
    return buffer.toString(); // return the string
  }
示例#11
0
  private String consecuente(
      myDataset dataset, int data[][], int classData[], int infoAttr[], int nClases, Rule rule) {

    int k, l;
    double tmp1, tmp2;
    int pos = 0, classPredicted;
    double Waip;

    classPredicted = -1;
    Waip = 0;

    tmp1 = Double.NEGATIVE_INFINITY;
    for (l = 0; l < nClases; l++) {
      tmp2 = 0;
      for (k = 0; k < rule.getRule().length; k++) {
        tmp2 += RuleSet.computeWeightEvidence(data, classData, rule.getiCondition(k), l, infoAttr);
      }
      if (tmp2 > tmp1) {
        tmp1 = tmp2;
        pos = l;
      }
    }
    classPredicted = pos;
    Waip = tmp1;

    return dataset.getOutputValue(classPredicted) + " [" + Double.toString(Waip) + "]";
  }
示例#12
0
  private void deserializeRule(DeserializationContext context, Build.Rule rulePb)
      throws PackageDeserializationException, InterruptedException {
    Location ruleLocation = EmptyLocation.INSTANCE;
    RuleClass ruleClass = packageDeserializationEnvironment.getRuleClass(rulePb, ruleLocation);
    Map<String, ParsedAttributeValue> attributeValues = new HashMap<>();
    for (Build.Attribute attrPb : rulePb.getAttributeList()) {
      Type<?> type = ruleClass.getAttributeByName(attrPb.getName()).getType();
      attributeValues.put(attrPb.getName(), deserializeAttribute(type, attrPb));
    }

    Label ruleLabel = deserializeLabel(rulePb.getName());
    try {
      Rule rule =
          ruleClass.createRuleWithParsedAttributeValues(
              ruleLabel,
              context.packageBuilder,
              ruleLocation,
              attributeValues,
              NullEventHandler.INSTANCE,
              new AttributeContainerWithoutLocation(ruleClass));
      context.packageBuilder.addRule(rule);

      Preconditions.checkState(!rule.containsErrors());
    } catch (NameConflictException | LabelSyntaxException e) {
      throw new PackageDeserializationException(e);
    }
  }
示例#13
0
  /**
   * This function generates a classifier from the CompSet of the generated fuzzy rules
   *
   * @return Classifier obtained
   */
  public RuleBase classifier() {
    int i, j;
    boolean stop;
    Rule rule;
    RuleBase bestRuleBase;

    for (i = 0; i < this.ruleBase.size(); i++) {
      rule = this.ruleBase.get(i);
      rule.orderDF();
    }

    this.fitness = this.train.size();
    bestRuleBase = this.clone();
    System.out.println("Fitness Inicial: " + this.fitness);

    if (this.ruleBase.size() > 1) {
      do {
        this.calculateRightNWrongN();
        this.removeRules();

        this.rateError();
        System.out.println("Fitness: " + this.fitness + " NRules: " + this.ruleBase.size());

        stop = true;
        if (this.fitness <= bestRuleBase.fitness) {
          bestRuleBase = this.clone();
          if (this.ruleBase.size() > 1 && this.fitness > 0) stop = false;
        }
      } while (!stop);
    }

    bestRuleBase.evalua();

    return (bestRuleBase);
  }
  public static boolean shouldBeInjected(String path, String contentType, String contentPreview) {
    int score = 0;

    if (log.isDebugEnabled()) {
      log.debug("shouldBeInjected(\"" + path + "\", \"" + contentType + "\", \"...\")");
    }

    for (Rule rule : rules) {
      int scoreDelta = rule.score(path, contentType, contentPreview);
      if (log.isDebugEnabled()) {
        log.debug("    applied rule " + rule + ": " + scoreDelta);
      }
      score += scoreDelta;
    }
    boolean shouldInject = (score > INJECTION_THRESHOLD);
    if (log.isDebugEnabled()) {
      log.debug(
          "    total : "
              + score
              + ">"
              + INJECTION_THRESHOLD
              + "?  (should "
              + (shouldInject ? "" : "not ")
              + "inject)");
    }
    return shouldInject;
  }
示例#15
0
文件: Rule.java 项目: StatNLP/otedama
  public Rule fromRuleFormatAndScores(String ruleformat) {

    Rule output = new Rule();
    String[] id = ruleformat.split("##");
    output.setRuleID(Integer.parseInt(id[0]));
    String[] stringParts = id[1].split("}");
    String mappings = stringParts[0];
    String reordering = stringParts[1];
    String scoreListString = stringParts[2];
    String[] nodeMapStrings = mappings.substring(1).split("#");
    for (String nodeString : nodeMapStrings) {
      String[] attributeValuePair = nodeString.split("=");
      output.setContextValue(attributeValuePair[0], attributeValuePair[1]);
    }
    String[] reorderingMapString = reordering.substring(1).split("=>");
    String[] previousSequence = reorderingMapString[0].split(",");
    String[] newSequence = reorderingMapString[1].split(",");
    for (int j = 0; j < previousSequence.length; j++) {
      int index = Integer.parseInt(previousSequence[j]);
      int newIndex = Integer.parseInt(newSequence[j]);
      output.setActionPair(index, newIndex);
    }
    String[] scoreMapString = scoreListString.substring(1).split("#");
    for (String scoreString : scoreMapString) {
      String[] nameAndScore = scoreString.split("=");
      String scoreName = nameAndScore[0];
      double score = Double.parseDouble(nameAndScore[1]);
      output.setScore(scoreName, score);
    }
    return output;
  }
  @Test
  public void update_debt_rule() throws Exception {
    verifyRulesInDb();

    // Update x1 rule
    RuleDto ruleDto = db.ruleDao().getByKey(dbSession, RuleTesting.XOO_X1);
    db.ruleDao()
        .update(
            dbSession,
            ruleDto
                .setDefaultSubCharacteristicId(123456)
                .setDefaultRemediationFunction("LINEAR_OFFSET")
                .setDefaultRemediationCoefficient("2h")
                .setDefaultRemediationOffset("35min"));
    dbSession.commit();
    dbSession.clearCache();

    // Re-execute startup tasks
    tester.get(Platform.class).executeStartupTasks();

    // Verify default debt has been reset to plugin definition
    Rule ruleReloaded = index.getByKey(RuleTesting.XOO_X1);
    assertThat(ruleReloaded.debtSubCharacteristicKey())
        .isEqualTo(RulesDefinition.SubCharacteristics.INTEGRATION_TESTABILITY);
    assertThat(ruleReloaded.debtRemediationFunction().type())
        .isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET);
    assertThat(ruleReloaded.debtRemediationFunction().coefficient()).isEqualTo("1h");
    assertThat(ruleReloaded.debtRemediationFunction().offset()).isEqualTo("30min");
  }
  private List<QuestionRule> getQuestionRules() {
    List<QuestionRule> questionRules;

    questionRules = new ArrayList<>();

    for (Rule rule : rules) {
      rule.accept(
          new RuleVisitor<Void, Void>() {

            @Override
            public Void visit(QuestionRule rule, Void context) {
              questionRules.add(rule);
              return null;
            }

            @Override
            public Void visit(ValueTypeRule rule, Void context) {
              return null;
            }
          },
          null);
    }

    return questionRules;
  }
  @Test
  public void remove_debt_rule() throws Exception {
    verifyRulesInDb();

    // Set some default debt on x2 rule, which has no debt provided by th plugin
    RuleDto ruleDto = db.ruleDao().getByKey(dbSession, RuleTesting.XOO_X2);
    db.ruleDao()
        .update(
            dbSession,
            ruleDto
                .setDefaultSubCharacteristicId(
                    db.debtCharacteristicDao()
                        .selectByKey(
                            RulesDefinition.SubCharacteristics.INTEGRATION_TESTABILITY, dbSession)
                        .getId())
                .setDefaultRemediationFunction("LINEAR_OFFSET")
                .setDefaultRemediationCoefficient("2h")
                .setDefaultRemediationOffset("35min"));
    dbSession.commit();
    dbSession.clearCache();

    // Re-execute startup tasks
    tester.get(Platform.class).executeStartupTasks();

    // Verify default debt has been removed
    Rule ruleReloaded = index.getByKey(RuleTesting.XOO_X2);
    assertThat(ruleReloaded.debtSubCharacteristicKey()).isNull();
    assertThat(ruleReloaded.debtRemediationFunction()).isNull();
  }
示例#19
0
  private void updateRule(Rule rule, String network, boolean blocked) {
    SharedPreferences prefs = context.getSharedPreferences(network, Context.MODE_PRIVATE);

    if ("wifi".equals(network)) {
      rule.wifi_blocked = blocked;
      if (rule.wifi_blocked == rule.wifi_default) {
        Log.i(TAG, "Removing " + rule.info.packageName + " " + network);
        prefs.edit().remove(rule.info.packageName).apply();
      } else {
        Log.i(TAG, "Setting " + rule.info.packageName + " " + network + "=" + blocked);
        prefs.edit().putBoolean(rule.info.packageName, blocked).apply();
      }
    }

    if ("other".equals(network)) {
      rule.other_blocked = blocked;
      if (rule.other_blocked == rule.other_default) {
        Log.i(TAG, "Removing " + rule.info.packageName + " " + network);
        prefs.edit().remove(rule.info.packageName).apply();
      } else {
        Log.i(TAG, "Setting " + rule.info.packageName + " " + network + "=" + blocked);
        prefs.edit().putBoolean(rule.info.packageName, blocked).apply();
      }
    }

    NotificationManagerCompat.from(context).cancel(rule.info.applicationInfo.uid);
  }
  @Test
  public void not_update_custom_rule_from_template_if_no_change() throws Exception {
    Rule templateRule = index.getByKey(RuleKey.of("xoo", "template1"));

    // Create custom rule
    RuleKey customRuleKey =
        tester
            .get(RuleCreator.class)
            .create(
                NewRule.createForCustomRule("CUSTOM_RULE", templateRule.key())
                    .setName("My custom")
                    .setHtmlDescription("Some description")
                    .setSeverity(Severity.MAJOR)
                    .setStatus(RuleStatus.READY)
                    .setParameters(ImmutableMap.of("format", "txt")));
    dbSession.commit();
    dbSession.clearCache();

    // Store updated at date
    Date updatedAt = index.getByKey(customRuleKey).updatedAt();

    // Re-execute startup tasks
    tester.get(Platform.class).executeStartupTasks();

    // Verify custom rule has not been updated
    Rule customRuleReloaded = index.getByKey(customRuleKey);
    assertThat(customRuleReloaded.updatedAt()).isEqualTo(updatedAt);
  }
示例#21
0
 @Override
 public String toString() {
   if (rules == null) return "";
   StringBuilder sb = new StringBuilder();
   for (Rule rule : rules) sb.append(rule.toString()).append('\n');
   return sb.toString();
 }
  @Test
  public void reactivate_disabled_custom_rules() {
    Rule templateRule = index.getByKey(RuleKey.of("xoo", "template1"));

    // Create custom rule
    RuleKey customRuleKey =
        tester
            .get(RuleCreator.class)
            .create(
                NewRule.createForCustomRule("CUSTOM_RULE", templateRule.key())
                    .setName("My custom")
                    .setHtmlDescription("Some description")
                    .setSeverity(Severity.MAJOR)
                    .setStatus(RuleStatus.READY));
    dbSession.commit();
    dbSession.clearCache();
    assertThat(index.getByKey(customRuleKey).status()).isEqualTo(RuleStatus.READY);

    // Restart without template rule
    rulesDefinition.includeTemplate1 = false;
    tester.get(Platform.class).executeStartupTasks();
    dbSession.clearCache();

    // Verify custom rule is removed
    assertThat(index.getByKey(customRuleKey).status()).isEqualTo(RuleStatus.REMOVED);

    // Restart with template rule
    rulesDefinition.includeTemplate1 = true;
    tester.get(Platform.class).executeStartupTasks();
    dbSession.clearCache();

    // Verify custom rule is reactivate
    assertThat(index.getByKey(customRuleKey).status()).isEqualTo(RuleStatus.READY);
  }
示例#23
0
  /**
   * Find all the instances in the dataset covered/not covered by the rule in given index, and the
   * correponding simple statistics and predicted class distributions are stored in the given double
   * array, which can be obtained by getSimpleStats() and getDistributions().<br>
   *
   * @param index the given index, assuming correct
   * @param insts the dataset to be covered by the rule
   * @param stats the given double array to hold stats, side-effected
   * @param dist the given array to hold class distributions, side-effected if null, the
   *     distribution is not necessary
   * @return the instances covered and not covered by the rule
   */
  private Instances[] computeSimpleStats(
      int index, Instances insts, double[] stats, double[] dist) {
    Rule rule = (Rule) m_Ruleset.elementAt(index);

    Instances[] data = new Instances[2];
    data[0] = new Instances(insts, insts.numInstances());
    data[1] = new Instances(insts, insts.numInstances());

    for (int i = 0; i < insts.numInstances(); i++) {
      Instance datum = insts.instance(i);
      double weight = datum.weight();
      if (rule.covers(datum)) {
        data[0].add(datum); // Covered by this rule
        stats[0] += weight; // Coverage
        if ((int) datum.classValue() == (int) rule.getConsequent())
          stats[2] += weight; // True positives
        else stats[4] += weight; // False positives
        if (dist != null) dist[(int) datum.classValue()] += weight;
      } else {
        data[1].add(datum); // Not covered by this rule
        stats[1] += weight;
        if ((int) datum.classValue() != (int) rule.getConsequent())
          stats[3] += weight; // True negatives
        else stats[5] += weight; // False negatives
      }
    }

    return data;
  }
示例#24
0
  @Test
  public void test() {
    final UserImpl user = new UserImpl("andrey");
    final UserImpl admin = new UserImpl("admin");
    final UserImpl mannheim = new UserImpl("mannheim");
    user.getParents().add(admin);
    user.getParents().add(mannheim);

    final OperationImpl read = new OperationImpl("read");
    final OperationImpl operation = new OperationImpl("op");
    read.getParents().add(operation);

    final ResourceImpl doc = new ResourceImpl("document");
    final ResourceImpl resource = new ResourceImpl("resource");
    doc.getParents().add(resource);

    final RuleSetImpl rules = new RuleSetImpl();
    rules.allow(admin, read, doc);

    final Rule rule = new Rule(user, read, doc, rules);
    final Collection<Rule> parents = rule.getParents();
    assertEquals(4, parents.size());

    final EvaluationStrategy eval = new BasicEvaluation();
    assertTrue(rule.value(eval));
  }
示例#25
0
 protected List<Rule> createRuleList(PMML pmmlDocument) {
   List<Rule> ruleList = new ArrayList<Rule>();
   for (Object obj : pmmlDocument.getAssociationModelsAndBaselineModelsAndClusteringModels()) {
     if (obj instanceof Scorecard) {
       Scorecard scorecard = (Scorecard) obj;
       Characteristics characteristics = getCharacteristicsFromScorecard(scorecard);
       createInitialRule(ruleList, scorecard);
       for (org.dmg.pmml.pmml_4_1.descr.Characteristic c : characteristics.getCharacteristics()) {
         int attributePosition = 0;
         for (org.dmg.pmml.pmml_4_1.descr.Attribute scoreAttribute : c.getAttributes()) {
           String name =
               formRuleName(
                   pmmlDocument, scorecard.getModelName().replaceAll(" ", ""), c, scoreAttribute);
           Rule rule = new Rule(name, 99, 1);
           String desc =
               ScorecardPMMLUtils.getExtensionValue(scoreAttribute.getExtensions(), "description");
           if (desc != null) {
             rule.setDescription(desc);
           }
           attributePosition++;
           populateLHS(rule, pmmlDocument, scorecard, c, scoreAttribute);
           populateRHS(rule, pmmlDocument, scorecard, c, scoreAttribute, attributePosition);
           ruleList.add(rule);
         }
       }
       createSummationRules(ruleList, scorecard);
     }
   }
   return ruleList;
 }
 public boolean atLeastOneRuleHasPriority() {
   for (int i = 0; i < this.currentRuleSet.size(); i++) {
     Rule r = this.currentRuleSet.get(i);
     if (r.getPriority() > 0) return true;
   }
   return false;
 }
 private Boolean visitRules(ArrayList<Rule> rules) {
   Boolean terminal = Boolean.FALSE;
   for (Rule rule : rules) {
     terminal = (Boolean) rule.accept(this);
   }
   return terminal;
 }
示例#28
0
 /** @see {@link LogicService#getRule(String)} */
 @Test
 @Verifies(value = "should return ReferenceRule", method = "getRule(String)")
 public void getRule_shouldReturnReferenceRule() throws Exception {
   Rule rule = Context.getLogicService().getRule("%%person.birthdate");
   Assert.assertNotNull(rule);
   Assert.assertTrue(rule.getClass().isAssignableFrom(ReferenceRule.class));
 }
示例#29
0
  /**
   * Glues the sentences back to paragraph.
   *
   * <p>As sentences are returned by {@link #segment(String, List)} without spaces before and after
   * them, this method adds spaces if needed:
   *
   * <ul>
   *   <li>For translation to Japanese does <b>not</b> add any spaces. <br>
   *       A special exceptions are the Break SRX rules that break on space, i.e. before and after
   *       patterns consist of spaces (they get trimmed to an empty string). For such rules all the
   *       spaces are added
   *   <li>For translation from Japanese adds one space
   *   <li>For all other language combinations adds those spaces as were in the paragraph before.
   * </ul>
   *
   * @param sentences list of translated sentences
   * @param spaces information about spaces in original paragraph
   * @param brules rules that account to breaks
   * @return glued translated paragraph
   */
  public static String glue(
      Language sourceLang,
      Language targetLang,
      List<String> sentences,
      List<StringBuffer> spaces,
      List<Rule> brules) {
    if (sentences.size() <= 0) return "";

    StringBuffer res = new StringBuffer();
    res.append(sentences.get(0));

    for (int i = 1; i < sentences.size(); i++) {
      StringBuffer sp = new StringBuffer();
      sp.append(spaces.get(2 * i - 1));
      sp.append(spaces.get(2 * i));

      if (CJK_LANGUAGES.contains(targetLang.getLanguageCode().toUpperCase(Locale.ENGLISH))) {
        Rule rule = brules.get(i - 1);
        char lastChar = res.charAt(res.length() - 1);
        if ((lastChar != '.')
            && (!PatternConsts.SPACY_REGEX.matcher(rule.getBeforebreak()).matches()
                || !PatternConsts.SPACY_REGEX.matcher(rule.getAfterbreak()).matches()))
          sp.setLength(0);
      } else if (CJK_LANGUAGES.contains(sourceLang.getLanguageCode().toUpperCase(Locale.ENGLISH))
          && sp.length() == 0) sp.append(" ");

      res.append(sp);
      res.append(sentences.get(i));
    }
    return res.toString();
  }
示例#30
0
  @Test
  public void update_manual_rule() {
    // Create manual rule
    RuleDto manualRule =
        RuleTesting.newManualRule("My manual")
            .setName("Old name")
            .setDescription("Old description")
            .setSeverity(Severity.INFO);
    ruleDao.insert(dbSession, manualRule);

    dbSession.commit();

    // Update manual rule
    RuleUpdate update =
        RuleUpdate.createForManualRule(manualRule.getKey())
            .setName("New name")
            .setMarkdownDescription("New description")
            .setSeverity(Severity.CRITICAL);
    updater.update(update, userSessionRule);

    dbSession.clearCache();

    // Verify manual rule is updated
    Rule manualRuleReloaded = ruleIndex.getByKey(manualRule.getKey());
    assertThat(manualRuleReloaded).isNotNull();
    assertThat(manualRuleReloaded.name()).isEqualTo("New name");
    assertThat(manualRuleReloaded.htmlDescription()).isEqualTo("New description");
    assertThat(manualRuleReloaded.severity()).isEqualTo(Severity.CRITICAL);
  }