/*
Private Method: inxbuild

sorts network and builds netindex[0..255]
763352
function inxbuild() {
    var i, j, p, q, smallpos, smallval, previouscol = 0, startpos = 0;
    for (i = 0; i < netsize; i++) {
      p = network[i];
      smallpos = i;
      smallval = p[1]; // index on g
      // find smallest in i..netsize-1
      for (j = i + 1; j < netsize; j++) {
        q = network[j];
        if (q[1] < smallval) { // index on g
          smallpos = j;
          smallval = q[1]; // index on g
        }
      }
      q = network[smallpos];
      // swap p (i) and q (smallpos) entries
      if (i != smallpos) {
        j = q[0];   q[0] = p[0];   p[0] = j;
        j = q[1];   q[1] = p[1];   p[1] = j;
        j = q[2];   q[2] = p[2];   p[2] = j;
        j = q[3];   q[3] = p[3];   p[3] = j;
      }
      // smallval entry is now in position i

      if (smallval != previouscol) {
        netindex[previouscol] = (startpos + i) >> 1;
        for (j = previouscol + 1; j < smallval; j++)
          netindex[j] = i;
        previouscol = smallval;
        startpos = i;
      }
    }
    netindex[previouscol] = (startpos + maxnetpos) >> 1;
    for (j = previouscol + 1; j < 256; j++)
      netindex[j] = maxnetpos; // really 256
  }
140915
def address_in_network(ip, net):
    
    ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
    netaddr, bits = net.split('/')
    netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
    network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
    return (ipaddr & netmask) == (network & netmask)
675690
function() {
		return {
			network: {
				name: '',
				hostname: '',
				ircd: '',
				nicklength: 9,
				maxtargets: {}
			},
			channel: {
				idlength: {},
				limit: {},
				length: 200,
				modes: 0,
				types: '#&',
				kicklength: 0,
				topiclength: 0
			},
			modes: {
				user: '',
				channel: '',
				param: '',
				types: {
					a: '',
					b: '',
					c: '',
					d: ''
				},
				prefixes: '~&@%+',
				prefixmodes: {
					q: '~',
					a: '&',
					o: '@',
					h: '%',
					v: '+'
				},
				maxlist: {}
			},
			raw: []
		};
	}
249164
def dev_from_index(self, if_index):
        """"""
        try:
            if_index = int(if_index)  # Backward compatibility
            return next(iface for iface in six.itervalues(self)
                        if iface.win_index == if_index)
        except (StopIteration, RuntimeError):
            if str(if_index) == "1":
                # Test if the loopback interface is set up
                if isinstance(scapy.consts.LOOPBACK_INTERFACE, NetworkInterface):  # noqa: E501
                    return scapy.consts.LOOPBACK_INTERFACE
            raise ValueError("Unknown network interface index %r" % if_index)
857864
func NewNetworkIndex() *NetworkIndex {
	return &NetworkIndex{
		AvailBandwidth: make(map[string]int),
		UsedPorts:      make(map[string]Bitmap),
		UsedBandwidth:  make(map[string]int),
	}
}
187595
function createIndex(addFn) {
  return lunr(/** @this */function() {
    this.pipeline.remove(lunr.stopWordFilter);
    this.ref('path');
    this.field('titleWords', {boost: 100});
    this.field('headingWords', {boost: 50});
    this.field('members', {boost: 40});
    this.field('keywords', {boost: 20});
    addFn(this);
  });
}
859795
void buildIndex(double desiredSpeed, boolean discardDuplicates, boolean verifyOnly)
        throws RepositoryException
    {
        final MergeSortBuffer buffer;
        final Comparator c;

        final Log log = LogFactory.getLog(IndexedStorage.class);

        final Query<S> masterQuery;
        {
            // Need to explicitly order master query by primary key in order
            // for fetchAfter to work correctly in case corrupt records are
            // encountered.
            masterQuery = mMasterStorage.query()
                .orderBy(naturalOrdering(mMasterStorage.getStorableType()));
        }

        // Quick check to see if any records exist in master.
        {
            Transaction txn = mRepository.enterTopTransaction(IsolationLevel.READ_COMMITTED);
            try {
                if (!masterQuery.exists()) {
                    if (mIndexEntryStorage.query().exists()) {
                        txn.exit();
                        mIndexEntryStorage.truncate();
                    }
                    return;
                }
            } finally {
                txn.exit();
            }
        }

        // Enter top transaction with isolation level of none to make sure
        // preload operation does not run in a long nested transaction.
        Transaction txn = mRepository.enterTopTransaction(IsolationLevel.NONE);
        try {
            Cursor<S> cursor = masterQuery.fetch();
            try {
                if (log.isInfoEnabled()) {
                    StringBuilder b = new StringBuilder();
                    b.append("Preparing index on ");
                    b.append(mMasterStorage.getStorableType().getName());
                    b.append(": ");
                    try {
                        mIndex.appendTo(b);
                    } catch (java.io.IOException e) {
                        // Not gonna happen.
                    }
                    log.info(b.toString());
                }

                // Preload and sort all index entries for improved performance.

                buffer = new MergeSortBuffer(mIndexEntryStorage, null, BUILD_SORT_BUFFER_SIZE);
                c = getComparator();
                buffer.prepare(c);

                long nextReportTime = System.currentTimeMillis() + BUILD_INFO_DELAY_MILLIS;

                // These variables are used when corrupt records are encountered.
                S lastUserStorable = null;
                int skippedCount = 0;

                while (cursor.hasNext()) {
                    S userStorable;
                    try {
                        userStorable = cursor.next();
                        skippedCount = 0;
                    } catch (CorruptEncodingException e) {
                        log.warn("Omitting corrupt record from index: " + e.toString());

                        // Exception forces cursor to close. Close again to be sure.
                        cursor.close();

                        if (lastUserStorable == null) {
                            cursor = masterQuery.fetch();
                        } else {
                            cursor = masterQuery.fetchAfter(lastUserStorable);
                        }

                        cursor.skipNext(++skippedCount);
                        continue;
                    }

                    buffer.add(makeIndexEntry(userStorable));

                    if (log.isInfoEnabled()) {
                        long now = System.currentTimeMillis();
                        if (now >= nextReportTime) {
                            log.info("Prepared " + buffer.size() + " index entries");
                            nextReportTime = now + BUILD_INFO_DELAY_MILLIS;
                        }
                    }

                    lastUserStorable = userStorable;
                }

                // No need to commit transaction because no changes should have been made.
            } finally {
                cursor.close();
            }
        } finally {
            txn.exit();
        }

        // This is not expected to take long, since MergeSortBuffer sorts as
        // needed. This just finishes off what was not written to a file.
        buffer.sort();

        if (isUnique()) {
            // If index is unique, scan buffer and check for duplicates
            // _before_ inserting index entries. If there are duplicates,
            // fail, since unique index cannot be built.

            log.info("Verifying index");

            Object last = null;
            for (Object obj : buffer) {
                if (last != null && c.compare(last, obj) == 0) {
                    if (discardDuplicates) {
                        log.warn("Unique index contains duplicates; skipping: "
                                 + this + ", " + last + " == " + obj);
                    } else {
                        buffer.close();
                        throw new UniqueConstraintException
                            ("Cannot build unique index because duplicates exist: "
                             + this + ", " + last + " == " + obj);
                    }
                }
                last = obj;
            }
        }

        if (verifyOnly) {
            log.info("Verification complete");
            buffer.close();
            return;
        }

        final int bufferSize = buffer.size();

        if (log.isInfoEnabled()) {
            log.info("Begin build of " + bufferSize + " index entries");
        }

        // Need this index entry query for deleting bogus entries.
        final Query indexEntryQuery = mIndexEntryStorage.query()
            .orderBy(naturalOrdering(mIndexEntryStorage.getStorableType()));

        Throttle throttle = desiredSpeed < 1.0 ? new Throttle(BUILD_THROTTLE_WINDOW) : null;

        long totalInserted = 0;
        long totalUpdated = 0;
        long totalDeleted = 0;
        long totalProgress = 0;

        txn = enterBuildTxn();
        try {
            Cursor<? extends Storable> indexEntryCursor = indexEntryQuery.fetch();
            Storable existingIndexEntry = null;

            if (!indexEntryCursor.hasNext()) {
                indexEntryCursor.close();
                // Don't try opening again.
                indexEntryCursor = null;
            }

            boolean retry = false;
            Storable indexEntry = null;
            Storable lastIndexEntry = null;

            long nextReportTime = System.currentTimeMillis() + BUILD_INFO_DELAY_MILLIS;

            Iterator it = buffer.iterator();
            bufferIterate: while (true) {
                if (!retry) {
                    Object obj;
                    if (it.hasNext()) {
                        obj = it.next();
                    } else if (indexEntryCursor != null && indexEntryCursor.hasNext()) {
                        obj = null;
                    } else {
                        break;
                    }

                    indexEntry = (Storable) obj;
                }

                try {
                    if (indexEntry != null) {
                        if (indexEntry.tryInsert()) {
                            totalInserted++;
                        } else if (!discardDuplicates) {
                            // Couldn't insert because an index entry already exists.
                            Storable existing = indexEntry.copy();
                            boolean doUpdate = false;
                            if (!existing.tryLoad()) {
                                doUpdate = true;
                            } else if (!existing.equalProperties(indexEntry)) {
                                // If only the version differs, leave existing entry alone.
                                indexEntry.copyVersionProperty(existing);
                                doUpdate = !existing.equalProperties(indexEntry);
                            }
                            if (doUpdate) {
                                indexEntry.tryDelete();
                                indexEntry.tryInsert();
                                totalUpdated++;
                            }
                        }
                    }

                    if (indexEntryCursor != null) while (true) {
                        if (existingIndexEntry == null) {
                            if (indexEntryCursor.hasNext()) {
                                existingIndexEntry = indexEntryCursor.next();
                            } else {
                                indexEntryCursor.close();
                                // Don't try opening again.
                                indexEntryCursor = null;
                                break;
                            }
                        }

                        int compare = c.compare(existingIndexEntry, indexEntry);

                        if (compare == 0) {
                            // Existing entry cursor matches so allow cursor to advance.
                            existingIndexEntry = null;
                            break;
                        } else if (compare > 0) {
                            // Existing index entry is ahead so check later.
                            break;
                        } else {
                            // Existing index entry might be bogus. Check again
                            // in case master record changed.
                            doDelete: {
                                S master = mMasterStorage.prepare();
                                copyToMasterPrimaryKey(existingIndexEntry, master);
                                if (master.tryLoad()) {
                                    Storable temp = makeIndexEntry(master);
                                    existingIndexEntry.copyVersionProperty(temp);
                                    if (existingIndexEntry.equalProperties(temp)) {
                                        break doDelete;
                                    }
                                }

                                existingIndexEntry.tryDelete();
                                totalDeleted++;

                                if (totalDeleted % BUILD_BATCH_SIZE == 0) {
                                    txn.commit();
                                    txn.exit();

                                    nextReportTime = logProgress
                                        (nextReportTime, log, totalProgress, bufferSize,
                                         totalInserted, totalUpdated, totalDeleted);

                                    txn = enterBuildTxn();

                                    indexEntryCursor.close();
                                    indexEntryCursor = indexEntryQuery
                                        .fetchAfter(existingIndexEntry);

                                    if (!indexEntryCursor.hasNext()) {
                                        indexEntryCursor.close();
                                        // Don't try opening again.
                                        indexEntryCursor = null;
                                        break;
                                    }
                                }
                            }

                            existingIndexEntry = null;

                            throttle(throttle, desiredSpeed);
                        }
                    }

                    if (indexEntry != null) {
                        totalProgress++;
                    }

                    lastIndexEntry = indexEntry;
                    retry = false;
                } catch (RepositoryException e) {
                    if (e instanceof FetchTimeoutException ||
                        e instanceof FetchDeadlockException ||
                        e instanceof PersistTimeoutException ||
                        e instanceof PersistDeadlockException)
                    {
                        log.warn("Lock conflict during index repair; will retry: " +
                                 indexEntry + ", " + e);
                        // This re-uses the last index entry to repair and forces
                        // the current transaction to commit.
                        retry = true;
                    } else {
                        throw e;
                    }
                }

                if (retry || (totalProgress % BUILD_BATCH_SIZE == 0)) {
                    txn.commit();
                    txn.exit();

                    nextReportTime = logProgress(nextReportTime, log, totalProgress, bufferSize,
                                                 totalInserted, totalUpdated, totalDeleted);

                    txn = enterBuildTxn();

                    if (indexEntryCursor != null) {
                        indexEntryCursor.close();
                        existingIndexEntry = null;

                        if (indexEntry == null || lastIndexEntry == null) {
                            indexEntryCursor = indexEntryQuery.fetch();
                        } else if (!retry) {
                            indexEntryCursor = indexEntryQuery.fetchAfter(indexEntry);
                        } else {
                            // Re-fetch starting at the same spot.
                            indexEntryCursor = indexEntryQuery.fetchAfter(lastIndexEntry);
                        }
                    }
                }

                throttle(throttle, desiredSpeed);
            }

            txn.commit();
        } finally {
            txn.exit();
            buffer.close();
        }

        if (log.isInfoEnabled()) {
            log.info("Finished building " + totalProgress + " index entries " +
                     progressSubMessgage(totalInserted, totalUpdated, totalDeleted));
        }
    }
723690
function orderNodes(ast) {
  var comments  = Array.isArray(ast.comments) ? ast.comments.slice() : [];
  var comparitor = ('sortIndex' in ast) ? compareIndex : compareLocation;
  return comments
    .concat(depthFirst(ast, ast.parent))
    .sort(comparitor)
    .map(setSortIndex);
}
943729
protected int selectFactoryIndex(Object session) throws ConnectException {
        Random rnd;
        if (session != null) {
            return session.hashCode() & 0x7fffffff;
        }
        else if ((rnd = mRnd) != null) {
            return rnd.nextInt() >>> 1;
        }
        else {
            synchronized (mFactories) {
                return mFactoryIndex++ & 0x7fffffff;
            }
        }
    }
601620
def divide_network(address_prefix)
      network_address = IPAddress(address_prefix)
      prefix = nil

      case network_address.count
      when 4097..65536
        prefix = "20"
      when 256..4096
        prefix = "24"
      end

      ## if the given network is small then do not divide it else divide using
      ## the prefix value calculated above ##
      prefix.nil? ? address_prefix : network_address.network.address.concat("/" + prefix)
    end
1256189
static InetAddress getNIFirstAddress(int niIndex) throws SocketException {
        if (niIndex > 0) {
            NetworkInterface networkInterface = NetworkInterface.getByIndex(niIndex);
            Enumeration<InetAddress> addressesEnum = networkInterface.getInetAddresses();
            if (addressesEnum.hasMoreElements()) {
                return addressesEnum.nextElement();
            }
        }
        return InetAddress.anyLocalAddress();
    }
27340
def sort_used_networks_by_hosts_size(used_network)
      used_network.sort_by.with_index { |nwrk, i| [-nwrk.hosts.size, i] }
    end
1023551
function buildDBNetworkAcl(appSubnets = []) {
  if (!Array.isArray(appSubnets) || appSubnets.length < 1) {
    return {};
  }

  const resources = buildNetworkAcl(DB_SUBNET);

  appSubnets.forEach((subnet, index) => {
    Object.assign(
      resources,
      buildNetworkAclEntry(`${DB_SUBNET}NetworkAcl`, subnet, {
        RuleNumber: 100 + index,
      }),
      buildNetworkAclEntry(`${DB_SUBNET}NetworkAcl`, subnet, {
        RuleNumber: 100 + index,
        Egress: true,
      }),
      buildNetworkAclAssociation(DB_SUBNET, index + 1),
    );
  });

  return resources;
}
1251983
function calcNetworkSpeed(iface, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors) {
  let result = {
    iface,
    operstate,
    rx_bytes,
    rx_dropped,
    rx_errors,
    tx_bytes,
    tx_dropped,
    tx_errors,
    rx_sec: -1,
    tx_sec: -1,
    ms: 0
  };

  if (_network[iface] && _network[iface].ms) {
    result.ms = Date.now() - _network[iface].ms;
    result.rx_sec = (rx_bytes - _network[iface].rx_bytes) >= 0 ? (rx_bytes - _network[iface].rx_bytes) / (result.ms / 1000) : 0;
    result.tx_sec = (tx_bytes - _network[iface].tx_bytes) >= 0 ? (tx_bytes - _network[iface].tx_bytes) / (result.ms / 1000) : 0;
    _network[iface].rx_bytes = rx_bytes;
    _network[iface].tx_bytes = tx_bytes;
    _network[iface].rx_sec = result.rx_sec;
    _network[iface].tx_sec = result.tx_sec;
    _network[iface].ms = Date.now();
    _network[iface].last_ms = result.ms;
    _network[iface].operstate = operstate;
  } else {
    if (!_network[iface]) _network[iface] = {};
    _network[iface].rx_bytes = rx_bytes;
    _network[iface].tx_bytes = tx_bytes;
    _network[iface].rx_sec = -1;
    _network[iface].tx_sec = -1;
    _network[iface].ms = Date.now();
    _network[iface].last_ms = 0;
    _network[iface].operstate = operstate;
  }
  return result;
}
564816
func (a *AllocatedTaskResources) NetIndex(n *NetworkResource) int {
	return a.Networks.NetIndex(n)
}
409014
function combineStatsAndIndexes(done, results) {
  var indexes = results.getIndexes;
  var stats = results.getIndexStats;
  var sizes = results.getIndexSizes;
  _.each(indexes, function(idx, i) {
    _.assign(indexes[i], stats[idx.name]);
    _.assign(indexes[i], sizes[idx.name]);
  });
  done(null, indexes);
}
1087572
private void skipPromotedIndex(final DataInput in) throws IOException {
        final int size = in.readInt();
        if (size <= 0) {
            return;
        }

        FileUtils.skipBytesFully(in, size);
    }