Converts parsed formula into DIMACS format.

@param formula parsed formula
@return formula in DIMACS format
11217
protected static String DIMACSfromList(ArrayList<ArrayList<String>> formula) {
        StringBuilder dimacs = new StringBuilder("");
        for (List<String> conjClause : formula) {
            for (String disjClause : conjClause) {
                dimacs.append(disjClause).append(" ");
            }
            dimacs.append(" 0\n");
        }
        return dimacs.toString();
    }
1362004
public static List<IElement> elements(IMolecularFormula formula) {

        List<IElement> elementList = new ArrayList<IElement>();
        List<String> stringList = new ArrayList<String>();
        for (IIsotope isotope : formula.isotopes()) {
            if (!stringList.contains(isotope.getSymbol())) {
                elementList.add(isotope);
                stringList.add(isotope.getSymbol());
            }

        }
        return elementList;
    }
887684
public void add(final Formula formula) {
        final Formula cnf = formula.cnf();
        switch (cnf.type()) {
            case TRUE:
                break;
            case FALSE:
            case LITERAL:
            case OR:
                this.addClause(generateClauseVector(cnf), null);
                break;
            case AND:
                for (final Formula op : cnf) {
                    this.addClause(generateClauseVector(op), null);
                }
                break;
            default:
                throw new IllegalStateException("Unexpected formula type in CNF: " + cnf.type());
        }
    }
1352253
def _parse_formula(formula):
    
    #TODO: DEAL WITH BSPLINE HAS MULTIPLE ARGUEMENTS (NOT JUST ONE)

    # break formula apart from encoding instructions
    formula,instr = formula.replace(' ','').split('|')
    # break formula apart at + sign
    formula_terms = formula.split('+') 
    # examine the instructions term, first split by ),
    instr = instr.split('),')
    # elements in the instr list will match the number of non interaction 
    #      elements in formula
    # go through each formula term, making a dictionary whose key is variable name
    formula_dict = {}
    encoding     = []
    other_arg    = []
    inter_list   = []
    for term in formula_terms:
        if "*" in term:
            # then this is an interaction term, make 'list of lists'
            term = term.split('*')
            inter_list.append(term)
        else:
            # then this is not an interaction term, make blank dictionary
            formula_dict[term] = [encoding, other_arg]
    # loop through instructions, parse each term
    for term in instr:
        # remove punctuation in term
        term = re.sub('[()]','',term)
        # check for each encoding type
        if "Dev" in term:
            # remove first three letters (Dev)
            term = term[3:]
            # split on comma
            var_name,arg = term.split(',')
            # split on equals sign in arg, take part after
            drop_name = arg.split('=')[1]
            # put var_name and drop_name into proper key in formula_dict
            formula_dict[var_name] = ["Dev",drop_name]
        elif "Dum" in term:
            # remove first three letters (Dum)
            term = term[3:]
            # split on comma
            var_name,arg = term.split(',')
            # split on equals sign in arg, take part after
            ref_name = arg.split('=')[1]
            # put var_name and drop_name into proper key in formula_dict
            formula_dict[var_name] = ["Dum",ref_name]
        elif "Poly" in term:
            # remove first four letters (Poly)
            term = term[4:]
            # split on comma
            var_name,arg = term.split(',')
            # split on equals sign in arg, take part after
            degree = arg.split('=')[1]
            # put var_name and drop_name into proper key in formula_dict
            formula_dict[var_name] = ["Poly",degree]
        else:
            raise Exception("Unknown Encoding")
    return formula_dict,inter_list
976666
public CellFormatResult format(final Cell cell, final Locale locale) {

        if(cell == null) {
            return createBlankCellResult();
        }

        final Locale runtimeLocale = locale != null ? locale : Locale.getDefault();

        switch(cell.getCellTypeEnum()) {
            case BLANK:
                if(isConsiderMergedCell()) {
                    // 結合しているセルの場合、左上のセル以外に値が設定されている場合がある。
                    return getMergedCellValue(cell, runtimeLocale);
                } else {
                    return createBlankCellResult();
                }

            case BOOLEAN:
                return getCellValue(cell, runtimeLocale);

            case STRING:
                return getCellValue(cell, runtimeLocale);

            case NUMERIC:
                return getCellValue(cell, runtimeLocale);

            case FORMULA:
                return getFormulaCellValue(cell, runtimeLocale);

            case ERROR:
                return getErrorCellValue(cell, runtimeLocale);

            default:
                final CellFormatResult result = new CellFormatResult();
                result.setCellType(FormatCellType.Unknown);
                result.setText("");
                return result;
        }
    }
1135250
public function calculateFormula($formula)
    {
        //check whether worksheet name is set or not
        if ($this->worksheetName == '')
            throw new Exception('Worksheet name not specified');
        $strURI = Product::$baseProductUri . '/cells/' . $this->getFileName() .
            '/worksheets/' . $this->worksheetName . '/formulaResult?formula=' . $formula;
        $signedURI = Utils::sign($strURI);
        $responseStream = Utils::processCommand($signedURI, 'GET', '', '');
        $json = json_decode($responseStream);
        return $json->Value->Value;

    }
1242498
private AbstractRule processFormula(RulesTextProvider textProvider)
    {
    	log.debug("processFormula");
        Formula rule = new Formula();
        int start = textProvider.getPos();
        LoadCommonRuleData(rule,textProvider);
        textProvider.addTOCElement(null, rule.getDescription(), start, textProvider.getPos(), TYPE_FORMULA);
        exactOrError("{",textProvider);
        Expression expression = processAction(textProvider);
        exactOrError("}",textProvider);
        rule.addAction(expression);

        return rule;
    }
993071
def columns_in_formula(formula):
    
    if formula is None:
        return []

    formula = str_model_expression(formula, add_constant=False)
    columns = []

    tokens = map(
        lambda x: x.extra,
        tz.remove(
            lambda x: x.extra is None,
            _tokens_from_patsy(patsy.parse_formula.parse_formula(formula))))

    for tok in tokens:
        # if there are parentheses in the expression we
        # want to drop them and everything outside
        # and start again from the top
        if '(' in tok:
            start = tok.find('(') + 1
            fin = tok.rfind(')')
            columns.extend(columns_in_formula(tok[start:fin]))
        else:
            for toknum, tokval, _, _, _ in generate_tokens(
                    StringIO(tok).readline):
                if toknum == NAME:
                    columns.append(tokval)

    return list(tz.unique(columns))
1091130
public String toPostfix(String formula) {
        FunctionFactory factory = FactoryManager.instance().function();
        //Space the operator to tokenize easier
        Set<String> toSpace = factory.availableOperators();
        toSpace.remove(Rule.FL_AND);
        toSpace.remove(Rule.FL_OR);
        toSpace.add("(");
        toSpace.add(")");
        toSpace.add(",");
        String spacedFormula = formula;
        for (String operator : toSpace) {
            spacedFormula = spacedFormula.replace(operator, " " + operator + " ");
        }
        FuzzyLite.logger().fine(spacedFormula);

        //Tokenizer
        Deque<String> queue = new ArrayDeque<String>();
        Deque<String> stack = new ArrayDeque<String>();

        StringTokenizer tokenizer = new StringTokenizer(spacedFormula);
        String token;
        while (tokenizer.hasMoreTokens()) {
            token = tokenizer.nextToken();

            Element element = factory.getObject(token);

            boolean isOperand = element == null && !"(".equals(token) && !")".equals(token)
                    && !",".equals(token);

            if (isOperand) {
                FuzzyLite.logger().fine(token + " is operand");
                queue.offer(token);

            } else if (element != null && element.isFunction()) {
                FuzzyLite.logger().fine(token + " is function");
                stack.push(token);

            } else if (",".equals(token)) {
                while (!stack.isEmpty() && !"(".equals(stack.peek())) {
                    queue.offer(stack.pop());
                }
                if (stack.isEmpty() || !"(".equals(stack.peek())) {
                    throw new RuntimeException(String.format(
                            "[parsing error] mismatching parentheses in: %s", formula));
                }

            } else if (element != null && element.isOperator()) {
                FuzzyLite.logger().fine(token + " is operator");
                Element op1 = element;
                for (; ; ) {
                    Element op2 = null;
                    if (!stack.isEmpty()) {
                        op2 = factory.getObject(stack.peek());
                    }
                    if (op2 == null) {
                        break;
                    }

                    if ((op1.associativity < 0 && op1.precedence == op2.precedence)
                            || op1.precedence < op2.precedence) {
                        queue.offer(stack.pop());
                    } else {
                        break;
                    }
                }
                stack.push(token);

            } else if ("(".equals(token)) {
                stack.push(token);

            } else if (")".equals(token)) {
                while (!stack.isEmpty() && !"(".equals(stack.peek())) {
                    queue.offer(stack.pop());
                }
                if (stack.isEmpty() || !"(".equals(stack.peek())) {
                    throw new RuntimeException(String.format(
                            "[parsing error] mismatching parentheses in: %s", formula));
                }
                stack.pop(); //get rid of "("

                Element top = null;
                if (!stack.isEmpty()) {
                    top = factory.getObject(stack.peek());
                }
                if (top != null && top.isFunction()) {
                    queue.offer(stack.pop());
                }
            } else {
                throw new RuntimeException(String.format(
                        "[parsing error] unexpected error with token <%s>", token));
            }
        }

        while (!stack.isEmpty()) {
            if ("(".equals(stack.peek()) || ")".equals(stack.peek())) {
                throw new RuntimeException(String.format(
                        "[parsing error] mismatching parentheses in: %s", formula));
            }
            queue.offer(stack.pop());
        }

        StringBuilder result = new StringBuilder();
        while (!queue.isEmpty()) {
            result.append(queue.poll());
            if (!queue.isEmpty()) {
                result.append(" ");
            }
        }

        return result.toString();
    }
451678
public static function _translateSeparator($fromSeparator,$toSeparator,$formula,&$inBraces) {
		$strlen = mb_strlen($formula);
		for ($i = 0; $i < $strlen; ++$i) {
			$chr = mb_substr($formula,$i,1);
			switch ($chr) {
				case '{' :	$inBraces = TRUE;
							break;
				case '}' :	$inBraces = FALSE;
							break;
				case $fromSeparator :
							if (!$inBraces) {
								$formula = mb_substr($formula,0,$i).$toSeparator.mb_substr($formula,$i+1);
							}
			}
		}
		return $formula;
	}
1037722
def _formulas(lexer, varname, fmt, nvars):
    """"""
    types = {IntegerToken, LPAREN} | _SAT_TOKS[fmt]
    tok = lexer.peek_token()
    if any(isinstance(tok, t) for t in types):
        first = _sat_formula(lexer, varname, fmt, nvars)
        rest = _formulas(lexer, varname, fmt, nvars)
        return (first, ) + rest
    # null
    else:
        return tuple()
846083
public static Backbone computeNegative(final Formula formula) {
        return compute(formula, formula.variables(), BackboneType.ONLY_NEGATIVE);
    }
1070567
public IAtomContainer processFormula(IAtomContainer parsedContent, String atomsEncoding) {
        logger.debug("Parsing atom data: ", atomsEncoding);

        Pattern pattern = Pattern.compile("([A-Z][a-z]?)(\\d+)?(.*)");
        String remainder = atomsEncoding;
        while (remainder.length() > 0) {
            logger.debug("Remaining: ", remainder);
            Matcher matcher = pattern.matcher(remainder);
            if (matcher.matches()) {
                String symbol = matcher.group(1);
                logger.debug("Atom symbol: ", symbol);
                if (symbol.equals("H")) {
                    // don't add explicit hydrogens
                } else {
                    String occurenceStr = matcher.group(2);
                    int occurence = 1;
                    if (occurenceStr != null) {
                        occurence = Integer.parseInt(occurenceStr);
                    }
                    logger.debug("  occurence: ", occurence);
                    for (int i = 1; i <= occurence; i++) {
                        parsedContent.addAtom(parsedContent.getBuilder().newInstance(IAtom.class, symbol));
                    }
                }
                remainder = matcher.group(3);
                if (remainder == null) remainder = "";
                logger.debug("  Remaining: ", remainder);
            } else {
                logger.error("No match found!");
                remainder = "";
            }
            logger.debug("NO atoms: ", parsedContent.getAtomCount());
        }
        return parsedContent;
    }
399407
private static BigDecimal[] calculateInlineFormula(int start, String formula) throws Exception {
        BigDecimal[] result = new BigDecimal[2];
        StringBuilder inlineFormula = new StringBuilder();
        for (; start < formula.length(); start++) {
            char c = formula.charAt(start);
            if (c == '(') {
                BigDecimal[] res = calculateInlineFormula(start + 1, formula);
                inlineFormula.append(res[0]);
                start = res[1].intValue();
            } else if (c == ')') {
                break;
            } else {
                inlineFormula.append(c);
            }
        }
        result[0] = calculate(inlineFormula.toString());
        result[1] = BigDecimal.valueOf(start);
        return result;
    }
201982
private int buildRec(final Formula formula) {
    switch (formula.type()) {
      case FALSE:
        return BDDKernel.BDD_FALSE;
      case TRUE:
        return BDDKernel.BDD_TRUE;
      case LITERAL:
        final Literal lit = (Literal) formula;
        Integer idx = this.var2idx.get(lit.variable());
        if (idx == null) {
          idx = this.var2idx.size();
          this.var2idx.put(lit.variable(), idx);
          this.idx2var.put(idx, lit.variable());
        }
        return lit.phase() ? this.kernel.ithVar(idx) : this.kernel.nithVar(idx);
      case NOT:
        final Not not = (Not) formula;
        return this.kernel.addRef(this.kernel.not(buildRec(not.operand())));
      case IMPL:
        final Implication impl = (Implication) formula;
        return this.kernel.addRef(this.kernel.implication(buildRec(impl.left()), buildRec(impl.right())));
      case EQUIV:
        final Equivalence equiv = (Equivalence) formula;
        return this.kernel.addRef(this.kernel.equivalence(buildRec(equiv.left()), buildRec(equiv.right())));
      case AND:
      case OR:
        final Iterator<Formula> it = formula.iterator();
        int res = buildRec(it.next());
        while (it.hasNext())
          res = formula.type() == AND
                  ? this.kernel.addRef(this.kernel.and(res, buildRec(it.next())))
                  : this.kernel.addRef(this.kernel.or(res, buildRec(it.next())));
        return res;
      case PBC:
        return buildRec(formula.nnf());
      default:
        throw new IllegalArgumentException("Unsupported operator for BDD generation: " + formula.type());
    }
  }
756518
def append_formula(self, formula, no_return=True):
        

        if self.maplesat:
            res = None
            for clause in formula:
                res = self.add_clause(clause, no_return)

            if not no_return:
                return res
34895
Formula translateToFormula(final List<Variable> varOrder) {
    final FormulaFactory f = varOrder.get(0).factory();
    assert this.bits.length == varOrder.size();
    final List<Literal> operands = new ArrayList<>(varOrder.size());
    for (int i = 0; i < this.bits.length; i++)
      if (this.bits[i] != Tristate.UNDEF)
        operands.add(this.bits[i] == Tristate.TRUE ? varOrder.get(i) : varOrder.get(i).negate());
    return f.and(operands);
  }