text:
"""
Classes for dealing with fields.
"""

from marklogic.utilities.validators import assert_list_of_type, assert_boolean
from marklogic.utilities import PropertyLists

class _IncludedExcludedElement:
    """
    An included or excluded element. This class is abstract.
    """
    def __init__(self):
        raise ValueError("Do not instantiate _IncludedExcludedElement directly")

    def namespace_uri(self):
        """
        The namespace URI"
        """
        return self._config['namespace-uri']

    def set_namespace_uri(self, namespace_uri):
        """
        Set the namespace URI.
        """
        self._config['namespace-uri'] = namespace_uri
        return self

    def localname(self):
        """
        The localname.
        """
        return self._config['localname']

    def set_localname(self, localname):
        """
        Set the localname.
        """
        self._config['localname'] = localname
        return self

    def weight(self):
        """
        The weight.
        """
        return self._config['weight']

    def set_weight(self, weight):
        """
        Set the weight.
        """
        self._config['weight'] = weight
        return self

    def attribute_namespace_uri(self):
        """
        The attribute namespace URI.
        """
        return self._config['attribute-namespace-uri']

    def set_attribute_namespace_uri(self, attribute_namespace_uri):
        """
        Set the attribute namespace URI.
        """
        self._config['attribute-namespace-uri'] = attribute_namespace_uri
        return self

    def attribute_localname(self):
        """
        The attribute localname.
        """
        return self._config['attribute-localname']

    def set_attribute_localname(self, attribute_localname):
        """
        Set the attribute localname.
        """
        self._config['attribute-localname'] = attribute_localname
        return self

    def attribute_value(self):
        """
        The attribute value.
        """
        return self._config['attribute-value']

    def set_attribute_value(self, attribute_value):
        """
        Set the attribute value.
        """
        self._config['attribute-value'] = attribute_value
        return self

class IncludedElement(_IncludedExcludedElement):
    """
    An included element.
    """
    def __init__(self, namespace_uri, localname, weight=1.0,
                 attribute_namespace_uri=None,
                 attribute_localname=None,
                 attribute_value=None):
        """
        Create an included element.
        """
        # FIXME: check for attribute ns/local/value errors
        self._config = {
            "namespace-uri": namespace_uri,
            "localname": localname,
            "weight": weight,
            "attribute-namespace-uri": \
              "" if attribute_namespace_uri is None else attribute_namespace_uri,
            "attribute-localname": \
              "" if attribute_localname is None else attribute_localname,
            "attribute-value": "" if attribute_value is None else attribute_value
            }

class ExcludedElement(_IncludedExcludedElement):
    """
    An excluded element.
    """
    def __init__(self, namespace_uri, localname,
                 attribute_namespace_uri=None,
                 attribute_localname=None,
                 attribute_value=None):
        """
        Create an excluded element.
        """
        # FIXME: check for attribute ns/local/value errors
        self._config = {
            "namespace-uri": namespace_uri,
            "localname": localname,
            "attribute-namespace-uri": \
              "" if attribute_namespace_uri is None else attribute_namespace_uri,
            "attribute-localname": \
              "" if attribute_localname is None else attribute_localname,
            "attribute-value": "" if attribute_value is None else attribute_value
            }

class TokenizerOverride:
    """
    A tokenizer override.
    """
    def __init__(self, character, tokenizer_class):
        """
        Instantiate a tokenizer override.
        """
        # FIXME: check classes
        self._config = {
            "character": character,
            "tokenizer-class": tokenizer_class
            }

    def character(self):
        """
        The character.
        """
        return self._config['character']

    def set_character(self, character):
        """
        Set the character.
        """
        self._config['character'] = character
        return self

    def tokenizer_override(self):
        """
        The override class.
        """
        return self._config['tokenizer-override']

    def set_tokenizer_override(self, override):
        """
        Set the overide class.
        """
        self._config['tokenizer-override'] = override
        return self

class FieldPath:
    """
    A field path.
    """
    def __init__(self, path, weight):
        """
        Initialize a field path.
        """
        self._config = {
            "path": path,
            "weight": weight
            }

    def path(self):
        """
        The path.
        """
        return self._config['path']

    def set_path(self, path):
        """
        Set the path.
        """
        self._config['path'] = path
        return self

    def weight(self):
        """
        The weight.
        """
        return self._config['weight']

    def set_weight(self, weight):
        """
        Set the weight.
        """
        self._config['weight'] = weight
        return self

class Field(PropertyLists):
    """
    A field. This class is abstract.
    """
    def __init__(self):
        raise ValueError("Do not instantiate Field directly")

    def field_name(self):
        """
        The field name.
        """
        return self._config['field-name']

    def set_field_name(self, name):
        """
        Set the field name.
        """
        if name is None or not name:
            raise ValidationError('Fields must have a non-empty name', name)
        self._config['field-name'] = name
        return self

    def word_lexicons(self):
        """
        Word lexicons.
        """
        if 'word-lexicon' in self._config:
            return self._config['word-lexicon']
        return None

    def add_word_lexicons(self, collation):
        """
        Add a word lexicon.
        """
        return self.add_to_property_list('word-lexicon', collation)

    def set_word_lexicons(self, collations):
        """
        Set the list of word lexicons
        """
        return self.set_property_list('word-lexicon', collations)

    def remove_word_lexicons(self, collation):
        """
        Remove a word lexicon.
        """
        return self.remove_from_property_list('word-lexicon', collation)

    def included_elements(self):
        """
        The included elements.
        """
        if 'included-element' in self._config:
            return self._config['included-element']
        return None

    def add_included_element(self, element):
        """
        Add an included element.
        """
        return self.add_to_property_list('included-element',
                                         element, IncludedElement)

    def remove_included_element(self, element):
        """
        Remove an included element.
        """
        return self.remove_from_property_list('included-element',
                                              element, IncludedElement)

    def set_included_elements(self, elements):
        """
        Set the included elements.
        """
        return self.set_property_list('included-element', elements,
                                      IncludedElement)

    def excluded_elements(self):
        """
        The excluded elements.
        """
        if 'excluded-element' in self._config:
            return self._config['excluded-element']
        return None

    def add_excluded_element(self, element):
        """
        Add an excluded element.
        """
        return self.add_to_property_list('excluded-element',
                                         element, ExcludedElement)

    def remove_excluded_element(self, element):
        """
        Remove an excluded element.
        """
        return self.remove_from_property_list('excluded-element',
                                              element, ExcludedElement)

    def set_excluded_elements(self, elements):
        """
        Set the excluded elements.
        """
        return self.set_property_list('excluded-element', elements,
                                      ExcludedElement)

    def tokenizer_overrides(self):
        """
        The tokenizer overrides.
        """
        if 'tokenizer-override' in self._config:
            return self._config['tokenizer-override']
        return None

    def add_tokenizer_overrides(self, override):
        """
        Add a tokenizer override.
        """
        return self.add_to_property_list('tokenizer-override', overide,
                                         TokenizerOverride)

    def remove_tokenizer_overrides(self, override):
        """
        Remove a tokenizer override.
        """
        return self.remove_from_property_list('tokenizer-override', overide,
                                              TokenizerOverride)

    def set_tokenizer_overrides(self, overrides):
        """
        Set the list of tokenizer overrides.
        """
        return self.set_property_list('tokenizer-override', overides,
                                      TokenizerOverride)

    def stemmed_searches(self):
        """
        Stemmed searches.
        """
        if 'stemmed-searches' in self._config:
            return self._config['stemmed-searches']
        return None

    def set_stemmed_searches(self, stemmed_searches):
        """
        Set stemmed searches.
        """
        self._config['stemmed-searches'] = stemmed_searches
        return self

    def word_searches(self):
        """
        Word searches.
        """
        if 'word-searches' in self._config:
            return self._config['word-searches']
        return None

    def set_word_searches(self, word_searches):
        """
        Set word searches.
        """
        self._config['word-searches'] = assert_boolean(word_searches)
        return self

    def field_value_searches(self):
        """
        Field value searches.
        """
        if 'field-value-searches' in self._config:
            return self._config['field-value-searches']
        return None

    def set_field_value_searches(self, field_value_searches):
        """
        Set field value searches.
        """
        self._config['field-value-searches'] = assert_boolean(field_value_searches)
        return self

    def field_value_positions(self):
        """
        Field value positions.
        """
        if 'field-value-positions' in self._config:
            return self._config['field-value-positions']
        return None

    def set_field_value_positions(self, field_value_positions):
        """
        Set field value positions.
        """
        self._config['field-value-positions'] = assert_boolean(field_value_positions)
        return self

    def fast_phrase_searches(self):
        """
        Fast phrase searches.
        """
        if 'fast-phrase-searches' in self._config:
            return self._config['fast-phrase-searches']
        return None

    def set_fast_phrase_searches(self, fast_phrase_searches):
        """
        Set fast phrase searches.
        """
        self._config['fast-phrase-searches'] = assert_boolean(fast_phrase_searches)
        return self

    def fast_case_sensitive_searches(self):
        """
        Fast case-sensitive searches.
        """
        if 'fast-case-sensitive-searches' in self._config:
            return self._config['fast-case-sensitive-searches']
        return None

    def set_fast_case_sensitive_searches(self, fast_case_sensitive_searches):
        """
        Set fast case-sensitive searches.
        """
        self._config['fast-case-sensitive-searches'] = assert_boolean(fast_case_sensitive_searches)
        return self

    def fast_diacritic_sensitive_searches(self):
        """
        Fast diacritic-sensitive searches.
        """
        if 'fast-diacritic-sensitive-searches' in self._config:
            return self._config['fast-diacritic-sensitive-searches']
        return None

    def set_fast_diacritic_sensitive_searches(self, fdss):
        """
        Set fast diacritic-sensitive searches
        """
        self._config['fast-diacritic-sensitive-searches'] = assert_boolean(fdss)
        return self

    def trailing_wildcard_searches(self):
        """
        Trailing wildcard searches.
        """
        if 'trailing_wildcard_searches' in self._config:
            return self._config['trailing-wildcard-searches']
        return None

    def set_trailing_wildcard_searches(self, trailing_wildcard_searches):
        """
        Set trailing wildcard searches.
        """
        self._config['trailing-wildcard-searches'] = assert_boolean(trailing_wildcard_searches)
        return self

    def trailing_wildcard_word_positions(self):
        """
        Trailing wildcard word positions.
        """
        if 'trailing_wildcard_word_positions' in self._config:
            return self._config['trailing-wildcard-word-positions']
        return None

    def set_trailing_wildcard_word_positions(self, trailing_wildcard_word_positions):
        """
        Set trailing wildcard word positions.
        """
        self._config['trailing-wildcard-word-positions'] = assert_boolean(trailing_wildcard_word_positions)
        return self

    def three_character_searches(self):
        """
        Three character searches.
        """
        if 'three_character_searches' in self._config:
            return self._config['three-character-searches']
        return None

    def set_three_character_searches(self, three_character_searches):
        """
        Set three character searches.
        """
        self._config['three-character-searches'] = assert_boolean(three_character_searches)
        return self

    def three_character_word_positions(self):
        """
        Three character word positions.
        """
        if 'three_character_word_positions' in self._config:
            return self._config['three-character-word-positions']
        return None

    def set_three_character_word_positions(self, three_character_word_positions):
        """
        Set three character word positions.
        """
        self._config['three-character-word-positions'] = assert_boolean(three_character_word_positions)
        return self

    def two_character_searches(self):
        """
        Two character searches.
        """
        if 'two_character_searches' in self._config:
            return self._config['two-character-searches']
        return None

    def set_two_character_searches(self, two_character_searches):
        """
        Set two character searches.
        """
        self._config['two-character-searches'] = assert_boolean(two_character_searches)
        return self

    def one_character_searches(self):
        """
        One character searches.
        """
        if 'one_character_searches' in self._config:
            return self._config['one-character-searches']
        return None

    def set_one_character_searches(self, one_character_searches):
        """
        Set one character searches.
        """
        self._config['one-character-searches'] = assert_boolean(one_character_searches)
        return self

    def unmarshal(self, field):
        """
        Construct a new field from a flat structure. This method is
        principally used to construct an object from a Management API
        payload. The configuration passed in is largely assumed to be
        valid.

        :param: config: A hash of properties
        :return: A newly constructed field object with the specified properties.
        """
        for key in field:
            if key == 'stemmed-searches':
                self._config[key] = field[key]
            elif key == 'word-searches':
                self._config[key] = (field[key] == 'true')
            elif key == 'word-searches':
                self._config[key] = (field[key] == 'true')
            elif key == 'field-value-searches':
                self._config[key] = (field[key] == 'true')
            elif key == 'field-value-positions':
                self._config[key] = (field[key] == 'true')
            elif key == 'fast-phrase-searches':
                self._config[key] = (field[key] == 'true')
            elif key == 'fast-case-sensitive-searches':
                self._config[key] = (field[key] == 'true')
            elif key == 'fast-diacritic-sensitive-searches':
                self._config[key] = (field[key] == 'true')
            elif key == 'trailing-wildcard-searches':
                self._config[key] = (field[key] == 'true')
            elif key == 'trailing-wildcard-word-positions':
                self._config[key] = (field[key] == 'true')
            elif key == 'three-character-searches':
                self._config[key] = (field[key] == 'true')
            elif key == 'three-character-word-positions':
                self._config[key] = (field[key] == 'true')
            elif key == 'two-character-searches':
                self._config[key] = (field[key] == 'true')
            elif key == 'one-character-searches':
                self._config[key] = (field[key] == 'true')
            elif key == 'word-lexicon':
                self._config[key] = field[key]
            elif key == 'included-element':
                elems = []
                for item in field[key]:
                    elem = IncludedElement(
                        item['namespace-uri'],
                        item['localname'],
                        item['weight'],
                        item['attribute-namespace-uri'],
                        item['attribute-localname'],
                        item['attribute-value'])
                    elems.append(elem)
                self._config[key] = elems
            elif key == 'excluded-element':
                elems = []
                for item in field[key]:
                    elem = ExcludedElement(
                        item['namespace-uri'],
                        item['localname'],
                        item['attribute-namespace-uri'],
                        item['attribute-localname'],
                        item['attribute-value'])
                    elems.append(elem)
                self._config[key] = elems
            elif key == 'tokenizer-override':
                elems = []
                for item in field[key]:
                    over = TokenizerOverride(
                        item['character'],
                        item['tokenizer-class'])
                    elems.append(over)
                self._config[key] = elems
            elif (key == 'field-name'
                  or key == 'include-root'
                  or key == 'field-path'):
                pass
            else:
                raise ValueError("Unexpected key in field: {0}".format(key))

    def marshal(self):
        """
        Return a flat structure suitable for conversion to JSON or XML.

        :return: A hash of the keys in this object and their values, recursively.
        """
        struct = { }
        for key in self._config:
            if (key == 'included-element'
                or key == 'excluded-element'
                or key == 'tokenizer-override'
                or key == 'field-path'):
                jlist = []
                for index in self._config[key]:
                    jlist.append(index._config)
                struct[key] = jlist
            else:
                struct[key] = self._config[key];
        return struct

class RootField(Field):
    """
    A root field.
    """
    def __init__(self, field_name, include_root=False, includes=None,
                 excludes=None, tokenizer_overrides=None):
        """
        Create a root field.
        """
        self._config = {
            'field-name': field_name,
            'include-root': include_root
            }

        if includes is not None:
            self.set_included_elements(includes)

        if excludes is not None:
            self.set_excluded_elements(excludes)

        if tokenizer_overrides is not None:
            self.set_tokenizer_overrides(tokenizer_overrides)

    def include_root(self):
        """
        Include the root?
        """
        return self._config['include-root']

    def set_include_root(self, name):
        """
        Set the included root.
        """
        self._config['include-root'] = name
        return self

class WordQuery(RootField):
    """
    Word query settings. In the database configuration, word query settings
    are stored as a field with an empty name. They're represented separately
    in the Python API.
    """
    def __init__(self, include_root):
        """
        Create word query settings.
        """
        self._config = {
            'field-name': "",
            'include-root': include_root
            }

    def field_name(self):
        """
        Always returns None.
        """
        return None

    def set_field_name(self, name):
        """
        Raises an error.
        """
        raise ValueError("Cannot set name on WordQuery", name)

class PathField(Field):
    """
    A path field.
    """
    def __init__(self, field_name, paths):
        """
        Create a path field.
        """
        self._config = {
            'field-name': field_name,
            'field-path': assert_list_of_type(paths, FieldPath)
            }

    def field_paths(self):
        """
        The field paths.
        """
        return self._config['field-path']

    def add_field_path(self, path):
        """
        Add a field path.
        """
        return self.add_to_property_list('field-path', path, FieldPath)

    def remove_field_path(self, path):
        """
        Remove a field path.
        """
        return self.remove_from_property_list('field-path', path, FieldPath)

    def set_field_paths(self, paths):
        """
        Set the field paths.
        """
        if paths is None or not paths:
            raise ValueError("The list of field paths cannot be empty", paths)
        return self.set_property_list('field-path', paths, FieldPath)


text:
#include "circuit.h"

using namespace LegionRuntime::Accessor;

const float AccumulateCharge::identity = 0.0f;

template <>
void AccumulateCharge::apply<true>(LHS &lhs, RHS rhs)
{
  lhs.charge += rhs;
}

template <>
void AccumulateCharge::apply<false>(LHS &lhs, RHS rhs)
{
  // most cpus don't let you atomic add a float, so we use gcc's builtin
  // compare-and-swap in a loop
  int *target = (int *)&(lhs.charge);
  union { int as_int; float as_float; } oldval, newval;
  do {
    oldval.as_int = *target;
    newval.as_float = oldval.as_float + rhs;
  } while(!__sync_bool_compare_and_swap(target, oldval.as_int, newval.as_int));
}

template <>
void AccumulateCharge::fold<true>(RHS &rhs1, RHS rhs2)
{
  rhs1 += rhs2;
}

template <>
void AccumulateCharge::fold<false>(RHS &rhs1, RHS rhs2)
{
  // most cpus don't let you atomic add a float, so we use gcc's builtin
  // compare-and-swap in a loop
  int *target = (int *)&rhs1;
  union { int as_int; float as_float; } oldval, newval;
  do {
    oldval.as_int = *target;
    newval.as_float = oldval.as_float + rhs2;
  } while(!__sync_bool_compare_and_swap(target, oldval.as_int, newval.as_int));
}

// Helper methods

template<typename AT>
static inline CircuitNode get_node(const RegionAccessor<AT,CircuitNode> &priv,
                                   const RegionAccessor<AT,CircuitNode> &shr,
                                   const RegionAccessor<AT,CircuitNode> &ghost,
                                   PointerLocation loc, ptr_t ptr)
{
  switch (loc)
  {
    case PRIVATE_PTR:
      return priv.read(ptr);
    case SHARED_PTR:
      return shr.read(ptr);
    case GHOST_PTR:
      return ghost.read(ptr);
    default:
      assert(false);
  }
  return CircuitNode();
}

template<typename REDOP, typename AT1, typename AT2>
static inline void reduce_node(const RegionAccessor<AT1,CircuitNode> &priv,
                               const RegionAccessor<AT2,CircuitNode> &shr,
                               const RegionAccessor<AT2,CircuitNode> &ghost,
                               PointerLocation loc, ptr_t ptr, typename REDOP::RHS value)
{
  switch (loc)
  {
    case PRIVATE_PTR:
      priv.template reduce<REDOP>(ptr, value);
      break;
    case SHARED_PTR:
      shr.template reduce(ptr, value);
      break;
    case GHOST_PTR:
      ghost.template reduce(ptr, value);
      break;
    default:
      assert(false);
  }
}

template<typename AT>
static inline void update_region_voltages(CircuitPiece *p,
                                          const RegionAccessor<AT,CircuitNode> &nodes,
                                          IndexIterator &itr)
{
  while (itr.has_next())
  {
    ptr_t node_ptr = itr.next();
    CircuitNode node = nodes.read(node_ptr);

    // charge adds in, and then some leaks away
    node.voltage += node.charge / node.capacitance;
    node.voltage *= (1.f - node.leakage);
    node.charge = 0.f;

    nodes.write(node_ptr, node);
  }
}

// Actual implementations

void calc_new_currents_cpu(CircuitPiece *p,
                           const std::vector<PhysicalRegion> &regions)
{
#ifndef DISABLE_MATH
  RegionAccessor<AccessorType::Generic, CircuitWire> pvt_wires = regions[0].get_accessor().typeify<CircuitWire>();
  RegionAccessor<AccessorType::Generic, CircuitNode> pvt_nodes = regions[1].get_accessor().typeify<CircuitNode>();
  RegionAccessor<AccessorType::Generic, CircuitNode> shr_nodes = regions[2].get_accessor().typeify<CircuitNode>();
  RegionAccessor<AccessorType::Generic, CircuitNode> ghost_nodes = regions[3].get_accessor().typeify<CircuitNode>();
  LegionRuntime::HighLevel::IndexIterator itr(p->pvt_wires);
  while (itr.has_next())
  {
    ptr_t wire_ptr = itr.next();
    CircuitWire wire = pvt_wires.read(wire_ptr);
    CircuitNode in_node  = get_node(pvt_nodes, shr_nodes, ghost_nodes, wire.in_loc, wire.in_ptr);
    CircuitNode out_node = get_node(pvt_nodes, shr_nodes, ghost_nodes, wire.out_loc, wire.out_ptr);

    // Solve RLC model iteratively
    float dt = p->dt;
    const int steps = p->steps;
    float new_v[WIRE_SEGMENTS+1];
    float new_i[WIRE_SEGMENTS];
    for (int i = 0; i < WIRE_SEGMENTS; i++)
      new_i[i] = wire.current[i];
    for (int i = 0; i < WIRE_SEGMENTS-1; i++)
      new_v[i] = wire.voltage[i];
    new_v[WIRE_SEGMENTS] = out_node.voltage;

    for (int j = 0; j < steps; j++)
    {
      // first, figure out the new current from the voltage differential
      // and our inductance:
      // dV = R*I + L*I' ==> I = (dV - L*I')/R
      for (int i = 0; i < WIRE_SEGMENTS; i++)
      {
        new_i[i] = ((new_v[i+1] - new_v[i]) -
                    (wire.inductance*(new_i[i] - wire.current[i])/dt)) / wire.resistance;
      }
      // Now update the inter-node voltages
      for (int i = 0; i < WIRE_SEGMENTS-1; i++)
      {
        new_v[i+1] = wire.voltage[i] + dt*(new_i[i] - new_i[i+1]) / wire.capacitance;
      }
    }

    // Copy everything back
    for (int i = 0; i < WIRE_SEGMENTS; i++)
      wire.current[i] = new_i[i];
    for (int i = 0; i < WIRE_SEGMENTS-1; i++)
      wire.voltage[i] = new_v[i+1];

    pvt_wires.write(wire_ptr, wire);
  }
#endif
}

void distribute_charge_cpu(CircuitPiece *p,
                           const std::vector<PhysicalRegion> &regions)
{
#ifndef DISABLE_MATH
  RegionAccessor<AccessorType::Generic, CircuitWire> pvt_wires = regions[0].get_accessor().typeify<CircuitWire>();
  RegionAccessor<AccessorType::Generic, CircuitNode> pvt_nodes = regions[1].get_accessor().typeify<CircuitNode>();
  RegionAccessor<AccessorType::Generic, CircuitNode> shr_temp = regions[2].get_accessor().typeify<CircuitNode>();
  RegionAccessor<AccessorType::Generic, CircuitNode> ghost_temp = regions[3].get_accessor().typeify<CircuitNode>();
  // Check that we can convert to reduction fold instances
  assert(shr_temp.can_convert<AccessorType::ReductionFold<AccumulateCharge> >());
  assert(ghost_temp.can_convert<AccessorType::ReductionFold<AccumulateCharge> >());
  // Perform the conversion
  RegionAccessor<AccessorType::ReductionFold<AccumulateCharge>, CircuitNode> shr_nodes =
            shr_temp.convert<AccessorType::ReductionFold<AccumulateCharge> >();
  RegionAccessor<AccessorType::ReductionFold<AccumulateCharge>, CircuitNode> ghost_nodes =
            ghost_temp.convert<AccessorType::ReductionFold<AccumulateCharge> >();
  LegionRuntime::HighLevel::IndexIterator itr(p->pvt_wires);
  while (itr.has_next())
  {
    ptr_t wire_ptr = itr.next();
    CircuitWire wire = pvt_wires.read(wire_ptr);

    const float dt = p->dt;

    reduce_node<AccumulateCharge>(pvt_nodes,shr_nodes,ghost_nodes,wire.in_loc,wire.in_ptr,-dt * wire.current[0]);
    reduce_node<AccumulateCharge>(pvt_nodes,shr_nodes,ghost_nodes,wire.out_loc,wire.out_ptr,dt* wire.current[WIRE_SEGMENTS-1]);
  }
#endif
}

void update_voltages_cpu(CircuitPiece *p,
                         const std::vector<PhysicalRegion> &regions)
{
#ifndef DISABLE_MATh
  RegionAccessor<AccessorType::Generic, CircuitNode> pvt_nodes = regions[0].get_accessor().typeify<CircuitNode>();
  IndexIterator pvt_itr(p->pvt_nodes);
  update_region_voltages(p, pvt_nodes, pvt_itr);
  RegionAccessor<AccessorType::Generic, CircuitNode> shr_nodes = regions[1].get_accessor().typeify<CircuitNode>();
  IndexIterator shr_itr(p->shr_nodes);
  update_region_voltages(p, shr_nodes, shr_itr);
#endif
}

redpajama_set_name: RedPajamaGithub


text:
define([
  'dojo/_base/declare', 'dojo/_base/lang',
  'dojo/on', 'dojo/topic', 'dojo/dom-construct', 'dojo/dom', 'dojo/query', 'dojo/when', 'dojo/request',
  'dijit/layout/ContentPane', 'dijit/layout/BorderContainer', 'dijit/TooltipDialog', 'dijit/Dialog', 'dijit/popup',
  'dijit/TitlePane', 'dijit/registry', 'dijit/form/Form', 'dijit/form/RadioButton', 'dijit/form/Select', 'dijit/form/Button',
  './ContainerActionBar', './HeatmapContainer', './SelectionToGroup', '../util/PathJoin', 'FileSaver'

], function (
  declare, lang,
  on, Topic, domConstruct, dom, Query, when, request,
  ContentPane, BorderContainer, TooltipDialog, Dialog, popup,
  TitlePane, registry, Form, RadioButton, Select, Button,
  ContainerActionBar, HeatmapContainer, SelectionToGroup, PathJoin, saveAs
) {

  var legend = [
    '
',
    '
HeatMap Cells
',
    '
Cell color represents the number of proteins
 from a specific genome in a given protein family.
',
    '
',
    '',
    '0',
    '

',
    '',
    '1',
    '

',
    '',
    '2',
    '

',
    '',
    '3+',
    '

',
    '
'
  ].join('\n');

  return declare([BorderContainer, HeatmapContainer], {
    gutters: false,
    state: null,
    visible: false,
    pfState: null,
    containerActions: [
      [
        'Legend',
        'fa icon-bars fa-2x',
        { label: 'Legend', multiple: false, validTypes: ['*'] },
        function () {
          if (this.containerActionBar._actions.Legend.options.tooltipDialog == null) {
            this.tooltip_legend = new TooltipDialog({
              content: legend
            });
            this.containerActionBar._actions.Legend.options.tooltipDialog = this.tooltip_legend;
          }

          if (this.isPopupOpen) {
            this.isPopupOpen = false;
            popup.close();
          } else {
            popup.open({
              parent: this,
              popup: this.containerActionBar._actions.Legend.options.tooltipDialog,
              around: this.containerActionBar._actions.Legend.button,
              orient: ['below']
            });
            this.isPopupOpen = true;
          }
        },
        true
      ],
      [
        'Flip Axis',
        'fa icon-rotate-left fa-2x',
        { label: 'Flip Axis', multiple: false, validTypes: ['*'] },
        'flipAxis',
        true
      ],
      [
        'Cluster',
        'fa icon-cluster fa-2x',
        { label: 'Cluster', multiple: false, validTypes: ['*'] },
        'cluster',
        true
      ],
      [
        'Advanced Clustering',
        'fa icon-cluster fa-2x',
        { label: 'Advanced', multiple: false, validTypes: ['*'] },
        function () {
          var self = this;

          this.dialog.set('content', this._buildPanelAdvancedClustering());

          // building action bar
          var actionBar = domConstruct.create('div', {
            'class': 'dijitDialogPaneActionBar'
          });
          var btnSubmit = new Button({
            label: 'Submit',
            onClick: function () {
              var param = {};
              var f = registry.byId('advancedClusterParams').value;

              param.g = (f.cluster_by === 3 || f.cluster_by === 1) ? f.algorithm : 0;
              param.e = (f.cluster_by === 3 || f.cluster_by === 2) ? f.algorithm : 0;
              param.m = f.type;

              // console.log('advanced cluster param: ', param);
              self.cluster(param);
              self.dialog.hide();
            }
          });
          var btnCancel = new Button({
            label: 'Cancel',
            onClick: function () {
              self.dialog.hide();
            }
          });
          btnSubmit.placeAt(actionBar);
          btnCancel.placeAt(actionBar);

          domConstruct.place(actionBar, this.dialog.containerNode, 'last');

          this.dialog.show();
        },
        true
      ],
      [
        'Anchor',
        'fa icon-random fa-2x',
        {
          label: 'Anchor',
          multiple: false,
          validType: ['*'],
          tooltip: 'Anchor by genome'
        },
        function () {

          // dialog for anchoring
          // if(this.containerActionBar._actions.Anchor.options.tooltipDialog == null){
          this.tooltip_anchoring = new TooltipDialog({
            content: this._buildPanelAnchoring()
          });
          this.containerActionBar._actions.Anchor.options.tooltipDialog = this.tooltip_anchoring;
          // }

          if (this.isPopupOpen) {
            this.isPopupOpen = false;
            popup.close();
          } else {
            popup.open({
              parent: this,
              popup: this.containerActionBar._actions.Anchor.options.tooltipDialog,
              around: this.containerActionBar._actions.Anchor.button,
              orient: ['below']
            });
            this.isPopupOpen = true;
          }
        },
        true
      ]
    ],
    constructor: function (options) {
      this.dialog = new Dialog({});

      this.topicId = options.topicId;
      // subscribe
      Topic.subscribe(this.topicId, lang.hitch(this, function () {
        // console.log("ProteinFamiliesHeatmapContainer:", arguments);
        var key = arguments[0],
          value = arguments[1];

        switch (key) {
          case 'updatePfState':
            this.pfState = value;
            break;
          case 'refreshHeatmap':
            Topic.publish(this.topicId, 'requestHeatmapData', this.pfState);
            break;
          case 'updateHeatmapData':
            this.currentData = value;
            if (this.flashDom && typeof (this.flashDom.refreshData) == 'function') {
              this.flashDom.refreshData();
              Topic.publish(this.topicId, 'hideLoadingMask');
            }
            break;
          default:
            break;
        }
      }));
    },
    _setVisibleAttr: function (visible) {
      this.visible = visible;

      if (this.visible && !this._firstView) {
        this.onFirstView();
        this.initializeFlash('ProteinFamilyHeatMap');
      }
    },
    onFirstView: function () {
      if (this._firstView) {
        return;
      }

      // action buttons for heatmap viewer
      this.containerActionBar = new ContainerActionBar({
        baseClass: 'BrowserHeader',
        region: 'top'
      });
      this.containerActions.forEach(function (a) {
        this.containerActionBar.addAction(a[0], a[1], a[2], lang.hitch(this, a[3]), a[4]);
      }, this);
      this.addChild(this.containerActionBar);

      this.addChild(new ContentPane({
        region: 'center',
        content: "

",
        style: 'padding:0'
      }));

      this.inherited(arguments);
      this._firstView = true;
    },
    flashReady: function () {
      if (typeof (this.flashDom.refreshData) == 'function') {
        Topic.publish(this.topicId, 'refreshHeatmap');
      }
    },
    flashCellClicked: function (flashObjectID, colID, rowID) {
      // console.log("flashCellClicked is called ", colID, rowID);
      var isTransposed = (this.pfState.heatmapAxis === 'Transposed');
      var originalAxis = this._getOriginalAxis(isTransposed, colID, rowID);

      var familyId = originalAxis.columnIds;
      var genomeId = originalAxis.rowIds;

      var query = '?and(eq(' + this.pfState.familyType + '_id,' + familyId + '),eq(genome_id,' + genomeId + '),eq(feature_type,CDS),eq(annotation,PATRIC))&select(feature_id,patric_id,refseq_locus_tag)&limit(250000)';

      Topic.publish(this.topicId, 'showLoadingMask');
      request.get(PathJoin(window.App.dataServiceURL, 'genome_feature', query), {
        handleAs: 'json',
        headers: {
          Accept: 'application/json',
          'X-Requested-With': null,
          Authorization: (window.App.authorizationToken || '')
        }
      }).then(lang.hitch(this, function (features) {
        Topic.publish(this.topicId, 'hideLoadingMask');

        this.dialog.set('content', this._buildPanelCellClicked(isTransposed, familyId, genomeId, features));
        var actionBar = this._buildPanelButtons(colID, rowID, familyId, genomeId, features);
        domConstruct.place(actionBar, this.dialog.containerNode, 'last');

        this.dialog.show();
      }));

    },
    flashCellsSelected: function (flashObjectID, colIDs, rowIDs) {
      if (rowIDs.length == 0) return;
      var isTransposed = (this.pfState.heatmapAxis === 'Transposed');
      var originalAxis = this._getOriginalAxis(isTransposed, colIDs, rowIDs);

      var familyIds = originalAxis.columnIds;
      var genomeIds = originalAxis.rowIds;

      var query = 'and(in(' + this.pfState.familyType + '_id,(' + familyIds + ')),in(genome_id,(' + genomeIds + ')),eq(feature_type,CDS),eq(annotation,PATRIC))&select(feature_id,patric_id,refseq_locus)&limit(250000)';

      Topic.publish(this.topicId, 'showLoadingMask');
      request.post(PathJoin(window.App.dataServiceURL, 'genome_feature'), {
        handleAs: 'json',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/rqlquery+x-www-form-urlencoded',
          'X-Requested-With': null,
          Authorization: (window.App.authorizationToken || '')
        },
        data: query
      }).then(lang.hitch(this, function (features) {
        Topic.publish(this.topicId, 'hideLoadingMask');

        this.dialog.set('content', this._buildPanelCellsSelected(isTransposed, familyIds, genomeIds, features));
        var actionBar = this._buildPanelButtons(colIDs, rowIDs, familyIds, genomeIds, features);
        domConstruct.place(actionBar, this.dialog.containerNode, 'last');

        this.dialog.show();
      }));
    },
    _buildPanelCellClicked: function (isTransposed, familyId, genomeId, features) {

      var gfs = this.pfState.genomeFilterStatus;

      var genomeName = gfs[genomeId].getLabel();
      var description = '',
        memberCount = 0,
        index = 0;

      if (isTransposed) {
        // rows: families, columns: genomes
        this.currentData.rows.forEach(function (row, idx) {
          if (row.rowID === familyId) {
            description = row.rowLabel;
            index = idx;
          }
        });
        this.currentData.columns.forEach(function (col) {
          if (col.colID === genomeId) {
            memberCount = parseInt(col.distribution.substr(2 * index, 2), 16);
          }
        });
      } else {
        index = gfs[genomeId].getIndex();
        this.currentData.columns.forEach(function (col) {
          if (col.colID === familyId) {
            description = col.colLabel;
            memberCount = parseInt(col.distribution.substr(2 * index, 2), 16);
          }
        });
      }

      var text = [];
      text.push('Genome: ' + genomeName);
      text.push('Product: ' + description);
      text.push('Family ID: ' + familyId);
      text.push('Members: ' + memberCount);
      features.forEach(function (feature) {
        var featureLink = '' + feature.patric_id + '';
        if (feature.refseq_locus_tag !== undefined) {
          featureLink += ', ' + feature.refseq_locus_tag;
        }
        if (feature.alt_locus_tag !== undefined) {
          featureLink += ', ' + feature.alt_locus_tag;
        }
        text.push(featureLink);
      });

      return text.join('
');
    },
    _buildPanelCellsSelected: function (isTransposed, familyIds, genomeIds, features) {

      // var membersCount = this._countMembers(colIDs, rowIDs);

      var text = [];
      text.push('Genomes Selected: ' + genomeIds.length);
      text.push('Family Selected: ' + familyIds.length);
      text.push('Members: ' + features.length);

      return text.join('
');
    },
    _buildPanelAdvancedClustering: function () {

      if (registry.byId('advancedClusterParams') !== undefined) {
        registry.byId('advancedClusterParams').destroyRecursive();
      }

      var form = new Form({
        id: 'advancedClusterParams'
      });

      var tp_dim = new TitlePane({
        title: 'Cluster by'
      }).placeAt(form.containerNode);

      new RadioButton({
        checked: false,
        value: 2,
        name: 'cluster_by',
        label: 'Protein Families'
      }).placeAt(tp_dim.containerNode);
      domConstruct.place('Protein Families
', tp_dim.containerNode, 'last');

      new RadioButton({
        checked: false,
        value: 1,
        name: 'cluster_by',
        label: 'Genomes'
      }).placeAt(tp_dim.containerNode);
      domConstruct.place('Genomes
', tp_dim.containerNode, 'last');

      new RadioButton({
        checked: true,
        value: 3,
        name: 'cluster_by',
        label: 'Both'
      }).placeAt(tp_dim.containerNode);
      domConstruct.place('Both', tp_dim.containerNode, 'last');

      var sel_algorithm = new Select({
        name: 'algorithm',
        value: 2,
        options: [{
          value: 0, label: 'No clustering'
        }, {
          value: 1, label: 'Un-centered correlation'
        }, {
          value: 2, label: 'Pearson correlation'
        }, {
          value: 3, label: 'Un-centered correlation, absolute value'
        }, {
          value: 4, label: 'Pearson correlation, absolute value'
        }, {
          value: 5, label: 'Spearman rank correlation'
        }, {
          value: 6, label: 'Kendall tau'
        }, {
          value: 7, label: 'Euclidean distance'
        }, {
          value: 8, label: 'City-block distance'
        }]
      });

      var sel_type = new Select({
        name: 'type',
        value: 'a',
        options: [{
          value: 'm', label: 'Pairwise complete-linkage'
        }, {
          value: 's', label: 'Pairwise single-linkage'
        }, {
          value: 'c', label: 'Pairwise centroid-linkage'
        }, {
          value: 'a', label: 'Pairwise average-linkage'
        }]
      });

      new TitlePane({
        title: 'Clustering algorithm',
        content: sel_algorithm
      }).placeAt(form.containerNode);

      new TitlePane({
        title: 'Clustering type',
        content: sel_type
      }).placeAt(form.containerNode);

      return form;
    },
    _buildPanelAnchoring: function () {

      var self = this;
      var pfState = self.pfState;
      var options = [{ value: '', label: 'Select a genome' }];
      options = options.concat(pfState.genomeIds.map(function (genomeId) {
        return {
          value: genomeId,
          label: pfState.genomeFilterStatus[genomeId].getLabel()
        };
      }).sort(function (a, b) {
        // return a.label - b.label;
        if (a.label  b.label) {
          return 1;
        }

        return 0;

      }));

      var anchor = new Select({
        name: 'anchor',
        options: options
      });
      anchor.on('change', lang.hitch(this, function (genomeId) {
        if (genomeId !== '') {
          Topic.publish(this.topicId, 'anchorByGenome', genomeId);
          popup.close(self.tooltip_anchoring);
        }
      }));

      return anchor;
    },
    _buildPanelButtons: function (colIDs, rowIDs, familyIds, genomeIds, features) {
      var _self = this;
      var actionBar = domConstruct.create('div', {
        'class': 'dijitDialogPaneActionBar'
      });

      var dhc = '
Download Table As...

Text

CSV
';

      var dfc = '
Download Table As...

Text

CSV

Excel
';
      var downloadHM = new TooltipDialog({
        content: dhc,
        onMouseLeave: function () {
          popup.close(downloadHM);
        }
      });
      var downloadPT = new TooltipDialog({
        content: dfc,
        onMouseLeave: function () {
          popup.close(downloadPT);
        }
      });

      var btnDownloadHeatmap = new Button({
        label: 'Download Heatmap Data'
      });
      on(downloadHM.domNode, 'click', function (e) {
        if (e.target.attributes.rel === undefined) return;
        var rel = e.target.attributes.rel.value;
        var DELIMITER,
          ext;
        if (rel === 'text/csv') {
          DELIMITER = ',';
          ext = 'csv';
        } else {
          DELIMITER = '\t';
          ext = 'txt';
        }

        var colIndexes = [];
        _self.currentData.columns.forEach(function (col, idx) {
          if (colIDs.indexOf(col.colID) > -1) {
            colIndexes[colIDs.indexOf(col.colID)] = idx;
          }
        });

        var header = _self.currentData.rowLabel + '/' + _self.currentData.colLabel;
        colIndexes.forEach(function (colIdx) {
          header += DELIMITER + _self.currentData.columns[colIdx].colLabel;
        });

        var data = [];
        _self.currentData.rows.forEach(function (row, idx) {
          if (rowIDs.indexOf(row.rowID) > -1) {
            var r = [];
            r.push(row.rowLabel);
            colIndexes.forEach(function (colIdx) {
              var val = parseInt(_self.currentData.columns[colIdx].distribution.substr(idx * 2, 2), 16);
              r.push(val);
            });
            data[rowIDs.indexOf(row.rowID)] = r.join(DELIMITER);
          }
        });

        saveAs(new Blob([header + '\n' + data.join('\n')], { type: rel }), 'PATRIC_protein_families_heatmap.' + ext);
        popup.close(downloadHM);
      });
      on(btnDownloadHeatmap.domNode, 'click', function () {
        popup.open({
          popup: downloadHM,
          around: btnDownloadHeatmap.domNode,
          orient: ['below']
        });
      });

      var btnDownloadProteins = new Button({
        label: 'Download Proteins',
        disabled: (features.length === 0)
      });
      on(downloadPT.domNode, 'click', function (e) {
        if (e.target.attributes.rel === undefined) return;
        var rel = e.target.attributes.rel.value;
        var currentQuery = '?in(feature_id,(' + features.map(function (f) {
          return f.feature_id;
        }).join(',') + '))&sort(+feature_id)';

        window.open(window.App.dataServiceURL + '/genome_feature/' + currentQuery + '&http_authorization=' + encodeURIComponent(window.App.authorizationToken) + '&http_accept=' + rel + '&http_download=true');
        popup.close(downloadPT);
      });

      on(btnDownloadProteins.domNode, 'click', function () {
        popup.open({
          popup: downloadPT,
          around: btnDownloadProteins.domNode,
          orient: ['below']
        });
      });

      var btnShowDetails = new Button({
        label: 'Show Proteins',
        disabled: (features.length === 0)
      });
      on(btnShowDetails.domNode, 'click', function () {

        var query = '?in(feature_id,(' + features.map(function (d) {
          return d.feature_id;
        }) + '))';
        Topic.publish('/navigate', {
          href: '/view/FeatureList/' + query + '#view_tab=features',
          target: 'blank'
        });

        _self.dialog.hide();
      });

      var btnAddToWorkspace = new Button({
        label: 'Add Proteins to Group',
        disabled: (features.length === 0)
      });
      on(btnAddToWorkspace.domNode, 'click', function () {
        if (!window.App.user || !window.App.user.id) {
          Topic.publish('/login');
          return;
        }

        var dlg = new Dialog({ title: 'Add This Feature To Group' });
        var stg = new SelectionToGroup({
          selection: features,
          type: 'feature_group'
        });
        on(dlg.domNode, 'dialogAction', function (evt) {
          dlg.hide();
          setTimeout(function () {
            dlg.destroy();
          }, 2000);
        });
        domConstruct.place(stg.domNode, dlg.containerNode, 'first');
        stg.startup();
        dlg.startup();
        dlg.show();
      });

      var btnCancel = new Button({
        label: 'Cancel',
        onClick: function () {
          _self.dialog.hide();
        }
      });

      btnDownloadHeatmap.placeAt(actionBar);
      btnDownloadProteins.placeAt(actionBar);
      btnShowDetails.placeAt(actionBar);
      btnAddToWorkspace.placeAt(actionBar);
      btnCancel.placeAt(actionBar);

      return actionBar;
    },
    _getOriginalAxis: function (isTransposed, columnIds, rowIds) {
      var originalAxis = {};
      // console.log("_getOriginalAxis: ", isTransposed, columnIds, rowIds);

      if (isTransposed) {
        originalAxis.columnIds = rowIds;
        originalAxis.rowIds = columnIds;
      } else {
        originalAxis.columnIds = columnIds;
        originalAxis.rowIds = rowIds;
      }
      return originalAxis;
    },
    flipAxis: function () {
      // flip internal flag
      if (this.pfState.heatmapAxis === '') {
        this.pfState.heatmapAxis = 'Transposed';
      } else {
        this.pfState.heatmapAxis = '';
      }

      Topic.publish(this.topicId, 'refreshHeatmap');
    },
    cluster: function (param) {

      // console.log("cluster is called", param);
      // this.set('loading', true);
      var p = param || { g: 2, e: 2, m: 'a' };

      var isTransposed = this.pfState.heatmapAxis === 'Transposed';
      var data = this.exportCurrentData(isTransposed);

      console.log('clustering data set size: ', data.length);
      if (data.length > 1500000) {
        new Dialog({
          title: 'Notice',
          content: 'The data set is too large to cluster. Please use filter panel to reduce the size',
          style: 'width: 300px'
        }).show();
        return;
      }

      Topic.publish(this.topicId, 'showLoadingMask');

      return when(window.App.api.data('cluster', [data, p]), lang.hitch(this, function (res) {
        // console.log("Cluster Results: ", res);
        // this.set('loading', false);

        // DO NOT TRANSPOSE. clustering process is based on the corrected axises
        this.pfState.clusterRowOrder = res.rows;
        this.pfState.clusterColumnOrder = res.columns;

        Topic.publish(this.topicId, 'updatePfState', this.pfState);
        Topic.publish(this.topicId, 'updateFilterGridOrder', res.rows);
        Topic.publish(this.topicId, 'updateMainGridOrder', res.columns);

        // re-draw heatmap
        Topic.publish(this.topicId, 'refreshHeatmap');
      }), function (err) {

        Topic.publish(this.topicId, 'hideLoadingMask');

        new Dialog({
          title: err.status || 'Error',
          content: err.text || err
        }).show();
      });
    }
  });
});


text:
define([
    'mongoose'
], function (mongoose) {
    'use strict';

    var Schema = mongoose.Schema;
    var ObjectId = Schema.Types.ObjectId;
    var Now = Date.now;
    var CommentSchema = new Schema({
        post: {
            type: ObjectId,
            index: true,
            required: true,
            ref: 'Post'
        },
        nickname: {
            type: String,
            required: true
        },
        email: {
            type: String,
            required: true
        },
        text: String,
        createAt: {
            type: Date,
            default: Now
        },
        clientIp: {
            type: String,
            default: '0.0.0.0'
        },
        removed: {
            type: Boolean,
            default: false
        }
    });
    var Comment = mongoose.model('Comment', CommentSchema);
    return Comment;
});


text:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;

namespace Rolodex.Silverlight.Behaviors
{
    public class EnterKeyBehavior : System.Windows.Interactivity.Behavior<FrameworkElement>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.KeyUp += AssociatedObjectKeyUp;
        }

        private void AssociatedObjectKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
            {
                if (TargetButton != null && TargetButton.IsEnabled)
                {
                    var peer = new ButtonAutomationPeer(TargetButton);
                    var invokeProvider =  peer.GetPattern(PatternInterface.Invoke)  as IInvokeProvider;
                    if (invokeProvider != null) invokeProvider.Invoke();
                }
            }
        }

        protected override void OnDetaching()
        {
            AssociatedObject.KeyUp -= AssociatedObjectKeyUp;
            base.OnDetaching();
        }

        public Button TargetButton
        {
            get { return (Button)GetValue(TargetButtonProperty); }
            set { SetValue(TargetButtonProperty, value); }
        }

        public static readonly DependencyProperty TargetButtonProperty =
            DependencyProperty.Register("TargetButton", typeof(Button), typeof(EnterKeyBehavior), new PropertyMetadata(null));

    }
}


text:
@interface SPNotification ()

// Private interface goes here.

@end

@implementation SPNotification

- (void)awakeFromInsert
{
    [super awakeFromInsert];
    [self setPrimitiveCreatedAt:[NSDate date]];
}

@end


text:
dumbo::v1::fibers::mutex check_mutex;
dumbo::v1::fibers::mutex fss_mutex;
int fss_instances = 0;
int fss_total = 0;

struct fss_value_t {
    fss_value_t() {
        std::unique_lock<dumbo::v1::fibers::mutex> lock(fss_mutex);
        ++fss_instances;
        ++fss_total;
        value = 0;
    }
    ~fss_value_t() {
        std::unique_lock<dumbo::v1::fibers::mutex> lock(fss_mutex);
        --fss_instances;
    }
    int value;
};

dumbo::v1::fibers::fiber_specific_ptr<fss_value_t> fss_value;

void fss_fiber() {
    fss_value.reset(new fss_value_t());
    for (int i=0; i<1000; ++i) {
        int& n = fss_value->value;
        if (n != i) {
            std::unique_lock<dumbo::v1::fibers::mutex> lock(check_mutex);
            BOOST_CHECK_EQUAL(n, i);
        }
        ++n;
    }
}

void fss() {
    fss_instances = 0;
    fss_total = 0;

    dumbo::v1::fibers::fiber f1( dumbo::v1::fibers::launch::post, fss_fiber);
    dumbo::v1::fibers::fiber f2( dumbo::v1::fibers::launch::post, fss_fiber);
    dumbo::v1::fibers::fiber f3( dumbo::v1::fibers::launch::post, fss_fiber);
    dumbo::v1::fibers::fiber f4( dumbo::v1::fibers::launch::post, fss_fiber);
    dumbo::v1::fibers::fiber f5( dumbo::v1::fibers::launch::post, fss_fiber);
    f1.join();
    f2.join();
    f3.join();
    f4.join();
    f5.join();

    std::cout
        << "fss_instances = " << fss_instances
        << "; fss_total = " << fss_total
        << "\n";
    std::cout.flush();

    BOOST_CHECK_EQUAL(fss_instances, 0);
    BOOST_CHECK_EQUAL(fss_total, 5);
}

void test_fss() {
    dumbo::v1::fibers::fiber( dumbo::v1::fibers::launch::post, fss).join();
}

bool fss_cleanup_called=false;

struct Dummy {
};

void fss_custom_cleanup(Dummy* d) {
    delete d;
    fss_cleanup_called=true;
}

dumbo::v1::fibers::fiber_specific_ptr<Dummy> fss_with_cleanup(fss_custom_cleanup);

void fss_fiber_with_custom_cleanup() {
    fss_with_cleanup.reset(new Dummy);
}

void fss_with_custom_cleanup() {
    dumbo::v1::fibers::fiber f( dumbo::v1::fibers::launch::post, fss_fiber_with_custom_cleanup);
    try {
        f.join();
    } catch(...) {
        f.join();
        throw;
    }

    BOOST_CHECK(fss_cleanup_called);
}

void test_fss_with_custom_cleanup() {
    dumbo::v1::fibers::fiber( dumbo::v1::fibers::launch::post, fss_with_custom_cleanup).join();
}

Dummy* fss_object=new Dummy;

void fss_fiber_with_custom_cleanup_and_release() {
    fss_with_cleanup.reset(fss_object);
    fss_with_cleanup.release();
}

void do_test_fss_does_no_cleanup_after_release() {
    fss_cleanup_called=false;
    dumbo::v1::fibers::fiber f( dumbo::v1::fibers::launch::post, fss_fiber_with_custom_cleanup_and_release);
    try {
        f.join();
    } catch(...) {
        f.join();
        throw;
    }

    BOOST_CHECK(!fss_cleanup_called);
    if(!fss_cleanup_called) {
        delete fss_object;
    }
}

struct dummy_class_tracks_deletions {
    static unsigned deletions;

    ~dummy_class_tracks_deletions() {
        ++deletions;
    }
};

unsigned dummy_class_tracks_deletions::deletions=0;

dumbo::v1::fibers::fiber_specific_ptr<dummy_class_tracks_deletions> fss_with_null_cleanup(NULL);

void fss_fiber_with_null_cleanup(dummy_class_tracks_deletions* delete_tracker) {
    fss_with_null_cleanup.reset(delete_tracker);
}

void do_test_fss_does_no_cleanup_with_null_cleanup_function() {
    dummy_class_tracks_deletions* delete_tracker=new dummy_class_tracks_deletions;
    dumbo::v1::fibers::fiber f( dumbo::v1::fibers::launch::post, [&delete_tracker](){
        fss_fiber_with_null_cleanup( delete_tracker); });
    try {
        f.join();
    } catch(...) {
        f.join();
        throw;
    }

    BOOST_CHECK(!dummy_class_tracks_deletions::deletions);
    if(!dummy_class_tracks_deletions::deletions) {
        delete delete_tracker;
    }
}

void test_fss_does_no_cleanup_after_release() {
    dumbo::v1::fibers::fiber( dumbo::v1::fibers::launch::post, do_test_fss_does_no_cleanup_after_release).join();
}

void test_fss_does_no_cleanup_with_null_cleanup_function() {
    dumbo::v1::fibers::fiber( dumbo::v1::fibers::launch::post, do_test_fss_does_no_cleanup_with_null_cleanup_function).join();
}

void fiber_with_local_fss_ptr() {
    {
        dumbo::v1::fibers::fiber_specific_ptr<Dummy> local_fss(fss_custom_cleanup);

        local_fss.reset(new Dummy);
    }
    BOOST_CHECK(fss_cleanup_called);
    fss_cleanup_called=false;
}

void fss_does_not_call_cleanup_after_ptr_destroyed() {
    dumbo::v1::fibers::fiber( dumbo::v1::fibers::launch::post, fiber_with_local_fss_ptr).join();
    BOOST_CHECK(!fss_cleanup_called);
}

void test_fss_does_not_call_cleanup_after_ptr_destroyed() {
    dumbo::v1::fibers::fiber( dumbo::v1::fibers::launch::post, fss_does_not_call_cleanup_after_ptr_destroyed).join();
}

void fss_cleanup_not_called_for_null_pointer() {
    dumbo::v1::fibers::fiber_specific_ptr<Dummy> local_fss(fss_custom_cleanup);
    local_fss.reset(new Dummy);
    fss_cleanup_called=false;
    local_fss.reset(0);
    BOOST_CHECK(fss_cleanup_called);
    fss_cleanup_called=false;
    local_fss.reset(new Dummy);
    BOOST_CHECK(!fss_cleanup_called);
}

void test_fss_cleanup_not_called_for_null_pointer() {
    dumbo::v1::fibers::fiber( dumbo::v1::fibers::launch::post, fss_cleanup_not_called_for_null_pointer).join();
}

void fss_at_the_same_adress() {
  for(int i=0; i<2; i++) {
    dumbo::v1::fibers::fiber_specific_ptr<Dummy> local_fss(fss_custom_cleanup);
    local_fss.reset(new Dummy);
    fss_cleanup_called=false;
    BOOST_CHECK(fss_cleanup_called);
    fss_cleanup_called=false;
    BOOST_CHECK(!fss_cleanup_called);
  }
}

void test_fss_at_the_same_adress() {
    dumbo::v1::fibers::fiber( dumbo::v1::fibers::launch::post, fss_at_the_same_adress).join();
}

boost::unit_test::test_suite* init_unit_test_suite(int, char*[]) {
    boost::unit_test::test_suite* test =
        BOOST_TEST_SUITE("Boost.Fiber: fss test suite");

    test->add(BOOST_TEST_CASE(test_fss));
    test->add(BOOST_TEST_CASE(test_fss_with_custom_cleanup));
    test->add(BOOST_TEST_CASE(test_fss_does_no_cleanup_after_release));
    test->add(BOOST_TEST_CASE(test_fss_does_no_cleanup_with_null_cleanup_function));
    test->add(BOOST_TEST_CASE(test_fss_does_not_call_cleanup_after_ptr_destroyed));
    test->add(BOOST_TEST_CASE(test_fss_cleanup_not_called_for_null_pointer));

    return test;
}


text:
package org.jetbrains.jps.incremental;

import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.builders.BuildTarget;
import org.jetbrains.jps.builders.impl.BuildOutputConsumerImpl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;

/**
* @author Eugene Zhuravlev
*         Date: 11/16/12
*/
class ChunkBuildOutputConsumerImpl implements ModuleLevelBuilder.OutputConsumer {
  private final CompileContext myContext;
  private Map<BuildTarget<?>, BuildOutputConsumerImpl> myTarget2Consumer = new THashMap<BuildTarget<?>, BuildOutputConsumerImpl>();
  private Map<String, CompiledClass> myClasses = new THashMap<String, CompiledClass>();
  private Map<BuildTarget<?>, Collection<CompiledClass>> myTargetToClassesMap = new THashMap<BuildTarget<?>, Collection<CompiledClass>>();

  public ChunkBuildOutputConsumerImpl(CompileContext context) {
    myContext = context;
  }

  @Override
  public Collection<CompiledClass> getTargetCompiledClasses(@NotNull BuildTarget<?> target) {
    final Collection<CompiledClass> classes = myTargetToClassesMap.get(target);
    if (classes != null) {
      return Collections.unmodifiableCollection(classes);
    }
    return Collections.emptyList();
  }

  @NotNull
  @Override
  public Map<String, CompiledClass> getCompiledClasses() {
    return Collections.unmodifiableMap(myClasses);
  }

  @Override
  @Nullable
  public BinaryContent lookupClassBytes(String className) {
    final CompiledClass object = myClasses.get(className);
    return object != null ? object.getContent() : null;
  }

  @Override
  public void registerCompiledClass(@Nullable BuildTarget<?> target, CompiledClass compiled) throws IOException {
    if (compiled.getClassName() != null) {
      myClasses.put(compiled.getClassName(), compiled);
      if (target != null) {
        Collection<CompiledClass> classes = myTargetToClassesMap.get(target);
        if (classes == null) {
          classes = new ArrayList<CompiledClass>();
          myTargetToClassesMap.put(target, classes);
        }
        classes.add(compiled);
      }
    }
    if (target != null) {
      registerOutputFile(target, compiled.getOutputFile(), compiled.getSourceFilesPaths());
    }
  }

  @Override
  public void registerOutputFile(@NotNull BuildTarget<?> target, File outputFile, Collection<String> sourcePaths) throws IOException {
    BuildOutputConsumerImpl consumer = myTarget2Consumer.get(target);
    if (consumer == null) {
      consumer = new BuildOutputConsumerImpl(target, myContext);
      myTarget2Consumer.put(target, consumer);
    }
    consumer.registerOutputFile(outputFile, sourcePaths);
  }

  public void fireFileGeneratedEvents() {
    for (BuildOutputConsumerImpl consumer : myTarget2Consumer.values()) {
      consumer.fireFileGeneratedEvent();
    }
  }

  public int getNumberOfProcessedSources() {
    int total = 0;
    for (BuildOutputConsumerImpl consumer : myTarget2Consumer.values()) {
      total += consumer.getNumberOfProcessedSources();
    }
    return total;
  }

  public void clear() {
    myTarget2Consumer.clear();
    myClasses.clear();
    myTargetToClassesMap.clear();
  }
}


text:
function lib(focusUtil) { //eslint-disable-line no-unused-vars
    var STACK = [];

    /**
     * Pushes an element into the stack
     * @param {Element} element
     */
    function push(element) {
        STACK.push(element);
    }

    /**
     * Pops an {element, xpath} object from the stack.
     * @returns {Object}
     */
    function pop() {
        return STACK.pop();
    }

    /**
     * Returns the current activeElement, if document's activeElement can be accessed.
     * @returns {Element | null}
     */
    function getActiveElement(cmp) {
        // Edge/IE11 throws an Unspecified Error for document.activeElement when accessed from an iframe.
        try {
            // IE11 use lastActive if it's specified.
            return (cmp && cmp.lastActive) || document.activeElement;
        } catch(e) {
            return null;
        }
    }

    /**
     * Returns an element if the given selector is available in the DOM.
     * @param {String} selector
     * @returns {Element | null}
     */
    function getQuerySelector(selector) {
        try {
            return document.querySelector(selector);
        } catch(e) {
            return null;
        }
    }

    /**
     * Returns true if the component has focus.
     * @param {Component} component
     * @returns {boolean}
     */
    function hasFocus(component) {
        if (!component || !component.isValid()) {
            return false;
        }
        var active = getActiveElement(component);
        var i, el, els;
        if (active) {
            els = component.getElements();
            for (i=0; i < els.length; i++) {
                el = els[i];
                if (el === active || el.contains(active)) {
                    return true;
                }
            }
        }
        return false;
    }

    function sanitizeClassName(className) {
        if (className) {
            var path = typeof className.trim === "function" ? className.trim() : $A.util.trim(className);
            return '.' + path.replace(/\s+/g, ".");
        } else {
            return "";
        }
    }

    /**
     * Generates selector for a given element.
     * @param {Element} element
     * @returns {String | undefined} selector
     */
    function generateSelector(element) {
        if (!(element instanceof Element)) {
            return undefined;
        }
        var selector = [];
        while (element && element.nodeType === Node.ELEMENT_NODE) {
            var path = element.nodeName.toLowerCase();
            var sibling = element, index = 1;
            while ((sibling = sibling.previousElementSibling)) {
                if (sibling.nodeName.toLowerCase() === path) {
                    index++;
                }
            }
            if (index !== 1) {
                path += ":nth-of-type("+index+")";
            }
            selector.unshift(path + sanitizeClassName(element.getAttribute('class')));
            element = element.parentNode;
        }
        return selector.join(" > ");
    }

    /**
     * Pushes the given element or activeElement and its Selector into the stack.
     * @param {Element} [element] - Element to which the focus should return.
     */
    function stackFocus(element) {
        var elem = element || getActiveElement();
        if (elem && elem !== document.body) {
            var path = generateSelector(elem);
            var el = {
                domElement: elem,
                selector: path
            };
            push(el);
        }
    }

    /**
     * For a given component that has focus it pops the element, xPath.
     * @param {Component} component - Component from which this method is called.
     */
    function popFocus(component, forcePop) {
        // hasFocus() works as expected if it's modal. For panel, such as closeOnClickOut,
        // focus is already changed, so hasFocus will always return false.
        if (!forcePop && !hasFocus(component)) {
            return null;
        }

        var el = pop();
        while (el && (!document.body.contains(el.domElement) || focusUtil.isElementHidden(el.domElement))) {
            if(el.selector) {
                var element = getQuerySelector(el.selector);
                if(element &&
                    document.body.contains(element) &&
                    !focusUtil.isElementHidden(element)) {
                    el.domElement = element;
                    break;
                }
            }
            el = pop();
        }

        if ($A.util.isUndefinedOrNull(el)) {
            return null;
        }

        if(!getActiveElement()) {
            // last resort, make sure focus is in the document
            el.domElement = document.body;
        }
        return el.domElement;
    }

    /**
     * For a given component that has focus it pops the element, xPath and
     * sets focus to it if its visible in the DOM.
     * @param {Component} component - Component from which this method is called.
     */
    function unstackFocus(component) {
        var domElement = popFocus(component);

        if (domElement && domElement.focus) {
            domElement.focus();
        }
    }

    return {
        stackFocus   : stackFocus,
        unstackFocus : unstackFocus,
        popFocus : popFocus
    };

}