Example usage for java.math BigInteger ONE

List of usage examples for java.math BigInteger ONE

Introduction

In this page you can find the example usage for java.math BigInteger ONE.

Prototype

BigInteger ONE

To view the source code for java.math BigInteger ONE.

Click Source Link

Document

The BigInteger constant one.

Usage

From source file:jp.co.ntts.vhut.util.Ipv4ConversionUtil.java

/**
 * ??IP??NW??????.//from w ww . j  a va 2  s  . co  m
 * @param bAddr IP?
 * @param bMask (?)
 * @return ??
 */
public static byte[] getNextNetworkAddressAsByte(byte[] bAddr, byte[] bMask) {
    BigInteger current = new BigInteger(getNetworkAddressAsByte(bAddr, bMask));
    BigInteger reversedMask = new BigInteger(byteXOR(bMask, getFullBytes()));
    return current.add(reversedMask).add(BigInteger.ONE).toByteArray();
}

From source file:org.opennms.netmgt.model.discovery.IPAddrRange.java

/**
 * <P>/*from   w  ww  .  j  a  v  a  2 s  .c  om*/
 * Returns the size of this range.
 * </P>
 */
public BigInteger size() {
    return InetAddressUtils
            .difference(InetAddressUtils.getInetAddress(m_end), InetAddressUtils.getInetAddress(m_begin))
            .add(BigInteger.ONE);
}

From source file:com.netxforge.oss2.config.AmiPeerFactory.java

/**
 * Combine specific and range elements so that AMIPeerFactory has to spend
 * less time iterating all these elements.
 * TODO This really should be pulled up into PeerFactory somehow, but I'm not sure how (given that "Definition" is different for both
 * SNMP and AMI.  Maybe some sort of visitor methodology would work.  The basic logic should be fine as it's all IP address manipulation
 *
 * @throws UnknownHostException//from w w  w .  j a  v  a 2 s  .c o m
 */
void optimize() throws UnknownHostException {
    getWriteLock().lock();

    try {
        // First pass: Remove empty definition elements
        for (final Iterator<Definition> definitionsIterator = m_config.getDefinitionCollection()
                .iterator(); definitionsIterator.hasNext();) {
            final Definition definition = definitionsIterator.next();
            if (definition.getSpecificCount() == 0 && definition.getRangeCount() == 0) {
                LogUtils.debugf(this, "optimize: Removing empty definition element");
                definitionsIterator.remove();
            }
        }

        // Second pass: Replace single IP range elements with specific elements
        for (Definition definition : m_config.getDefinitionCollection()) {
            for (Iterator<Range> rangesIterator = definition.getRangeCollection().iterator(); rangesIterator
                    .hasNext();) {
                Range range = rangesIterator.next();
                if (range.getBegin().equals(range.getEnd())) {
                    definition.addSpecific(range.getBegin());
                    rangesIterator.remove();
                }
            }
        }

        // Third pass: Sort specific and range elements for improved XML
        // readability and then combine them into fewer elements where possible
        for (final Definition definition : m_config.getDefinitionCollection()) {
            // Sort specifics
            final TreeMap<InetAddress, String> specificsMap = new TreeMap<InetAddress, String>(
                    new InetAddressComparator());
            for (final String specific : definition.getSpecificCollection()) {
                specificsMap.put(InetAddressUtils.getInetAddress(specific), specific.trim());
            }

            // Sort ranges
            final TreeMap<InetAddress, Range> rangesMap = new TreeMap<InetAddress, Range>(
                    new InetAddressComparator());
            for (final Range range : definition.getRangeCollection()) {
                rangesMap.put(InetAddressUtils.getInetAddress(range.getBegin()), range);
            }

            // Combine consecutive specifics into ranges
            InetAddress priorSpecific = null;
            Range addedRange = null;
            for (final InetAddress specific : specificsMap.keySet()) {
                if (priorSpecific == null) {
                    priorSpecific = specific;
                    continue;
                }

                if (BigInteger.ONE.equals(InetAddressUtils.difference(specific, priorSpecific))
                        && InetAddressUtils.inSameScope(specific, priorSpecific)) {
                    if (addedRange == null) {
                        addedRange = new Range();
                        addedRange.setBegin(InetAddressUtils.toIpAddrString(priorSpecific));
                        rangesMap.put(priorSpecific, addedRange);
                        specificsMap.remove(priorSpecific);
                    }

                    addedRange.setEnd(InetAddressUtils.toIpAddrString(specific));
                    specificsMap.remove(specific);
                } else {
                    addedRange = null;
                }

                priorSpecific = specific;
            }

            // Move specifics to ranges
            for (final InetAddress specific : new ArrayList<InetAddress>(specificsMap.keySet())) {
                for (final InetAddress begin : new ArrayList<InetAddress>(rangesMap.keySet())) {

                    if (!InetAddressUtils.inSameScope(begin, specific)) {
                        continue;
                    }

                    if (InetAddressUtils.toInteger(begin).subtract(BigInteger.ONE)
                            .compareTo(InetAddressUtils.toInteger(specific)) > 0) {
                        continue;
                    }

                    final Range range = rangesMap.get(begin);

                    final InetAddress end = InetAddressUtils.getInetAddress(range.getEnd());

                    if (InetAddressUtils.toInteger(end).add(BigInteger.ONE)
                            .compareTo(InetAddressUtils.toInteger(specific)) < 0) {
                        continue;
                    }

                    if (InetAddressUtils.toInteger(specific).compareTo(InetAddressUtils.toInteger(begin)) >= 0
                            && InetAddressUtils.toInteger(specific)
                                    .compareTo(InetAddressUtils.toInteger(end)) <= 0) {
                        specificsMap.remove(specific);
                        break;
                    }

                    if (InetAddressUtils.toInteger(begin).subtract(BigInteger.ONE)
                            .equals(InetAddressUtils.toInteger(specific))) {
                        rangesMap.remove(begin);
                        rangesMap.put(specific, range);
                        range.setBegin(InetAddressUtils.toIpAddrString(specific));
                        specificsMap.remove(specific);
                        break;
                    }

                    if (InetAddressUtils.toInteger(end).add(BigInteger.ONE)
                            .equals(InetAddressUtils.toInteger(specific))) {
                        range.setEnd(InetAddressUtils.toIpAddrString(specific));
                        specificsMap.remove(specific);
                        break;
                    }
                }
            }

            // Combine consecutive ranges
            Range priorRange = null;
            InetAddress priorBegin = null;
            InetAddress priorEnd = null;
            for (final Iterator<InetAddress> rangesIterator = rangesMap.keySet().iterator(); rangesIterator
                    .hasNext();) {
                final InetAddress beginAddress = rangesIterator.next();
                final Range range = rangesMap.get(beginAddress);
                final InetAddress endAddress = InetAddressUtils.getInetAddress(range.getEnd());

                if (priorRange != null) {
                    if (InetAddressUtils.inSameScope(beginAddress, priorEnd) && InetAddressUtils
                            .difference(beginAddress, priorEnd).compareTo(BigInteger.ONE) <= 0) {
                        priorBegin = new InetAddressComparator().compare(priorBegin, beginAddress) < 0
                                ? priorBegin
                                : beginAddress;
                        priorRange.setBegin(InetAddressUtils.toIpAddrString(priorBegin));
                        priorEnd = new InetAddressComparator().compare(priorEnd, endAddress) > 0 ? priorEnd
                                : endAddress;
                        priorRange.setEnd(InetAddressUtils.toIpAddrString(priorEnd));

                        rangesIterator.remove();
                        continue;
                    }
                }

                priorRange = range;
                priorBegin = beginAddress;
                priorEnd = endAddress;
            }

            // Update changes made to sorted maps
            definition.setSpecific(specificsMap.values().toArray(new String[0]));
            definition.setRange(rangesMap.values().toArray(new Range[0]));
        }
    } finally {
        getWriteLock().unlock();
    }
}

From source file:org.opendaylight.genius.interfacemanager.commons.InterfaceManagerCommonUtils.java

public static void makeTunnelIngressFlow(List<ListenableFuture<Void>> futures, IMdsalApiManager mdsalApiManager,
        IfTunnel tunnel, BigInteger dpnId, long portNo, String interfaceName, int ifIndex,
        int addOrRemoveFlow) {
    LOG.debug("make tunnel ingress flow for {}", interfaceName);
    String flowRef = InterfaceManagerCommonUtils.getTunnelInterfaceFlowRef(dpnId,
            NwConstants.VLAN_INTERFACE_INGRESS_TABLE, interfaceName);
    List<MatchInfoBase> matches = new ArrayList<>();
    List<InstructionInfo> mkInstructions = new ArrayList<>();
    if (NwConstants.ADD_FLOW == addOrRemoveFlow) {
        matches.add(new MatchInPort(dpnId, portNo));
        if (BooleanUtils.isTrue(tunnel.isTunnelRemoteIpFlow())) {
            matches.add(new NxMatchTunnelSourceIp(tunnel.getTunnelDestination().getIpv4Address()));
        }/*from   ww w . j  av  a  2s.co  m*/
        if (BooleanUtils.isTrue(tunnel.isTunnelSourceIpFlow())) {
            matches.add(new NxMatchTunnelDestinationIp(tunnel.getTunnelSource().getIpv4Address()));
        }

        mkInstructions
                .add(new InstructionWriteMetadata(MetaDataUtil.getLportTagMetaData(ifIndex).or(BigInteger.ONE),
                        MetaDataUtil.METADATA_MASK_LPORT_TAG_SH_FLAG));
        short tableId = tunnel.getTunnelInterfaceType().isAssignableFrom(TunnelTypeMplsOverGre.class)
                ? NwConstants.L3_LFIB_TABLE
                : tunnel.isInternal() ? NwConstants.INTERNAL_TUNNEL_TABLE
                        : NwConstants.DHCP_TABLE_EXTERNAL_TUNNEL;
        mkInstructions.add(new InstructionGotoTable(tableId));
    }

    FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpnId, NwConstants.VLAN_INTERFACE_INGRESS_TABLE, flowRef,
            IfmConstants.DEFAULT_FLOW_PRIORITY, interfaceName, 0, 0, NwConstants.COOKIE_VM_INGRESS_TABLE,
            matches, mkInstructions);
    if (NwConstants.ADD_FLOW == addOrRemoveFlow) {
        mdsalApiManager.batchedAddFlow(dpnId, flowEntity);
    } else {
        mdsalApiManager.batchedRemoveFlow(dpnId, flowEntity);
    }
}

From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java

private void stepTwoC() throws Exception {
    byte[] send;//from   w w w . j a  va 2 s  .  c  om
    IHttpRequestResponse response;
    byte[] request;

    BigInteger n = this.pubKey.getModulus();

    loggerInstance.log(getClass(), "Step 2c: Searching with one interval left", Logger.LogLevel.INFO);

    // initial ri computation - ri = 2(b*(si-1)-2*B)/n
    BigInteger ri = this.si.multiply(this.m[0].upper);
    ri = ri.subtract(BigInteger.valueOf(2).multiply(this.bigB));
    ri = ri.multiply(BigInteger.valueOf(2));
    ri = ri.divide(n);

    // initial si computation
    BigInteger upperBound = step2cComputeUpperBound(ri, n, this.m[0].lower);
    BigInteger lowerBound = step2cComputeLowerBound(ri, n, this.m[0].upper);

    // to counter .add operation in do while
    this.si = lowerBound.subtract(BigInteger.ONE);

    do {
        // Check if user has cancelled the worker
        if (isCancelled()) {
            loggerInstance.log(getClass(), "Decryption Attack Executor Worker cancelled by user",
                    Logger.LogLevel.INFO);
            return;
        }

        this.si = this.si.add(BigInteger.ONE);
        // lowerBound <= si < upperBound
        if (this.si.compareTo(upperBound) > 0) {
            // new values
            ri = ri.add(BigInteger.ONE);
            upperBound = step2cComputeUpperBound(ri, n, this.m[0].lower);
            lowerBound = step2cComputeLowerBound(ri, n, this.m[0].upper);
            this.si = lowerBound;
        }
        send = prepareMsg(this.c0, this.si);

        request = this.requestResponse.getRequest();
        String[] components = Decoder.getComponents(this.parameter.getJoseValue());
        components[1] = Decoder.base64UrlEncode(send);

        String newComponentsConcatenated = Decoder.concatComponents(components);

        request = JoseParameter.updateRequest(request, this.parameter, helpers, newComponentsConcatenated);

        response = callbacks.makeHttpRequest(this.httpService, request);
        updateAmountRequest();

    } while (oracle.getResult(response.getResponse()) != BleichenbacherPkcs1Oracle.Result.VALID);
    loggerInstance.log(getClass(), "Matching response: " + helpers.bytesToString(response.getResponse()),
            Logger.LogLevel.DEBUG);
}

From source file:com.github.jrrdev.mantisbtsync.core.services.JdbcIssuesServiceTest.java

/**
 * Test method for {@link com.github.jrrdev.mantisbtsync.core.services.JdbcIssuesService#insertCustomFieldIfNotExists(biz.futureware.mantis.rpc.soap.client.ObjectRef, java.math.BigInteger)}.
 *//*w w w  .  j a v a 2s .c o  m*/
@Test
public void testInsertCustomFieldIfNotExists() {
    final Operation op = sequenceOf(
            insertInto("mantis_project_table").columns("id", "name").values(1, "project_1").build(),

            insertInto("mantis_enum_custom_field_types").columns("id", "name").values(1, "type_1").build());

    lauchOperation(op);

    final ObjectRef item = new ObjectRef(BigInteger.ONE, "item");
    dao.insertCustomFieldIfNotExists(item, BigInteger.ONE);

    final List<ObjectRef> list = getJdbcTemplate()
            .query("SELECT cf.id, cf.name" + " FROM mantis_custom_field_table cf"
                    + " INNER JOIN mantis_custom_field_project_table cfp ON cf.id = cfp.field_id"
                    + " WHERE cfp.project_id = 1", new BeanPropertyRowMapper<ObjectRef>(ObjectRef.class));

    assertEquals(1, list.size());
    assertEquals(item, list.get(0));

    dao.insertCustomFieldIfNotExists(item, BigInteger.ONE);
}

From source file:nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage.java

@TargetApi(18)
private KeyStore initKeyStore() throws SecureLocalStorageException {
    try {//from  www .  j av  a2 s .c o  m
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);

        if (!keyStore.containsAlias(SECURELOCALSTORAGEALIAS)) {

            Calendar start = Calendar.getInstance();
            Calendar end = Calendar.getInstance();
            end.add(Calendar.YEAR, 3);

            KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(_cordova.getActivity())
                    .setAlias(SECURELOCALSTORAGEALIAS)
                    .setSubject(new X500Principal(String.format("CN=%s, O=%s", "SecureLocalStorage",
                            _cordova.getActivity().getBaseContext().getPackageName())))
                    .setSerialNumber(BigInteger.ONE).setStartDate(start.getTime()).setEndDate(end.getTime())
                    .build();
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
            generator.initialize(spec);

            generator.generateKeyPair();
        }

        return keyStore;
    } catch (Exception e) {
        throw new SecureLocalStorageException("Could not initialize keyStore", e);
    }
}

From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java

private static Response invoke(UrlBuilder url, String method, String contentType,
        Map<String, List<String>> httpHeaders, Output writer, boolean forceOutput, BigInteger offset,
        BigInteger length, Map<String, String> params) {
    try {//from   w  ww  .  j a v a  2s  . c  o m
        // Log.d("URL", url.toString());

        // connect
        HttpURLConnection conn = (HttpURLConnection) (new URL(url.toString())).openConnection();
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(writer != null || forceOutput);
        conn.setAllowUserInteraction(false);
        conn.setUseCaches(false);
        conn.setRequestProperty("User-Agent", ClientVersion.OPENCMIS_CLIENT);

        // set content type
        if (contentType != null) {
            conn.setRequestProperty("Content-Type", contentType);
        }
        // set other headers
        if (httpHeaders != null) {
            for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) {
                if (header.getValue() != null) {
                    for (String value : header.getValue()) {
                        conn.addRequestProperty(header.getKey(), value);
                    }
                }
            }
        }

        // range
        BigInteger tmpOffset = offset;
        if ((tmpOffset != null) || (length != null)) {
            StringBuilder sb = new StringBuilder("bytes=");

            if ((tmpOffset == null) || (tmpOffset.signum() == -1)) {
                tmpOffset = BigInteger.ZERO;
            }

            sb.append(tmpOffset.toString());
            sb.append("-");

            if ((length != null) && (length.signum() == 1)) {
                sb.append(tmpOffset.add(length.subtract(BigInteger.ONE)).toString());
            }

            conn.setRequestProperty("Range", sb.toString());
        }

        conn.setRequestProperty("Accept-Encoding", "gzip,deflate");

        // add url form parameters
        if (params != null) {
            DataOutputStream ostream = null;
            OutputStream os = null;
            try {
                os = conn.getOutputStream();
                ostream = new DataOutputStream(os);

                Set<String> parameters = params.keySet();
                StringBuffer buf = new StringBuffer();

                int paramCount = 0;
                for (String it : parameters) {
                    String parameterName = it;
                    String parameterValue = (String) params.get(parameterName);

                    if (parameterValue != null) {
                        parameterValue = URLEncoder.encode(parameterValue, "UTF-8");
                        if (paramCount > 0) {
                            buf.append("&");
                        }
                        buf.append(parameterName);
                        buf.append("=");
                        buf.append(parameterValue);
                        ++paramCount;
                    }
                }
                ostream.writeBytes(buf.toString());
            } finally {
                if (ostream != null) {
                    ostream.flush();
                    ostream.close();
                }
                IOUtils.closeStream(os);
            }
        }

        // send data

        if (writer != null) {
            // conn.setChunkedStreamingMode((64 * 1024) - 1);
            OutputStream connOut = null;
            connOut = conn.getOutputStream();
            OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE);
            writer.write(out);
            out.flush();
        }

        // connect
        conn.connect();

        // get stream, if present
        int respCode = conn.getResponseCode();
        InputStream inputStream = null;
        if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED)
                || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION)
                || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) {
            inputStream = conn.getInputStream();
        }

        // get the response
        return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream,
                conn.getErrorStream());
    } catch (Exception e) {
        throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e);
    }
}

From source file:org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet.java

public boolean initDefaults() {
    if (enableDHCP == null) {
        enableDHCP = true;//from   w w  w  .  ja  v  a2 s  .c o  m
    }
    if (ipVersion == null) {
        ipVersion = IPV4_VERSION;
    }
    dnsNameservers = new ArrayList<>();
    if (hostRoutes == null) {
        hostRoutes = new ArrayList<>();
    }
    if (allocationPools == null) {
        allocationPools = new ArrayList<>();
        if (ipVersion == IPV4_VERSION) {
            try {
                SubnetUtils util = new SubnetUtils(cidr);
                SubnetInfo info = util.getInfo();
                if (gatewayIP == null || ("").equals(gatewayIP)) {
                    gatewayIP = info.getLowAddress();
                }
                if (allocationPools.size() < 1) {
                    NeutronSubnetIPAllocationPool source = new NeutronSubnetIPAllocationPool(
                            info.getLowAddress(), info.getHighAddress());
                    allocationPools = source.splitPool(gatewayIP);
                }
            } catch (IllegalArgumentException e) {
                LOGGER.warn("Failure in initDefault()", e);
                return false;
            }
        }
        if (ipVersion == IPV6_VERSION) {
            String[] parts = cidr.split("/");
            if (parts.length != 2) {
                return false;
            }
            try {
                int length = Integer.parseInt(parts[1]);
                BigInteger lowAddress_bi = NeutronSubnetIPAllocationPool.convertV6(parts[0]);
                String lowAddress = NeutronSubnetIPAllocationPool
                        .bigIntegerToIP(lowAddress_bi.add(BigInteger.ONE));
                BigInteger mask = BigInteger.ONE.shiftLeft(length).subtract(BigInteger.ONE);
                String highAddress = NeutronSubnetIPAllocationPool
                        .bigIntegerToIP(lowAddress_bi.add(mask).subtract(BigInteger.ONE));
                if (gatewayIP == null || ("").equals(gatewayIP)) {
                    gatewayIP = lowAddress;
                }
                if (allocationPools.size() < 1) {
                    NeutronSubnetIPAllocationPool source = new NeutronSubnetIPAllocationPool(lowAddress,
                            highAddress);
                    allocationPools = source.splitPoolV6(gatewayIP);
                }
            } catch (Exception e) {
                LOGGER.warn("Failure in initDefault()", e);
                return false;
            }
        }
    }
    return true;
}

From source file:com.udojava.evalex.Expression.java

/**
 * Creates a new expression instance from an expression string with a given
 * default match context./*from   w w  w .  jav  a2s .c  o m*/
 *
 * @param expression The expression. E.g. <code>"2.4*sin(3)/(2-4)"</code> or
 *                   <code>"sin(y)>0 & max(z, 3)>3"</code>
 */
public Expression(String expression, LinkedList<String> hist, Variables vars) {
    this.history = hist;
    this.expression = expression;

    mainVars = vars;

    addOperator(new Operator("+", 20, true, "Addition") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            if (v1.type == ValueType.ARRAY) {
                MyComplex vo = new MyComplex(v1.list);
                vo.list.add(v2);
                return vo;
            }
            return v1.add(v2);
        }
    });

    addOperator(new Operator("-", 20, true, "Subtraction") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            if (v1.type == ValueType.ARRAY) {
                MyComplex vo = new MyComplex(v1.list);
                vo.list.removeIf(o -> o.equals(v2));
                return vo;
            }
            return v1.subtract(v2);
        }
    });
    addOperator(new Operator("*", 30, true, "Real number multiplication") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            return v1.multiply(v2);
        }
    });
    addOperator(new Operator("/", 30, true, "Real number division") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            return v1.divide(v2);
        }
    });
    addOperator(new Operator("%", 30, true, "Remainder of integer division") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            double r = v1.real % v2.real;
            return new MyComplex(r);
        }
    });
    addOperator(
            new Operator("^", 40, false, "Exponentation. See: https://en.wikipedia.org/wiki/Exponentiation") {
                @Override
                public MyComplex eval(MyComplex v1, MyComplex v2) {
                    return v1.pow(v2);
                }
            });
    addOperator(new Operator("&&", 4, false, "Logical AND. Evaluates to 1 if both operands are not 0") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            boolean b1 = (v1.real == 0.0 && v2.real == 0.0);
            return new MyComplex(b1 ? 1 : 0);
        }
    });

    addOperator(new Operator("||", 2, false, "Logical OR. Evaluates to 0 if both operands are 0") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            boolean b1 = (v1.real == 0.0 && v2.real == 0.0);
            return new MyComplex(b1 ? 0 : 1);
        }
    });

    addOperator(new Operator(">", 10, false,
            "Greater than. See: See: https://en.wikipedia.org/wiki/Inequality_(mathematics)") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) {
                return new MyComplex(v1.real > v2.real ? 1 : 0);
            } else {
                return new MyComplex(v1.abs() > v2.abs() ? 1 : 0);
            }
        }
    });

    addOperator(new Operator(">=", 10, false, "Greater or equal") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) {
                return new MyComplex(v1.real >= v2.real ? 1 : 0);
            } else {
                return new MyComplex(v1.abs() >= v2.abs() ? 1 : 0);
            }
        }
    });

    addOperator(new Operator("<", 10, false,
            "Less than. See: https://en.wikipedia.org/wiki/Inequality_(mathematics)") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) {
                return new MyComplex(v1.real < v2.real ? 1 : 0);
            } else {
                return new MyComplex(v1.abs() < v2.abs() ? 1 : 0);
            }
        }
    });

    addOperator(new Operator("<=", 10, false, "less or equal") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) {
                return new MyComplex(v1.real <= v2.real ? 1 : 0);
            } else {
                return new MyComplex(v1.abs() <= v2.abs() ? 1 : 0);
            }
        }
    });

    addOperator(new Operator("->", 7, false, "Set variable v to new value ") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            if (v1 instanceof PitDecimal) {
                PitDecimal target = (PitDecimal) v1;
                String s = target.getVarToken();
                setVariable(s, v2);
                return v2;
            }
            throw new ExpressionException("LHS not variable");
        }
    });

    addOperator(new Operator("=", 7, false, "Equality") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) {
                return new MyComplex(v1.real == v2.real ? 1 : 0);
            } else {
                return new MyComplex(v1.abs() == v2.abs() ? 1 : 0);
            }
        }
    });

    addOperator(new Operator("!=", 7, false,
            "Inequality. See: https://en.wikipedia.org/wiki/Inequality_(mathematics)") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) {
                return new MyComplex(v1.real != v2.real ? 1 : 0);
            } else {
                return new MyComplex(v1.abs() != v2.abs() ? 1 : 0);
            }
        }
    });
    addOperator(
            new Operator("or", 7, false, "Bitwise OR. See: https://en.wikipedia.org/wiki/Logical_disjunction") {
                @Override
                public MyComplex eval(MyComplex v1, MyComplex v2) {
                    return new MyComplex((long) v1.real | (long) v2.real);
                }
            });
    addOperator(new Operator("and", 7, false,
            "Bitwise AND. See: https://en.wikipedia.org/wiki/Logical_conjunction") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            return new MyComplex((long) v1.real & (long) v2.real);
        }
    });
    addOperator(new Operator("xor", 7, false, "Bitwise XOR, See: https://en.wikipedia.org/wiki/Exclusive_or") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            return new MyComplex((long) v1.real ^ (long) v2.real);
        }
    });

    addOperator(new Operator("!", 50, true, "Factorial. See https://en.wikipedia.org/wiki/Factorial") {
        public BigInteger factorial(long n) {
            BigInteger factorial = BigInteger.ONE;
            for (long i = 1; i <= n; i++) {
                factorial = factorial.multiply(BigInteger.valueOf(i));
            }
            return factorial;
        }

        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            BigInteger fact = factorial((long) v1.real);
            return new MyComplex(fact, BigInteger.ZERO);
        }
    });

    addOperator(new Operator("~", 8, false, "Bitwise negation") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            BigInteger bi = v2.toBigIntegerReal();
            int c = bi.bitLength();
            if (c == 0) {
                return new MyComplex(1);
            }
            for (int s = 0; s < c; s++) {
                bi = bi.flipBit(s);
            }
            return new MyComplex(bi);
        }
    });

    addOperator(new Operator("shl", 8, false, "Left Bit shift") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            return new MyComplex((long) v1.real << (long) v2.real);
        }
    });

    addOperator(new Operator("shr", 8, false, "Right bit shift") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            return new MyComplex((long) v1.real >>> (long) v2.real);
        }
    });

    addFunction(new Function("NOT", 1, "evaluates to 0 if argument != 0") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            boolean zero = parameters.get(0).abs() == 0;
            return new MyComplex(zero ? 1 : 0);
        }
    });

    addFunction(new Function("RND", 2, "Give random number in the range between first and second argument") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double low = parameters.get(0).real;
            double high = parameters.get(1).real;
            return new MyComplex(low + Math.random() * (high - low));
        }
    });

    MersenneTwister mers = new MersenneTwister(System.nanoTime());

    addFunction(new Function("MRS", 0, "Mersenne twister random generator") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return new MyComplex(mers.nextDouble());
        }
    });

    addFunction(new Function("BIN", 2, "Binomial Coefficient 'n choose k'") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            int n = (int) parameters.get(0).real;
            int k = (int) parameters.get(1).real;
            double d = CombinatoricsUtils.binomialCoefficientDouble(n, k);
            return new MyComplex(d);
        }
    });
    addFunction(new Function("STIR", 2,
            "Stirling number of 2nd kind: http://mathworld.wolfram.com/StirlingNumberoftheSecondKind.html") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            int n = (int) parameters.get(0).real;
            int k = (int) parameters.get(1).real;
            double d = CombinatoricsUtils.stirlingS2(n, k);
            return new MyComplex(d);
        }
    });

    addFunction(new Function("SIN", 1, "Sine function") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).sin();
        }
    });
    addFunction(new Function("COS", 1, "Cosine function") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).cos();
        }
    });
    addFunction(new Function("TAN", 1, "Tangent") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).tan();
        }
    });
    addFunction(new Function("ASIN", 1, "Reverse Sine") { // added by av
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).asin();
        }
    });
    addFunction(new Function("ACOS", 1, "Reverse Cosine") { // added by av
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).acos();
        }
    });
    addFunction(new Function("ATAN", 1, "Reverse Tangent") { // added by av
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).atan();
        }
    });
    addFunction(new Function("SINH", 1, "Hyperbolic Sine") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).sinh();
        }
    });
    addFunction(new Function("COSH", 1, "Hyperbolic Cosine") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).cosh();
        }
    });
    addFunction(new Function("TANH", 1, "Hyperbolic Tangent") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).tanh();
        }
    });
    addFunction(new Function("RAD", 1, "Transform degree to radian") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double d = Math.toRadians(parameters.get(0).real);
            return new MyComplex(d);
        }
    });
    addFunction(new Function("DEG", 1, "Transform radian to degree") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double d = Math.toDegrees(parameters.get(0).real);
            return new MyComplex(d);
        }
    });
    addFunction(new Function("MAX", -1, "Find the biggest value in a list") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            MyComplex save = new MyComplex(Double.MIN_VALUE);
            if (parameters.size() == 0) {
                throw new ExpressionException("MAX requires at least one parameter");
            }
            //                if (parameters.get(0).type == ValueType.ARRAY)
            //                    parameters = parameters.get(0).list;
            if (parameters.get(0).type == ValueType.COMPLEX) {
                for (MyComplex parameter : parameters) {
                    if (parameter.abs() > save.abs()) {
                        save = parameter;
                    }
                }
                save.type = ValueType.COMPLEX;
            } else {
                for (MyComplex parameter : parameters) {
                    if (parameter.real > save.real) {
                        save = parameter;
                    }
                }
                save.type = ValueType.REAL;
            }
            return save;
        }
    });
    ///////////////////////////////////////////////////////
    addFunction(new Function("IF", 3, "Conditional: give param3 if param1 is 0, otherwise param2") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            if (parameters.get(0).real == 0.0) {
                return parameters.get(2);
            }
            return parameters.get(1);
        }
    });

    addFunction(new Function("PERC", 2, "Get param1 percent of param2") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).divide(new MyComplex(100)).multiply(parameters.get(1));
        }
    });

    addFunction(new Function("PER", 2, "How many percent is param1 of param2") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).multiply(new MyComplex(100)).divide(parameters.get(1));
        }
    });

    addFunction(new Function("H", 1, "Evaluate _history element") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            int i = (int) parameters.get(0).real;
            Expression ex = new Expression(history.get(i), history, mainVars);
            return ex.eval();
        }
    });

    addFunction(new Function("MERS", 1, "Calculate Mersenne Number") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            MyComplex p = parameters.get(0);
            return new MyComplex(2).pow(p).subtract(new MyComplex(1));
        }
    });

    addFunction(new Function("GCD", 2, "Find greatest common divisor of 2 values") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double a = parameters.get(0).real;
            double b = parameters.get(1).real;
            long r = ArithmeticUtils.gcd((long) a, (long) b);
            return new MyComplex(r);
        }
    });
    addFunction(new Function("LCM", 2, "Find least common multiple of 2 values") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double a = parameters.get(0).real;
            double b = parameters.get(1).real;
            long r = ArithmeticUtils.lcm((long) a, (long) b);
            return new MyComplex(r);
        }
    });
    addFunction(new Function("AMEAN", -1, "Arithmetic mean of a set of values") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            if (parameters.size() == 0) {
                throw new ExpressionException("MEAN requires at least one parameter");
            }
            Mean m = new Mean();
            double[] d = MyComplex.getRealArray(parameters);
            double d2 = m.evaluate(d);
            return new MyComplex(d2);
        }
    });
    //        addFunction(new Function("BYT", -1,
    //                "Value from sequence of bytes")
    //        {
    //            @Override
    //            public MyComplex eval (List<MyComplex> parameters)
    //            {
    //                if (parameters.size() == 0)
    //                {
    //                    return MyComplex.ZERO;
    //                }
    //                BigInteger res = BigInteger.ZERO;
    //                for (MyComplex parameter : parameters)
    //                {
    //                    if (parameter.intValue() < 0 || parameter.intValue() > 255)
    //                    {
    //                        throw new ExpressionException("not a byte value");
    //                    }
    //                    res = res.shiftLeft(8);
    //                    res = res.or(parameter.toBigInteger());
    //                }
    //                return new MyComplex(res, BigInteger.ZERO);
    //            }
    //        });
    addFunction(new Function("SEQ", 3, "Generate Sequence p1=start, p2=step, p3=count") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double start = parameters.get(0).real;
            ArrayList<MyComplex> arr = new ArrayList<>();
            for (int s = 0; s < (int) (parameters.get(2).real); s++) {
                arr.add(new MyComplex(start));
                start += parameters.get(1).real;
            }
            return new MyComplex(arr);
        }
    });

    addFunction(new Function("PROD", -1, "Product of real values") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            Product p = new Product();
            double[] d = MyComplex.getRealArray(parameters);
            return new MyComplex(p.evaluate(d));
        }
    });

    addFunction(new Function("SUM", -1, "Sum of values") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            Sum p = new Sum();
            double[] d = MyComplex.getRealArray(parameters);
            return new MyComplex(p.evaluate(d));
        }
    });

    addFunction(new Function("ANG", 1, "Angle phi of complex number in radians") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double b = parameters.get(0).angle();
            return new MyComplex(b);
        }
    });

    addFunction(new Function("IM", 1, "Get imaginary part") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return new MyComplex(parameters.get(0).imaginary);
        }
    });

    addFunction(new Function("RE", 1, "Get real part") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return new MyComplex(parameters.get(0).real);
        }
    });

    addFunction(new Function("POL", 2, "Make complex number from polar coords. angle is first arg") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double angle = parameters.get(0).real;
            double len = parameters.get(1).real;
            Complex c = ComplexUtils.polar2Complex(len, angle);
            return new MyComplex(c);
        }
    });

    addFunction(new Function("GMEAN", -1, "Geometric mean of a set of values") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            if (parameters.size() == 0) {
                throw new ExpressionException("MEAN requires at least one parameter");
            }
            GeometricMean m = new GeometricMean();
            double[] d = MyComplex.getRealArray(parameters);
            double d2 = m.evaluate(d);
            return new MyComplex(d2);
        }
    });

    addFunction(new Function("HMEAN", -1, "Harmonic mean of a set of values") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            if (parameters.size() == 0) {
                throw new ExpressionException("MEAN requires at least one parameter");
            }
            MyComplex res = new MyComplex(0);
            int num = 0;
            for (MyComplex parameter : parameters) {
                res = res.add(new MyComplex(1).divide(parameter));
                num++;
            }
            res = new MyComplex(res.abs());
            return new MyComplex(num).divide(res);
        }
    });

    addFunction(new Function("VAR", -1, "Variance of a set of values") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            if (parameters.size() == 0) {
                throw new ExpressionException("MEAN requires at least one parameter");
            }
            double[] arr = new double[parameters.size()];
            for (int s = 0; s < parameters.size(); s++) {
                arr[s] = parameters.get(s).real;
            }
            return new MyComplex(variance(arr));
        }
    });

    addFunction(new Function("NPR", 1, "Next prime number greater or equal the argument") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return new MyComplex(nextPrime((int) parameters.get(0).real));
        }
    });

    addFunction(new Function("NSWP", 1, "Swap nibbles") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            BigInteger bi = parameters.get(0).toBigIntegerReal();
            String s = bi.toString(16);
            s = new StringBuilder(s).reverse().toString();
            return new MyComplex(new BigInteger(s, 16), BigInteger.ZERO);
        }
    });

    addFunction(new Function("BSWP", 1, "Swap bytes") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            BigInteger bi = parameters.get(0).toBigIntegerReal();
            String s = bi.toString(16);
            while (s.length() % 4 != 0) {
                s = s + "0";
            }
            if (bi.intValue() < 256) {
                s = "00" + s;
            }
            s = Misc.reverseHex(s);
            return new MyComplex(new BigInteger(s, 16), BigInteger.ZERO);
        }
    });

    addFunction(new Function("PYT", 2,
            "Pythagoras's result = sqrt(param1^2+param2^2) https://en.wikipedia.org/wiki/Pythagorean_theorem") {
        @Override
        public MyComplex eval(List<MyComplex> par) {
            double a = par.get(0).real;
            double b = par.get(1).real;
            return new MyComplex(Math.sqrt(a * a + b * b));
        }
    });

    addFunction(new Function("FIB", 1, "Fibonacci number") {
        // --Commented out by Inspection (2/19/2017 7:46 PM):private final Operator exp = operators.get("^");

        @Override
        public MyComplex eval(List<MyComplex> par) {
            return Misc.iterativeFibonacci((int) par.get(0).real);
        }
    });

    ///////////////////////////////////////////////

    addFunction(new Function("MIN", -1, "Find the smallest in a list of values") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            MyComplex save = new MyComplex(Double.MAX_VALUE);
            if (parameters.size() == 0) {
                throw new ExpressionException("MAX requires at least one parameter");
            }
            if (parameters.get(0).type == ValueType.COMPLEX) {
                for (MyComplex parameter : parameters) {
                    if (parameter.abs() < save.abs()) {
                        save = parameter;
                    }
                }
                save.type = ValueType.COMPLEX;
            } else {
                for (MyComplex parameter : parameters) {
                    if (parameter.real < save.real) {
                        save = parameter;
                    }
                }
                save.type = ValueType.REAL;
            }
            return save;
        }
    });
    addFunction(new Function("ABS", 1, "Get absolute value of a number") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return new MyComplex(parameters.get(0).abs());
        }
    });
    addFunction(new Function("LN", 1, "Logarithm base e of the argument") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double d = Math.log(parameters.get(0).real);
            return new MyComplex(d);
        }
    });
    addFunction(new Function("LOG", 1, "Logarithm base 10 of the argument") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double d = Math.log10(parameters.get(0).real);
            return new MyComplex(d);
        }
    });
    addFunction(new Function("FLOOR", 1, "Rounds DOWN to nearest Integer") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double d = Math.floor(parameters.get(0).real);
            return new MyComplex(d);
        }
    });
    addFunction(new Function("CEIL", 1, "Rounds UP to nearest Integer") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double d = Math.ceil(parameters.get(0).real);
            return new MyComplex(d);
        }
    });
    addFunction(new Function("ROU", 1, "Rounds to nearest Integer") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            int d = (int) (parameters.get(0).real + 0.5);
            return new MyComplex(d);
        }
    });
    addFunction(new Function("SQRT", 1, "Square root") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            MyComplex p = parameters.get(0);
            if (p.type == ValueType.REAL) {
                return new MyComplex(Math.sqrt(p.real));
            }
            return p.sqrt();
        }
    });
    addFunction(new Function("ARR", -1, "Create array") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return new MyComplex(parameters);
        }
    });
    addFunction(new Function("POLY", -1, "Treat array as Polynom") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double[] d = MyComplex.getRealArray(parameters);
            PolynomialFunction p = new PolynomialFunction(d);
            return new MyComplex(p);
        }
    });
    addFunction(new Function("DRVE", -1, "Make derivative of polynomial") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            PolynomialFunction p;
            if (parameters.get(0).isPoly()) {
                p = new PolynomialFunction(parameters.get(0).getRealArray());
            } else {
                double[] d = MyComplex.getRealArray(parameters);
                p = new PolynomialFunction(d);
            }
            return new MyComplex(p.polynomialDerivative());
        }
    });
    addFunction(new Function("ADRVE", -1, "Make antiderivative of polynomial. Constant is always zero") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            PolynomialFunction p;
            if (parameters.get(0).isPoly()) {
                p = new PolynomialFunction(parameters.get(0).getRealArray());
            } else {
                double[] d = MyComplex.getRealArray(parameters);
                p = new PolynomialFunction(d);
            }
            return new MyComplex(Misc.antiDerive(p));
        }
    });

    addFunction(new Function("PVAL", 2, "Compute value of polynom for the given argument.") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            if (parameters.get(0).isPoly()) {
                PolynomialFunction p = new PolynomialFunction(parameters.get(0).getRealArray());
                double v = p.value(parameters.get(1).real);
                return new MyComplex(v);
            }
            throw new ExpressionException("first arg must be polynomial");
        }
    });

    addFunction(new Function("INTGR", 3, "Numerical integration") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            if (parameters.get(0).isPoly()) {
                PolynomialFunction p = new PolynomialFunction(parameters.get(0).getRealArray());
                double start = parameters.get(1).real;
                double end = parameters.get(2).real;
                SimpsonIntegrator si = new SimpsonIntegrator();
                double d = si.integrate(1000, p, start, end);
                return new MyComplex(d);
            }
            throw new ExpressionException("first arg must be polynomial");
        }
    });

}