text:
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.

#include "json_diff.h"
#include "mldb/types/value_description.h"
#include "mldb/types/structure_description.h"
#include "mldb/types/map_description.h"
#include "mldb/types/vector_description.h"
#include "mldb/types/pointer_description.h"
#include "mldb/types/pair_description.h"
#include "mldb/base/parse_context.h"

#include <regex>

using namespace std;

namespace MLDB {

JsonDiff::Deleted JsonDiff::deleted;

/*****************************************************************************/
/* JSON DIFF                                                                 */
/*****************************************************************************/

void
JsonDiff::
reverse()
{
    std::swap(oldValue, newValue);

    for (auto & f: fields)
        f.second.reverse();
    for (auto & e: elements)
        e.reverse();
}

/** Ignore the given values.  The regex will be called with strings like this:

    key1.key2.value:+new,-old

    Any which the regex matches against that string will be removed from the
    diff.
*/
void
JsonDiff::
ignore(const std::string & toIgnoreRegex, bool debug)
{
    std::regex regex(toIgnoreRegex);

    std::function<bool (JsonDiff & diff, const std::string & path)> process
        = [&] (JsonDiff & diff, const std::string & path) -> bool
        {
            if (!diff.fields.empty()) {
                std::vector<string> fieldsToRemove;
                for (auto & f: diff.fields) {
                    bool remove = process(f.second, (path.empty() ? "": path + ".") + f.first);
                    if (remove)
                        fieldsToRemove.push_back(f.first);
                }

                for (auto & r: fieldsToRemove) {
                    diff.fields.erase(r);
                }

                return diff.fields.empty();
            }
            else if (!diff.elements.empty()) {
                // Reverse order so we can erase as we go
                for (int i = diff.elements.size() - 1;  i >= 0;  --i) {
                    auto & f = diff.elements[i];
                    bool remove = process(f, path + "[" + to_string(f.oldEl) + "]");
                    if (remove)
                        diff.elements.erase(diff.elements.begin() + i);
                }
                return diff.elements.empty();
            }
            else {
                string toMatch = path + ":";

                if (diff.oldValue) {
                    toMatch += "-[" + diff.oldValue->toStringNoNewLine() + "]";
                }
                if (diff.newValue) {
                    toMatch += "+[" + diff.newValue->toStringNoNewLine() + "]";
                }

                //cerr << "testing " << toMatch << endl;

                return std::regex_match(toMatch, regex);
            }
        };

    process(*this, "");
}

JsonDiff
JsonDiff::
ignored(const std::string & toIgnoreRegex, bool debug) const
{
    JsonDiff result(*this);
    result.ignore(toIgnoreRegex, debug);
    return result;
}

/*****************************************************************************/
/* FREE FUNCTIONS                                                            */
/*****************************************************************************/

bool compareObjects(const Json::Value & val1,
                    const Json::Value & val2,
                    bool strict)
{
    if (strict)
        return val1 == val2;

    if (val1.type() == val2.type()) {
        switch (val1.type()) {
        case Json::objectValue: {
            vector<string> members1 = val1.getMemberNames();
            vector<string> members2 = val2.getMemberNames();

            if (members1 != members2)
                return false;

            for (auto && m: members1) {
                if (!compareObjects(val1[m], val2[m], strict))
                    return false;
            }

            return true;
        }

        case Json::arrayValue: {
            if (val1.size() != val2.size())
                return false;

            for (unsigned i = 0;  i < val1.size();  ++i) {
                if (!compareObjects(val1[i], val2[i], strict))
                    return false;
            }

            return true;
        }
        default:
            return val1 == val2;
        }
    }
    if (val1.isNumeric() && val2.isNumeric()
        && val1.asDouble() == val2.asDouble()) {
        return true;
    }
    return false;
}

JsonDiff
jsonDiffObjects(const Json::Value & obj1,
                const Json::Value & obj2,
                bool strict)
{
    JsonDiff result;

    auto members1 = obj1.getMemberNames(), members2 = obj2.getMemberNames();

    std::sort(members1.begin(), members1.end());
    std::sort(members2.begin(), members2.end());

    auto it1 = members1.begin(), end1 = members1.end();
    auto it2 = members2.begin(), end2 = members2.end();

    while (it1 != end1 || it2 != end2) {
        if (it1 != end1 && it2 != end2 && *it1 == *it2) {
            // Same name

            auto diff = jsonDiff(obj1[*it1], obj2[*it2], strict);

            if (diff)
                result.fields[*it1] = std::move(diff);

            ++it1;
            ++it2;
        }
        else if (it1 != end1 && (it2 == end2 || *it1 < *it2)) {
            // Deleted field
            result.fields[*it1] = JsonDiff(obj1[*it1], JsonDiff::deleted);
            ++it1;
        }
        else {
            // Inserted field
            result.fields[*it2] = JsonDiff(JsonDiff::deleted, obj2[*it2]);
            ++it2;
        }
    }

    return result;
}

/** Find the edit distance */

struct DistanceEntry {
    DistanceEntry(double dist = 0)
        : dist(dist), ins(0), del(0), sub(0)
    {
    }

    double dist; ///< Distance

    int ins:1;   ///< Insertion is optimal
    int del:1;   ///< Deletion is optimal
    int sub:1;   ///< Substitution is optimal
};

vector<vector<DistanceEntry> >
getDistances(const Json::Value & arr1, const Json::Value & arr2,
             bool debug, bool strict)
{
    int m = arr1.size(), n = arr2.size();

    if (debug) {
        cerr << "getDistances: arr1 = " << endl << arr1 << " arr2 = "
             << endl << arr2 << endl;
    }

    vector<vector<DistanceEntry> > result(m + 1,
                                          vector<DistanceEntry>(n + 1));

    // Initialize with insertion only
    for (unsigned i = 0;  i <= m;  ++i) {
        result[i][0] = i;
    }

    for (unsigned j = 0;  j <= n;  ++j) {
        result[0][j] = j;
    }

    double minDistLastColumn = 0;
    double beamWidth = 1000;

    // Now create the table
    for (unsigned j = 0;  j < n && m > 0;  ++j) {
        if (debug)
            cerr << "j = " << j << " of " << n << endl;

        double minDistThisColumn = INFINITY;

        for (unsigned i = 0;  i < m;  ++i) {
            if (debug)
                cerr << "i = " << i << " of " << m << endl;

            DistanceEntry dist;

            if (debug)
                cerr << "entry " << i << "," << j << endl;

            if (result[i][j].dist > minDistThisColumn + beamWidth) {
                dist.dist = INFINITY;
            }
            else if (compareObjects(arr1[i], arr2[j], strict)) {
                // Same element
                dist.dist = result[i][j].dist;
                if (debug)
                    cerr << "  ** SAME; dist = " << dist.dist << endl;
            }
            else {
                double deletionDist     = result[i][j + 1].dist + 1;
                double insertionDist    = result[i + 1][j].dist + 1;
                double substitutionDist = result[i][j].dist + 1;

                dist = std::min(std::min(deletionDist,
                                         insertionDist),
                                substitutionDist);

                dist.ins = (insertionDist == dist.dist);
                dist.del = (deletionDist  == dist.dist);
                dist.sub = (substitutionDist == dist.dist);

                if (debug) {
                    cerr << "  ** del " << deletionDist << " ins "
                         << insertionDist << " sub " << substitutionDist
                         << " dist " << dist.dist << endl;
                }
            }

            result[i + 1][j + 1] = dist;
            minDistThisColumn = std::min(minDistThisColumn, dist.dist);
        }

        if (!isfinite(minDistThisColumn)) {
            if (!debug)
                getDistances(arr1, arr2, true, strict);
        }

        ExcAssert(std::isfinite(minDistThisColumn));

        minDistLastColumn = minDistThisColumn;
    }

    if (debug)
        cerr << "distance is " << result[m][n].dist << " of " << m << "," << n << endl;

    return result;
}

JsonDiff
jsonDiffArrays(const Json::Value & arr1,
               const Json::Value & arr2,
               bool strict)
{
    bool debug = false;

    if (debug) {
        cerr << "arr1 = " << arr1.toString();
        cerr << "arr2 = " << arr2.toString();
    }

    if (compareObjects(arr1, arr2, strict)) {
        return JsonDiff();
    }

#if 0
    if (arr1.size() == arr2.size()
        && arr1.toString() == arr2.toString()) {
        cerr << "Warning: different in comparison but same printed" << endl;
        cerr << arr1 << arr2 << endl;
        return JsonDiff();
    }
#endif

    JsonDiff result;

    // TODO: this is a hack; fix it
    return JsonDiff(arr1, arr2);

    auto d = getDistances(arr1, arr2, debug, strict);

    int m = arr1.size(), n = arr2.size();

    int i = m - 1, j = n - 1;

    double totalDist = d[m][n].dist;

    if (debug) {
        cerr << "totalDist = " << totalDist << endl;
    }

    while (i >= 0 || j >= 0) {
        ExcAssertLessEqual(d[i + 1][j + 1].dist, totalDist);

        if (debug) {
            if (/*arr1[i] != arr2[j] ||*/ true) {
                cerr << "i = " << i << " j = " << j;
                if (i >= 0)
                    cerr << " arr1[i] = " << arr1[i].toString();
                if (j >= 0)
                    cerr << " arr2[j] = " << arr2[j].toString();
                cerr << " dist1 "
                     << d[i + 1][j + 1].dist;
                if (i >= 0 && j >= 0)
                    cerr << " dist2 " << d[i][j].dist;
                cerr << (d[i + 1][j + 1].sub ? "sub " : "")
                     << (d[i + 1][j + 1].ins ? "ins " : "")
                     << (d[i + 1][j + 1].del ? "del " : "")
                     << endl;
            }
        }

        if (i >= 0 && j >= 0 && d[i + 1][j + 1].sub) {
            if (debug)
                cerr << "subst" << endl;

            ExcAssert(i >= 0);
            ExcAssert(j >= 0);
            // substitution
            result.elements.emplace_back(i, j,
                                         jsonDiff(arr1[i], arr2[j], strict));

            --i;
            --j;
        }
        else if (i == -1 || d[i + 1][j + 1].ins) {
            ExcAssert(j >= 0);
            if (debug)
                cerr << "ins" << endl;
            // insertion
            result.elements.emplace_back(i, j,
                                         JsonDiff(JsonDiff::deleted, arr2[j]));
            --j;
        }
        else if (j == -1 || d[i + 1][j + 1].del) {
            ExcAssert(i >= 0);
            if (debug)
                cerr << "del" << endl;
            // deletion
            result.elements.emplace_back(i, j,
                                         JsonDiff(arr1[i], JsonDiff::deleted));
            --i;
        }
        else {
            if (debug)
                cerr << "skip" << endl;

            ExcAssert(i >= 0);
            ExcAssert(j >= 0);
            if (arr1[i] != arr2[j]) {
                cerr << "arr1 = " << arr1 << endl;
                cerr << "arr2 = " << arr2 << endl;
            }
            ExcAssertEqual(arr1[i], arr2[j]);
            // No difference; nothing to do
            --i;
            --j;
        }

    }

    // They were backwards; put them in the right order
    std::reverse(result.elements.begin(), result.elements.end());

    if (debug) {
        cerr << "i = " << i << " j = " << j << endl;
    }

    ExcAssertEqual(i, -1);
    ExcAssertEqual(j, -1);

    return result; //JsonDiff(arr1, arr2);
}

JsonDiff
jsonDiff(const Json::Value & val1,
         const Json::Value & val2,
         bool strict)
{
    if (compareObjects(val1, val2, strict))
        return JsonDiff();  // no difference

    if (val1.type() == val2.type()) {
        switch (val1.type()) {
        case Json::objectValue:
            return jsonDiffObjects(val1, val2, strict);
        case Json::arrayValue:
            return jsonDiffArrays(val1, val2, strict);
        default:
            return JsonDiff(val1, val2);
        }
    }

    // Different types
    return JsonDiff(val1, val2);
}

std::pair<std::unique_ptr<Json::Value>, JsonDiff>
jsonPatch(const Json::Value * val,
          const JsonDiff & diff)
{
    std::unique_ptr<Json::Value> patchedValue;
    JsonDiff conflicts;

    //cerr << "diff is = " << jsonEncodeStr(diff) << endl;

    // No differences; return what we were passed in
    if (!diff) {
        if (val)
            patchedValue.reset(new Json::Value(*val));
    }
    else if (diff.elements.size()) {
        // Array
#if 1
        if (!val || !val->isArray())
            conflicts = diff;
        else {
            cerr << endl;
            cerr << "diff is " << diff << endl;
            cerr << "array patch with " << diff.elements.size()
                 << " elements" << endl;

            std::vector<Json::Value> newVals(val->begin(), val->end());

            for (auto it = diff.elements.rbegin();  it != diff.elements.rend();
                 ++it) {

                cerr << "applying patch: oldEl = " << it->oldEl
                     << " newEl = " << it->newEl << endl;

                const JsonDiff & eldiff = *it;

                if (!eldiff.oldValue) {
                    ExcAssert(eldiff.newValue);

                    int pos = it->newEl;
                    if (pos == -1) {
                        // insert at end
                        newVals.insert(newVals.end(), *eldiff.newValue);
                    }
                    else if (pos < 0 || pos > newVals.size()) {
                        cerr << "*** insert conflict at " << pos << endl;
                        conflicts.elements.push_back(*it);
                    }
                    else {
                        newVals.insert(newVals.begin() + pos,
                                       *eldiff.newValue);
                    }
                }
                else if (!eldiff.newValue) {
                    // erased

                    int pos = it->oldEl;

                    ExcAssert(eldiff.oldValue);
                    if (pos < 0 || pos >= newVals.size()
                        || newVals[pos] != *eldiff.oldValue) {
                        cerr << "*** erase conflict at " << pos << endl;
                        conflicts.elements.push_back(*it);
                    }
                    else {
                        newVals.erase(newVals.begin() + pos);
                    }
                }
                else {
                    // modified

                    int pos = it->oldEl;

                    if (pos < 0 || pos >= newVals.size()) {
                        cerr << "*** modify conflict at " << pos << endl;
                        conflicts.elements.push_back(*it);
                    }
                    else {
                        std::unique_ptr<Json::Value> newVal;
                        JsonDiff elConflicts;

                        std::tie(newVal, elConflicts)
                            = jsonPatch(&newVals[pos], eldiff);
                        if (newVal)
                            newVals[pos] = std::move(*newVal);
                        if (elConflicts)  {
                            conflicts.elements.emplace_back(it->oldEl, it->newEl, std::move(elConflicts));
                            cerr << "*** patch conflict at " << pos << endl;
                            cerr << "newVals[pos] = " << newVals[pos] << endl;
                            cerr << "eldiff = " << eldiff << endl;
                        }
                    }
                }
            }

            patchedValue.reset(new Json::Value(newVals.begin(), newVals.end()));
            std::reverse(conflicts.elements.begin(), conflicts.elements.end());
#else
        if (!val || !val->isArray()) {
            cerr << "dest val is nil or not an array\n";
            conflicts = diff;
        }
        else {
            patchedValue.reset(new Json::Value(*val));

            for (auto & f: diff.elements) {
                if (f.second.newValue) {
                    if (f.second.oldValue) {
                        // cerr << "value replacement\n";
                        const Json::Value * current = nullptr;
                        if (val->isValidIndex(f.first)) {
                            current = &(*val)[f.first];
                        }
                        else {
                            throw MLDB::Exception("element does not exist");
                        }

                        JsonDiff fieldConflicts;
                        std::unique_ptr<Json::Value> newVal;

                        std::tie(newVal, fieldConflicts)
                            = jsonPatch(current, f.second);
                        if (fieldConflicts)
                            conflicts.elements[f.first] = fieldConflicts;
                        (*patchedValue)[f.first].swap(*newVal);
                    }
                    else {
                        // cerr << "value insertion/addition\n";
                        size_t oldSize = patchedValue->size();
                        size_t newSize = oldSize + 1;
                        patchedValue->resize(newSize);
                        if (patchedValue->isValidIndex(f.first)) {
                            /* first, shift the remaining elements */
                            for (size_t i = newSize - 1; i > f.first; i--) {
                                (*patchedValue)[i] = move((*patchedValue)[i-1]);
                            }
                        }
                        else if (f.first > oldSize) {
                            throw MLDB::Exception("index " + to_string(f.first)
                                                + " is invalid");
                        }
                        (*patchedValue)[f.first] = *f.second.newValue;
                    }
                }
                else {
                    // cerr << "f.first: " << f.first
                    //      << "; f.second: " << f.second
                    //      << "; f.second.oldValue: " << *f.second.oldValue
                    //      << endl;
                    if (val->isValidIndex(f.first)
                        && (*val)[f.first] == *f.second.oldValue) {
                        size_t newSize = patchedValue->size() - 1;
                        for (int i = f.first; i < newSize; i++) {
                            (*patchedValue)[i] = move((*patchedValue)[i+1]);
                        }
                        patchedValue->resize(newSize);
                    }
                    else {
                        conflicts.elements[f.first] = f.second;
                    }
                }
            }
#endif
        }
    }
    else if (diff.fields.size()) {
        // Object
        if (!val || !val->isObject())
            conflicts = diff;
        else {
            patchedValue.reset(new Json::Value(*val));

            //cerr << "starting object: " << jsonEncodeStr(*patchedValue)
            //     << endl;

            for (auto & f: diff.fields) {
                const Json::Value * current = 0;
                if (val->isMember(f.first))
                    current = &(*val)[f.first];

                JsonDiff fieldConflicts;
                std::unique_ptr<Json::Value> newVal;

                //cerr << "field " << f.first << " " << jsonEncodeStr(f.second)
                //     << " newVal "
                //     << (newVal ? *newVal: "<null>") << endl;

                std::tie(newVal, fieldConflicts)
                    = jsonPatch(current, f.second);

                if (fieldConflicts)
                    conflicts.fields[f.first] = fieldConflicts;

                if (newVal && current)
                    (*patchedValue)[f.first].swap(*newVal);
                else if (newVal)
                    (*patchedValue)[f.first] = std::move(*newVal);
                else {
                    patchedValue->removeMember(f.first);
                }
            }
            //cerr << "finished object: " << jsonEncodeStr(*patchedValue)
            //     << endl;
        }

    }
    else if (diff.oldValue) {
        // There was an old value; if it matches we replace with the new
        // value
        if (val && *diff.oldValue == *val) {
            // It matches.  Is there a new value, or should we erase it
            // completely?
            if (diff.newValue) {
                // has a new value
                patchedValue.reset(new Json::Value(*diff.newValue));
            }
        }
        // TODO: Already applied?
        else {
            conflicts = diff;
        }
    }
    else if (diff.newValue) {
        // There was no old value but a new value.  Check that there is
        // no current value.
        if (val) {
            // There was an old value.  This is a conflict.
            // TODO: Already applied
            conflicts = diff;
        }
        else {
            // There was no old value either.  Becomes a new value
            patchedValue.reset(new Json::Value(*diff.newValue));
        }
    }
    else {
        throw MLDB::Exception("logic error");
    }

    return make_pair(std::move(patchedValue), std::move(conflicts));
}

/*****************************************************************************/
/* JSON DIFF DESCRIPTION                                                     */
/*****************************************************************************/

DEFINE_STRUCTURE_DESCRIPTION(JsonArrayElementDiff);
DEFINE_STRUCTURE_DESCRIPTION(JsonDiff);

JsonDiffDescription::
JsonDiffDescription()
{
    addField("f", &JsonDiff::fields,
             "differences per-field");
    addField("el", &JsonDiff::elements,
             "differences per array element");
    addField("-", &JsonDiff::oldValue,
             "old (previous) value of this element");
    addField("+", &JsonDiff::newValue,
             "new (updated) value of this element");
}

std::ostream & operator << (std::ostream & stream, const JsonDiff & diff)
{
    return stream << jsonEncode(diff);
}

JsonArrayElementDiffDescription::
JsonArrayElementDiffDescription()
{
    addParent<JsonDiff>();
    addField("-idx", &JsonArrayElementDiff::oldEl,
             "Index of element in old array", -2);
    addField("+idx", &JsonArrayElementDiff::newEl,
             "Index of element in new array", -2);
}

} // namespace MLDB


text:
""" uses DSViewer to interact with molecules

"""
from rdkit import Chem
from win32com.client import Dispatch
import tempfile, os

_nextDisplayId = 1

class Displayable(object):

  def __init__(self, doc, id=-1):
    global _nextDisplayId
    if id < 0:
      id = _nextDisplayId
      _nextDisplayId += 1

    self.doc = doc
    self.id = id
    self.visible = True
    self.children = []

  def Select(self, atoms=[], state=True, recurse=False):
    if state:
      selText = 'true'
    else:
      selText = 'false'
    if not atoms or atoms == '*':
      atomStr = '; atom "*"'
    else:
      # DSViewer has atom ids from 1, we do it from 0:
      atoms = ['id=%d' % (x) for x in atoms]
      atomStr = '; atom %s' % ','.join(atoms)

    cmd = 'SetProperty object RD_Visual=%d %s: select=%s' % (self.id, atomStr, selText)
    r = int(str(self.doc.DoCommand(cmd)))
    if not r and not atoms:
      # this handles an annoying case where if you try to select
      # a molecule by ID in DSViewer, you get nothing selected:
      atomStr = ''
      cmd = 'SetProperty object RD_Visual=%d %s: select=%s' % (self.id, atomStr, selText)
      r = int(str(self.doc.DoCommand(cmd)))
    #print 'sel cmd:',cmd
    #print 'result:', r

    # stupid DSViewer will select the bonds between pairs of highlighted atoms,
    # stop that nonsense right now:
    if r:
      cmd = 'SetProperty object RD_Visual=%d; bond index="*": select=off' % (self.id)
      self.doc.DoCommand(cmd)

    if recurse:
      for child in self.children:
        child.Select(atoms=atoms, state=state, recurse=True)
    return r

  def Hide(self, recurse=True):
    self.Select(state=True, recurse=True)
    self.doc.DoCommand('hide')
    self.Select(state=False, recurse=True)

  def Show(self, recurse=True):
    self.Select(state=True, recurse=True)
    self.doc.DoCommand('Show')
    self.Select(state=False, recurse=True)

  def ShowOnly(self, recurse=True):
    self.doc.DoCommand('HideAll')
    self.Select(state=True, recurse=True)
    self.doc.DoCommand('Show')
    self.Select(state=False, recurse=True)

  def __del__(self):
    self.doc.DoCommand('UnselectAll')
    count = self.Select(state=True, recurse=True)
    if count:
      self.doc.DoCommand('Delete')

class MolViewer(object):

  def __init__(self, force=0, title='Untitled', **kwargs):
    self.app = Dispatch('WebLabViewerPro.Application')
    self.app.Visible = 1
    if force or self.app.ActiveDocument is None:
      self.doc = self.app.New(title)
    else:
      self.doc = self.app.ActiveDocument

    self.displayables = {}

  def DeleteAll(self):
    self.doc.DoCommand('SelectAll')
    self.doc.DoCommand('Delete')
    self.displayables = {}

  def DeleteAllExcept(self, excludes):
    excludes = [x.lower() for x in excludes]
    allNames = self.displayables.keys()
    for nm in allNames:
      if nm not in excludes:
        del self.displayables[nm]

  def ShowMol(self, mol, name='molecule', showOnly=True, highlightFeatures=[], molB="", confId=-1,
              zoom=True):
    if showOnly:
      self.DeleteAll()
      obj = None
    else:
      obj = self.displayables.get(name.lower(), None)
      #if obj:
      #  obj.Select(state=True)
      #  self.doc.DoCommand('Delete')
      #  obj.Select(state=False)

    if not molB:
      molB = Chem.MolToMolBlock(mol, confId=confId)

    tmp = name + "\n" + molB[molB.index('\n') + 1:]
    molB = tmp

    if not obj:
      obj = Displayable(self.doc)
    if not hasattr(obj, '_molBlock') or obj._molBlock != molB:
      obj._molBlock = molB
      fN = tempfile.mktemp('.mol')
      open(fN, 'w+').write(molB)
      self.doc.DoCommand('PasteFrom %s' % fN)
      self.doc.DoCommand('SetProperty molecule id=0 : RD_Visual=%d' % (obj.id))
      self.doc.DoCommand('SetProperty molecule id=0 : id=%d' % (obj.id))
      self.doc.DoCommand('SetProperty molecule id=0 : select=off')
      os.unlink(fN)
    else:
      obj.Select(state=True)
      self.doc.DoCommand('Show')

    self.displayables[name.lower()] = obj

    if zoom:
      self.doc.DoCommand('Center')
      self.doc.DoCommand('FitView')

    return

  def LoadFile(self, filename, name, showOnly=False):
    if showOnly:
      self.DeleteAll()
    self.doc.DoCommand('PasteFrom %s' % filename)
    obj = Displayable(self.doc)
    self.doc.DoCommand('SetProperty molecule id=0 : id=%d' % (obj.id))
    self.doc.DoCommand('SetProperty molecule id=0 : select=off')
    count = self.doc.DoCommand('SetProperty AminoAcidChain id=0 : RD_Visual=%d' % (obj.id))
    if not count or int(count) <= 0:
      count = self.doc.DoCommand('SetProperty molecule id=0 : RD_Visual=%d' % (obj.id))
    self.displayables[name.lower()] = obj
    return obj

  def GetSelectedAtoms(self, whichSelection=''):
    #print 'WHICH',repr(whichSelection),self.displayables.has_key(whichSelection.lower())
    if not whichSelection:
      d = str(self.doc.DoCommand('GetPropertyValue atom select=true: id=?'))
      d2 = str(self.doc.DoCommand('GetPropertyValue atom select=true: molecule=?'))
      if d2:
        molIds = []
        tmpD = {}
        for id in d2.split(','):
          id = int(id.split('/')[1]) + 1
          if tmpD.has_key(id):
            molIds.append(tmpD[id])
          else:
            for k, v in self.displayables.iteritems():
              if id == v.id:
                tmpD[id] = k
                molIds.append(k)
      else:
        molIds = [''] * (d.count(',') + 1)
    elif self.displayables.has_key(whichSelection.lower()):
      whichSelection = whichSelection.lower()
      whichSelection = self.displayables[whichSelection].id
      d = str(
        self.doc.DoCommand('GetPropertyValue molecule RD_Visual=%d; atom select=true: id=?' %
                           whichSelection))
      molIds = [whichSelection] * (d.count(',') + 1)
    else:
      d = None
      molIds = None

    if d:
      splitD = d.split(',')
      #print 'splitD:',splitD
      #print 'molIds:',molIds
      try:
        res = []
        for i in range(len(splitD)):
          # DSViewer has atom ids from 1, we do it from 0:
          idx = int(splitD[i])
          res.append((molIds[i], idx))
      except Exception:
        import traceback
        traceback.print_exc()
        res = []
    else:
      res = []
    return res

  def HighlightAtoms(self, indices, where, extraHighlight=False):
    self.doc.DoCommand('UnSelectAll')
    self.SelectAtoms(where, indices)

  def SelectAtoms(self, itemId, atomIndices, selName='selection'):
    self.doc.DoCommand('UnSelectAll')
    self.doc.DoCommand('SetProperty atom id="*": select=off')
    o = self.displayables.get(itemId.lower(), None)
    #print 'O:',itemId,atomIndices
    if o:
      o.Select(atoms=atomIndices)

  def SetDisplayUpdate(self, val):
    if not val:
      self.doc.DoCommand('UpdateView off')
    else:
      self.doc.DoCommand('UpdateView on')

  def GetAtomCoords(self, sels):
    res = {}
    for label, idx in sels:
      whichSelection = label.lower()
      whichSelection = self.displayables[label].id
      # DSViewer has atom ids from 1, we do it from 0:
      idx += 1
      cmd = 'GetPropertyValue molecule RD_Visual=%d; atom id=%d: xyz=?' % (whichSelection, idx)
      coords = self.doc.DoCommand(cmd)
      coords = [float(x) for x in coords.split(' ')]
      res[(label, idx)] = coords
      #print 'grab:',label,idx,coords
    return res

  def AddPharmacophore(self, locs, colors, label, sphereRad=0.5):
    label = label.lower()
    self.SetDisplayUpdate(False)
    parent = Displayable(self.doc)
    for i, loc in enumerate(locs):
      color = colors[i]
      color = ' '.join([str(int(255 * x)) for x in color])
      obj = Displayable(self.doc)
      nm = 'sphere-%d' % obj.id
      self.doc.DoCommand('Sphere %s' % nm)
      self.doc.DoCommand('SetProperty Object name=%s : xyz=%f %f %f' % (nm, loc[0], loc[1], loc[2]))
      self.doc.DoCommand('SetProperty Object name=%s : radius=%f' % (nm, sphereRad))
      self.doc.DoCommand('SetProperty Object name=%s : color=%s' % (nm, color))
      self.doc.DoCommand('SetProperty Object name=%s : RD_Visual=%d' % (nm, parent.id))
      self.doc.DoCommand('SetProperty Object name=%s : id=%d' % (nm, parent.id))
      #parent.children.append(obj)
    self.displayables[label] = parent
    self.SetDisplayUpdate(True)

  def SetDisplayStyle(self, obj, style=''):
    self.doc.DoCommand('UnSelectAll')
    obj = obj.lower()
    o = self.displayables.get(obj, None)
    if o:
      o.Select(state=True)
      if style == 'sticks':
        self.doc.DoCommand('DisplayStyle Atom Stick')
      elif style == 'lines':
        self.doc.DoCommand('DisplayStyle Atom Line')
      elif style == '':
        self.doc.DoCommand('DisplayStyle Atom Off')
      o.Select(state=False)

  def HideAll(self):
    self.doc.DoCommand('HideAll')

  def HideObject(self, objName):
    self.doc.DoCommand('UnSelectAll')
    objName = objName.lower()
    o = self.displayables.get(objName, None)
    if o:
      o.Hide()

  def DisplayObject(self, objName):
    self.doc.DoCommand('UnSelectAll')
    objName = objName.lower()
    o = self.displayables.get(objName, None)
    if o:
      o.Show()

  def Zoom(self, objName):
    self.doc.DoCommand('UnSelectAll')
    objName = objName.lower()
    o = self.displayables.get(objName, None)
    if o:
      r = o.Select(state=True)
      self.doc.DoCommand('Center')
      self.doc.DoCommand('FitView')
      o.Select(state=False)

  def SelectProteinNeighborhood(self, aroundObj, inObj, distance=5.0, name='neighborhood',
                                showSurface=False):
    """ FIX: the surface display stuff here is all screwed up due to
    differences between the way PyMol and DSViewer handle surfaces.
    In PyMol they are essentially a display mode for the protein, so
    they don't need to be managed separately.
    In DSViewer, on the other hand, the surface is attached to the
    protein, but it needs to be hidden or shown on its own.  I haven't
    figured out how to do that yet.
    """
    self.doc.DoCommand('UnSelectAll')
    o = self.displayables.get(aroundObj.lower(), None)
    p = self.displayables.get(inObj.lower(), None)
    if o and p:
      self.SetDisplayUpdate(False)
      p.Show()
      self.doc.DoCommand('UnSelectAll')
      tmp = self.doc.DoCommand('SetProperty object RD_Visual=%d;object id="*":select=on' % o.id)
      tmp = self.doc.DoCommand('SelectByRadius inside %f atom' % distance)
      # that selects all atoms in the radius, now we need to make sure
      #  only atoms in _inObj_ are selected:
      for obj in self.displayables.values():
        if obj.id != p.id:
          self.doc.DoCommand('SetProperty object RD_Visual=%d;object id="*":select=off' % obj.id)

      # ----
      # now get all the residue names for the selected atoms:
      rs = self.doc.DoCommand('GetPropertyValue atom select=true: parent=?')
      if rs:
        rs = rs.split(',')
        residues = {}
        for r in rs:
          residues[r] = 1

        # and select each atom in those residues:
        parents = ','.join(['parent="%s"' % x for x in residues.keys()])
        cmd = 'SetProperty atom %s: select=on' % parents
        tmp = self.doc.DoCommand(cmd)
      if showSurface:
        # create the surface:
        self.doc.DoCommand('Surface')
        obj = Displayable(self.doc)
        self.displayables[name] = obj
        self.doc.DoCommand('SetProperty surface id="*":RD_Visual=%d' % obj.id)

        self.doc.DoCommand('UnSelectAll')

      self.SetDisplayUpdate(True)

  def Redraw(self):
    self.SetDisplayUpdate(True)

if __name__ == '__main__':
  from rdkit import Chem
  from rdkit.Chem import rdDistGeom, rdForceFieldHelpers

  m = Chem.MolFromSmiles('c1cccc2c1cccc2')
  rdDistGeom.EmbedMolecule(m)
  rdForceFieldHelpers.UFFOptimizeMolecule(m)

  s = MolViewer()
  s.ShowMol(m)

redpajama_set_name: RedPajamaGithub


text:
import {fromJS} from 'immutable'
import codexReducer from '../../../app/redux/reducers/codex-reducer'
import should from 'should'
import {
    FETCH_CODEX_STARTED,
    FETCH_CODEX_SUCCESS,
    FETCH_CODEX_FAILURE,
    SEARCH_CODEX_SUCCESS,
    SEARCH_CODEX_FAILURE,
} from '../../../app/redux/actions/action-types'

describe('codex reducer tests:', function() {

  describe('reducer receives the fetch started action:', function(){
    const currentState = fromJS({
        fetching: false,
        ready: false,
        fail: false,
        codexList: []
    })

    const result = codexReducer(currentState, {type: FETCH_CODEX_STARTED}).toJS()

    it('fetching field in resulting state should be true', function (){
      result.fetching.should.be.true()
    })

    it('fail field in resulting state should be false', function (){
      result.fail.should.be.false()
    })

    it('codex list in resulting state should be empty', function (){
      result.codexList.should.be.empty()
    })
  })

  describe('reducer receives the fetch success action:', function(){
    const currentState = fromJS({
        fetching: true,
        ready: false,
        fail: false,
        codexList: []
    })

    const result = codexReducer(currentState, {type: FETCH_CODEX_SUCCESS, result: [{},{}] }).toJS()

    it('fetching field in resulting state should be false', function (){
      result.fetching.should.be.false()
    })

    it('fail field in resulting state should be false', function (){
      result.fail.should.be.false()
    })

    it('codex result in resulting state should contain the result', function (){
      result.codexList.should.be.instanceof(Array)
    })

  })

  describe('reducer receives the fetch failure action:', function(){
      const currentState = fromJS({
          fetching: true,
          ready: false,
          fail: false,
          codexList: []
      })

      const result = codexReducer(currentState, {type: FETCH_CODEX_FAILURE}).toJS()

    it('fetching field in resulting state should be false', function (){
      result.fetching.should.be.false()
    })

    it('fail field in resulting state should be true', function (){
      result.fail.should.be.true()
    })

    it('codex result in resulting state should be empty', function (){
      result.codexList.should.be.empty()
    })
  })

  describe('reducer receives the search success action:', function(){
      const currentState = fromJS({
          fetching: false,
          ready: true,
          fail: false,
          codexList: [{},{},{}]
      })

      const result = codexReducer(currentState, {type: SEARCH_CODEX_SUCCESS, result: [{}]}).toJS()

    it('fail field in resulting state should be false', function (){
      result.fail.should.be.false()
    })

    it('codex result in resulting state should contain one item', function (){
      result.codexList.should.be.instanceof(Array).and.have.lengthOf(1)
    })
  })

  describe('reducer receives the search failure action:', function(){
      const currentState = fromJS({
          fetching: false,
          ready: true,
          fail: false,
          codexList: [{},{},{}]
      })

      const result = codexReducer(currentState, {type: SEARCH_CODEX_FAILURE, result: [{}]}).toJS()

    it('fail field in resulting state should be true', function (){
      result.fail.should.be.true()
    })
  })

})


text:
function EFFECT:Init(data)
	self.Ent = data:GetEntity()

	if not IsValid( self.Ent ) then
		self.Ent = nil
		return
	end

	if self.Ent:GetClass() == "unit_nw_entity" then
		self.count = 1
	else
		self.count = 2
	end

	self.Sc = data:GetScale()
	self.LifeTime = data:GetMagnitude()
	self.LifeTime = self.LifeTime and CurTime() + self.LifeTime or nil
	self.Mins = self.Ent:OBBMins()/2
	self.Maxs = self.Ent:OBBMaxs()/2
	self.Emitter = ParticleEmitter( self.Ent:GetPos() )
end

function EFFECT:Think( )
	if not self.Ent then return false end
	if not IsValid( self.Ent ) then self.Emitter:Finish() return false end
	if self.LifeTime and CurTime() > self.LifeTime then self.Emitter:Finish() return false end

	self.Size = math.Rand(4,8) * self.Sc

	local position = self.Ent:LocalToWorld(self.Ent:OBBCenter())
	position.z = self.Ent:GetPos().z

	for i = 1, self.count do
		local random = Vector(math.Rand(self.Mins.x or 0, 1), math.Rand(self.Mins.y or 0, 1), -self.Mins.z*2) +Vector(math.Rand(-1, self.Maxs.x or 0), math.Rand(-1, self.Maxs.y or 0), self.Mins.z*2)
		local particle = self.Emitter:Add("effects/fire_cloud1", position +random)

		particle:SetVelocity(Vector(math.Rand(-1,1),math.Rand(-1,1),math.Rand(1,10)))
		particle:SetDieTime( math.Rand(0.5,1) )
		particle:SetStartAlpha( math.Rand( 130, 150 ) )
		particle:SetEndAlpha(1)
		particle:SetStartSize( self.Size )
		particle:SetEndSize( 0 )
		particle:SetRoll( math.Rand( -95, 95 ) )
		particle:SetRollDelta( math.Rand( -0.1, 0.1 ) )
		particle:SetColor( math.Rand( 150, 255 ), math.Rand( 120, 150 ), 100 )
		particle:SetGravity(Vector(0, 0, 20))
	end

	return true
end

function EFFECT:Render()
end


text:
import re

from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib import admin
from django.forms import ModelForm, CharField, Textarea
from django.forms.models import ModelChoiceField, ModelMultipleChoiceField
from django.template.loader import render_to_string
from gcse.models import Label, Annotation, CustomSearchEngine, FacetItem
from ordered_model.admin import OrderedModelAdmin

class CustomSearchEngineForm(ModelForm):

    def clean_input_xml(self):
        # strip xml encoding so lxml is happy
        input_xml = self.cleaned_data["input_xml"]
        if not input_xml:
            return ""
        result = re.sub(r'<\?xml.*\?>\r?\n?', '', input_xml)
        return result

    class Meta:
        model = CustomSearchEngine

class CustomSearchEngineAdmin(admin.ModelAdmin):
    list_display = ('title', 'description', 'gid')
    save_on_top = True
    readonly_fields = ('output_xml', 'creator', 'created', 'modified')
    form = CustomSearchEngineForm

admin.site.register(CustomSearchEngine, CustomSearchEngineAdmin)

class LabelAdmin(admin.ModelAdmin):
    list_display = ('name', 'description', 'background', 'mode', 'weight', )
    list_filter = ('mode',)
    save_on_top = True

    class Meta:
        model = Label

admin.site.register(Label, LabelAdmin)

class AnnotationAdminForm(ModelForm):
    # Only allow non hidden fields to be selected as Labels
    labels = ModelMultipleChoiceField(Label.objects.filter(background=False))
    # Only allow hidden fields to be selected as Feed Labels
    feed_label = ModelChoiceField(Label.objects.filter(background=True), label='Feed Label')
    description = CharField(widget=Textarea(attrs={'rows':5, 'cols':60}), required=False)

    class Meta:
        model = Annotation

# class AnnotationModelAdmin(admin.ModelAdmin):
#     '''Provide a side by side editor for copying submitted Annotation fields to the active/parent Annotation.
#     Deletes delete the copy.'''
#     def change_view(self, request, object_id, extra_context=None):
#         updated = get_object_or_404(Annotation, pk=object_id)
#         active = updated.parent_version
#         if active:
#             # Edit the active Annotation and display the updated Annotation to copy from
#             object_id = str(active.id)
#             ModelForm = self.get_form(request, obj=updated)
#             if request.method == 'POST':
#                 # let the super class handle the save of the active annotation
#                 result = super(AnnotationModelAdmin, self).change_view(request, object_id, extra_context)
#                 if request.POST.has_key("_save_delete"):
#                     # active is saved. now delete the updated
#                     result = super(AnnotationModelAdmin, self).delete_view(request, str(updated.id), extra_context)
#                 # send the reply email to the submitter and owner using the object_id
#                 return HttpResponseRedirect(reverse('cse.admin_views.send_submission_reply', args=(object_id,)))
#             else: # GET of active with updated: add updated to context for rendering
#                 if not extra_context:
#                     extra_context = {}
#                 extra_context['sourceAnnotation'] = admin.helpers.AdminForm(ModelForm(instance=updated),
#                                                                             list(self.get_fieldsets(request)),
#                                                                             self.prepopulated_fields)
#         # change handling for non-updated annotations using GET and POST
#         return super(AnnotationModelAdmin, self).change_view(request, object_id, extra_context)

#class AnnotationAdmin(AnnotationModelAdmin):
class AnnotationAdmin(admin.ModelAdmin):
    list_display = ('comment', 'original_url', 'status', 'modified', 'created',)
    list_filter = ('status', 'labels', 'created', 'modified')
    search_fields = ['comment', 'about']
    save_on_top = True
#     form = AnnotationAdminForm

admin.site.register(Annotation, AnnotationAdmin)

class FacetItemAdmin(OrderedModelAdmin):
    list_display = ('title', 'move_up_down_links')

admin.site.register(FacetItem, FacetItemAdmin)


text:
import "./init";
// tslint:disable-next-line:ordered-imports
import { HttpClientModule } from "@angular/common/http";
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
import { MatMenuModule } from "@angular/material/menu";
import { BrowserModule, HammerModule } from "@angular/platform-browser";
import { NoopAnimationsModule } from "@angular/platform-browser/animations";
import { RouterModule, Routes } from "@angular/router";
import { ServiceWorkerModule } from "@angular/service-worker";
import { NgxGalleryModule } from "@kolkov/ngx-gallery";
import { ExternalHRefModule } from "@marco-eckstein/angular-lib-common";

import { environment } from "../environments/environment";

import { AppComponent } from "./app.component";
import { ConfigurationService } from "./configuration.service";
import { GeocoderService } from "./geocoder.service";
import { HammerProvider } from "./hammer-provider";
import { I18nProvider } from "./i18n-provider";
import { I18nService } from "./i18n.service";
import { LocalStorageService } from "./local-storage.service";
import { LocationService } from "./location.service";
import { OpeningTimesService } from "./opening-times.service";
import { AboutComponent } from "./pages/about/about.component";
import { GoogleMapComponent } from "./pages/main/google-map/google-map.component";
import { AddressComponent } from "./pages/main/info-box/address/address.component";
import { InfoBoxComponent } from "./pages/main/info-box/info-box.component";
import { ShareLinkComponent } from "./pages/main/info-box/share-link/share-link.component";
import { KilometerPipe } from "./pages/main/kilometer.pipe";
import { MainComponent } from "./pages/main/main.component";
import { ResultsListComponent } from "./pages/main/results-list/results-list.component";
import { GeolocationComponent } from "./pages/main/search/geolocation/geolocation.component";
import { PlaceSelectComponent } from "./pages/main/search/geolocation/place-select/place-select.component";
import { SearchComponent } from "./pages/main/search/search.component";
import { SortComponent } from "./pages/main/sort/sort.component";
import { StatisticsComponent } from "./pages/main/statistics/statistics.component";
import { SettingsComponent } from "./pages/settings/settings.component";
import { SearchService } from "./search.service";
import { HeaderComponent } from "./shared-components/header/header.component";
import { NewIndicatorComponent } from "./shared-components/new-indicator/new-indicator.component";
import { TextClearComponent } from "./shared-components/text-clear/text-clear.component";

const appRoutes: Routes = [
    { path: "gastro", component: MainComponent },
    { path: "shops", component: MainComponent },
    { path: "about", component: AboutComponent },
    { path: "settings", component: SettingsComponent },
    { path: "shopping", redirectTo: "shops" }, // Legacy
    { path: "**", redirectTo: "gastro" },
].filter(it => environment.shoppingLocationsUrl || !it.path.startsWith("shop"));

@NgModule({
    declarations: [
        AboutComponent,
        AddressComponent,
        AppComponent,
        GeolocationComponent,
        GoogleMapComponent,
        HeaderComponent,
        InfoBoxComponent,
        KilometerPipe,
        MainComponent,
        NewIndicatorComponent,
        PlaceSelectComponent,
        ResultsListComponent,
        SearchComponent,
        SettingsComponent,
        ShareLinkComponent,
        SortComponent,
        StatisticsComponent,
        TextClearComponent,
    ],
    imports: [
        BrowserModule,
        ExternalHRefModule.forRoot({
            isExternalHRef: isExternalHRef,
            externalHRefTargetDefaultsToBlank: true,
            safeBlankRelTokens: ["noopener"],
        }),
        FormsModule,
        HammerModule,
        HttpClientModule,
        MatMenuModule,
        NgxGalleryModule,
        RouterModule.forRoot(appRoutes),
        ServiceWorkerModule.register("./ngsw-worker.js", { enabled: environment.production }),
        NoopAnimationsModule,
    ],
    providers: [
        ConfigurationService,
        GeocoderService,
        HammerProvider,
        I18nProvider,
        I18nService,
        LocationService,
        LocalStorageService,
        OpeningTimesService,
        SearchService,
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

export function isExternalHRef(href: string): boolean {
    return href.startsWith("http://") || href.startsWith("https://");
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.XPath;

namespace Apprenda.Log4NetConnectorPolicy.WorkloadUpdate
{
    public class ConfigBindingRedirectUpdateService
    {
        private readonly string _path;
        private readonly BindingRedirectSettings _settings;
        private XDocument _document;
        private List<string> _messages;
        private XElement _configurationElement;

        /// <summary>
        /// When provided the path to a .Net app.config (including web.config),
        /// this service will attempt to probe for a binding redirect stanza,
        /// update it to add or update a redirection for a specified assembly
        /// to an specified version.
        /// </summary>
        public ConfigBindingRedirectUpdateService(string path, BindingRedirectSettings settings)
        {
            _path = path;
            _settings = settings;
        }

        public IEnumerable<string> Update()
        {
            _messages = new List<string>();

            if (!File.Exists(_path))
            {
                _messages.Add(string.Format("No configuration file was found at {0}", _path));
                return _messages;
            }
            LoadDocument();

            _configurationElement = _document.XPathSelectElement("//configuration");
            if (_configurationElement == null)
            {
                _messages.Add("Could not find root configuration element in application configuration file.");
                return _messages;
            }

            ConfigRuntimeBindingRedirectWorker.ModifyConfigurationElement(_configurationElement, _settings, _messages);
            if (!_messages.Any())
            {
                SaveDocument();
            }

            return _messages;
        }

        /// <summary>
        /// Attempt to load the configuration file
        /// </summary>
        private void LoadDocument()
        {
            try
            {
                _document = XDocument.Load(_path);
            }
            catch (Exception ex)
            {
                _messages.Add(ex.ToString());
            }
        }

        /// <summary>
        /// Save the configuration file.
        /// </summary>
        private void SaveDocument()
        {
            try
            {
                _document.Save(_path);
            }
            catch (Exception ex)
            {
                _messages.Add(ex.ToString());
            }
        }
    }
}


text:
from telemetry.page import action_runner as action_runner_module
from telemetry.page import test_expectations

class TestNotSupportedOnPlatformError(Exception):
  """PageTest Exception raised when a required feature is unavailable.

  The feature required to run the test could be part of the platform,
  hardware configuration, or browser.
  """

class MultiTabTestAppCrashError(Exception):
  """PageTest Exception raised after browser or tab crash for multi-tab tests.

  Used to abort the test rather than try to recover from an unknown state.
  """

class Failure(Exception):
  """PageTest Exception raised when an undesired but designed-for problem."""

class MeasurementFailure(Failure):
  """PageTest Exception raised when an undesired but designed-for problem."""

class PageTest(object):
  """A class styled on unittest.TestCase for creating page-specific tests.

  Test should override ValidateAndMeasurePage to perform test
  validation and page measurement as necessary.

     class BodyChildElementMeasurement(PageTest):
       def ValidateAndMeasurePage(self, page, tab, results):
         body_child_count = tab.EvaluateJavaScript(
             'document.body.children.length')
         results.AddValue(scalar.ScalarValue(
             page, 'body_children', 'count', body_child_count))

  Args:
    discard_first_run: Discard the first run of this page. This is
        usually used with page_repeat and pageset_repeat options.
  """

  def __init__(self,
               needs_browser_restart_after_each_page=False,
               discard_first_result=False,
               clear_cache_before_each_run=False):
    super(PageTest, self).__init__()

    self.options = None
    self._needs_browser_restart_after_each_page = (
        needs_browser_restart_after_each_page)
    self._discard_first_result = discard_first_result
    self._clear_cache_before_each_run = clear_cache_before_each_run
    self._close_tabs_before_run = True

  @property
  def is_multi_tab_test(self):
    """Returns True if the test opens multiple tabs.

    If the test overrides TabForPage, it is deemed a multi-tab test.
    Multi-tab tests do not retry after tab or browser crashes, whereas,
    single-tab tests too. That is because the state of multi-tab tests
    (e.g., how many tabs are open, etc.) is unknown after crashes.
    """
    return self.TabForPage.__func__ is not PageTest.TabForPage.__func__

  @property
  def discard_first_result(self):
    """When set to True, the first run of the test is discarded.  This is
    useful for cases where it's desirable to have some test resource cached so
    the first run of the test can warm things up. """
    return self._discard_first_result

  @discard_first_result.setter
  def discard_first_result(self, discard):
    self._discard_first_result = discard

  @property
  def clear_cache_before_each_run(self):
    """When set to True, the browser's disk and memory cache will be cleared
    before each run."""
    return self._clear_cache_before_each_run

  @property
  def close_tabs_before_run(self):
    """When set to True, all tabs are closed before running the test for the
    first time."""
    return self._close_tabs_before_run

  @close_tabs_before_run.setter
  def close_tabs_before_run(self, close_tabs):
    self._close_tabs_before_run = close_tabs

  def RestartBrowserBeforeEachPage(self):
    """ Should the browser be restarted for the page?

    This returns true if the test needs to unconditionally restart the
    browser for each page. It may be called before the browser is started.
    """
    return self._needs_browser_restart_after_each_page

  def StopBrowserAfterPage(self, browser, page):  # pylint: disable=W0613
    """Should the browser be stopped after the page is run?

    This is called after a page is run to decide whether the browser needs to
    be stopped to clean up its state. If it is stopped, then it will be
    restarted to run the next page.

    A test that overrides this can look at both the page and the browser to
    decide whether it needs to stop the browser.
    """
    return False

  def CustomizeBrowserOptions(self, options):
    """Override to add test-specific options to the BrowserOptions object"""

  def CustomizeBrowserOptionsForSinglePage(self, page, options):
    """Set options specific to the test and the given page.

    This will be called with the current page when the browser is (re)started.
    Changing options at this point only makes sense if the browser is being
    restarted for each page. Note that if page has a startup_url, the browser
    will always be restarted for each run.
    """
    if page.startup_url:
      options.browser_options.startup_url = page.startup_url

  def WillStartBrowser(self, platform):
    """Override to manipulate the browser environment before it launches."""

  def DidStartBrowser(self, browser):
    """Override to customize the browser right after it has launched."""

  def SetOptions(self, options):
    """Sets the BrowserFinderOptions instance to use."""
    self.options = options

  def DidRunTest(self, browser, results): # pylint: disable=W0613
    """Override to do operations after all page set(s) are completed.

    This will occur before the browser is torn down.
    """
    self.options = None

  def WillNavigateToPage(self, page, tab):
    """Override to do operations before the page is navigated, notably Telemetry
    will already have performed the following operations on the browser before
    calling this function:
    * Ensure only one tab is open.
    * Call WaitForDocumentReadyStateToComplete on the tab."""

  def DidNavigateToPage(self, page, tab):
    """Override to do operations right after the page is navigated and after
    all waiting for completion has occurred."""

  def WillRunActions(self, page, tab):
    """Override to do operations before running the actions on the page."""

  def DidRunActions(self, page, tab):
    """Override to do operations after running the actions on the page."""

  def CleanUpAfterPage(self, page, tab):
    """Called after the test run method was run, even if it failed."""

  def CreateExpectations(self, page_set):   # pylint: disable=W0613
    """Override to make this test generate its own expectations instead of
    any that may have been defined in the page set."""
    return test_expectations.TestExpectations()

  def TabForPage(self, page, browser):   # pylint: disable=W0613
    """Override to select a different tab for the page.  For instance, to
    create a new tab for every page, return browser.tabs.New()."""
    return browser.tabs[0]

  def ValidateAndMeasurePage(self, page, tab, results):
    """Override to check test assertions and perform measurement.

    When adding measurement results, call results.AddValue(...) for
    each result. Raise an exception or add a failure.FailureValue on
    failure. page_test.py also provides several base exception classes
    to use.

    Prefer metric value names that are in accordance with python
    variable style. e.g., metric_name. The name 'url' must not be used.

    Put together:
      def ValidateAndMeasurePage(self, page, tab, results):
        res = tab.EvaluateJavaScript('2+2')
        if res != 4:
          raise Exception('Oh, wow.')
        results.AddValue(scalar.ScalarValue(
            page, 'two_plus_two', 'count', res))

    Args:
      page: A telemetry.page.Page instance.
      tab: A telemetry.core.Tab instance.
      results: A telemetry.results.PageTestResults instance.
    """
    raise NotImplementedError

  def RunPage(self, page, tab, results):
    # Run actions.
    action_runner = action_runner_module.ActionRunner(
        tab, skip_waits=page.skip_waits)
    self.WillRunActions(page, tab)
    page.RunPageInteractions(action_runner)
    self.DidRunActions(page, tab)
    self.ValidateAndMeasurePage(page, tab, results)

  def RunNavigateSteps(self, page, tab):
    """Navigates the tab to the page URL attribute.

    Runs the 'navigate_steps' page attribute as a compound action.
    """
    action_runner = action_runner_module.ActionRunner(
        tab, skip_waits=page.skip_waits)
    page.RunNavigateSteps(action_runner)


text:
declare namespace GoogleAppsScript {
  namespace Appsactivity {
    namespace Collection {
      interface ActivitiesCollection {
        // Returns a list of activities visible to the current logged in user. Visible activities are determined by the visiblity settings of the object that was acted on, e.g. Drive files a user can see. An activity is a record of past events. Multiple events may be merged if they are similar. A request is scoped to activities from a given Google service using the source parameter.
        list(): Appsactivity.Schema.ListActivitiesResponse;
        // Returns a list of activities visible to the current logged in user. Visible activities are determined by the visiblity settings of the object that was acted on, e.g. Drive files a user can see. An activity is a record of past events. Multiple events may be merged if they are similar. A request is scoped to activities from a given Google service using the source parameter.
        list(optionalArgs: object): Appsactivity.Schema.ListActivitiesResponse;
      }
    }
    namespace Schema {
      interface Activity {
        combinedEvent?: Appsactivity.Schema.Event | undefined;
        singleEvents?: Appsactivity.Schema.Event[] | undefined;
      }
      interface Event {
        additionalEventTypes?: string[] | undefined;
        eventTimeMillis?: string | undefined;
        fromUserDeletion?: boolean | undefined;
        move?: Appsactivity.Schema.Move | undefined;
        permissionChanges?: Appsactivity.Schema.PermissionChange[] | undefined;
        primaryEventType?: string | undefined;
        rename?: Appsactivity.Schema.Rename | undefined;
        target?: Appsactivity.Schema.Target | undefined;
        user?: Appsactivity.Schema.User | undefined;
      }
      interface ListActivitiesResponse {
        activities?: Appsactivity.Schema.Activity[] | undefined;
        nextPageToken?: string | undefined;
      }
      interface Move {
        addedParents?: Appsactivity.Schema.Parent[] | undefined;
        removedParents?: Appsactivity.Schema.Parent[] | undefined;
      }
      interface Parent {
        id?: string | undefined;
        isRoot?: boolean | undefined;
        title?: string | undefined;
      }
      interface Permission {
        name?: string | undefined;
        permissionId?: string | undefined;
        role?: string | undefined;
        type?: string | undefined;
        user?: Appsactivity.Schema.User | undefined;
        withLink?: boolean | undefined;
      }
      interface PermissionChange {
        addedPermissions?: Appsactivity.Schema.Permission[] | undefined;
        removedPermissions?: Appsactivity.Schema.Permission[] | undefined;
      }
      interface Photo {
        url?: string | undefined;
      }
      interface Rename {
        newTitle?: string | undefined;
        oldTitle?: string | undefined;
      }
      interface Target {
        id?: string | undefined;
        mimeType?: string | undefined;
        name?: string | undefined;
      }
      interface User {
        isDeleted?: boolean | undefined;
        isMe?: boolean | undefined;
        name?: string | undefined;
        permissionId?: string | undefined;
        photo?: Appsactivity.Schema.Photo | undefined;
      }
    }
  }
  interface Appsactivity {
    Activities?: Appsactivity.Collection.ActivitiesCollection | undefined;
  }
}

declare var Appsactivity: GoogleAppsScript.Appsactivity;


text:
module Ttlv.Validator.Attributes ( uniqueIdentifier
                                 , name
                                 , objectType
                                 , cryptographicAlgorithm
                                 , cryptographicLength
                                 , cryptographicParameters
                                 , cryptographicDomainParameters
                                 , certificateType
                                 , certificateIdentifier
                                 , certificateSubject
                                 , certificateIssuer
                                 , digest
                                 , operationPolicyName
                                 , cryptographicUsageMask
                                 , leaseTime
                                 , usageLimits
                                 , state
                                 , initialDate
                                 , activationDate
                                 , processStartDate
                                 , protectStopDate
                                 , deactivationDate
                                 , destroyDate
                                 , compromiseOccurrenceDate
                                 , compromiseDate
                                 , revocationReason
                                 , archiveDate
                                 , objectGroup
                                 , link
                                 , applicationSpecificInfo
                                 , contactInformation
                                 , lastChangeDate
                                 , customAttribute
                                 , anyAttribute
                                 ) where

import           Control.Applicative       ((<|>))
import           Ttlv.Data
import qualified Ttlv.Tag                  as T
import           Ttlv.Validator.Structures
import           Ttlv.Validator.Types

uniqueIdentifier :: TtlvParser Ttlv
uniqueIdentifier = tag T.UniqueIdentifier <+>
                   tString

name :: TtlvParser Ttlv
name = tag T.Name <+>
       apply T.NameValue tString <+>
       apply T.NameType tEnum

objectType :: TtlvParser Ttlv
objectType = tag T.ObjectType <+>
             tEnum

cryptographicAlgorithm :: TtlvParser Ttlv
cryptographicAlgorithm = tag T.CryptographicAlgorithm <+>
                         tEnum

cryptographicLength :: TtlvParser Ttlv
cryptographicLength = tag T.CryptographicLength <+>
                      tInt

cryptographicParameters = tag T.CryptographicParameters <+>
                          optional T.BlockCipherMode tEnum <+>
                          optional T.PaddingMethod tEnum <+>
                          optional T.HashingAlgorithm tEnum <+>
                          optional T.KeyRoleType tEnum

cryptographicDomainParameters = tag T.CryptographicDomainParameters <+>
                                optional T.Qlength tInt <+>
                                optional T.RecommendedCurve tEnum

certificateType = tag T.CertificateType <+>
                  tEnum

certificateIdentifier = tag      T.CertificateIdentifier <+>
                        apply    T.Issuer tString <+>
                        optional T.SerialNumber tString

certificateSubject = tag   T.CertificateSubject <+>
                     apply T.CertificateSubjectDistinguishedName tString <+>
                     many  T.CertificateSubjectAlternativeName tString

certificateIssuer = tag   T.CertificateIssuer <+>
                    apply T.CertificateIssuerDistinguishedName tString <+>
                    many  T.CertificateIssuerAlternativeName tString

digest = tag T.Digest <+>
         apply T.HashingAlgorithm tEnum <+>
         apply T.DigestValue tByteString

operationPolicyName = tag T.OperationPolicyName <+>
                      tString

cryptographicUsageMask = tag T.CryptographicUsageMask <+>
                         tInt

leaseTime = tag T.LeaseTime <+>
            tInterval

usageLimits = tag T.UsageLimits <+>
              apply T.UsageLimitsTotal tLong <+>
              apply T.UsageLimitsCount tLong <+>
              apply T.UsageLimitsUnit tLong

state = tag T.State <+>
        tEnum

initialDate = tag T.InitialDate <+>
              tDateTime

activationDate = tag T.ActivationDate <+>
                 tDateTime

processStartDate = tag T.ProcessStartDate <+>
                   tDateTime

protectStopDate = tag T.ProcessStartDate <+>
                  tDateTime

deactivationDate = tag T.DeactivationDate <+>
                   tDateTime

destroyDate = tag T.DestroyDate <+>
              tDateTime

compromiseOccurrenceDate = tag T.CompromiseOccurrenceDate <+>
                           tDateTime

compromiseDate = tag T.CompromiseDate <+>
                 tDateTime

revocationReason = tag T.RevocationReason <+>
                   apply T.RevocationReasonCode tEnum <+>
                   optional T.RevocationMessage tString

archiveDate = tag T.ArchiveDate <+>
              tDateTime

objectGroup = tag T.ObjectGroup <+>
              tString

link = tag T.Link <+>
       apply T.LinkType tEnum <+>
       apply T.LinkedObjectIdentifier tString

applicationSpecificInfo = tag T.ApplicationSpecificInformation <+>
                          apply T.ApplicationNamespace tString <+>
                          apply T.ApplicationData tString

contactInformation = tag T.ContactInformation <+>
                     tString

lastChangeDate = tag T.LastChangeDate <+>
                 tDateTime

customAttribute = tag T.CustomAttribute <+>
                  ok -- TODO disallow sub-structures

-- any attribute
anyAttribute = uniqueIdentifier <|>
               name <|>
               objectType <|>
               cryptographicAlgorithm <|>
               cryptographicLength <|>
               cryptographicParameters <|>
               cryptographicDomainParameters <|>
               certificateType <|>
               certificateIdentifier <|>
               certificateSubject <|>
               certificateIssuer <|>
               digest <|>
               operationPolicyName <|>
               cryptographicUsageMask <|>
               leaseTime <|>
               usageLimits <|>
               state <|>
               initialDate <|>
               activationDate <|>
               processStartDate <|>
               protectStopDate <|>
               deactivationDate <|>
               destroyDate <|>
               compromiseOccurrenceDate <|>
               compromiseDate <|>
               revocationReason <|>
               archiveDate <|>
               objectGroup <|>
               link <|>
               applicationSpecificInfo <|>
               contactInformation <|>
               lastChangeDate <|>
               customAttribute


text:
{% extends "account/base.html" %}

{% load i18n %}
{% load uni_form_tags %}
{% load account_tags %}

{% block head_title %}{% trans "Password Reset" %}{% endblock %}

{% block body %}

{% trans "Password Reset" %}

    {% if user.is_authenticated %}

            {% trans "Note" %}:
            {% user_display user as user_display %}
            {% blocktrans %}you are already logged in as {{ user_display }}.{% endblocktrans %}

    {% endif %}

        {% blocktrans %}
            Forgotten your password? Enter your e-mail address below, and we'll
            send you an e-mail allowing you to reset it.
        {% endblocktrans %}

    <form method="POST" action="" class="uniForm">
        {% csrf_token %}
        <fieldset class="inlineLabels">
            {{ password_reset_form|as_uni_form }}

                 <input type="submit" value="{% trans "Reset my password" %}" />

        </fieldset>
    </form>

{% blocktrans %}If you have any trouble resetting your password, contact us at {{ CONTACT_EMAIL }}.{% endblocktrans %}

{% endblock %}

{% block extra_body %}

{% endblock %}


text:
import React, { Component } from 'react';

import Input from './fragments/Input';
import Button from './fragments/Button';

export default class Form extends Component {

    constructor(props) {
        super(props);
        this.state = {
            inputs: [],
            button: null
        }

    }

    componentDidMount() {
        this.setState({
            inputs: this.props.inputs.map((x, i) =>  <Input key={i} text={x.text} type={x.type} func={x.changeFunc} name={x.name} />),
            button: <Button text={this.props.button.text} type={this.props.button.type} func={this.props.button.submitFunc}/>
        });
    }

    render() {
        return (

{this.props.text}

            <form>
                {this.state.inputs}

                {this.state.button}
            </form>

                {this.props.link ? {this.props.link.text} : ''}

        );
    };
}


text:
require 'faker'

FactoryGirl.define do
  factory :assignment do |f|
    f.name {Faker::Name.name}
    f.loss_address {Faker::Address.street_address}
    f.loss_city {Faker::Address.city}
    f.loss_state {Faker::Address.state_abbr}
    f.loss_zip {Faker::Address.zip}
    f.policy_number {Faker::Code.isbn}
    f.date_of_loss {Faker::Date.between(7.days.ago, Date.today)}
    f.insurer_claim_number {Faker::Code.ean}
    f.client_id "1"
    f.archived false
  end
end


text:
#ifndef __HW_FLASH_CTRL_H__
#define __HW_FLASH_CTRL_H__

//*****************************************************************************
//
// The following are defines for the FLASH_CTRL register offsets.
//
//*****************************************************************************
#define FLASH_CTRL_FCTL         0x400D3008  // Flash control This register
                                            // provides control and monitoring
                                            // functions for the flash module.
#define FLASH_CTRL_FADDR        0x400D300C  // Flash address The register sets
                                            // the address to be written in
                                            // flash memory. See the bitfield
                                            // descriptions for formatting
                                            // information.
#define FLASH_CTRL_FWDATA       0x400D3010  // Flash data This register
                                            // contains the 32-bits of data to
                                            // be written to the flash location
                                            // selected in FADDR.
#define FLASH_CTRL_DIECFG0      0x400D3014  // These settings are a function
                                            // of the FLASH information page
                                            // bit settings, which are
                                            // programmed during production
                                            // test, and are subject for
                                            // specific configuration for
                                            // multiple device flavors of
                                            // cc2538.
#define FLASH_CTRL_DIECFG1      0x400D3018  // These settings are a function
                                            // of the FLASH information page
                                            // bit settings, which are
                                            // programmed during production
                                            // test, and are subject for
                                            // specific configuration for
                                            // multiple device flavors of
                                            // cc2538.
#define FLASH_CTRL_DIECFG2      0x400D301C  // These settings are a function
                                            // of the FLASH information page
                                            // bit settings, which are
                                            // programmed during production
                                            // test, and are subject for
                                            // specific configuration for
                                            // multiple device flavors of
                                            // cc2538. The DIE_*_REVISION
                                            // registers are an exeception to
                                            // this, as they are hardwired and
                                            // are not part of the FLASH
                                            // information page.

//*****************************************************************************
//
// The following are defines for the bit fields in the
// FLASH_CTRL_FCTL register.
//
//*****************************************************************************
#define FLASH_CTRL_FCTL_UPPER_PAGE_ACCESS \
                                0x00000200  // Lock bit for lock bit page 0:
                                            // Neither write nor erase not
                                            // allowed 1: Both write and erase
                                            // allowed

#define FLASH_CTRL_FCTL_UPPER_PAGE_ACCESS_M \
                                0x00000200
#define FLASH_CTRL_FCTL_UPPER_PAGE_ACCESS_S 9
#define FLASH_CTRL_FCTL_SEL_INFO_PAGE \
                                0x00000100  // Flash erase or write operation
                                            // on APB bus must assert this when
                                            // accessing the information page

#define FLASH_CTRL_FCTL_SEL_INFO_PAGE_M \
                                0x00000100
#define FLASH_CTRL_FCTL_SEL_INFO_PAGE_S 8
#define FLASH_CTRL_FCTL_BUSY    0x00000080  // Set when the WRITE or ERASE bit
                                            // is set; that is, when the flash
                                            // controller is busy
#define FLASH_CTRL_FCTL_BUSY_M  0x00000080
#define FLASH_CTRL_FCTL_BUSY_S  7
#define FLASH_CTRL_FCTL_FULL    0x00000040  // Write buffer full The CPU can
                                            // write to FWDATA when this bit is
                                            // 0 and WRITE is 1. This bit is
                                            // cleared when BUSY is cleared.
#define FLASH_CTRL_FCTL_FULL_M  0x00000040
#define FLASH_CTRL_FCTL_FULL_S  6
#define FLASH_CTRL_FCTL_ABORT   0x00000020  // Abort status This bit is set to
                                            // 1 when a write sequence or page
                                            // erase is aborted. An operation
                                            // is aborted when the accessed
                                            // page is locked. Cleared when a
                                            // write or page erase is started.
                                            // If a write operation times out
                                            // (because the FWDATA register is
                                            // not written fast enough), the
                                            // ABORT bit is not set even if the
                                            // page is locked. If a page erase
                                            // and a write operation are
                                            // started simultaneously, the
                                            // ABORT bit reflects the status of
                                            // the last write operation. For
                                            // example, if the page is locked
                                            // and the write times out, the
                                            // ABORT bit is not set because
                                            // only the write operation times
                                            // out.
#define FLASH_CTRL_FCTL_ABORT_M 0x00000020
#define FLASH_CTRL_FCTL_ABORT_S 5
#define FLASH_CTRL_FCTL_CM_M    0x0000000C  // Cache Mode Disabling the cache
                                            // increases the power consumption
                                            // and reduces performance.
                                            // Prefetching improves performance
                                            // at the expense of a potential
                                            // increase in power consumption.
                                            // Real-time mode provides
                                            // predictable flash read access
                                            // time, the execution time is
                                            // equal to cache disabled mode,
                                            // but the power consumption is
                                            // lower. 00: Cache disabled 01:
                                            // Cache enabled 10: Cache enabled,
                                            // with prefetch 11: Real-time mode
                                            // Note: The read value always
                                            // represents the current cache
                                            // mode. Writing a new cache mode
                                            // starts a cache mode change
                                            // request that does not take
                                            // effect until the controller is
                                            // ready. Writes to this register
                                            // are ignored if there is a
                                            // current cache change request in
                                            // progress.
#define FLASH_CTRL_FCTL_CM_S    2
#define FLASH_CTRL_FCTL_WRITE   0x00000002  // Write bit Start a write
                                            // sequence by setting this bit to
                                            // 1. Cleared by hardware when the
                                            // operation completes. Writes to
                                            // this bit are ignored when
                                            // FCTL.BUSY is 1. If FCTL.ERASE is
                                            // set simultaneously with this
                                            // bit, the erase operation is
                                            // started first, then the write is
                                            // started.
#define FLASH_CTRL_FCTL_WRITE_M 0x00000002
#define FLASH_CTRL_FCTL_WRITE_S 1
#define FLASH_CTRL_FCTL_ERASE   0x00000001  // Erase bit Start an erase
                                            // operation by setting this bit to
                                            // 1. Cleared by hardware when the
                                            // operation completes. Writes to
                                            // this bit are ignored when
                                            // FCTL.BUSY is 1. If FCTL.WRITE is
                                            // set simultaneously with this
                                            // bit, the erase operation is
                                            // started first, then the write is
                                            // started.
#define FLASH_CTRL_FCTL_ERASE_M 0x00000001
#define FLASH_CTRL_FCTL_ERASE_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the
// FLASH_CTRL_FADDR register.
//
//*****************************************************************************
#define FLASH_CTRL_FADDR_FADDR_M \
                                0x0001FFFF  // Bit number [16:9] selects one
                                            // of 256 pages for page erase. Bit
                                            // number [8:7] selects one of the
                                            // 4 row in a given page Bit number
                                            // [6:1] selects one of the 64-bit
                                            // wide locations in a give row.
                                            // Bit number [0] will select
                                            // upper/lower 32-bits in a given
                                            // 64-bit location - 64Kbytes -->
                                            // Bits [16:14] will always be 0. -
                                            // 128Kbytes --> Bits [16:15] will
                                            // always be 0. - 256Kbytes --> Bit
                                            // [16] will always be 0. -
                                            // 384/512Kbytes --> All bits
                                            // written and valid. Writes to
                                            // this register will be ignored
                                            // when any of FCTL.WRITE and
                                            // FCTL.ERASE is set. FADDR should
                                            // be written with byte addressable
                                            // location of the Flash to be
                                            // programmed. Read back value
                                            // always reflects a 32-bit aligned
                                            // address. When the register is
                                            // read back, the value that was
                                            // written to FADDR gets right
                                            // shift by 2 to indicate 32-bit
                                            // aligned address. In other words
                                            // lower 2 bits are discarded while
                                            // reading back the register. Out
                                            // of range address results in roll
                                            // over. There is no status signal
                                            // generated by flash controller to
                                            // indicate this. Firmware is
                                            // responsible to managing the
                                            // addresses correctly.

#define FLASH_CTRL_FADDR_FADDR_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the
// FLASH_CTRL_FWDATA register.
//
//*****************************************************************************
#define FLASH_CTRL_FWDATA_FWDATA_M \
                                0xFFFFFFFF  // 32-bit flash write data Writes
                                            // to this register are accepted
                                            // only during a flash write
                                            // sequence; that is, writes to
                                            // this register after having
                                            // written 1 to the FCTL.WRITE bit.
                                            // New 32-bit data is written only
                                            // if FCTL.FULL = 0.

#define FLASH_CTRL_FWDATA_FWDATA_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the
// FLASH_CTRL_DIECFG0 register.
//
//*****************************************************************************
#define FLASH_CTRL_DIECFG0_CHIPID_M \
                                0xFFFF0000  // Register copy of configuration
                                            // bits Three clock cycles after
                                            // reset is released, this bit
                                            // field is equal to the field with
                                            // the same name in the information
                                            // page.

#define FLASH_CTRL_DIECFG0_CHIPID_S 16
#define FLASH_CTRL_DIECFG0_CLK_SEL_GATE_EN_N \
                                0x00000400  // Register copy of configuration
                                            // bits Three clock cycles after
                                            // reset is released, this bit is
                                            // equal to the field with the same
                                            // name in the information page.

#define FLASH_CTRL_DIECFG0_CLK_SEL_GATE_EN_N_M \
                                0x00000400
#define FLASH_CTRL_DIECFG0_CLK_SEL_GATE_EN_N_S 10
#define FLASH_CTRL_DIECFG0_SRAM_SIZE_M \
                                0x00000380  // Register copy of configuration
                                            // bits Three clock cycles after
                                            // reset is released, this bit
                                            // field is equal to the field with
                                            // the same name in the information
                                            // page.

#define FLASH_CTRL_DIECFG0_SRAM_SIZE_S 7
#define FLASH_CTRL_DIECFG0_FLASH_SIZE_M \
                                0x00000070  // Register copy of configuration
                                            // bits Three clock cycles after
                                            // reset is released, this bit
                                            // field is equal to the field with
                                            // the same name in the information
                                            // page.

#define FLASH_CTRL_DIECFG0_FLASH_SIZE_S 4
#define FLASH_CTRL_DIECFG0_USB_ENABLE \
                                0x00000008  // Register copy of configuration
                                            // bits Three clock cycles after
                                            // reset is released, this bit is
                                            // equal to the field with the same
                                            // name in the information page.

#define FLASH_CTRL_DIECFG0_USB_ENABLE_M \
                                0x00000008
#define FLASH_CTRL_DIECFG0_USB_ENABLE_S 3
#define FLASH_CTRL_DIECFG0_MASS_ERASE_ENABLE \
                                0x00000004  // Register copy of configuration
                                            // bits Three clock cycles after
                                            // reset is released, this bit is
                                            // equal to the field with the same
                                            // name in the information page.

#define FLASH_CTRL_DIECFG0_MASS_ERASE_ENABLE_M \
                                0x00000004
#define FLASH_CTRL_DIECFG0_MASS_ERASE_ENABLE_S 2
#define FLASH_CTRL_DIECFG0_LOCK_FWT_N \
                                0x00000002  // Register copy of configuration
                                            // bits Three clock cycles after
                                            // reset is released, this bit is
                                            // equal to the field with the same
                                            // name in the information page.

#define FLASH_CTRL_DIECFG0_LOCK_FWT_N_M \
                                0x00000002
#define FLASH_CTRL_DIECFG0_LOCK_FWT_N_S 1
#define FLASH_CTRL_DIECFG0_LOCK_IP_N \
                                0x00000001  // Register copy of configuration
                                            // bits Three clock cycles after
                                            // reset is released, this bit is
                                            // equal to the field with the same
                                            // name in the information page.

#define FLASH_CTRL_DIECFG0_LOCK_IP_N_M \
                                0x00000001
#define FLASH_CTRL_DIECFG0_LOCK_IP_N_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the
// FLASH_CTRL_DIECFG1 register.
//
//*****************************************************************************
#define FLASH_CTRL_DIECFG1_I2C_EN \
                                0x01000000  // 1: I2C is enabled. 0: I2C is
                                            // permanently disabled.

#define FLASH_CTRL_DIECFG1_I2C_EN_M \
                                0x01000000
#define FLASH_CTRL_DIECFG1_I2C_EN_S 24
#define FLASH_CTRL_DIECFG1_UART1_EN \
                                0x00020000  // 1: UART1 is enabled. 0: UART1
                                            // is permanently disabled.

#define FLASH_CTRL_DIECFG1_UART1_EN_M \
                                0x00020000
#define FLASH_CTRL_DIECFG1_UART1_EN_S 17
#define FLASH_CTRL_DIECFG1_UART0_EN \
                                0x00010000  // 1: UART0 is enabled. 0: UART0
                                            // is permanently disabled.

#define FLASH_CTRL_DIECFG1_UART0_EN_M \
                                0x00010000
#define FLASH_CTRL_DIECFG1_UART0_EN_S 16
#define FLASH_CTRL_DIECFG1_SSI1_EN \
                                0x00000200  // 1: SSI1 is enabled. 0: SSI1 is
                                            // permanently disabled.

#define FLASH_CTRL_DIECFG1_SSI1_EN_M \
                                0x00000200
#define FLASH_CTRL_DIECFG1_SSI1_EN_S 9
#define FLASH_CTRL_DIECFG1_SSI0_EN \
                                0x00000100  // 1: SSI0 is enabled. 0: SSI0 is
                                            // permanently disabled.

#define FLASH_CTRL_DIECFG1_SSI0_EN_M \
                                0x00000100
#define FLASH_CTRL_DIECFG1_SSI0_EN_S 8
#define FLASH_CTRL_DIECFG1_GPTM3_EN \
                                0x00000008  // 1: GPTM3 is enabled. 0: GPTM3
                                            // is permanently disabled.

#define FLASH_CTRL_DIECFG1_GPTM3_EN_M \
                                0x00000008
#define FLASH_CTRL_DIECFG1_GPTM3_EN_S 3
#define FLASH_CTRL_DIECFG1_GPTM2_EN \
                                0x00000004  // 1: GPTM2 is enabled. 0: GPTM2
                                            // is permanently disabled.

#define FLASH_CTRL_DIECFG1_GPTM2_EN_M \
                                0x00000004
#define FLASH_CTRL_DIECFG1_GPTM2_EN_S 2
#define FLASH_CTRL_DIECFG1_GPTM1_EN \
                                0x00000002  // 1: GPTM1 is enabled. 0: GPTM1
                                            // is permanently disabled.

#define FLASH_CTRL_DIECFG1_GPTM1_EN_M \
                                0x00000002
#define FLASH_CTRL_DIECFG1_GPTM1_EN_S 1
#define FLASH_CTRL_DIECFG1_GPTM0_EN \
                                0x00000001  // 1: GPTM0 is enabled. 0: GPTM0
                                            // is permanently disabled.

#define FLASH_CTRL_DIECFG1_GPTM0_EN_M \
                                0x00000001
#define FLASH_CTRL_DIECFG1_GPTM0_EN_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the
// FLASH_CTRL_DIECFG2 register.
//
//*****************************************************************************
#define FLASH_CTRL_DIECFG2_DIE_MAJOR_REVISION_M \
                                0x0000F000  // Indicates the major revision
                                            // (all layer change) number for
                                            // the cc2538 0x0 - PG1.0 0x2 -
                                            // PG2.0

#define FLASH_CTRL_DIECFG2_DIE_MAJOR_REVISION_S 12
#define FLASH_CTRL_DIECFG2_DIE_MINOR_REVISION_M \
                                0x00000F00  // Indicates the minor revision
                                            // (metla layer only) number for
                                            // the cc2538 0x0 - PG1.0 or PG2.0

#define FLASH_CTRL_DIECFG2_DIE_MINOR_REVISION_S 8
#define FLASH_CTRL_DIECFG2_RF_CORE_EN \
                                0x00000004  // 1: RF_CORE is enabled. 0:
                                            // RF_CORE is permanently disabled.

#define FLASH_CTRL_DIECFG2_RF_CORE_EN_M \
                                0x00000004
#define FLASH_CTRL_DIECFG2_RF_CORE_EN_S 2
#define FLASH_CTRL_DIECFG2_AES_EN \
                                0x00000002  // 1: AES is enabled. 0: AES is
                                            // permanently disabled.

#define FLASH_CTRL_DIECFG2_AES_EN_M \
                                0x00000002
#define FLASH_CTRL_DIECFG2_AES_EN_S 1
#define FLASH_CTRL_DIECFG2_PKA_EN \
                                0x00000001  // 1: PKA is enabled. 0: PKA is
                                            // permanently disabled.

#define FLASH_CTRL_DIECFG2_PKA_EN_M \
                                0x00000001
#define FLASH_CTRL_DIECFG2_PKA_EN_S 0

#endif // __HW_FLASH_CTRL_H__