text:
""" A module for mapping operators to their corresponding eigenstates
and vice versa

It contains a global dictionary with eigenstate-operator pairings.
If a new state-operator pair is created, this dictionary should be
updated as well.

It also contains functions operators_to_state and state_to_operators
for mapping between the two. These can handle both classes and
instances of operators and states. See the individual function
descriptions for details.

TODO List:
- Update the dictionary with a complete list of state-operator pairs
"""

from __future__ import print_function, division

from sympy.physics.quantum.cartesian import (XOp, YOp, ZOp, XKet, PxOp, PxKet,
                                             PositionKet3D)
from sympy.physics.quantum.operator import Operator
from sympy.physics.quantum.state import StateBase, BraBase, Ket
from sympy.physics.quantum.spin import (JxOp, JyOp, JzOp, J2Op, JxKet, JyKet,
                                        JzKet)

__all__ = [
    'operators_to_state',
    'state_to_operators'
]

#state_mapping stores the mappings between states and their associated
#operators or tuples of operators. This should be updated when new
#classes are written! Entries are of the form PxKet : PxOp or
#something like 3DKet : (ROp, ThetaOp, PhiOp)

#frozenset is used so that the reverse mapping can be made
#(regular sets are not hashable because they are mutable
state_mapping = { JxKet: frozenset((J2Op, JxOp)),
                  JyKet: frozenset((J2Op, JyOp)),
                  JzKet: frozenset((J2Op, JzOp)),
                  Ket: Operator,
                  PositionKet3D: frozenset((XOp, YOp, ZOp)),
                  PxKet: PxOp,
                  XKet: XOp }

op_mapping = dict((v, k) for k, v in state_mapping.items())

def operators_to_state(operators, **options):
    """ Returns the eigenstate of the given operator or set of operators

    A global function for mapping operator classes to their associated
    states. It takes either an Operator or a set of operators and
    returns the state associated with these.

    This function can handle both instances of a given operator or
    just the class itself (i.e. both XOp() and XOp)

    There are multiple use cases to consider:

    1) A class or set of classes is passed: First, we try to
    instantiate default instances for these operators. If this fails,
    then the class is simply returned. If we succeed in instantiating
    default instances, then we try to call state._operators_to_state
    on the operator instances. If this fails, the class is returned.
    Otherwise, the instance returned by _operators_to_state is returned.

    2) An instance or set of instances is passed: In this case,
    state._operators_to_state is called on the instances passed. If
    this fails, a state class is returned. If the method returns an
    instance, that instance is returned.

    In both cases, if the operator class or set does not exist in the
    state_mapping dictionary, None is returned.

    Parameters
    ==========

    arg: Operator or set
         The class or instance of the operator or set of operators
         to be mapped to a state

    Examples
    ========

    >>> from sympy.physics.quantum.cartesian import XOp, PxOp
    >>> from sympy.physics.quantum.operatorset import operators_to_state
    >>> from sympy.physics.quantum.operator import Operator
    >>> operators_to_state(XOp)
    |x>
    >>> operators_to_state(XOp())
    |x>
    >>> operators_to_state(PxOp)
    |px>
    >>> operators_to_state(PxOp())
    |px>
    >>> operators_to_state(Operator)
    |psi>
    >>> operators_to_state(Operator())
    |psi>
    """

    if not (isinstance(operators, Operator)
            or isinstance(operators, set) or issubclass(operators, Operator)):
        raise NotImplementedError("Argument is not an Operator or a set!")

    if isinstance(operators, set):
        for s in operators:
            if not (isinstance(s, Operator)
                   or issubclass(s, Operator)):
                raise NotImplementedError("Set is not all Operators!")

        ops = frozenset(operators)

        if ops in op_mapping:  # ops is a list of classes in this case
            #Try to get an object from default instances of the
            #operators...if this fails, return the class
            try:
                op_instances = [op() for op in ops]
                ret = _get_state(op_mapping[ops], set(op_instances), **options)
            except NotImplementedError:
                ret = op_mapping[ops]

            return ret
        else:
            tmp = [type(o) for o in ops]
            classes = frozenset(tmp)

            if classes in op_mapping:
                ret = _get_state(op_mapping[classes], ops, **options)
            else:
                ret = None

            return ret
    else:
        if operators in op_mapping:
            try:
                op_instance = operators()
                ret = _get_state(op_mapping[operators], op_instance, **options)
            except NotImplementedError:
                ret = op_mapping[operators]

            return ret
        elif type(operators) in op_mapping:
            return _get_state(op_mapping[type(operators)], operators, **options)
        else:
            return None

def state_to_operators(state, **options):
    """ Returns the operator or set of operators corresponding to the
    given eigenstate

    A global function for mapping state classes to their associated
    operators or sets of operators. It takes either a state class
    or instance.

    This function can handle both instances of a given state or just
    the class itself (i.e. both XKet() and XKet)

    There are multiple use cases to consider:

    1) A state class is passed: In this case, we first try
    instantiating a default instance of the class. If this succeeds,
    then we try to call state._state_to_operators on that instance.
    If the creation of the default instance or if the calling of
    _state_to_operators fails, then either an operator class or set of
    operator classes is returned. Otherwise, the appropriate
    operator instances are returned.

    2) A state instance is returned: Here, state._state_to_operators
    is called for the instance. If this fails, then a class or set of
    operator classes is returned. Otherwise, the instances are returned.

    In either case, if the state's class does not exist in
    state_mapping, None is returned.

    Parameters
    ==========

    arg: StateBase class or instance (or subclasses)
         The class or instance of the state to be mapped to an
         operator or set of operators

    Examples
    ========

    >>> from sympy.physics.quantum.cartesian import XKet, PxKet, XBra, PxBra
    >>> from sympy.physics.quantum.operatorset import state_to_operators
    >>> from sympy.physics.quantum.state import Ket, Bra
    >>> state_to_operators(XKet)
    X
    >>> state_to_operators(XKet())
    X
    >>> state_to_operators(PxKet)
    Px
    >>> state_to_operators(PxKet())
    Px
    >>> state_to_operators(PxBra)
    Px
    >>> state_to_operators(XBra)
    X
    >>> state_to_operators(Ket)
    O
    >>> state_to_operators(Bra)
    O
    """

    if not (isinstance(state, StateBase) or issubclass(state, StateBase)):
        raise NotImplementedError("Argument is not a state!")

    if state in state_mapping:  # state is a class
        state_inst = _make_default(state)
        try:
            ret = _get_ops(state_inst,
                           _make_set(state_mapping[state]), **options)
        except (NotImplementedError, TypeError):
            ret = state_mapping[state]
    elif type(state) in state_mapping:
        ret = _get_ops(state,
                       _make_set(state_mapping[type(state)]), **options)
    elif isinstance(state, BraBase) and state.dual_class() in state_mapping:
        ret = _get_ops(state,
                       _make_set(state_mapping[state.dual_class()]))
    elif issubclass(state, BraBase) and state.dual_class() in state_mapping:
        state_inst = _make_default(state)
        try:
            ret = _get_ops(state_inst,
                           _make_set(state_mapping[state.dual_class()]))
        except (NotImplementedError, TypeError):
            ret = state_mapping[state.dual_class()]
    else:
        ret = None

    return _make_set(ret)

def _make_default(expr):
    try:
        ret = expr()
    except Exception:
        ret = expr

    return ret

def _get_state(state_class, ops, **options):
    # Try to get a state instance from the operator INSTANCES.
    # If this fails, get the class
    try:
        ret = state_class._operators_to_state(ops, **options)
    except NotImplementedError:
        ret = _make_default(state_class)

    return ret

def _get_ops(state_inst, op_classes, **options):
    # Try to get operator instances from the state INSTANCE.
    # If this fails, just return the classes
    try:
        ret = state_inst._state_to_operators(op_classes, **options)
    except NotImplementedError:
        if isinstance(op_classes, (set, tuple, frozenset)):
            ret = tuple(_make_default(x) for x in op_classes)
        else:
            ret = _make_default(op_classes)

    if isinstance(ret, set) and len(ret) == 1:
        return ret[0]

    return ret

def _make_set(ops):
    if isinstance(ops, (tuple, list, frozenset)):
        return set(ops)
    else:
        return ops


text:
"""
bacpypes-dweet

This application reads the values of BACnet points, packages them up into a
JSON document and it to https://dweet.io where it is very simple to follow
the values and create a dashboard.

This application requires the BACpypes and dweepy library, both are available
in PyPI.

    $ pip install bacpypes dweepy

For a description of the contents of the JSON configuration file, see the
README.
"""

import os
import sys
import signal
import json
import logging

from time import time, sleep
from threading import Thread
from collections import namedtuple, OrderedDict
from configparser import ConfigParser as _ConfigParser

from bacpypes.debugging import bacpypes_debugging, ModuleLogger
from bacpypes.consolelogging import ArgumentParser

from bacpypes.core import run, deferred
from bacpypes.iocb import IOCB

from bacpypes.pdu import Address
from bacpypes.object import get_datatype

from bacpypes.apdu import ReadPropertyRequest
from bacpypes.primitivedata import Unsigned
from bacpypes.constructeddata import Array

from bacpypes.app import BIPSimpleApplication
from bacpypes.local.device import LocalDeviceObject

import dweepy

# some debugging
_debug = 0
_log = ModuleLogger(globals())

# settings
BACPYPES_INI = os.getenv('BACPYPES_INI', 'BACpypes.ini')
SETTINGS = os.getenv("SETTINGS", "bacpypes-dweet.json")

# globals
this_application = None

#
#   DweetThread
#

@bacpypes_debugging
class DweetThread(Thread):

    def __init__(self, dweet):
        if _debug: DweetThread._debug("__init__ %r", dweet)
        Thread.__init__(self)

        # save the parameters for reference
        self.thing_name = dweet.thingName
        self.point_list = dweet.tagList
        self.interval = dweet.interval

        # this is a daemon
        self.daemon = True

        # run after the core is ready
        deferred(self.start)

    def run(self):
        if _debug: DweetThread._debug("run")

        while True:
            # sleep until the next interval
            now = time()
            sleep(self.interval - (now % self.interval))
            if _debug: DweetThread._debug("    - awake")

            # gathering spot for the data
            dweet_data = OrderedDict()

            # loop through the points
            for point in self.point_list:
                # build a request
                request = ReadPropertyRequest(
                    destination=Address(point.address),
                    objectIdentifier=(point.objectType, point.objectInstance),
                    propertyIdentifier=getattr(point, 'property', 'presentValue'),
                    )
                if _debug: DweetThread._debug("    - request: %r", request)

                # make an IOCB
                iocb = IOCB(request)
                if _debug: DweetThread._debug("    - iocb: %r", iocb)

                # give it to the application
                this_application.request_io(iocb)

                # wait for the response
                iocb.wait()

                if iocb.ioResponse:
                    apdu = iocb.ioResponse

                    # find the datatype
                    datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier)
                    if _debug: DweetThread._debug("    - datatype: %r", datatype)
                    if not datatype:
                        raise TypeError("unknown datatype")

                    # special case for array parts, others are managed by cast_out
                    if issubclass(datatype, Array) and (apdu.propertyArrayIndex is not None):
                        if apdu.propertyArrayIndex == 0:
                            value = apdu.propertyValue.cast_out(Unsigned)
                        else:
                            value = apdu.propertyValue.cast_out(datatype.subtype)
                    else:
                        value = apdu.propertyValue.cast_out(datatype)
                    if _debug: DweetThread._debug("    - value: %r", value)

                    if value == 'active' and hasattr(point, 'active'):
                        value = getattr(point, 'acitve', value)
                    elif value == 'inactive':
                        value = getattr(point, 'inactive', value)

                    # trim the display
                    if isinstance(value, float) and hasattr(point, 'decnum'):
                        value = round(value, point.decnum)
                        if _debug: DweetThread._debug("    - rounded: %r", value)

                    # save the value
                    dweet_data[point.tag] = value

                if iocb.ioError:
                    if _debug: DweetThread._debug("    - error: %r", iocb.ioError)

            # send the data
            if dweet_data:
                if _debug: DweetThread._debug(self.thing_name + ' ' + ', '.join("{}: {}".format(k,v) for k, v in dweet_data.items()) + '\n')
                dweepy.dweet_for(self.thing_name, dweet_data)

#
#   load_settings
#

@bacpypes_debugging
def load_settings(*signal_args):
    """Call to stop running, may be called with a signum and frame
    parameter if called as a signal handler."""
    if _debug: load_settings._debug("load_settings %r", signal_args)
    global args, settings

    if signal_args:
        sys.stderr.write("===== HUP Signal, %s\n" % time.strftime("%d-%b-%Y %H:%M:%S"))
        sys.stderr.flush()

    with open(args.settings) as settings_file:
        settings = json.load(
            settings_file,
            object_hook=lambda d: namedtuple('Settings', d.keys())(*d.values())
            )
        if _debug: load_settings._debug("    - settings: %r", settings)

    # add the points
    for dweet in settings.dweets:
        if _debug: load_settings._debug("    - dweet: %r", dweet)

        # make a thing
        dweet_thing = DweetThread(dweet)
        if _debug: load_settings._debug("    - dweet_thing: %r", dweet_thing)

# set a TERM signal handler
if hasattr(signal, 'SIGHUP'):
    signal.signal(signal.SIGHUP, load_settings)

#
#   main
#

def main():
    global args, settings, this_application

    # build a parser for the command line arguments
    parser = ArgumentParser(description=__doc__)

    # add a way to read a configuration file
    parser.add_argument('--ini', type=str,
        help="device object configuration file",
        )

    # settings file name
    parser.add_argument(
        "--settings", type=str,
        default=SETTINGS,
        help="settings file",
        )

    # parse the command line arguments
    args = parser.parse_args()

    if _debug: _log.debug("initialization")
    if _debug: _log.debug("    - args: %r", args)

    # load the settings
    load_settings()

    # read in the configuration file
    if args.ini:
        config = _ConfigParser()

        # case sensitive
        config.optionxform = str

        # read in the file
        config.read(args.ini)
        if _debug: _log.debug("    - config: %r", config)

        # check for BACpypes section
        if not config.has_section('BACpypes'):
            raise RuntimeError("INI file with BACpypes section expected")

        # convert the contents to an object
        ini_obj = type('ini', (object,), dict(config.items('BACpypes')))
        if _debug: _log.debug("    - ini_obj: %r", ini_obj)

        # add the object to the parsed arguments
        setattr(args, 'ini', ini_obj)

    # only one configuration
    if hasattr(settings, "config") and args.ini:
        raise RuntimeError("ambiguous settings")
    elif hasattr(settings, "config"):
        device_settings = settings.config
    elif args.ini:
        device_settings = args.ini
    else:
        raise RuntimeError("missing settings")
    if _debug: _log.debug("    - device_settings: %r", device_settings)

    # make a device object
    this_device = LocalDeviceObject(
        objectName=device_settings.objectName,
        objectIdentifier=int(device_settings.objectIdentifier),
        maxApduLengthAccepted=int(device_settings.maxApduLengthAccepted),
        segmentationSupported=device_settings.segmentationSupported,
        vendorIdentifier=int(device_settings.vendorIdentifier),
        )

    # make a simple application
    this_application = BIPSimpleApplication(this_device, device_settings.address)

    # get the services supported
    services_supported = this_application.get_services_supported()
    if _debug: _log.debug("    - services_supported: %r", services_supported)

    # let the device object know
    this_device.protocolServicesSupported = services_supported.value

    _log.debug("running")

    run()

    _log.debug("fini")

if __name__ == "__main__":
    main()

redpajama_set_name: RedPajamaGithub


text:
package privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.ui.main.sort;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.R;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.framework.comparators.PFAComparators;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.framework.context.AbstractInstanceFactory;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.framework.context.InstanceFactory;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.logic.shoppingList.business.ShoppingListService;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.logic.shoppingList.business.domain.ListItem;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.ui.main.MainActivity;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.ui.settings.SettingsKeys;

import java.util.ArrayList;
import java.util.List;

/**
 * Description:
 * Author: Grebiel Jose Ifill Brito
 * Created: 16.07.16 creation date
 */
public class SortListsDialog extends DialogFragment
{

    private AppCompatActivity activity;

    public static SortListsDialog newInstance(AppCompatActivity activity)
    {
        SortListsDialog sortListsDialog = new SortListsDialog();
        sortListsDialog.setActivity(activity);
        return sortListsDialog;
    }

    public void setActivity(AppCompatActivity activity)
    {
        this.activity = activity;
    }

    @Override
    public void onAttach(Activity activity)
    {
        super.onAttach(activity);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {

        LayoutInflater i = getActivity().getLayoutInflater();
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.DialogColourful);
        View rootView = i.inflate(R.layout.sort_lists_dialog, null);

        SortListsDialogCache cache = new SortListsDialogCache(rootView);
        setupPreviosOptions(cache);

        builder.setView(rootView);
        builder.setTitle(getActivity().getString(R.string.sort_options));
        builder.setNegativeButton(getActivity().getString(R.string.cancel), null);
        builder.setPositiveButton(getActivity().getString(R.string.okay), new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                MainActivity host = (MainActivity) activity;
                AbstractInstanceFactory instanceFactory = new InstanceFactory(host.getApplicationContext());
                ShoppingListService shoppingListService = (ShoppingListService) instanceFactory.createInstance(ShoppingListService.class);

                String criteria = PFAComparators.SORT_BY_NAME;
                if ( cache.getPriority().isChecked() )
                {
                    criteria = PFAComparators.SORT_BY_PRIORITY;
                }
                final String finalCriteria = criteria;
                boolean ascending = cache.getAscending().isChecked();

                List<ListItem> listItems = new ArrayList<>();

                shoppingListService.getAllListItems()
                        .doOnNext(item -> listItems.add(item))
                        .doOnCompleted(() ->
                        {
                            shoppingListService.sortList(listItems, finalCriteria, ascending);
                            host.reorderListView(listItems);
                        })
                        .doOnError(Throwable::printStackTrace)
                        .subscribe();

                // save sort options
                SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(activity);
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString(SettingsKeys.LIST_SORT_BY, criteria);
                editor.putBoolean(SettingsKeys.LIST_SORT_ASCENDING, ascending);
                editor.commit();
            }
        });

        return builder.create();
    }

    private void setupPreviosOptions(SortListsDialogCache cache)
    {
        boolean prevAscending = PreferenceManager.getDefaultSharedPreferences(activity).getBoolean(SettingsKeys.LIST_SORT_ASCENDING, true);
        cache.getAscending().setChecked(prevAscending);
        cache.getDescending().setChecked(!prevAscending);

        String prevCriteria = PreferenceManager.getDefaultSharedPreferences(activity).getString(SettingsKeys.LIST_SORT_BY, PFAComparators.SORT_BY_NAME);
        switch ( prevCriteria )
        {
            case PFAComparators.SORT_BY_PRIORITY:
                cache.getPriority().setChecked(true);
                break;
            default:
                cache.getName().setChecked(true);
        }
    }
}


text:
import { expect } from 'chai';
import { setupComponentTest } from 'ember-mocha';
import { beforeEach, describe, it } from 'mocha';
import sinon from 'sinon';
import hbs from 'htmlbars-inline-precompile';
import xSelectInteractor from 'emberx-select/test-support/interactor';

describe('Integration: XSelectActionsComponent', function() {
  let xselect = new xSelectInteractor('.x-select');

  setupComponentTest('x-select-actions', {
    integration: true
  });

  describe('x-option actions', function() {
    beforeEach(function() {
      this.set('handleDisable', sinon.spy());

      this.render(hbs`
        {{#x-select value=value as |xs|}}
          {{#xs.option value="Hello" onDisable=(action handleDisable) disabled=disabledProp}}
            Hello
          {{/xs.option}}
        {{/x-select}}
      `);
      this.set('disabledProp', false);
    });

    it('the option is not disabled', async () => {
      await xselect.when(() => {
        expect(xselect.options(0).isDisabled).to.equal(false);
        expect(xselect.options(0).text).to.equal('Hello');
      });
    });

    it('does not fire the action', function() {
      expect(this.get('handleDisable')).to.not.have.been.called;
    });

    describe('disabling an option', function() {
      beforeEach(function() {
        this.set('disabledProp', true);
      });

      it('disables the option', async () => {
        await xselect.when(() => expect(xselect.options(0).isDisabled).to.equal(true));
      });

      it('calls the disable action', function() {
        expect(this.get('handleDisable')).to.have.been.called;
      });

      it('has the correct arguments passed to the action', function() {
        expect(this.get('handleDisable').args[0][0]).to.equal('Hello', 'First argument should be the value');
        expect(this.get('handleDisable').args[0][1]).to.equal(
          true,
          'Second argument should be the disabled boolean'
        );
      });

      describe('setting the same value', function() {
        beforeEach(function() {
          this.set('disabledProp', true);
        });

        it("doesn't fire the action twice", function() {
          // Once because this spy has already been called in the
          // parent describe
          expect(this.get('handleDisable')).to.have.been.calledOnce;
        });
      });
    });
  });
});


text:
#ifndef STATIC_GRAPH_HPP
#define STATIC_GRAPH_HPP

#include "util/integer_range.hpp"
#include "util/percent.hpp"
#include "util/shared_memory_vector_wrapper.hpp"
#include "util/typedefs.hpp"

#include <boost/assert.hpp>

#include <algorithm>
#include <limits>
#include <utility>
#include <vector>

namespace osrm
{
namespace util
{

template <typename EdgeDataT, bool UseSharedMemory = false> class StaticGraph
{
  public:
    using NodeIterator = NodeID;
    using EdgeIterator = NodeID;
    using EdgeData = EdgeDataT;
    using EdgeRange = range<EdgeIterator>;

    class InputEdge
    {
      public:
        NodeIterator source;
        NodeIterator target;
        EdgeDataT data;

        template <typename... Ts>
        InputEdge(NodeIterator source, NodeIterator target, Ts &&... data)
            : source(source), target(target), data(std::forward<Ts>(data)...)
        {
        }
        bool operator<(const InputEdge &right) const
        {
            if (source != right.source)
            {
                return source < right.source;
            }
            return target < right.target;
        }
    };

    struct NodeArrayEntry
    {
        // index of the first edge
        EdgeIterator first_edge;
    };

    struct EdgeArrayEntry
    {
        NodeID target;
        EdgeDataT data;
    };

    EdgeRange GetAdjacentEdgeRange(const NodeID node) const
    {
        return irange(BeginEdges(node), EndEdges(node));
    }

    template <typename ContainerT> StaticGraph(const int nodes, const ContainerT &graph)
    {
        BOOST_ASSERT(std::is_sorted(const_cast<ContainerT &>(graph).begin(),
                                    const_cast<ContainerT &>(graph).end()));

        number_of_nodes = nodes;
        number_of_edges = static_cast<EdgeIterator>(graph.size());
        node_array.resize(number_of_nodes + 1);
        EdgeIterator edge = 0;
        EdgeIterator position = 0;
        for (const auto node : irange(0u, number_of_nodes + 1))
        {
            EdgeIterator last_edge = edge;
            while (edge < number_of_edges && graph[edge].source == node)
            {
                ++edge;
            }
            node_array[node].first_edge = position; //=edge
            position += edge - last_edge;           // remove
        }
        edge_array.resize(position); //(edge)
        edge = 0;
        for (const auto node : irange(0u, number_of_nodes))
        {
            EdgeIterator e = node_array[node + 1].first_edge;
            for (const auto i : irange(node_array[node].first_edge, e))
            {
                edge_array[i].target = graph[edge].target;
                edge_array[i].data = graph[edge].data;
                edge++;
            }
        }
    }

    StaticGraph(typename ShM<NodeArrayEntry, UseSharedMemory>::vector &nodes,
                typename ShM<EdgeArrayEntry, UseSharedMemory>::vector &edges)
    {
        number_of_nodes = static_cast<decltype(number_of_nodes)>(nodes.size() - 1);
        number_of_edges = static_cast<decltype(number_of_edges)>(edges.size());

        using std::swap;
        swap(node_array, nodes);
        swap(edge_array, edges);
    }

    unsigned GetNumberOfNodes() const { return number_of_nodes; }

    unsigned GetNumberOfEdges() const { return number_of_edges; }

    unsigned GetOutDegree(const NodeIterator n) const { return EndEdges(n) - BeginEdges(n); }

    inline NodeIterator GetTarget(const EdgeIterator e) const
    {
        return NodeIterator(edge_array[e].target);
    }

    EdgeDataT &GetEdgeData(const EdgeIterator e) { return edge_array[e].data; }

    const EdgeDataT &GetEdgeData(const EdgeIterator e) const { return edge_array[e].data; }

    EdgeIterator BeginEdges(const NodeIterator n) const
    {
        return EdgeIterator(node_array.at(n).first_edge);
    }

    EdgeIterator EndEdges(const NodeIterator n) const
    {
        return EdgeIterator(node_array.at(n + 1).first_edge);
    }

    // searches for a specific edge
    EdgeIterator FindEdge(const NodeIterator from, const NodeIterator to) const
    {
        for (const auto i : irange(BeginEdges(from), EndEdges(from)))
        {
            if (to == edge_array[i].target)
            {
                return i;
            }
        }
        return SPECIAL_EDGEID;
    }

    /**
     * Finds the edge with the smallest `.weight` going from `from` to `to`
     * @param from the source node ID
     * @param to the target node ID
     * @param filter a functor that returns a `bool` that determines whether an edge should be
     * tested or not.
     *   Takes `EdgeData` as a parameter.
     * @return the ID of the smallest edge if any were found that satisfied *filter*, or
     * `SPECIAL_EDGEID` if no
     *   matching edge is found.
     */
    template <typename FilterFunction>
    EdgeIterator
    FindSmallestEdge(const NodeIterator from, const NodeIterator to, FilterFunction &&filter) const
    {
        EdgeIterator smallest_edge = SPECIAL_EDGEID;
        EdgeWeight smallest_weight = INVALID_EDGE_WEIGHT;
        for (auto edge : GetAdjacentEdgeRange(from))
        {
            const NodeID target = GetTarget(edge);
            const auto &data = GetEdgeData(edge);
            if (target == to && data.weight < smallest_weight &&
                std::forward<FilterFunction>(filter)(data))
            {
                smallest_edge = edge;
                smallest_weight = data.weight;
            }
        }
        return smallest_edge;
    }

    EdgeIterator FindEdgeInEitherDirection(const NodeIterator from, const NodeIterator to) const
    {
        EdgeIterator tmp = FindEdge(from, to);
        return (SPECIAL_NODEID != tmp ? tmp : FindEdge(to, from));
    }

    EdgeIterator
    FindEdgeIndicateIfReverse(const NodeIterator from, const NodeIterator to, bool &result) const
    {
        EdgeIterator current_iterator = FindEdge(from, to);
        if (SPECIAL_NODEID == current_iterator)
        {
            current_iterator = FindEdge(to, from);
            if (SPECIAL_NODEID != current_iterator)
            {
                result = true;
            }
        }
        return current_iterator;
    }

  private:
    NodeIterator number_of_nodes;
    EdgeIterator number_of_edges;

    typename ShM<NodeArrayEntry, UseSharedMemory>::vector node_array;
    typename ShM<EdgeArrayEntry, UseSharedMemory>::vector edge_array;
};
}
}

#endif // STATIC_GRAPH_HPP


text:
//
//  MovieListViewController.m
//  rotten tomatoes
//
//  Created by Emmanuel Texier on 2/3/15.
//  Copyright (c) 2015 Emmanuel Texier. All rights reserved.
//

#import "MovieListViewController.h"
#import "Constants.h"
#import <SVProgressHUD/SVProgressHUD.h>

@interface MovieListViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *movies;
-(void) reload;
@property (nonatomic, strong) SVProgressHUD *hud;

@end

@implementation MovieListViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [super viewDidLoad];

    UIRefreshControl *refreshControl = [UIRefreshControl new];
    [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
    refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"Pull to refresh..."];
    self.refreshControl = refreshControl;
    [self reload];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    NSURL *url = [NSURL URLWithString:kRottenTomatoesUrl];
    [request setURL:url];
    [request setHTTPMethod:@"GET"];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    // show network activity in status bar
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)refresh:(UIRefreshControl *)sender{
    [self reload];
    [sender endRefreshing];
}

- (void) reload{
    [SVProgressHUD showWithStatus:@"Updating" maskType:SVProgressHUDMaskTypeBlack];

    NSString *url = kRottenTomatoesUrl;

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:12];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
        if (!connectionError && responseCode == 200){
            NSDictionary *object = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[object objectForKey:@"movies"]];
            self.movies = [[NSMutableArray alloc]init];

            for(NSDictionary *item in array){
                SFMovie *movie = [[SFMovie alloc]initWithDictionary:item];
                [self.movies addObject:movie];
                [SVProgressHUD dismiss];
            }

            [self.tableView reloadData];
            NSLog(@"%@", object);
        }
        else{
            //show error message
            NSLog(@"connectionError=%@", connectionError);
            NSLog(@"responseCode=%d", responseCode);
            [SVProgressHUD showErrorWithStatus:@"Oops, unable to load movies, check your internet!"];
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return 0;
}

/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];

    // Configure the cell...

    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here, for example:
    // Create the next view controller.
    DetailViewController *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];

    // Pass the selected object to the new view controller.

    // Push the view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Solorina octospora Arnold

### Remarks
null


text:
<!DOCTYPE html>

<meta charset="utf-8"/>
<meta content="IE=edge" http-equiv="X-UA-Compatible"/>
<meta content="initial-scale=1.0" name="viewport"/>
<meta content="7MiYjX2ZghMOWvtKRWlar--c6mD2ose5EcbQFQ6szFA" name="google-site-verification"/>
<title>Office of the Vice Chancellor for Equity, Diversity, and Inclusion </title>
<meta content="University of California, San Diego" name="ORGANIZATION"/>
<meta content="index,follow,noarchive" name="robots"/>
<meta content="Diversity" name="SITE"/>
<meta content="Office of the Vice Chancellor for Equity, Diversity, and Inclusion " name="PAGETITLE"/>
<meta content="Office of the Vice Chancellor for Equity, Diversity, and Inclusion  " name="DESCRIPTION"/>
<link href="//cdn.ucsd.edu/cms/decorator-4.5/styles/bootstrap.css" rel="stylesheet"/>
<link href="//cdn.ucsd.edu/cms/decorator-4.5/styles/base-min.css" rel="stylesheet"/>
<link href="//cdn.ucsd.edu/cms/decorator-4.5/styles/_homepage-template/homepage-wide-min.css" rel="stylesheet"/>

<link href="_resources/css/themes/white.css" media="all" rel="stylesheet" type="text/css"/>
<link href="_resources/css/themes/white.css" media="all" rel="stylesheet" type="text/css"/>

<title></title>

Skip to main content

<button class="btn-nav">
Toggle Navigation

</button>

            Equity, Diversity, and Inclusion

            Diversity

UC San Diego

<button class="search-toggle btn-default">

</button>

<form action="//act.ucsd.edu/cwp/tools/search-redir" id="cse-site-search" method="get">
Search
<select class="search-scope" id="search-scope" name="search-scope">
<option selected="selected" value="diversity">This Site</option>
<option value="default_collection">All UCSD Sites</option>
<option value="faculty-staff">Faculty/Staff</option>
</select>

Search Term
<input autofocus="autofocus" class="form-control search-term" id="q" name="search-term" placeholder="Search..." type="search"/>

</form>

About

Mission

News

Events

Campus Resources

Centers

Student Campus Community Centers

Engaging Our Principles of Community

Faculty Excellence

Initiatives

Black Academic Excellence

EDI Advisory Council

Diversity Initiatives Database

LEAD Fellows

Accountability

Report Archive

Funding Opportunities

Climate Enhancement Grants

Innovation Grants

Co-sponsorships

HOME

                    Fostering equal opportunity, open dialogue, mutual respect and cross-cultural collaboration

                    Office of the Vice Chancellor for Equity, Diversity, and Inclusion

We believe that true excellence is achieved through productive relationships among people of diverse perspectives. When the collective talents of our students, faculty, and staff at UC San Diego are united in an environment that is open and inclusive, creativity and innovation prospers.

At the Office of the Vice Chancellor for Equity, Diversity, and Inclusion, we work to ensure that our campus community is one of equal opportunity, where mutual respect and cross-cultural collaboration is fostered and open dialogue is encouraged. UC San Diego has many resources that support the recruitment and retention of historically underserved populations, deepen understanding and challenge misconceptions surrounding diversity, and develop proactive leaders who advocate for inclusion.

For additional information, please contact us at diversity@ucsd.edu.

Resources

Campus Community Centers

Disability Resources

Student Veterans Resource Center

Undocumented Student Services

Contact Office of Equity, Diversity, and Inclusion
<address>Phone: 858-822-3542</address>
<address>Campus Location: University Center 109</address>
<address>Mailing Address: 9500 Gilman Drive #0056 La Jolla, CA  92093-0056</address>

                        News

                                        Welcoming the Inaugural Director of the Inter-Tribal Resource Center

                            Campus and community members gathered recently at the Student Services Center to welcome UC San Diego's inaugural Director of the Inter-Tribal Resource Center Elena Hood.

                                        Resources for Faculty Provide Help to Succeed and Advance

                            The Office for Equity, Diversity and Inclusion is leading the charge in policy development, community building, professional development and campus resources to create an environment where all UC San Diego faculty can succeed and advance.

                                        UC San Diego Reaches out to Hispanic and Native American Students at SACNAS Conference

                            Faculty, staff and student representatives of UC San Diego met with hundreds of prospective graduate students at the annual Society for Advancement of Hispanics/Chicanos and Native Americans in Science (SACNAS) national conference.

                                        Educational and Artistic Events Center of UC San Diego's California Native American Day Celebration

                            Spoken word and theatrical performances, film screenings, a powwow as well as an art and essay contest are all part of UC San Diego's 11th annual California Native American Day celebration.

                                        Convocation Keynote to Students

                            UCSD transgender alumna serves as keynote speaker at this year's Convocation. The story of her success is filled with perspective on what true success is.

                                        UC San Diego Admits Most Diverse Class of Freshman and Transfer Students for Fall 2016

                            Historically underrepresented students up 46.2 percent at freshman level and 30.7 percent among transfers.

<news-footer></news-footer>

            UC San Diego 9500 Gilman Dr. La Jolla, CA 92093 (858) 534-2230

            Copyright © 2016 Regents of the University of California. All rights reserved.

Terms & Conditions

Feedback


text: package org.apache.pulsar.client.api;


text:
package aop

import (
	"time"
)

//Delay will call work after time of d
func Delay(work func(), d time.Duration) {
	time.Sleep(d)
	work()
}


text:
namespace quic {
namespace test {

class MockRandom : public QuicRandom {
 public:
  // Initializes base_ to 0xDEADBEEF.
  MockRandom();
  explicit MockRandom(uint32_t base);
  MockRandom(const MockRandom&) = delete;
  MockRandom& operator=(const MockRandom&) = delete;

  MOCK_METHOD(void, RandBytes, (void* data, size_t len), (override));
  MOCK_METHOD(uint64_t, RandUint64, (), (override));
  MOCK_METHOD(void, InsecureRandBytes, (void* data, size_t len), (override));
  MOCK_METHOD(uint64_t, InsecureRandUint64, (), (override));

  // Default QuicRandom implementations. They are used if the caller does not
  // setup the MockRandom via EXPECT_CALLs.

  // Fills the |data| buffer with a repeating byte, initially 'r'.
  void DefaultRandBytes(void* data, size_t len);
  // Returns base + the current increment.
  uint64_t DefaultRandUint64();

  // InsecureRandBytes behaves equivalently to RandBytes.
  void DefaultInsecureRandBytes(void* data, size_t len);
  // InsecureRandUint64 behaves equivalently to RandUint64.
  uint64_t DefaultInsecureRandUint64();

  // ChangeValue increments |increment_|. This causes the value returned by
  // |RandUint64| and the byte that |RandBytes| fills with, to change.
  // Used by the Default implementations.
  void ChangeValue();

  // Sets the base to |base| and resets increment to zero.
  // Used by the Default implementations.
  void ResetBase(uint32_t base);

 private:
  uint32_t base_;
  uint8_t increment_;
};

}  // namespace test
}  // namespace quic

#endif  // QUICHE_QUIC_TEST_TOOLS_MOCK_RANDOM_H_


text:
badge_sytem
===========

a badge system to evaluate accomplishment of tasks so to get skill set and level of people


text:
#include "Images.h"
#include "Query.h"
#include "Xml.h"
#include "Words.h"
#include "Sections.h"
#include "XmlDoc.h"
#include "Threads.h"
#include "Hostdb.h"
#include "XmlDoc.h" // my_system_r()

// TODO: image is bad if repeated on same page, check for that

//static void gotTermFreqWrapper ( void *state ) ;
static void gotTermListWrapper ( void *state ) ;
static void *thumbStartWrapper_r ( void *state , ThreadEntry *te );
static void getImageInfo ( char *buf, long size, long *dx, long *dy, long *it);

Images::Images ( ) {
	reset();
}

void Images::reset() {
	m_imgData        = NULL;
	m_imgDataSize    = 0;
	m_setCalled      = false;
	m_thumbnailValid = false;
	m_imgReply       = NULL;
	m_imgReplyLen    = 0;
	m_imgReplyMaxLen = 0;
	m_numImages      = 0;
	m_imageBufValid  = false;
	m_phase = 0;
}

/*
bool Images::hash ( long       titleRecVersion ,
		    Xml       *xml             ,
		    Url       *pageUrl         ,
		    TermTable *table           ,
		    long       score           ) {

	for ( long i = 0 ; i < m_numImages ; i++ ) {
		// get the node number
		long nn = m_imageNodes[i];
		// get the url of the image
		long  srcLen;
		char *src = xml->getString(nn,nn+1,"src",&srcLen);
		// set it to the full url
		Url iu;
		// use "pageUrl" as the baseUrl
		iu.set ( pageUrl , src , srcLen , true );  // addWWW? yes...
		// hash each one
		if ( ! table->hash ( titleRecVersion ,
				     "image"      , // desc
				     5            , // descLen
				     "gbimage"    , // field
				     7            ,
				     iu.getUrl(),
				     iu.getUrlLen(),
				     score*256,
				     TERMTABLE_MAXSCORE , // maxScore
				     false , // doSpamDetection?
				     false , // hashSingletons?
				     false , // hashPhrases?
				     true  , // hashAsWhole?
				     false , // useStems?
				     false , // useStopWords?
				     true  , // hashIfUniqueOnly?
				     false ))// hashSingletonsIffNotInPhrase
			return false;
	}
	return true;
}
*/

void Images::setCandidates ( Url *pageUrl , Words *words , Xml *xml ,
			     Sections *sections , XmlDoc *xd ) {
	// not valid for now
	m_thumbnailValid = false;
	// reset our array of image node candidates
	m_numImages = 0;
	// flag it
	m_setCalled = true;
	// strange...
	if ( m_imgReply ) { char *xx=NULL;*xx=0; }
	// save this
	m_xml       = xml;
	m_pageUrl   = pageUrl;

	// if we are a diffbot json reply, trust that diffbot got the
	// best candidate, and just use that
	if ( xd->m_isDiffbotJSONObject ) return;

	//
	// first add any open graph candidate.
	// basically they page telling us the best image straight up.
	//

	long node2 = -1;
	long startNode = 0;

	// . field can be stuff like "summary","description","keywords",...
	// . if "convertHtmlEntites" is true we change < to < and > to >
	// . <meta property="og:image" content="http://example.com/rock2.jpg"/>
	// . <meta property="og:image" content="http://example.com/rock3.jpg"/>
 ogimgloop:
	char ubuf[2000];
	long ulen = xml->getMetaContent ( ubuf , // store the val here
					  1999 ,
					  "og:image",
					  8,
					  "property",
					  false, // convertHtmlEntities
					  startNode ,
					  &node2 ); // matchedNode
	// update this in case goto ogimgloop is called
	startNode = node2 + 1;
	// see section below for explanation of what we are storing here...
	if ( node2 >= 0 ) {
		// save it
		m_imageNodes[m_numImages] = node2;
		Query q;
		if ( ulen > MAX_URL_LEN ) goto ogimgloop;
		// set it to the full url
		Url iu;
		// use "pageUrl" as the baseUrl
		iu.set ( pageUrl , ubuf , ulen );
		// skip if invalid domain or TLD
		if ( iu.getDomainLen() <= 0 ) goto ogimgloop;
		// for looking it up on disk to see if unique or not
		char buf[2000];
		// if we don't put in quotes it expands '|' into
		// the "PiiPe" operator in Query.cpp
		snprintf ( buf , 1999, "gbimage:\"%s\"",iu.getUrl());
		// TODO: make sure this is a no-split termid storage thingy
		// in Msg14.cpp
		if ( ! q.set2 ( buf , langUnknown , false ) ) return;
		// sanity test
		if ( q.getNumTerms() != 1 ) { char *xx=0;*xx=0; }
		// store the termid
		m_termIds[m_numImages] = q.getTermId(0);
		// advance the counter
		m_numImages++;
		// try to get more graph images if we have some room
		if ( m_numImages + 2 < MAX_IMAGES ) goto ogimgloop;
	}

	//m_pageSite  = pageSite;
	// scan the words
	long       nw     = words->getNumWords();
	nodeid_t  *tids   = words->getTagIds();
	long long *wids   = words->getWordIds();
	//long      *scores = scoresArg->m_scores;
	Section **sp = NULL;
	if ( sections ) sp = sections->m_sectionPtrs;
	// not if we don't have any identified sections
	if ( sections && sections->m_numSections <= 0 ) sp = NULL;
	// the positive scored window
	long firstPosScore = -1;
	long lastPosScore  = -1;
	long badFlags = SEC_SCRIPT|SEC_STYLE|SEC_SELECT|SEC_MARQUEE;
	// find positive scoring window
	for ( long i = 0 ; i < nw ; i++ ) {
		// skip if in bad section
		if ( sp && (sp[i]->m_flags & badFlags) ) continue;
		if ( wids[i]   != 0 ) continue;
		// set first positive scoring guy
		if ( firstPosScore == -1 ) firstPosScore = i;
		// keep track of last guy
		lastPosScore = i;
	}
	// sanity check
	if ( getNumXmlNodes() > 512 ) { char *xx=NULL;*xx=0; }
	// . pedal firstPosScore back until we hit a section boundary
	// . i.e. stop once we hit a front/back tag pair, like <div> and </div>
	char tc[512];
	memset ( tc , 0 , 512 );
	long a = firstPosScore;
	for ( ; a >= 0 ; a-- ) {
		// get the tid
		nodeid_t tid = tids[a];
		// remove back bit, if any
		tid &= BACKBITCOMP;
		// skip if not a tag, or a generic xml tag
		if ( tid <= 1 ) continue;
		// mark it
		if ( words->isBackTag(a) ) tc[tid] |= 0x02;
		else                       tc[tid] |= 0x01;
		// continue if not a full front/back pair
		if ( tc[tid] != 0x03 ) continue;
		// continue if not a "section" type tag (see Scores.cpp)
		if ( tid != TAG_DIV      &&
		     tid != TAG_TEXTAREA &&
                     tid != TAG_TR       &&
                     tid != TAG_TD       &&
                     tid != TAG_TABLE      )
			continue;
		// ok we should stop now
		break;
	}
	// min is 0
	if ( a < 0 ) a = 0;

	// now look for the image urls within this window
	for ( long i = a ; i < lastPosScore ; i++ ) {
		// skip if not <img> tag
		if (tids[i] != TAG_IMG ) continue;
		// get the node num into Xml.cpp::m_nodes[] array
		long nn = words->m_nodes[i];
		// check width to rule out small decorating imgs
		long width = xml->getLong(nn,nn+1,"width", -1 );
		if ( width != -1 && width < 50 ) continue;
		// same with height
		long height = xml->getLong(nn,nn+1, "height", -1 );
		if ( height != -1 && height < 50 ) continue;
		// get the url of the image
		long  srcLen;
		char *src = xml->getString(nn,"src",&srcLen);
		// skip if none
		if ( srcLen <= 2 ) continue;
		// set it to the full url
		Url iu;
		// use "pageUrl" as the baseUrl
		iu.set ( pageUrl , src , srcLen );
		// skip if invalid domain or TLD
		if ( iu.getDomainLen() <= 0 ) continue;
		// skip if not from same domain as page url
		//long dlen = pageUrl->getDomainLen();
		//if ( iu.getDomainLen() != dlen ) continue;
		//if(strncmp(iu.getDomain(),pageUrl->getDomain(),dlen))continue
		// get the full url
		char *u    = iu.getUrl();
		long  ulen = iu.getUrlLen();
		// skip common crap
		if ( strncasestr(u,ulen,"logo"           ) ) continue;
		if ( strncasestr(u,ulen,"comment"        ) ) continue;
		if ( strncasestr(u,ulen,"print"          ) ) continue;
		if ( strncasestr(u,ulen,"subscribe"      ) ) continue;
		if ( strncasestr(u,ulen,"header"         ) ) continue;
		if ( strncasestr(u,ulen,"footer"         ) ) continue;
		if ( strncasestr(u,ulen,"menu"           ) ) continue;
		if ( strncasestr(u,ulen,"button"         ) ) continue;
		if ( strncasestr(u,ulen,"banner"         ) ) continue;
		if ( strncasestr(u,ulen,"ad.doubleclick.") ) continue;
		if ( strncasestr(u,ulen,"ads.webfeat."   ) ) continue;
		if ( strncasestr(u,ulen,"xads.zedo."     ) ) continue;

		// save it
		m_imageNodes[m_numImages] = nn;

		// before we lookup the image url to see if it is unique we
		// must first make sure that we have an adequate number of
		// permalinks from this same site with this same hop count.
		// we need at least 10 before we extract image thumbnails.
		char buf[2000];
		// set the query
		Query q;

		// if we do have 10 or more, then we lookup the image url to
		// make sure it is indeed unique
		sprintf ( buf , "gbimage:\"%s\"",u);
		// TODO: make sure this is a no-split termid storage thingy
		// in Msg14.cpp
		if ( ! q.set2 ( buf , langUnknown , false ) )
			// return true with g_errno set on error
			return;
		// store the termid
		m_termIds[m_numImages] = q.getTermId(0);

		// advance the counter
		m_numImages++;

		// break if full
		if ( m_numImages >= MAX_IMAGES ) break;
	}
}

// . returns false if blocked, returns true otherwise
// . sets g_errno on error
bool Images::getThumbnail ( char *pageSite ,
			    long  siteLen  ,
			    long long docId ,
			    XmlDoc *xd ,
			    collnum_t collnum,//char *coll ,
			    //char **statusPtr ,
			    long hopCount,
			    void *state ,
			    void   (*callback)(void *state) ) {
	// sanity check
	if ( ! m_setCalled ) { char *xx=NULL;*xx=0; }
	// we haven't had any error
	m_hadError  = 0;
	// no reason to stop yet
	m_stopDownloading = false;
	// reset here now
	m_i = 0;
	m_j = 0;
	m_phase = 0;

	// sanity check
	if ( ! m_pageUrl ) { char *xx=NULL;*xx=0; }
	// sanity check
	if ( ! pageSite ) { char *xx=NULL;*xx=0; }
	// we need to be a permalink
	//if ( ! isPermalink ) return true;

	// save these
	//m_statusPtr = statusPtr;
	// save this
	m_collnum = collnum;
	m_docId = docId;
	m_callback = callback;
	m_state = state;

	// if this doc is a json diffbot reply it already has the primary
	// image selected so just use that
	m_xd = xd;
	if ( m_xd->m_isDiffbotJSONObject )
		return downloadImages();

	// if no candidates, we are done, no error
	if ( m_numImages == 0 ) return true;

	//Vector *v = xd->getTagVector();
	// this will at least have one component, the 0/NULL component
	uint32_t *tph = xd->getTagPairHash32();
	// must not block or error on us
	if ( tph == (void *)-1 ) { char *xx=NULL;*xx=0; }
	// must not error on use?
	if ( ! tph ) { char *xx=NULL;*xx=0; }

	// . see DupDetector.cpp, very similar to this
	// . see how many pages we have from our same site with our same
	//   html template (and that are permalinks)
	char buf[2000];
	char c = pageSite[siteLen];
	pageSite[siteLen]=0;
	// site MUST NOT start with "http://"
	if ( strncmp ( pageSite , "http://", 7)==0){char*xx=NULL;*xx=0;}
	// this must match what we hash in XmlDoc::hashNoSplit()
	sprintf ( buf , "gbsitetemplate:%lu%s", (unsigned long)*tph,pageSite );
	pageSite[siteLen]=c;
	// TODO: make sure this is a no-split termid storage thingy
	// in Msg14.cpp
	Query q;
	if ( ! q.set2 ( buf , langUnknown , false ) )
		// return true with g_errno set on error
		return true;
	// store the termid
	long long termId = q.getTermId(0);

	key144_t startKey ;
	key144_t endKey   ;
	g_posdb.makeStartKey(&startKey,termId);
	g_posdb.makeEndKey  (&endKey  ,termId);

	// get shard of that (this termlist is sharded by termid -
	// see XmlDoc.cpp::hashNoSplit() where it hashes gbsitetemplate: term)
	long shardNum = g_hostdb.getShardNumByTermId ( &startKey );

	if ( g_conf.m_logDebugImage )
		log("image: image checking %s list on shard %li",buf,shardNum);

	// if ( ! m_msg36.getTermFreq ( m_collnum               ,
	// 			     0                  , // maxAge
	// 			     termId             ,
	// 			     this               ,
	// 			     gotTermFreqWrapper ,
	// 			     MAX_NICENESS       ,
	// 			     true               ,  // exact count?
	// 			     false              ,  // inc count?
	// 			     false              ,  // dec count?
	// 			     false              )) // is split?
	// 	return false;

	// just use msg0 and limit to like 1k or something
	if ( ! m_msg0.getList ( -1    , // hostid
				-1    , // ip
				-1    , // port
				0     , // maxAge
				false , // addToCache?
				RDB_POSDB ,
				m_collnum      ,
				&m_list     , // RdbList ptr
				(char *)&startKey    ,
				(char *)&endKey      ,
				1024        , // minRecSize
				this        ,
				gotTermListWrapper ,
				MAX_NICENESS       ,
				false , // err correction?
				true  , // inc tree?
				true  , // domergeobsolete
				-1    , // firstHostId
				0     , // start filenum
				-1    , // numFiles
				30    , // timeout
				-1    , // syncpoint
				-1    , // preferlocalreads
				NULL  , // msg5
				NULL  , // msg5b
				false , // isRealMerge?
				true  , // allow pg cache
				false , // focelocalindexdb
				false , // doIndexdbSplit?
				shardNum ))// force paritysplit
		return false;

	// did not block
	return gotTermFreq();
}

// void gotTermFreqWrapper ( void *state ) {
// 	Images *THIS = (Images *)state;
// 	// process/store the reply
// 	if ( ! THIS->gotTermFreq() ) return;
// 	// all done
// 	THIS->m_callback ( THIS->m_state );
// }

// returns false if blocked, true otherwise
bool Images::gotTermFreq ( ) {
	// error?
	if ( g_errno ) return true;
	// bail if less than 10
	//long long nt = m_msg36.getTermFreq();
	// each key but the first is 12 bytes (compressed)
	long long nt = (m_list.getListSize() - 6)/ 12;
	// . return true, without g_errno set, we are done
	// . if we do not have 10 or more webpages that share this same
	//   template then do not do image extraction at all, it is too risky
	//   that we get a bad image
	// . MDW: for debugging, do not require 10 pages of same template
	//if ( nt < 10 ) return true;
	if ( nt < -2 ) return true;
	// now see which of the image urls are unique
	if ( ! launchRequests () ) return false;
	// i guess we did not block
	return true;
}

// . returns false if blocked, true otherwise
// . see if other pages we've indexed have this same image url
bool Images::launchRequests ( ) {
	// loop over all images
	for ( long i = m_i ; i < m_numImages ; i++ ) {
		// advance
		m_i++;
		// assume no error
		m_errors[i] = 0;
		// make the keys. each term is a gbimage:<imageUrl> term
		// so we are searching for the image url to see how often
		// it is repeated on other pages.
		key144_t startKey ;
		key144_t endKey   ;
		g_posdb.makeStartKey(&startKey,m_termIds[i]);
		g_posdb.makeEndKey  (&endKey  ,m_termIds[i]);
		// get our residing groupid
		//unsigned long gid = g_indexdb.getNoSplitGroupId(&startKey);
		// no split is true for this one, so we do not split by docid
		//uint32_t gid = getGroupId(RDB_INDEXDB,&startKey,false);
		unsigned long shardNum;
		//shardNum = getShardNum(RDB_POSDB,&startKey);
		//uint32_t getShardNum (char rdbId, void *key );
		//uint32_t getShardNumFromDocId ( long long d ) ;
		// assume to be for posdb here
		shardNum = g_hostdb.getShardNumByTermId ( &startKey );

		// debug msg
		if ( g_conf.m_logDebugImage )
			log("image: image checking shardnum %li (termid0=%llu)"
			    " for image url #%li",
			    shardNum ,m_termIds[i],i);

		// get the termlist
		if ( ! m_msg0.getList ( -1    , // hostid
					-1    , // ip
					-1    , // port
					0     , // maxAge
					false , // addToCache?
					RDB_POSDB,
					m_collnum      ,
					&m_list     , // RdbList ptr
					(char *)&startKey    ,
					(char *)&endKey      ,
					1024        , // minRecSize
					this        ,
					gotTermListWrapper ,
					MAX_NICENESS       ,
					false , // err correction?
					true  , // inc tree?
					true  , // domergeobsolete
					-1    , // firstHostId
					0     , // start filenum
					-1    , // numFiles
					30    , // timeout
					-1    , // syncpoint
					-1    , // preferlocalreads
					NULL  , // msg5
					NULL  , // msg5b
					false , // isRealMerge?
					true  , // allow pg cache
					false , // focelocalindexdb
					false , // doIndexdbSplit?
					shardNum ))// force paritysplit
			return false;
		// process the msg36 response
		gotTermList ();
	}
	// i guess we didn't block
	return downloadImages();
}

// we got a reply
void gotTermListWrapper ( void *state ) {
	Images *THIS = (Images *)state;
	// process/store the reply
	THIS->gotTermList();
	// try to launch more, returns false if it blocks
	if ( ! THIS->launchRequests() ) return;
	// all done
	THIS->m_callback ( THIS->m_state );
}

void Images::gotTermList ( ) {
	long i = m_i - 1;
	// i guess get errors too
	if ( g_errno ) m_errors[i] = g_errno;
	// set a globalish flag
	if ( ! m_hadError ) m_hadError = g_errno;
	// on error skip this
	if ( g_errno ) return;
	// check docids in termlist
	m_list.resetListPtr();
	// loop over it
	for ( ; ! m_list.isExhausted() ; m_list.skipCurrentRecord() ) {
		// get the first rec
		long long d = m_list.getCurrentDocId();
		// note it
		//log("dup: image is dupped");
		// is it us? if so ignore it
		if ( d == m_docId ) continue;
		// crap, i guess our image url is not unique. mark it off.
		m_errors[i] = EDOCDUP;
		// no need to go further
		break;
	}
}

bool Images::downloadImages () {
	// all done if we got a valid thumbnail
	//if ( m_thumbnailValid ) return true;

	long  srcLen;
	char *src = NULL;
	long node;

	// downloading an image from diffbot json reply?
	if ( m_xd->m_isDiffbotJSONObject ) {
		// i guess this better not block cuz we'll core!
		char **iup = m_xd->getDiffbotPrimaryImageUrl();
		// if no image, nothing to download
		if ( ! *iup ) {
			//log("no diffbot image url for %s",
			//    m_xd->m_firstUrl.m_url);
			return true;
		}
		// force image count to one
		m_numImages = 1;
		// do not error out
		m_errors[0] = 0;
		// set it to the full url
		src = *iup;
		srcLen = gbstrlen(src);
		// need this
		m_imageUrl.set ( src , srcLen );
		// jump into the for loop below
		//if ( m_phase == 0 ) goto insertionPoint;
	}

	// . download each leftover image
	// . stop as soon as we get one with good dimensions
	// . make a thumbnail of that one
	for (  ; m_j < m_numImages ; m_j++ , m_phase = 0 ) {

		// did collection get nuked?
		CollectionRec *cr = g_collectiondb.getRec(m_collnum);
		if ( ! cr ) { g_errno = ENOCOLLREC; return true; }

		// clear error
		g_errno = 0;

		if ( m_phase == 0 ) {
			// advance
			m_phase++;
			// only if not diffbot, we set "src" above for it
			if ( ! m_xd->m_isDiffbotJSONObject ) {
				// get img tag node
				node = m_imageNodes[m_j];
				// get the url of the image
				src = getImageUrl ( m_j , &srcLen );
				// use "pageUrl" as the baseUrl
				m_imageUrl.set ( m_pageUrl , src , srcLen );
			}
			// if we should stop, stop
			if ( m_stopDownloading ) break;
			// skip if bad or not unique
			if ( m_errors[m_j] ) continue;
			// set status msg
			sprintf ( m_statusBuf ,"downloading image %li",m_j);
			// point to it
			if ( m_xd ) m_xd->setStatus ( m_statusBuf );
		}

		// get image ip
		if ( m_phase == 1 ) {
			// advance
			m_phase++;
			// this increments phase if it should
			if ( ! getImageIp() ) return false;
			// error?
			if ( g_errno ) continue;
		}

		// download the actual image
		if ( m_phase == 2 ) {
			// advance
			m_phase++;
			// download image data
			if ( ! downloadImage() ) return false;
			// error downloading?
			if ( g_errno ) continue;
		}

		// get thumbnail using threaded call to netpbm stuff
		if ( m_phase == 3 ) {
			// advance
			m_phase++;
			// call pnmscale etc. to make thumbnail
			if ( ! makeThumb() ) return false;
			// error downloading?
			if ( g_errno ) continue;
		}

		// error making thumb or just not a good thumb size?
		if ( ! m_thumbnailValid ) {
			// free old image we downloaded, if any
			m_msg13.reset();
			// i guess do this too, it was pointing at it in msg13
			m_imgReply = NULL;
			// try the next image candidate
			continue;
		}

		// it's a keeper
		long urlSize = m_imageUrl.getUrlLen() + 1; // include \0
		// . make our ThumbnailArray out of it
		long need = 0;
		// the array itself
		need += sizeof(ThumbnailArray);
		// and each thumbnail it contains
		need += urlSize;
		need += m_thumbnailSize;
		need += sizeof(ThumbnailInfo);
		// reserve it
		m_imageBuf.reserve ( need );
		// point to array
		ThumbnailArray *ta =(ThumbnailArray *)m_imageBuf.getBufStart();
		// set that as much as possible, version...
		ta->m_version = 0;
		// and thumb count
		ta->m_numThumbnails = 1;
		// now store the thumbnail info
		ThumbnailInfo *ti = ta->getThumbnailInfo (0);
		// and set our one thumbnail
		ti->m_origDX = m_dx;
		ti->m_origDY = m_dy;
		ti->m_dx = m_tdx;
		ti->m_dy = m_tdy;
		ti->m_urlSize = urlSize;
		ti->m_dataSize = m_thumbnailSize;
		// now copy the data over sequentially
		char *p = ti->m_buf;
		// the image url
		memcpy(p,m_imageUrl.getUrl(),urlSize);
		p += urlSize;
		// the image thumbnail data
		memcpy(p,m_imgData,m_thumbnailSize);
		p += m_thumbnailSize;
		// update buf length of course
		m_imageBuf.setLength ( p - m_imageBuf.getBufStart() );

		// validate the buffer
		m_imageBufValid = true;

		// save mem. do this after because m_imgData uses m_msg13's
		// reply buf to store the thumbnail for now...
		m_msg13.reset();
		m_imgReply = NULL;

		g_errno = 0;

		return true;
	}

	// don't tell caller EBADIMG it will make him fail to index doc
	g_errno = 0;

	return true;
}

static void gotImgIpWrapper ( void *state , long ip ) {
	Images *THIS = (Images *)state;
	// control loop
	if ( ! THIS->downloadImages() ) return;
	// call callback at this point, we are done with the download loop
	THIS->m_callback ( THIS->m_state );
}

bool Images::getImageIp ( ) {
	if ( ! m_msgc.getIp ( m_imageUrl.getHost   () ,
			      m_imageUrl.getHostLen() ,
			      &m_latestIp     ,
			      this            ,
			      gotImgIpWrapper    ))
		// we blocked
		return false;
	return true;
}

static void downloadImageWrapper ( void *state ) {
	Images *THIS = (Images *)state;
	// control loop
	if ( ! THIS->downloadImages() ) return;
	// all done
	THIS->m_callback ( THIS->m_state );
}

bool Images::downloadImage ( ) {
	// error?
	if ( m_latestIp == 0 || m_latestIp == -1 ) {
		log(LOG_DEBUG,"images: ip of %s is %li (%s)",
		    m_imageUrl.getUrl(),m_latestIp,mstrerror(g_errno));
		// ignore errors
		g_errno = 0;
		return true;
	}
	CollectionRec *cr = g_collectiondb.getRec(m_collnum);
	if ( ! cr ) { g_errno = ENOCOLLREC; return true; }
	// assume success
	m_httpStatus = 200;
	// set the request
	Msg13Request *r = &m_msg13Request;
	r->reset();
	r->m_maxTextDocLen  = 200000;
	r->m_maxOtherDocLen = 500000;
	r->m_urlIp = m_latestIp;
	// no, this slows down image stuff too much for now!! so take out
	// MDW 9/10/14
	// if ( ! strcmp(cr->m_coll,"qatest123")) {
	// 	r->m_useTestCache   = 1;
	// 	//if ( g_conf.m_qaBuildMode ) r->m_addToTestCache = 1;
	// 	r->m_addToTestCache = 1;
	// }
	// url is the most important
	//strcpy(r->m_url,m_imageUrl.getUrl());
	r-> ptr_url = m_imageUrl.getUrl();
	r->size_url = m_imageUrl.getUrlLen()+1; // include \0
	// . try to download it
	// . i guess we are ignoring hammers at this point
	if ( ! m_msg13.getDoc(r,false,this,downloadImageWrapper))
		return false;

	return true;
}

static void makeThumbWrapper ( void *state , ThreadEntry *t ) {
	Images *THIS = (Images *)state;
	// control loop
	if ( ! THIS->downloadImages() ) return;
	// all done
	THIS->m_callback ( THIS->m_state );
}

bool Images::makeThumb ( ) {
	// did it have an error?
	if ( g_errno ) {
		// just give up on all of them if one has an error
		log ( "image: had error downloading image on page %s: %s. "
		      "Not downloading any more.",
		      m_pageUrl->getUrl(),mstrerror(g_errno));
		// stop it
		m_stopDownloading = true;
		return true;
	}
	char *buf;
	long  bufLen, bufMaxLen;
	HttpMime mime;
	m_imgData     = NULL;
	m_imgDataSize = 0;

	log( LOG_DEBUG, "image: gotImage() entered." );
	// . if there was a problem, just ignore, don't let it stop getting
	//   the real page.
	if ( g_errno ) {
		log( "ERROR? g_errno puked: %s", mstrerror(g_errno) );
		//g_errno = 0;
		return true;
	}
	//if ( ! slot ) return true;
	// extract image data from the socket
	buf       = m_msg13.m_replyBuf;
	bufLen    = m_msg13.m_replyBufSize;
	bufMaxLen = m_msg13.m_replyBufAllocSize;
	// no image?
	if ( ! buf || bufLen <= 0 ) {
		g_errno = EBADIMG;
		return true;
	}
	// we are image candidate #i
	//long i = m_j - 1;
	// get img tag node
	// get the url of the image
	long  srcLen;
	char *src = NULL;
	if ( m_xd->m_isDiffbotJSONObject ) {
		src = *m_xd->getDiffbotPrimaryImageUrl();
		srcLen = gbstrlen(src);
	}
	else {
		src = getImageUrl ( m_j , &srcLen );
	}
	// set it to the full url
	Url iu;
	// use "pageUrl" as the baseUrl
	iu.set ( m_pageUrl , src , srcLen );
	// get the mime
	if ( ! mime.set ( buf, bufLen, &iu ) ) {
		log ( "image: MIME.set() failed in gotImage()" );
		// give up on the remaining images then
		m_stopDownloading = true;
		g_errno = EBADIMG;
		return true;
	}
	// set the status so caller can see
	long httpStatus = mime.getHttpStatus();
	// check the status
	if ( httpStatus != 200 ) {
		log( LOG_DEBUG, "image: http status of img download is %li.",
		     m_httpStatus);
		// give up on the remaining images then
		m_stopDownloading = true;
		g_errno = EBADIMG;
		return true;
	}
	// make sure this is an image
	m_imgType = mime.getContentType();
	if ( m_imgType < CT_GIF || m_imgType > CT_TIFF ) {
		log( LOG_DEBUG, "image: gotImage() states that this image is "
		     "not in a format we currently handle." );
		// try the next image if any
		g_errno = EBADIMG;
		return true;
	}
	// get the content
	m_imgData     = buf + mime.getMimeLen();
	m_imgDataSize = bufLen - mime.getMimeLen();
	// Reset socket, so socket doesn't free the data, now we own
	// We must free the buf after thumbnail is inserted in TitleRec
	m_imgReply       = buf;//slot->m_readBuf;
	m_imgReplyLen    = bufLen;//slot->m_readBufSize;
	m_imgReplyMaxLen = bufMaxLen;//slot->m_readBufMaxSize;
	// do not let UdpServer free the reply, we own it now
	//slot->m_readBuf = NULL;

	if ( ! m_imgReply || m_imgReplyLen == 0 ) {
		log( LOG_DEBUG, "image: Returned empty image reply!" );
		g_errno = EBADIMG;
		return true;
	}

	// get next if too small
	if ( m_imgDataSize < 20 ) { g_errno = EBADIMG; return true; }

	long imageType;
	getImageInfo ( m_imgData, m_imgDataSize, &m_dx, &m_dy, &imageType );

	// log the image dimensions
	log( LOG_DEBUG,"image: Image Link: %s", iu.getUrl() );
	log( LOG_DEBUG,"image: Max Buffer Size: %lu bytes.",m_imgReplyMaxLen);
	log( LOG_DEBUG,"image: Image Original Size: %lu bytes.",m_imgReplyLen);
	log( LOG_DEBUG,"image: Image Buffer @ 0x%lx - 0x%lx",(long)m_imgReply,
	     (long)m_imgReply+m_imgReplyMaxLen );
	log( LOG_DEBUG, "image: Size: %lupx x %lupx", m_dx, m_dy );

	// what is this?
	if ( m_dx <= 0 || m_dy <= 0 ) {
		log(LOG_DEBUG, "image: Image has bad dimensions.");
		g_errno = EBADIMG;
		return true;
	}

	// skip if bad dimensions
	if( ((m_dx < 50) || (m_dy < 50)) && ((m_dx > 0) && (m_dy > 0)) ) {
		log(LOG_DEBUG,
		    "image: Image is too small to represent a news article." );
		g_errno = EBADIMG;
		return true;
	}

	// skip if bad aspect ratio. 5x1 or 1x5 is bad i guess
	if ( m_dx > 0 && m_dy > 0 ) {
		float aspect = (float)m_dx / (float)m_dy;
		if ( aspect < .2 || aspect > 5.0 ) {
			log(LOG_DEBUG,
			    "image: Image aspect ratio is worse that 5 to 1");
			g_errno = EBADIMG;
			return true;
		}
	}

	CollectionRec *cr = g_collectiondb.getRec(m_collnum);
	if ( ! cr ) { g_errno = ENOCOLLREC; return true; }

	// save how big of thumbnails we should make. user can change
	// this in the 'spider controls'
	m_xysize = cr->m_thumbnailMaxWidthHeight ;
	// make it 250 pixels if no decent value provided
	if ( m_xysize <= 0 ) m_xysize = 250;
	// and keep it sane
	if ( m_xysize > 2048 ) m_xysize = 2048;

	// update status
	if ( m_xd ) m_xd->setStatus ( "making thumbnail" );
	// log it
	log ( LOG_DEBUG, "image: gotImage() thumbnailing image." );
	// create the thumbnail...
	// reset this... why?
	g_errno = 0;
	// reset this since filterStart_r() will set it on error
	m_errno = 0;
	// callThread returns true on success, in which case we block
	if ( g_threads.call ( FILTER_THREAD        ,
			      MAX_NICENESS         ,
			      this                 ,
			      makeThumbWrapper    ,
			      thumbStartWrapper_r ) ) return false;
	// threads might be off
	logf ( LOG_DEBUG, "image: Calling thumbnail gen without thread.");
	thumbStartWrapper_r ( this , NULL );
	return true;
}

void *thumbStartWrapper_r ( void *state , ThreadEntry *t ) {
	Images *THIS = (Images *)state;
	THIS->thumbStart_r ( true /* am thread?*/ );
	return NULL;
}

void Images::thumbStart_r ( bool amThread ) {

	long long start = gettimeofdayInMilliseconds();

	//static char  scmd[200] = "%stopnm %s | "
	//                         "pnmscale -xysize 100 100 - | "
	//                         "ppmtojpeg - > %s";

	log( LOG_DEBUG, "image: thumbStart_r entered." );

	//DIR  *d;
	//char  cmd[2500];
	//sprintf( cmd, "%strash", g_hostdb.m_dir );

	makeTrashDir();

	// get thread id
	long id = getpidtid();

	// pass the input to the program through this file
	// rather than a pipe, since popen() seems broken.
	// m_dir ends in / so this should work.
	char in[364];
	snprintf ( in , 363,"%strash/in.%li", g_hostdb.m_dir, id );
	unlink ( in );

	log( LOG_DEBUG, "image: thumbStart_r create in file." );

	// collect the output from the filter from this file
	// m_dir ends in / so this should work.
	char out[364];
	snprintf ( out , 363,"%strash/out.%li", g_hostdb.m_dir, id );
        unlink ( out );

	log( LOG_DEBUG, "image: thumbStart_r create out file." );

        // ignore errno from those unlinks
        errno = 0;

        // Open/Create temporary file to store image to
        int   fhndl;
        if( (fhndl = open( in, O_RDWR+O_CREAT, S_IWUSR+S_IRUSR )) < 0 ) {
               log( "image: Could not open file, %s, for writing: %s - %d.",
       		    in, mstrerror( m_errno ), fhndl );
	       m_imgDataSize = 0;
       	       return;
        }

        // Write image data into temporary file
        if( write( fhndl, m_imgData, m_imgDataSize ) < 0 ) {
               log( "image: Could not write to file, %s: %s.",
       		    in, mstrerror( m_errno ) );
       	       close( fhndl );
	       unlink( in );
	       m_imgDataSize = 0;
       	       return;
        }

        // Close temporary image file now that we have finished writing
        if( close( fhndl ) < 0 ) {
               log( "image: Could not close file, %s, for writing: %s.",
       	            in, mstrerror( m_errno ) );
	       unlink( in );
	       m_imgDataSize = 0;
      	       return;
        }
	fhndl = 0;

        // Grab content type from mime
	//long imgType = mime.getContentType();
        char  ext[5];
        switch( m_imgType ) {
               case CT_GIF:
		       strcpy( ext, "gif" );
	               break;
               case CT_JPG:
		       strcpy( ext, "jpeg" );
		       break;
               case CT_PNG:
		       strcpy( ext, "png" );
		       break;
               case CT_TIFF:
		       strcpy( ext, "tiff" );
		       break;
	       case CT_BMP:
		       strcpy( ext, "bmp" );
		       break;
        }

	//long xysize = 250;//100;
	// make thumbnail a little bigger for diffbot for widget
	//if ( m_xd->m_isDiffbotJSONObject ) xysize = 250;

	// i hope 2500 is big enough!
	char  cmd[2501];

	//sprintf( cmd, scmd, ext, in, out);
	char *wdir = g_hostdb.m_dir;
	// can be /dev/stderr or like /var/gigablast/data/log000 etc.
	char *logFile = g_log.getFilename();
	// wdir ends in / so this should work.
	snprintf( cmd, 2500 ,
		 "LD_LIBRARY_PATH=%s %s%stopnm %s 2>> %s | "
		 "LD_LIBRARY_PATH=%s %spnmscale -xysize %li %li - 2>> %s | "
		  // put all its stderr msgs into /dev/null
		  // so "jpegtopnm: WRITING PPM FILE" doesn't clog console
		 "LD_LIBRARY_PATH=%s %sppmtojpeg - > %s 2>> %s"
		  , wdir , wdir , ext , in , logFile
		  , wdir , wdir , m_xysize , m_xysize , logFile
		  , wdir , wdir , out , logFile
		 );

	// if they already have netpbm package installed use that then
	static bool s_checked = false;
	static bool s_hasNetpbm = false;
	if ( ! s_checked ) {
		s_checked = true;
		File f;
		f.set("/usr/bin/pnmscale");
		s_hasNetpbm = f.doesExist() ;
	}
	if ( s_hasNetpbm )
		snprintf( cmd, 2500 ,
			  "%stopnm %s 2>> %s | "
			  "pnmscale -xysize %li %li - 2>> %s | "
			  "ppmtojpeg - > %s 2>> %s"
			  , ext , in , logFile
			  , m_xysize , m_xysize , logFile
			  , out , logFile
			  );

        // Call clone function for the shell to execute command
        // This call WILL BLOCK	. timeout is 30 seconds.
	//int err = my_system_r( cmd, 30 ); // m_thmbconvTimeout );
	int err = system( cmd ); // m_thmbconvTimeout );

	//if( (m_dx != 0) && (m_dy != 0) )
	//	unlink( in );
	unlink ( in );

	if ( err == 127 ) {
		m_errno = EBADENGINEER;
		log("image: /bin/sh does not exist.");
		unlink ( out );
		m_stopDownloading = true;
		return;
	}
	// this will happen if you don't upgrade glibc to 2.2.4-32 or above
	if ( err != 0 ) {
		m_errno = EBADENGINEER;
		log("image: Call to system(\"%s\") had error.",cmd);
		unlink ( out );
		m_stopDownloading = true;
		return;
	}

        // Open new file with thumbnail image
        if( (fhndl = open( out, O_RDONLY )) < 0 ) {
               log( "image: Could not open file, %s, for reading: %s.",
		    out, mstrerror( m_errno ) );
		unlink ( out );
		m_stopDownloading = true;
	       return;
        }

	if( (m_thumbnailSize = lseek( fhndl, 0, SEEK_END )) < 0 ) {
		log( "image: Seek of file, %s, returned invalid size: %ld",
		     out, m_thumbnailSize );
		m_stopDownloading = true;
		close(fhndl);
		unlink ( out );
		return;
	}

	if( m_thumbnailSize > m_imgReplyMaxLen ) {
		log(LOG_DEBUG,"image: Image thumbnail larger than buffer!" );
		log(LOG_DEBUG,"image: File Read Bytes: %ld", m_thumbnailSize);
		log(LOG_DEBUG,"image: Buf Max Bytes  : %ld",m_imgReplyMaxLen );
		log(LOG_DEBUG,"image: -----------------------" );
		log(LOG_DEBUG,"image: Diff           : %ld",
		     m_imgReplyMaxLen-m_thumbnailSize );
		close(fhndl);
		unlink ( out );
		return;

	}

	if( lseek( fhndl, 0, SEEK_SET ) < 0 ) {
		log( "image: Seek couldn't rewind file, %s.", out );
		m_stopDownloading = true;
		close(fhndl);
		unlink ( out );
		return;
	}

        // . Read contents back into image ptr
	// . this is somewhat of a hack since it overwrites the original img
        if( (m_thumbnailSize = read( fhndl, m_imgData, m_imgDataSize )) < 0 ) {
                log( "image: Could not read from file, %s: %s.",
 		     out, mstrerror( m_errno ) );
	        close( fhndl );
		m_stopDownloading = true;
		unlink( out );
	        return;
        }

        if( close( fhndl ) < 0 ) {
                log( "image: Could not close file, %s, for reading: %s.",
 		     out, mstrerror( m_errno ) );
		unlink( out );
		m_stopDownloading = true;
		unlink ( out );
 	        return;
        }
	fhndl = 0;
       	unlink( out );
	long long stop = gettimeofdayInMilliseconds();
	// tell the loop above not to download anymore, we got one
	m_thumbnailValid = true;

	// MDW: this was m_imgReply
	getImageInfo ( m_imgData , m_thumbnailSize , &m_tdx , &m_tdy , NULL );

	// now make the meta data struct
	// <imageUrl>\0<width><height><thumbnailData>

	log( LOG_DEBUG, "image: Thumbnail size: %li bytes.", m_imgDataSize );
	log( LOG_DEBUG, "image: Thumbnail dx=%li dy=%li.", m_tdx,m_tdy );
	log( LOG_DEBUG, "image: Thumbnail generated in %lldms.", stop-start );
}

// . *it is the image type
void getImageInfo ( char *buf , long bufSize ,
		    long *dx , long *dy , long *it ) {

	// default to zeroes
	*dx = 0;
	*dy = 0;

	char *strPtr;
	// get the dimensions of the image
	if( (strPtr = strncasestr( buf, 20, "Exif"  )) ) {
		log(LOG_DEBUG, "image: Image Link: ");
		log(LOG_DEBUG, "image: We currently do not handle EXIF image "
		     "types." );
		// try the nextone
		return;
	}
	else if( (strPtr = strncasestr( buf, 20, "GIF"  )) ) {
		if ( it ) *it = CT_GIF;
		log( LOG_DEBUG, "image: GIF INFORMATION:" );
		if( bufSize > 9 ) {
			*dx = ((unsigned long)buf[7]) << 8;
			*dx += (unsigned char)buf[6];
			*dy = ((unsigned long)buf[9]) << 8;
			*dy += (unsigned char)buf[8];
		}
	}
	else if( (strPtr = strncasestr( buf, 20, "JFIF" )) ) {
		if ( it ) *it = CT_JPG;
		log( LOG_DEBUG, "image: JPEG INFORMATION:" );
		long i;
		for( i = 0; i < bufSize; i++ ) {
			if( bufSize < i+8 )
				break;
			if( (unsigned char)buf[i] != 0xFF ) continue;
			if( (unsigned char)buf[i+1] == 0xC0 ){
				*dy = ((unsigned long)buf[i+5]) << 8;
				*dy += (unsigned char)buf[i+6];
				*dx = ((unsigned long)buf[i+7]) << 8;
				*dx += (unsigned char)buf[i+8];
				break;
			}
			else if( (unsigned char) buf[i+1] == 0xC2 ) {
				*dy = ((unsigned long)buf[i+5]) << 8;
				*dy += (unsigned char)buf[i+6];
				*dx = ((unsigned long)buf[i+7]) << 8;
				*dx += (unsigned char)buf[i+8];
				break;
			}
		}
	}
	else if( (strPtr = strncasestr( buf, 20, "PNG" )) ) {
		if ( it ) *it = CT_PNG;
		log( LOG_DEBUG, "image: PNG INFORMATION:" );
		if( bufSize > 25 ) {
			*dx=(unsigned long)(*(unsigned long *)&buf[16]);
			*dy=(unsigned long)(*(unsigned long *)&buf[20]);
			// these are in network order
			*dx = ntohl(*dx);
			*dy = ntohl(*dy);
		}
	}
	else if( (strPtr = strncasestr( buf, 20, "MM" )) ) {
		if ( it ) *it = CT_TIFF;
		log( LOG_DEBUG, "image: TIFF INFORMATION:" );
		long startCnt = (unsigned long)buf[7]+4;
		for( long i = startCnt; i < bufSize; i += 12 ) {
			if( bufSize < i+10 )
				break;
			if( buf[i] != 0x01 ) continue;
			if( buf[i+1] == 0x01 )
				*dy = (unsigned long)
					(*(unsigned short *)&buf[i+8]);
			else if( buf[i+1] == 0x00 )
				*dx = (unsigned long)
					(*(unsigned short *)&buf[i+8]);
		}
	}
	else if( (strPtr = strncasestr( buf, 20, "II" )) ) {
		if ( it ) *it = CT_TIFF;
		log( LOG_DEBUG, "image: TIFF INFORMATION:" );
		long startCnt = (unsigned long)buf[7]+4;
		for( long i = startCnt; i < bufSize; i += 12 ) {
			if( bufSize < i+10 )
				break;
			if( buf[i] == 0x01 && buf[i+1] == 0x01 )
				*dy = (unsigned long)
					(*(unsigned short *)&buf[i+8]);
			if( buf[i] == 0x00 && buf[i+1] == 0x01 )
				*dx = (unsigned long)
					(*(unsigned short *)&buf[i+8]);
		}
	}
	else if( (strPtr = strncasestr( buf, 20, "BM" )) ) {
		if ( it ) *it = CT_BMP;
		log( LOG_DEBUG, "image: BMP INFORMATION:" );
		if( bufSize > 27 ) {
			*dx=(unsigned long)(*(unsigned long *)&buf[18]);
			*dy=(unsigned long)(*(unsigned long *)&buf[22]);
		}
	}
	else
		log( LOG_DEBUG, "image: Image Corrupted? No type found in "
		     "data." );
}

// container is maxWidth X maxHeight, so try to fix widget in there
bool ThumbnailInfo::printThumbnailInHtml ( SafeBuf *sb ,
					   long maxWidth ,
					   long maxHeight,
					   bool printLink ,
					   long *retNewdx ,
					   char *style ,
					   char format )  {
	if ( ! style ) style = "";
	// account for scrollbar on the right
	//maxSide -= (long)SCROLLBAR_WIDTH;
	// avoid distortion.
	// if image is wide, use that to scale
	if ( m_dx <= 0 ) return true;
	if ( m_dy <= 0 ) return true;
	float xscale =
		(float)maxWidth/
		(float)m_dx;
	float yscale =
		(float)maxHeight/
		(float)m_dy;
	float min = xscale;
	if ( yscale < min ) min = yscale;
	long newdx = (long)((float)m_dx * min);
	long newdy = (long)((float)m_dy * min);

	// might be FORMAT_AJAX!
	if ( printLink && format !=FORMAT_XML && format != FORMAT_JSON )
		sb->safePrintf("<a href=%s>", getUrl() );

	if ( format !=FORMAT_XML && format != FORMAT_JSON )
		sb->safePrintf("<img width=%li height=%li align=left "
			       "%s"
			       "src=\"data:image/"
			       "jpg;base64,"
			       , newdx
			       , newdy
			       , style
			       );

	if ( format == FORMAT_XML )
		sb->safePrintf("\t<imageBase64>");

	if ( format == FORMAT_JSON )
		sb->safePrintf("\t\"imageBase64\":\"");

	// encode image in base 64
	sb->base64Encode ( getData(), m_dataSize , 0 ); // 0 niceness
	if ( format !=FORMAT_XML && format != FORMAT_JSON ) {
		sb->safePrintf("\">");
		if ( printLink ) sb->safePrintf ("</a>");
	}

	if ( format == FORMAT_XML )
		sb->safePrintf("</imageBase64>\n");

	if ( format == FORMAT_JSON )
		sb->safePrintf("\",\n");

	// widget needs to know the width of the thumb for formatting
	// the text either on top of the thumb or to the right of it
	if ( retNewdx ) *retNewdx = newdx;
	return true;
}

char *Images::getImageUrl ( long j , long *urlLen ) {

	long node = m_imageNodes[j];
	long srcLen = 0;
	char *src = m_xml->getString(node,"src",&srcLen);
	// maybe it was an og:image meta tag
	if ( ! src )
		src = m_xml->getString(node,"content",&srcLen);

	// wtf?
	if ( ! src )
		log("image: image bad/null src");

	*urlLen = srcLen;
	return src;
}


text:
package com.swfarm.biz.warehouse.web;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.swfarm.biz.chain.bo.ShippingForwarderCompany;
import com.swfarm.biz.chain.srv.ChainService;
import com.swfarm.biz.warehouse.bo.Warehouse;
import com.swfarm.biz.warehouse.srv.WarehouseService;
import com.swfarm.pub.utils.DateUtils;

public class ShowWarehouseController extends AbstractController {

	private WarehouseService warehouseService;

	private ChainService chainService;

	public void setWarehouseService(WarehouseService warehouseService) {
		this.warehouseService = warehouseService;
	}

	public void setChainService(ChainService chainService) {
		this.chainService = chainService;
	}

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		Map dataMap = new HashMap();
		String idStr = req.getParameter("warehouse");
		Long warehouseId = new Long(idStr);
		Warehouse warehouse = this.warehouseService.findWarehouse(warehouseId);
		Date startDate = DateUtils.getToday();
		Date endDate = null;
		Object[] wcivResults = this.warehouseService
				.findWarehouseCheckInVouchersByWarehouseAndStartDateAndEndDate(
						warehouseId, startDate, endDate);
		List warehouseCheckInVouchers = (List) wcivResults[0];
		Double totalCheckInQuantity = (Double) wcivResults[1];
		dataMap.put("warehouseCheckInVouchers", warehouseCheckInVouchers);
		dataMap.put("totalCheckInQuantity", totalCheckInQuantity);
		Object[] wcovResults = this.warehouseService
				.findWarehouseCheckOutVouchersByWarehouseAndStartDateAndEndDate(
						warehouseId, startDate, endDate);
		List warehouseCheckOutVouchers = (List) wcovResults[0];
		Double totalCheckOutQuantity = (Double) wcovResults[1];
		dataMap.put("warehouseCheckOutVouchers", warehouseCheckOutVouchers);
		dataMap.put("totalCheckOutQuantity", totalCheckOutQuantity);
		Object[] wtvResults = this.warehouseService
				.findWarehouseTransferVouchersByWarehouseAndStartDateAndEndDate(
						warehouseId, startDate, endDate);
		List warehouseTransferVouchers = (List) wtvResults[0];
		Double totalTransferQuantity = (Double) wtvResults[1];
		dataMap.put("warehouseTransferVouchers", warehouseTransferVouchers);
		dataMap.put("totalTransferQuantity", totalTransferQuantity);
		List shippingForwarderCompanies = this.chainService
				.findShippingForwarderCompaniesByWarehouse(warehouseId);
		Map<ShippingForwarderCompany, List> sfcmMap = new HashMap<ShippingForwarderCompany, List>();
		for (Iterator iter = shippingForwarderCompanies.iterator(); iter
				.hasNext();) {
			ShippingForwarderCompany shippingForwarderCompany = (ShippingForwarderCompany) iter
					.next();
			List shippingForwarderMethods = this.chainService
					.findShippingForwarderMethodsBySfcAndWarehouse(
							shippingForwarderCompany.getId(), warehouseId);
			sfcmMap.put(shippingForwarderCompany, shippingForwarderMethods);
		}
		List sfcmList = new ArrayList();
		sfcmList.addAll(sfcmMap.entrySet());
		Collections.sort(sfcmList, new Comparator() {

			public int compare(Object o1, Object o2) {
				Map.Entry<ShippingForwarderCompany, List> entry1 = (Map.Entry<ShippingForwarderCompany, List>) o1;
				Map.Entry<ShippingForwarderCompany, List> entry2 = (Map.Entry<ShippingForwarderCompany, List>) o2;
				return entry1.getKey().getId().compareTo(
						entry2.getKey().getId());
			}

		});
		dataMap.put("warehouse", warehouse);
		dataMap.put("shippingForwarderCompanies", shippingForwarderCompanies);
		dataMap.put("sfcmList", sfcmList);
		return new ModelAndView("warehouse/warehouse", dataMap);
	}
}


text:
package com.action.gaobingfachenxusheji.chapter04;

import java.util.Random;
import java.util.concurrent.*;

public class RndMultiThread {

    public static final int GEN_COUNT = 10000000;
    public static final int THREAD_COUNT = 4;
    static ExecutorService exe = Executors.newFixedThreadPool(THREAD_COUNT);
    public static Random rnd = new Random(123);

    public static ThreadLocal<Random> tRnd = new ThreadLocal<Random>() {
        @Override
        protected Random initialValue() {
            return new Random(123);
        }
    };

    public static class RndTask implements Callable<Long> {

        private int mode = 0;

        public RndTask(int mode) {
            this.mode = mode;
        }

        public Random getRandom() {
            if (mode == 0) {
                return rnd;
            } else if (mode == 1) {
                return tRnd.get();
            } else {
                return null;
            }
        }

        @Override
        public Long call() throws Exception {
            long b = System.currentTimeMillis();
            for (long i = 0; i < GEN_COUNT; i++) {
                getRandom().nextInt();
            }
            long e = System.currentTimeMillis();
            System.out.println(Thread.currentThread().getName() + " spend" + (e - b) + "ms");
            return e - b;
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Future<Long>[] futs = new Future[THREAD_COUNT];
        for (int i = 0; i < THREAD_COUNT; i++) {
            futs[i] = exe.submit(new RndTask(0));
        }

        long totalTime = 0;
        for (int i = 0; i < THREAD_COUNT; i++) {
            totalTime += futs[i].get();
        }

        System.out.println("多线程访问同一个Random实例:" + totalTime + "ms");

        for (int i = 0; i < THREAD_COUNT; i++) {
            futs[i] = exe.submit(new RndTask(1));
        }
        totalTime = 0;
        for (int i = 0; i < THREAD_COUNT; i++) {
            totalTime += futs[i].get();
        }

        System.out.println("使用ThreadLocal包装Random实例:" + totalTime + "ms");
        exe.shutdown();

    }

}


text:
module Drupal
  module CCK
    module NodeMethods
      def cck_class
        @cck_class ||= eval("Drupal::#{type.camelcase}")
      end

      def cck
        @cck ||= cck_class.first(:nid => nid)
      end

      def find_or_create_cck
        return cck if cck
        @cck = cck_class.create! :vid => vid, :nid => nid
      end
    end

    class ContentType
      eval Drupal.common
      storage_names[:drupal] = 'node_type'

      property :content_type, String,
        :key => true, :field => 'type'
    end

    class ContentNodeFieldInstance
      eval Drupal.common
      storage_names[:drupal] = 'content_node_field_instance'

      property :field_name, String,
        :length => 32, :key => true
      property :content_type, String,
        :length => 32, :key => true,
        :field => 'type_name'

      def field
        @field ||= ContentNodeField.first :field_name => field_name
      end

      def field_type
        @field_type ||= field.type
      end

      def to_s
        f = field_name.match(/^field_(.*)/)[1]
        case field_type
        when 'userreference'
          if through?
            r = "has 1, :#{f},
                   :class_name => Drupal::#{f.camelcase},
                   :child_key => [:nid]

                 has 1, :#{f}_user,
                   :remote_name => :user,
                   :class_name => Drupal::User,
                   :child_key => [:nid],
                   :through => :#{f}"
          else
            r = "belongs_to :#{field_name},
              :class_name => 'Drupal::User'"
          end
        when 'number_integer'
          r  = "property :#{f}, Integer,
                  :field => 'field_#{f}_value'"
        when 'text'
          r  = "property :#{f}, Text,
                  :field => 'field_#{f}_value'"
        end
        r
      end

      def through?
        Drupal::CCK::Builder.fields.include? "content_#{field_name}"
      end
    end

    class ContentNodeField
      eval Drupal.common
      storage_names[:drupal] = 'content_node_field'

      property :type, String,
        :length => 127
      property :field_name, String,
        :length => 32
    end
  end

  Node.send :include, CCK::NodeMethods
end

require 'drupal/cck/fields.rb'
require 'drupal/cck/builder.rb'


text:
import {
  EXPECTED_COLOR,
  INVERTED_COLOR,
  RECEIVED_COLOR,
  printReceived,
  stringify,
} from 'jest-matcher-utils';

// Format substring but do not enclose in double quote marks.
// The replacement is compatible with pretty-format package.
const printSubstring = (val: string): string => val.replace(/"|\\/g, '\\$&');

export const printReceivedStringContainExpectedSubstring = (
  received: string,
  start: number,
  length: number, // not end
): string =>
  RECEIVED_COLOR(
    '"' +
      printSubstring(received.slice(0, start)) +
      INVERTED_COLOR(printSubstring(received.slice(start, start + length))) +
      printSubstring(received.slice(start + length)) +
      '"',
  );

export const printReceivedStringContainExpectedResult = (
  received: string,
  result: RegExpExecArray | null,
): string =>
  result === null
    ? printReceived(received)
    : printReceivedStringContainExpectedSubstring(
        received,
        result.index,
        result[0].length,
      );

// The serialized array is compatible with pretty-format package min option.
// However, items have default stringify depth (instead of depth - 1)
// so expected item looks consistent by itself and enclosed in the array.
export const printReceivedArrayContainExpectedItem = (
  received: Array<unknown>,
  index: number,
): string =>
  RECEIVED_COLOR(
    '[' +
      received
        .map((item, i) => {
          const stringified = stringify(item);
          return i === index ? INVERTED_COLOR(stringified) : stringified;
        })
        .join(', ') +
      ']',
  );

export const printExpectedConstructorName = (
  label: string,
  expected: Function,
) => printConstructorName(label, expected, false, true) + '\n';

export const printExpectedConstructorNameNot = (
  label: string,
  expected: Function,
) => printConstructorName(label, expected, true, true) + '\n';

export const printReceivedConstructorName = (
  label: string,
  received: Function,
) => printConstructorName(label, received, false, false) + '\n';

// Do not call function if received is equal to expected.
export const printReceivedConstructorNameNot = (
  label: string,
  received: Function,
  expected: Function,
) =>
  typeof expected.name === 'string' &&
  expected.name.length !== 0 &&
  typeof received.name === 'string' &&
  received.name.length !== 0
    ? printConstructorName(label, received, true, false) +
      ` ${
        Object.getPrototypeOf(received) === expected
          ? 'extends'
          : 'extends … extends'
      } ${EXPECTED_COLOR(expected.name)}` +
      '\n'
    : printConstructorName(label, received, false, false) + '\n';

const printConstructorName = (
  label: string,
  constructor: Function,
  isNot: boolean,
  isExpected: boolean,
): string =>
  typeof constructor.name !== 'string'
    ? `${label} name is not a string`
    : constructor.name.length === 0
    ? `${label} name is an empty string`
    : `${label}: ${!isNot ? '' : isExpected ? 'not ' : '    '}${
        isExpected
          ? EXPECTED_COLOR(constructor.name)
          : RECEIVED_COLOR(constructor.name)
      }`;


text:
        <button type="button" class="close" ng-click="dismiss()">x</button>

Have an Account?

            <form name="loginForm">

                    Email
                    <input type="email" name="email" class="form-control"
                        ng-model="user.email" required="required"  ng-blur="emailError = !!loginForm.email.$error.email"
                        ng-focus="emailError = false" />

                    Password
                    <input type="password" name="password" class="form-control" ng-model="user.password" required="required" />

                <button class="btn btn-primary" ng-click="login()">Login</button>
            </form>


text:
#ifndef _SDS_PORTINFO_H
#define _SDS_PORTINFO_H
/* File: /proj/xsjhdstaff4/xd-relman/work/Rodin/REL/2015.4_sdsoc/regression/products/sdsoc/platforms/prebuilt/generate/zc702/TEST_WORK_lnx64/add_gen_prebuilt/apf/_sds/p0/.cf_work/portinfo.h */
#ifdef __cplusplus
extern "C" {
#endif

void _p0_cf_framework_open(int);
void _p0_cf_framework_close(int);

#ifdef __cplusplus
};
#endif
#ifdef __cplusplus
extern "C" {
#endif
void switch_to_next_partition(int);
void init_first_partition();
void close_last_partition();
#ifdef __cplusplus
};
#endif /* extern "C" */
#endif /* _SDS_PORTINFO_H_ */