text:
import argparse
import io
import json
import logging
import os
import re
import sys
import threading
import time
import traceback
from queue import Empty, Queue

import arrow
import boto
import coloredlogs
import ruamel.yaml as yaml
from boto.s3.connection import OrdinaryCallingFormat
from jinja2 import Template
from plumbum import SshMachine, local
from plumbum.cmd import ssh  # pylint: disable=import-error
from plumbum.cmd import chmod, curl, rm, ssh_keygen, tar
from plumbum.commands.processes import ProcessExecutionError

LOGGER = logging.getLogger("third_party_ci")
dprint = LOGGER.debug
iprint = LOGGER.info
eprint = LOGGER.error

COND = {"QUIT": False, "ALL_EVENTS": False}

PATCH_QUEUE = Queue()

UPLOAD_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "upload_logs.sh")

DEVSTACK_FILE = os.path.join(
    os.path.dirname(os.path.abspath(__file__)), "devstack_up.py"
)

SUCCESS = 0
FAIL = 255
UNSTABLE = 254
BASE_URL = "http://stkci.daterainc.com.s3-website-us-west-2.amazonaws.com/"
LISTING_TEMPLATE = os.path.join(
    os.path.dirname(os.path.abspath(__file__)), "listing.j2"
)

def create_indexes(rootdir, ref_name):
    template = Template(open(LISTING_TEMPLATE).read())
    previous_subdir = None
    stripped_subdir = None
    back_dir = None
    for subdir, dirs, file_names in os.walk(rootdir):
        files = []

        if previous_subdir != subdir:
            stripped_subdir = subdir.replace(rootdir, "")

            back_dir = re.sub(r"\/\w+$", "", stripped_subdir)

        for directory in dirs:
            full_path = os.path.join(stripped_subdir, directory)
            f = {
                "name": directory,
                "type": "folder",
                "relpath": full_path.strip("/"),
                "topkey": ref_name,
                "dir": True,
            }
            files.append(f)

        for file_name in file_names:
            full_path = os.path.join(stripped_subdir, file_name)

            f = {
                "name": file_name,
                "type": "text",
                "topkey": ref_name,
                "relpath": full_path.strip("/"),
            }
            files.append(f)

        previous_subdir = subdir

        output = template.render(
            {
                "ref_name": ref_name,
                "back": back_dir.strip("/"),
                "files": files,
                "base_url": BASE_URL,
            }
        )

        index_file_path = os.path.join(subdir, "index.html")

        with open(index_file_path, "w") as fd:
            fd.write(output)

class ThirdParty:
    def __init__(
        self,
        project,
        ghost,
        guser,
        gport,
        gkeyfile,
        ci_name,
        aws_key_id,
        aws_secret_key,
        remote_bucket,
        upload=False,
        use_existing_devstack=False,
        nocleanup=False,
    ):
        self.project = project
        self.ci_name = ci_name
        self.upload = upload
        self.aws_key_id = aws_key_id
        self.aws_secret_key = aws_secret_key
        self.remote_results_bucket = remote_bucket
        self.use_existing_devstack = use_existing_devstack
        self.nocleanup = nocleanup

        self.ssh_gerrit = ssh[
            "-i", gkeyfile, "-p", gport, f"{guser}@{ghost}",
        ]

    def run_ci_on_patch(
        self,
        node_ip,
        username,
        password,
        cluster_ip,
        patchset,
        cinder_driver_version,
        glance_driver_version,
    ):
        """
        This will actually run the CI logic.  If post_failed is set to `False`,
        it will try again if it detects failure in the results.  This should
        hopefully decrease our false failure rate.
        """
        dprint("Running against: %s", patchset)

        # Remove any offending keys
        cmd = ssh_keygen["-R", node_ip]
        dprint(cmd)
        cmd()

        try:
            # Run tests on devstack
            local.python[
                DEVSTACK_FILE,
                cluster_ip,
                node_ip,
                username,
                password,
                "--patchset",
                patchset,
                "--only-update-drivers",
                "--glance-driver-version",
                "none",
                "--skip-tox",
                "--reimage-client" if not self.use_existing_devstack else None,
            ]()
        except ProcessExecutionError as error:
            eprint(
                "Devstack_up ran into an error. Still trying to figure out the"
                "results, but this should be fixed"
            )
            eprint(error.stdout)
            return UNSTABLE

        commit_id, success, log_location = self._upload_logs(
            node_ip, username, password, patchset
        )
        if self.upload:
            self._post_results(commit_id, success, log_location)
        if success:
            return SUCCESS
        else:
            return FAIL

    def _upload_logs(self, node_ip, username, password, patchset):
        patch_ref_name = os.environ.get(
            "GERRIT_PATCHSET_REVISION", patchset.replace("/", "-")
        )

        # Collect logs
        filename = f"{patch_ref_name}.tar.gz"
        tempfilename = f"/tmp/{filename}"
        tempfiledirectory = tempfilename.replace(".tar.gz", "")

        # Remove any offending keys
        cmd = ssh_keygen["-R", node_ip]
        dprint(cmd)
        cmd()

        dprint("SSHing: %s, %s, %s", node_ip, username, password)
        with SshMachine(node_ip, user=username, password=password) as devstack:
            devstack.upload(UPLOAD_FILE, "/tmp/upload_logs.sh")
            devstack["chmod"]("+x", "/tmp/upload_logs.sh")
            devstack["sudo"]("/tmp/upload_logs.sh", patch_ref_name)
            devstack.download(filename, tempfilename)

        # Analyze
        cmd = tar["-zxvf", tempfilename, "-C", "/tmp/"]
        dprint("Running: %s", cmd)
        cmd()

        create_indexes(tempfiledirectory, patch_ref_name)

        with io.open(f"{tempfiledirectory}/console.out.log") as f:
            logs = f.read()
            # Find the commit id
            match = re.search(r"^cinder_commit_id\s(?P<commit_id>.*)$", logs, re.M)
            if match:
                commit_id = match.group("commit_id")
                dprint("Commit ID: %s", commit_id)
            # Find failures
            success = re.search(r"Failed: 0", logs)
            if success:
                dprint("Success:")
            else:
                dprint("Failure:")

        # Upload logs
        self._boto_up_data(patch_ref_name)

        # Cleanup artifacts
        if not self.nocleanup:
            rm["-rf", tempfiledirectory]()

        log_location = "".join((BASE_URL, patch_ref_name, "/index.html"))
        return commit_id, success, log_location

    def _post_results(self, commit_id, success, log_location):
        dprint("Logs: %s", log_location)

        # Post results
        if success:
            msg = f"* {self.ci_name} {log_location} : SUCCESS "
            iprint("Gerrit results: %s", msg)
        else:
            msg = (
                f"* {self.ci_name} {log_location} : FAILURE \n"
                + f"You can rerun this CI by commenting run-Datera"
            )
            eprint("Gerrit results: %s", msg)
        cmd = self.ssh_gerrit[f"gerrit review -m '{msg}' {commit_id}"]
        dprint(" -- command: %s", cmd)
        cmd()

    def _boto_up_data(self, data):
        dprint("Uploading Data: %s", data)

        bucket = self._get_boto_bucket()
        key = boto.s3.key.Key(bucket)
        key.key = data
        key.set_contents_from_string("")
        key.set_acl("public-read")

        curdir = os.path.abspath(os.curdir)
        os.chdir("/tmp/")
        try:
            for subdir, _, files, in os.walk(data):
                for file in files:
                    path = os.path.join(subdir, file)
                    dprint("-- path: %s", path)
                    subkey = boto.s3.key.Key(bucket)
                    subkey.key = path
                    subkey.set_contents_from_filename(path)
                    subkey.set_acl("public-read")
        finally:
            os.chdir(curdir)

    def _get_boto_bucket(self):
        access_key = self.aws_key_id
        secret_key = self.aws_secret_key
        bucket_name = self.remote_results_bucket

        dprint("aws conf: %s, %s, %s", access_key, secret_key, bucket_name)

        conn = boto.s3.connect_to_region(
            "us-west-2",
            aws_access_key_id=access_key,
            aws_secret_access_key=secret_key,
            calling_format=OrdinaryCallingFormat(),
        )
        dprint("conn: %s", conn)
        bucket = conn.get_bucket(bucket_name)
        return bucket

    def purge_old_keys(self):
        bucket = self._get_boto_bucket()
        size = 0
        n = 0
        utc = arrow.utcnow()
        old = utc.shift(months=-4)
        for key in bucket.list(prefix="refs-"):
            if arrow.get(key.last_modified) < old:
                n += 1
                size += key.size
                dprint("Deleting key: %s", key.name)
                key.delete()
        dprint("Deleted %s keys with a total size of %s", n, size)

def watcher(third_party):
    def _helper():
        dprint("Cmd: %s", third_party.ssh_gerrit["gerrit stream-events"])
        for line in iter(
            third_party.ssh_gerrit["gerrit stream-events"].popen().stdout.readline, b""
        ):
            event = json.loads(line)
            if event["type"] == "comment-added":
                try:
                    comment = event["comment"]
                    author = event["author"]["username"]
                    project = event["change"]["project"]
                    patchSet = event["patchSet"]["ref"]
                    branch = event["change"]["branch"]
                except KeyError as err:
                    eprint("Error parsing event. Line: %s", line)
                    eprint(err)
                    continue
                if (
                    COND["ALL_EVENTS"]
                    or "Verified+2" in comment
                    or "Verified+1" in comment
                ):
                    iprint(
                        "project: %s | author: %s | patchSet: %s |"
                        "branch: %s | comment: %s",
                        project,
                        author,
                        patchSet,
                        branch,
                        comment[:25].replace("\n", " "),
                    )
                if "run-Datera" in comment:
                    iprint("Found manual patchset: %s", patchSet)
                    PATCH_QUEUE.put(patchSet)
                if (
                    author
                    and author.lower() == "zuul"
                    and project == "openstack/cinder"
                    and branch == "master"
                ):
                    if "Verified+2" in comment or "Verified+1" in comment:
                        iprint("Found patchset: %s", patchSet)
                        PATCH_QUEUE.put(patchSet)

    wt = threading.Thread(target=_helper, name="WatcherThread")
    wt.daemon = True
    iprint("Starting watcher")
    wt.start()

def runner(conf, third_party, upload):
    def _helper():
        # count = 0
        while True:
            patchref = None
            try:
                patchref = PATCH_QUEUE.get(block=False)
            except Empty:
                time.sleep(1.5)
                if COND["QUIT"]:
                    dprint("Cleaning up...")
                    break
                continue
            # count += 1
            # # Every 10 tests we'll reimage the box
            # if count % 10 == 0:
            #     reimage_datera()
            dprint("Starting CI on: %s", patchref)
            try:
                third_party.run_ci_on_patch(
                    # Read these from environment variables
                    conf["node_ip"],
                    conf["node_user"],
                    conf["node_password"],
                    conf["cluster_ip"],
                    patchref,
                    conf["cinder_driver_version"],
                    conf["glance_driver_version"],
                )
                iprint("Finished CI on: %s", patchref)
            except Exception:
                eprint("Exception occurred during CI run:")
                traceback.print_exc()
            PATCH_QUEUE.task_done()

    rt = threading.Thread(target=_helper, name="RunnerThread")
    iprint("Starting runner")
    rt.start()

def reimage_datera(cluster="tlx222s", train="3.0.PROD", build="3.1.5"):
    pxeboot = local["./pxeboot-from-build.sh"]

    curl["-O", f"http://releases.daterainc.com/{train}/{build}/pxeboot-from-build.sh"]()
    chmod["+x", "pxeboot-from-build.sh"]()
    pxeboot["-c", cluster, "-v", train, "-b", build]()

def parse_config_file(config_file):
    with io.open(config_file) as f:
        return yaml.safe_load(f)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("config")
    parser.add_argument("-u", "--upload", action="store_true")
    parser.add_argument("--upload-only", action="store_true")
    parser.add_argument("--use-existing-devstack", action="store_true")
    parser.add_argument("--single-run-patchset")
    parser.add_argument("--debug", action="store_true")
    parser.add_argument("--show-all-events", action="store_true")
    parser.add_argument("--no-cleanup", action="store_true")
    args = parser.parse_args()

    if args.debug:
        dprint("Running with DEBUG on")

    coloredlogs.install(
        level="DEBUG" if args.debug else "INFO",
        logger=LOGGER,
        fmt="%(asctime)s %(hostname)s %(name)s[%(threadName)s] "
        + "%(levelname)s %(message)s",
    )

    if args.show_all_events:
        COND["ALL_EVENTS"] = True

    if not os.path.exists(DEVSTACK_FILE):
        eprint("Missing required devstack_up.py file in current directory")

    conf = parse_config_file(args.config)

    # Remove any offending keys
    cmd = ssh_keygen["-R", conf["node_ip"]]
    dprint(cmd)
    cmd()

    third_party = ThirdParty(
        conf["project"],
        conf["host"],
        conf["username"],
        conf["port"],
        conf["gerrit_key"],
        conf["ci_name"],
        conf["aws_key_id"],
        conf["aws_secret_key"],
        conf["remote_results_bucket"],
        upload=args.upload,
        use_existing_devstack=args.use_existing_devstack,
        nocleanup=args.no_cleanup,
    )

    if args.single_run_patchset:
        return third_party.run_ci_on_patch(
            conf["node_ip"],
            conf["node_user"],
            conf["node_password"],
            conf["cluster_ip"],
            args.single_run_patchset,
            conf["cinder_driver_version"],
            conf["glance_driver_version"],
        )

    if args.upload_only:
        dprint(
            "SSHing: %s, %s, %s",
            conf["node_ip"],
            conf["node_user"],
            conf["node_password"],
        )
        with SshMachine(
            conf["node_ip"], user=conf["node_user"], password=conf["node_password"]
        ) as devstack:
            with devstack.cwd("/opt/stack/cinder"):
                head = devstack["git"]("rev-parse", "HEAD")

        dprint("head: %s", head)
        patchsets_json = third_party.ssh_gerrit(
            f"gerrit query {head} --patch-sets --format json"
        )
        patchset_line = json.loads(patchsets_json.split("\n")[0])
        if not "patchSets" in patchset_line:
            eprint("Could not retrieve patchsets for %s", head)
            dprint("Line: %s", patchset_line)
            return FAIL

        patchset = patchset_line["patchSets"][-1]["ref"]
        dprint("patchSet: %s", patchset)
        commit_id, success, log_location = third_party._upload_logs(
            conf["node_ip"], conf["node_user"], conf["node_password"], patchset
        )
        if args.upload:
            third_party._post_results(commit_id, success, log_location)
        dprint(head)
        dprint(patchset)
        if success:
            return SUCCESS
        else:
            return FAIL

    watcher(third_party)
    runner(conf, third_party, args.upload)

    while True:
        try:
            while True:
                time.sleep(0.2)
        except KeyboardInterrupt:
            if input("Do you really want to quit? [Y/n]: ") in {"Y", "y"}:
                COND["QUIT"] = True
                break
            continue

    return SUCCESS

if __name__ == "__main__":
    sys.exit(main())


text:
package common.base.adapters;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

/**
 * ******************(^_^)***********************

 * User: fee(QQ/WeiXin:1176610771)

 * Date: 2019/10/9

 * Time: 20:37

 *
DESC:
 * 关于多类型item view视图的 并且可选择item操作基类适配器
 *

 * ******************(^_^)***********************
 */
public abstract class BaseSelectableMultiItemQuickAdapter<T extends MultiItemEntity, VH extends BaseViewHolder>
                extends BaseMultiItemQuickAdapter<T, VH> implements ASelectableDelegate.ISelectableObserver<T>,
        ASelectableDelegate.ISelectOptions<T> {
    protected ASelectableDelegate<T> selectableDelegate;

    protected int curAdapterMode = MODE_NORMAL;

    /**
     * Same as QuickAdapter#QuickAdapter(Context,int) but with
     * some initialization data.
     *
     */
    public BaseSelectableMultiItemQuickAdapter() {
        super(null);
        selectableDelegate = new ASelectableDelegate<>();
        selectableDelegate.setSelectableObserver(this);
    }

    //----------------------------- @接口 ISelectableObserver 的基类可实行方法 start -----

    /**
     * 当有选择状态发生更改时,通知观察者数据发生了改变
     *
     * @param selectStateChangeItemPos 选中状态的更改的数据实体在受选数据集里的position,当为负数时,为全部刷新; 为>=0时
     *                                 表示仅position处的数据更改
     */
    @Override
    public void notifySelectDatasChanged(int selectStateChangeItemPos) {
        if (selectStateChangeItemPos < 0) {
            notifyDataChangedInVisibleScope();
        }
        else {
            refreshNotifyItemChanged(selectStateChangeItemPos);
        }
    }

    /**
     * 回调选中的数量,观察者自己可以再回调是否为全选
     *
     * @param selectedCount 选中的数量
     */
    @Override
    public void onSelected(int selectedCount) {
        if (chooseCallback != null) {
            boolean isAllSelected = selectedCount == getJustDataCount();
            if (selectedCount == 0) {
                isAllSelected = false;
            }
            chooseCallback.onSelected(this,selectedCount,isAllSelected);
        }
    }

    /**
     * 由观察者提供受选 的数据集数据
     *
     * @return 受选择的数据集
     */
    @Override
    public List<T> provideSelectSampleDatas() {
        return mData;
    }
    //----------------------------- @接口 ISelectableObserver 的基类可实行方法 end -----

    //----------------------------- @接口 ISelectOptions 的基类可实行方法 start -----

    /**
     * 操作之:判断形参数据是否被选中
     *
     * @param theItemData 要判断的数据
     * @return true:选中了;false:未选中
     */
    @Override
    public boolean isTheItemSelected(T theItemData) {
        if (selectableDelegate != null) {
            return selectableDelegate.isTheDataSelected(theItemData);
        }
        return false;
    }

    /**
     * 操作之:获取选中的惟一标识集
     *
     * @return 可标识选中的惟一的标识集
     */
    @Override
    public HashSet<Object> getSelectedUniqueMarks() {
        if (selectableDelegate != null) {
            selectableDelegate.getSelectedUniqueMarks();
        }
        return null;
    }

    /**
     * 操作之:挑出已经选中的数据
     *
     * @return 受选数据集里已经被标识为选中的数据集
     */
    @Override
    public List<T> pickOutSelectedDatas() {
        if (selectableDelegate != null) {
            selectableDelegate.pickOutSelectedDatas();
        }
        return null;
    }

    /**
     * 操作之:设置选中状态回调监听者
     *
     * @param selectStateListener 监听者
     */
    @Override
    public void setSelectStateListener(ASelectableDelegate.IChooseCallback selectStateListener) {
        this.chooseCallback = selectStateListener;
    }

    /**
     * 操作之:依惟一标识信息来标记选中或者取消选中状态
     *
     * @param isToSelectOrNot     true:选中;false:取消选中
     * @param itemDataUniqueMarks 可标记为选中状态的惟一标识集
     * @return true: 操作了;false: do nothing
     */
    @Override
    public boolean markSelectedOrNot(boolean isToSelectOrNot, Collection<Object> itemDataUniqueMarks) {
        if (selectableDelegate != null) {
            return selectableDelegate.markSelectedOrNot(isToSelectOrNot, itemDataUniqueMarks);
        }
        return false;
    }

    /**
     * 操作之:直接标记目标原数据集(受选数据集)为选中或者取消选中
     *
     * @param isToSelectOrNot true:选中;false:取消选中
     * @param itemDatas       受选数据集的原数据
     * @return true: 操作了;false: do nothing
     */
    @Override
    public boolean markItemDatasSelectedOrNot(boolean isToSelectOrNot, Collection<T> itemDatas) {
        if (selectableDelegate != null) {
            return selectableDelegate.markItemDatasSelectedOrNot(isToSelectOrNot, itemDatas);
        }
        return false;
    }

    /**
     * 操作之:依惟一标识来取消选中
     *
     * @param itemDataUniqueMark 可标志为选中状态的标识
     * @return true: 取消被选中生效;false:未操作
     */
    @Override
    public boolean markUnSelected(Object itemDataUniqueMark) {
        if (selectableDelegate != null) {
            return selectableDelegate.markUnSelected(itemDataUniqueMark);
        }
        return false;
    }

    /**
     * 操作之:依惟一标识来标志为选中
     *
     * @param itemDataUniqueMark 可标志为选中状态的标识
     * @return true:标记了;false:未操作
     */
    @Override
    public boolean markSelected(Object itemDataUniqueMark) {
        if (selectableDelegate != null) {
            return selectableDelegate.markSelected(itemDataUniqueMark);
        }
        return false;
    }

    /**
     * 操作之:直接对受选原数据标志为选中或者取消选中
     *
     * @param isSelectOrNot true:要选中;false:取消选中
     * @param itemData      受选原数据
     * @return true: 操作了; false: 未操作
     */
    @Override
    public boolean markItemDataSelectedOrNot(boolean isSelectOrNot, T itemData) {
        if (selectableDelegate != null) {
            return selectableDelegate.markItemDataSelectedOrNot(isSelectOrNot, itemData);
        }
        return false;
    }

    /**
     * 操作之:全选或者取消全选
     *
     * @param toSelectAll true: 要全选;false:取消全选
     */
    @Override
    public void selectAllOrCancelAll(boolean toSelectAll) {
        if (selectableDelegate != null) {
            selectableDelegate.selectAllOrCancelAll(toSelectAll);
        }
    }

    /**
     * 操作之: 受选数据集中某个position位置的数据点击了
     *
     * @param clickedPos 点击的位置
     * @return true:当前位置的item数据选中了; false:未选择/取消选中
     */
    @Override
    public boolean theItemClicked(int clickedPos) {
        if (selectableDelegate != null) {
            return selectableDelegate.willSelectTheItemData(clickedPos);
        }
        return false;
    }

    /**
     * 操作之:设置当前的选择模式
     *
     * @param adapterMode 单选;多选
     */
    @Override
    public void setCurSelectMode(int adapterMode) {
        if (selectableDelegate != null) {
            selectableDelegate.setCurSelectableMode(adapterMode);
        }
    }

    /**
     * 操作之:获取当前的选择模式
     *
     * @return 单选;多选
     */
    @Override
    public int getCurSelectMode() {
        return curAdapterMode;
    }

    /**
     * 操作之:清空已选择的惟一标识
     */
    @Override
    public void clearSelectedUniqMarks() {
        if (selectableDelegate != null) {
            selectableDelegate.clearSelectedUniqMarks();
        }
    }

    protected ASelectableDelegate.IChooseCallback chooseCallback;

    //----------------------------- @接口 ISelectOptions 的基类可实行方法 end -----
}

redpajama_set_name: RedPajamaGithub


text:
Variational least-squares part I
========================================================
autosize: true
incremental: true
width: 1920
height: 1080

 Instructions:

Use the left and right arrow keys to navigate the presentation forward and backward respectively.  You can also use the arrows at the bottom right of the screen to navigate with a mouse.

FAIR USE ACT DISCLAIMER:

This site is for educational purposes only.  This website may contain copyrighted material, the use of which has not been specifically authorized by the copyright holders. The material is made available on this website as a way to advance teaching, and copyright-protected materials are used to the extent necessary to make this class function in a distance learning environment.  The Fair Use Copyright Disclaimer is under section 107 of the Copyright Act of 1976, allowance is made for "fair use" for purposes such as criticism, comment, news reporting, teaching, scholarship, education and research.

========================================================

Outline

* The following topics will be covered in this lecture:
  * Linear least-squares estimation
  * Linear least-squares estimation and Newton's algorithm
  * Linear least-squares estimation and the square root Kalman filter

========================================================
## Motivation

* In the last two lectures, we saw a development of the classical Kalman filter from the standpoint of statistical estimation.

* Particularly, we made the connections between:

  * the minimum variance and maximum a posteriori estimators;
  * the Bayesian posterior and how the "optimal" estimate parameterizes this posterior; and
  * various boundedness, stability and practical considerations for this estimator in practice, with, e.g., unknown system parameters.

* While the statistical viewpoint is the one that we will focus on in this course, many of these ideas have a parallel development in optimization and optimal control theory.

* In the next two lectures, we will explore the connections between the classical Kalman filter and optimal statistical estimators and an optimal control development of the estimation problem.

* Particularly, we will see how the optimization of an objective function has a natural interpretation in the Gauss-Markov model.

* Furthermore, we will see how the optimization interpretation easily extends our analysis to scenarios including nonlinear estimation when, e.g., we are simultaneously estimating process model parameters.

========================================================
## Linear least-squares estimation

* Recall how we constructed the minimum variance estimator by minimizing the expected residual sum of squares,

  $$\begin{align}
  \text{RSS} = \hat{\pmb{\epsilon}}^\top \hat{\pmb{\epsilon}}
  \end{align}$$

* A related notion to minimizing the expected sum of squares is the linear least-squares problem.

Linear least-squares estimator

Let $\pmb{y}$ be a vector of observed data related to an input parameter $\pmb{x}$ via a linear map $\mathbf{H}$ such that
$$\begin{align}
\pmb{y} = \mathbf{H} \pmb{x} + \pmb{v}
\end{align}$$
where $\mathbb{E}\left[\pmb{v}\right]=\pmb{0}$ and $\mathrm{cov}(\pmb{v})=\mathbf{R}$.  The linear least-squares estimator $\hat{\pmb{x}}$ is the one satisfying the relationship
$$\begin{align}
\hat{\pmb{x}}:= \mathrm{argmin}_{\pmb{x}} \parallel \pmb{y} - \mathbf{H}\pmb{x} \parallel_{\mathbf{R}}^2
\end{align}$$

* This is to say, in a linear least-squares problem, we will try to:

  * minimize the square distance between the input function $\mathbf{H}\pmb{x}$; from

  * the observed data $\pmb{y}$; relative to

  * the distance implied by the inverse observation error covariance.

* The linear least-squares refers to the fact that $\mathbf{H}$ is a linear function relating the inputs to the data.

* Particularly, this means that the objective function is convex, so that the critical value is the unique minimizer.

========================================================
### Linear least-squares estimation

* Let's define the least-squares objective function as

  $$\begin{align}
  \mathcal{J}(\pmb{x})=\frac{1}{2} \parallel \pmb{y} - \mathbf{H}\pmb{x} \parallel_{\mathbf{R}}^2
  \end{align}$$

* Calculating the gradient of the objective function,

  $$\begin{align}
  \nabla_{\pmb{x}} \mathcal{J} &=  -\mathbf{H}^\top \mathbf{R}^{-1}\left(\pmb{y} - \mathbf{H}\pmb{x}\right),
  \end{align}$$

* and setting the gradient of the objective function equal to zero for $\hat{\pmb{x}}$,

  $$\begin{align}
  \mathbf{H}^\top\mathbf{R}^{-1}\mathbf{H}\hat{\pmb{x}}= \mathbf{H}^\top\mathbf{R}^{-1}\pmb{y}.
  \end{align}$$

* The above equations are known as the "normal equations" that define the generalized linear least-squares solution to the objective function.

* If we suppose that $\mathbf{H}$ has full column rank, then $\mathbf{H}^\top\mathbf{R}^{-1}\mathbf{H}$ is invertible, i.e.,

  $$\begin{align}
  \hat{\pmb{x}} = \left(\mathbf{H}^\top\mathbf{R}^{-1}\mathbf{H} \right)^{-1}\mathbf{H}\mathbf{R}^{-1}\pmb{y}.
  \end{align}$$

* Therefore, by the convexity of the objective function, we know that $\hat{\pmb{x}}$ as defined above is the global minimizer of the distance between any choice of input $\pmb{x}$ and the observed data $\pmb{y}$ in the distance relative to the inverse observation uncertainty.

========================================================
### Linear least-squares estimation

* Notice, the special case where $\mathbf{R}=\mathbf{I}$ gives,

  $$\begin{align}
  \hat{\pmb{x}} = \left(\mathbf{H}^\top\mathbf{H} \right)^{-1}\mathbf{H}^\top\pmb{y}= \mathbf{H}^\dagger \pmb{y}.
  \end{align}$$

* I.e., in the simple case where $\mathbf{R}=\mathbf{I}$, we see that the pseudo-inverse applied to the observation vector $\pmb{y}$ is indeed the optimal solution.

* This was discussed before in that this satisfies the orthogonal projection lemma, where

  $$\begin{align}
  \mathbf{H}\hat{\pmb{x}}&= \mathbf{H}\mathbf{H}^\dagger \pmb{y}
  \end{align}$$

  is precisely the orthogonal projection of the data into the column space of the observation operator $\mathbf{H}$.

* This approach above is extremely similar to the Kalman filter, though  differing in that this is a static estimation, invariant-in-time, and it doesn't utilize any background information on $\pmb{x}$.

* If we supposed that we had a good prior knowledge of what $\pmb{x}$ might look like without observed data,

  * or we had some region in which we would like to constrain a solution to,

* we can introduce an additional penalty term for the least-squares analysis.

* Suppose that we have a background solution which we will define in terms of $\overline{\pmb{x}}$, and a positive definite matrix $\mathbf{B}$ defining weights for the distance in how we measure $\pmb{x}$ deviating from $\overline{\pmb{x}}$.

========================================================
### Linear least-squares estimation

* With the background information on the last slide, a new, penalized objective function can be defined as

  $$\begin{align}
  \mathcal{J}_p(\pmb{x}) := \frac{1}{2} \parallel \pmb{x} - \overline{\pmb{x}}\parallel_{\mathbf{B}}^2 + \frac{1}{2} \parallel \pmb{y} - \mathbf{H}\pmb{x}\parallel_{\mathbf{R}}^2.
  \end{align}$$

* where, like in the Gaussian maximum a posteriori estimation, we estimate an optimal state as a balance between:

the deviation from the background estimate, weighted inverse proportionally to the uncertainty weights $\mathbf{B}$; and

the deviation from the observed data, weighted inverse proportionally to the uncertainty of the data $\mathbf{R}$.

* In order to simplify the analysis, let $\mathbf{B}:= \boldsymbol{\Sigma}\boldsymbol{\Sigma}^\top$ be a matrix factor such as a Cholesky decomposition or a symmetric SVD.

* Provided that $\mathbf{B}$ is full rank, we can equivalently write the problem in terms of a weight vector $\pmb{w}$ which will be defined by the relationship,

  $$\begin{align}
  \pmb{x} = \overline{\pmb{x}} + \boldsymbol{\Sigma} \pmb{w},
  \end{align}$$
  so that,

  * $\pmb{x}$ is written as a deviation from the base point $\overline{\pmb{x}}$;
  * in terms of a linear combination of the columns of the matrix factor $\boldsymbol{\Sigma}$.

* This renders the above objective function equivalently as,

  $$\begin{align}
  \mathcal{J}_w(\pmb{w}) := \frac{1}{2} \parallel \pmb{w}\parallel^2 + \frac{1}{2} \parallel \pmb{y} - \mathbf{H}\overline{\pmb{x}} - \mathbf{H}\boldsymbol{\Sigma}\pmb{w}\parallel_{\mathbf{R}}^2.
  \end{align}$$

========================================================
### Linear least-squares estimation

* Furthermore, let's define an uncertainty weighted innovation from the base-point as

  $$\begin{align}
  \overline{\pmb{\delta}} &:= \mathbf{R}^{-\frac{1}{2}}\left(\pmb{y} - \mathbf{H} \overline{\pmb{x}}\right).
  \end{align}$$

* Let $\boldsymbol{\Gamma}:= \mathbf{R}^{-\frac{1}{2}} \mathbf{H} \boldsymbol{\Sigma}$, then the objective function can be equivalently written entirely in terms of the weights as

  $$\begin{align}
  \mathcal{J}_w(\pmb{w}) := \frac{1}{2} \parallel \pmb{w}\parallel^2 + \frac{1}{2} \parallel \overline{\pmb{\delta}}- \boldsymbol{\Gamma}\pmb{w}\parallel^2.
  \end{align}$$

* Taking the gradient with respect to the weights,

  $$\begin{align}
  \nabla_{\pmb{w}} \mathcal{J}_w(\pmb{w}) = \pmb{w} - \boldsymbol{\Gamma}^\top \left( \overline{\pmb{\delta}}- \boldsymbol{\Gamma}\pmb{w}\right),
  \end{align}$$

* we will suppose that the gradient is zero at $\hat{\pmb{w}}$,

  $$\begin{align}
  &\pmb{0} = \hat{\pmb{w}} - \boldsymbol{\Gamma}^\top \left( \overline{\pmb{\delta}}- \boldsymbol{\Gamma}\hat{\pmb{w}}\right) \\
  \Leftrightarrow &\boldsymbol{\Gamma}^\top \overline{\pmb{\delta}} =  \left(\mathbf{I} + \boldsymbol{\Gamma}^\top\boldsymbol{\Gamma} \right)\hat{\pmb{w}} \\
  \Leftrightarrow &\hat{\pmb{w}} =  \left(\mathbf{I} + \boldsymbol{\Gamma}^\top\boldsymbol{\Gamma} \right)^{-1}\boldsymbol{\Gamma}^\top \overline{\pmb{\delta}}.
  \end{align}$$

========================================================
### Linear least-squares estimation

* From the last slide, this optimal set of weights tells us that

  $$\begin{align}
  \hat{\pmb{x}} &= \overline{\pmb{x}} + \boldsymbol{\Sigma} \hat{\pmb{w}} \\
  & = \overline{\pmb{x}} + \boldsymbol{\Sigma}  \left(\mathbf{I} + \boldsymbol{\Gamma}^\top\boldsymbol{\Gamma} \right)^{-1}\boldsymbol{\Gamma}^\top \overline{\pmb{\delta}}\\
  &= \overline{\pmb{x}} + \boldsymbol{\Sigma}\left( \mathbf{I} + \boldsymbol{\Sigma}^\top \mathbf{H}^\top \mathbf{R}^{-1} \mathbf{H}\boldsymbol{\Sigma}\right)^{-1} \boldsymbol{\Sigma}^\top\mathbf{H}^\top \mathbf{R}^{-1}\left(\pmb{y} - \mathbf{H} \overline{\pmb{x}}\right),
  \end{align}$$
  which you may recognize as an alternative form for the Kalman gain applied to the innovation.

* We can in fact recover the classic Kalman filter equation with the matrix shift lemma,

Matrix shift lemma

Let $\mathbf{A} \in \mathbb{R}^{n \times m}$ and $\mathbf{B}\in \mathbf{R}^{m\times n}$.  Provided that $\left(\mathbf{I}_m + \mathbf{B}\mathbf{A}\right)^{-1}$ and $\left(\mathbf{I}_n + \mathbf{A}\mathbf{B}\right)^{-1}$ both exist, the following equality holds:
$$\begin{align}
\mathbf{A}\left(\mathbf{I}_m + \mathbf{B}\mathbf{A}\right)^{-1} = \left(\mathbf{I}_n +\mathbf{A}\mathbf{B}\right)^{-1} \mathbf{A}.
\end{align}$$

* In particular, with a proper choice of substitution, we recover the classical equations;

  * the proof of the matrix shift lemma and the equivalence of these forms of the Kalman gain are left to the reader.

* For now, let's recall the form of the gradient,

  $$\begin{align}
  \nabla_{\pmb{w}} \mathcal{J}_w(\pmb{w}) = \pmb{w} - \boldsymbol{\Gamma}^\top \left( \overline{\pmb{\delta}}- \boldsymbol{\Gamma}\pmb{w}\right)...
  \end{align}$$

========================================================
## Linear least-squares estimation and Newton's algorithm

*  From the last slide, we should note the following:

  $$\begin{align}
  \nabla_{\pmb{w}} \mathcal{J}_w|_{\pmb{0}} =- \boldsymbol{\Gamma}^\top \overline{\pmb{\delta}},
  \end{align}$$

* and the Hessian is likewise given as

  $$\begin{align}
  \mathbf{H}_{\mathcal{J}_w} := \nabla_{\pmb{w}}^2 \mathcal{J}_w = \left( \mathbf{I} + \boldsymbol{\Gamma}^\top \boldsymbol{\Gamma}\right),
  \end{align}$$

* Therefore, viewing the linear least-squares problem as Newton's descent algorithm, let us define the zeroth iterate as $\pmb{w}^0 := \pmb{0}$; this corresponds to initializing Newton with

  $$\begin{align}
  \pmb{x}^0 &:= \overline{\pmb{x}} + \boldsymbol{\Sigma} \pmb{w}^0 \\
  &=  \overline{\pmb{x}} + \boldsymbol{\Sigma} \pmb{0} = \overline{\pmb{x}},
  \end{align}$$
  i.e., starting with the base point.

* Recall the form of the optimal correction,

  $$\begin{align}
   \left(\mathbf{I} + \boldsymbol{\Gamma}^\top\boldsymbol{\Gamma} \right)^{-1}\boldsymbol{\Gamma}^\top \overline{\pmb{\delta}} \equiv - \mathbf{H}_{\mathcal{J}}^{-1} \nabla_{\pmb{w}}\mathcal{J}_w;
  \end{align}$$

* therefore, we recover the optimal solution via,

  $$\begin{align}
  \pmb{w}^1 := \pmb{w}^0 - \mathbf{H}_{\mathcal{J}_w}^{-1} \nabla_{\pmb{w}}\mathcal{J}_w|_{\pmb{w}^0},
  \end{align}$$
  i.e., with a single iteration of Newton's descent algorithm.

========================================================
### Linear least-squares estimation and Newton's algorithm

* From the last slide, we have the remarkable fact that the Kalman filter is formally equivalent to Newton's descent, if $\mathbf{B} = \mathbf{B}_k$ is the background covariance and $\mathbf{R} = \mathbf{R}_k$ is the observation error covariance.

  * In this case, with the linear relationship between the observational data and the model state, the global minimizer indicates that the optimization requires only a single iteration.

  * However, this is quite suggestive that, if we wanted to define an iterative Kalman filter for nonlinear optimization, this would strongly resemble Newton's algorithm, with second order convergence...

  * We will return to this notion later in the course.

* However, Newton's descent does not in and of itself provide a means to update the background penalty weights $\mathbf{B}$ along with the background state for the optimization;

  * this is critical if we wish to apply this analysis recursively in time like the Kalman filter.

* In order to do so, let's consider a second cost function, where we will define the analysis $\pmb{x}^{\mathrm{a}}$ and $\mathbf{B}^{\mathrm{a}}$ as the optimal state and background weights derived by the solution of the earlier cost function.

* We write an equivalent minimization, in terms of the unknown $\mathbf{B}^{\mathrm{a}}$ and the known $\pmb{x}^{\mathrm{a}} \equiv \hat{\pmb{x}}$ as

  $$\begin{align}
  \mathcal{J}_a(\pmb{x}) = \frac{1}{2} \parallel \pmb{x}^{\mathrm{a}} - \pmb{x} \parallel^2_{\mathbf{B}^{\mathrm{a}}}
  \end{align}$$

* The cost of course is minimized when we select the analysis solution, $\pmb{x} = \hat{\pmb{x}}$, equivalently to the earlier penalized cost function...

========================================================
### Linear least-squares estimation and Newton's algorithm

* Let's denote a new matrix factor $\mathbf{B}^{\mathrm{a}} = \boldsymbol{\Sigma}^{\mathrm{a}} \left(\boldsymbol{\Sigma}^{\mathrm{a}}\right)^\top$, but where we still write $\pmb{x}$ as before

  $$\begin{align}
  \pmb{x} = \overline{\pmb{x}} + \boldsymbol{\Sigma}\pmb{w}.
  \end{align}$$

* The equivalent cost function is thus defined as

  $$\begin{align}
  \mathcal{J}_a(\pmb{w}) = \frac{1}{2} \parallel \pmb{x}^{\mathrm{a}} -\overline{\pmb{x}} - \boldsymbol{\Sigma}\pmb{w} \parallel^2_{\mathbf{B}^{\mathrm{a}}} .
  \end{align}$$

* Let us define the change of variables,

  $$\begin{align}
  \boldsymbol{\Omega} &:= \left(\boldsymbol{\Sigma}^{\mathrm{a}}\right)^{-1}\boldsymbol{\Sigma},\\
  \pmb{\gamma} &:= \left(\boldsymbol{\Sigma}^{\mathrm{a}}\right)^{-1}\left(\pmb{x}^{\mathrm{a}} -  \overline{\pmb{x}}\right),
  \end{align}$$

* such that we have

  $$\begin{align}
  \mathcal{J}_a(\pmb{w}) = \frac{1}{2} \parallel \pmb{\gamma} - \boldsymbol{\Omega}\pmb{w} \parallel^2 .
  \end{align}$$

========================================================
### Linear least-squares estimation and Newton's algorithm

* From the former derivation, we say that the two forms of the cost function,

 $$\begin{align}
  \mathcal{J}_a(\pmb{w}) &= \frac{1}{2} \parallel \pmb{\gamma} - \boldsymbol{\Omega}\pmb{w} \parallel^2 \\
  \mathcal{J}_w(\pmb{w})&=\frac{1}{2} \parallel \pmb{w}\parallel^2 + \frac{1}{2} \parallel \overline{\pmb{\delta}}- \boldsymbol{\Gamma}\pmb{w}\parallel^2
  \end{align}$$
  are equivalent.

* If we compute the Hessian from both definitions, we find a resulting equivalence as

  $$\begin{align}
  &\left(\mathbf{I} +\boldsymbol{\Gamma}^\top \boldsymbol{\Gamma}\right) = \boldsymbol{\Omega}^\top \boldsymbol{\Omega}\\
  \Leftrightarrow & \left(\mathbf{I} +\boldsymbol{\Gamma}^\top \boldsymbol{\Gamma}\right) = \boldsymbol{\Sigma}^{\top}\left(\boldsymbol{\Sigma}^{\mathrm{a}}\right)^{-\top}\left(\boldsymbol{\Sigma}^{\mathrm{a}}\right)^{-1} \boldsymbol{\Sigma}\\
  \Leftrightarrow &\mathbf{B}^{\mathrm{a}} = \boldsymbol{\Sigma}\left( \mathbf{I} + \boldsymbol{\Gamma}^\top \boldsymbol{\Gamma}\right)^{-1} \boldsymbol{\Sigma}^\top.
  \end{align}$$

* Therefore, if we identify $\mathbf{T}:= \mathbf{H}_{\mathcal{J}}^{-\frac{1}{2}}$, $\boldsymbol{\Sigma}_{k|k-1} = \boldsymbol{\Sigma}$ and $\boldsymbol{\Sigma}^{\mathrm{a}}:=\boldsymbol{\Sigma}_{k|k}$,  this derivation gives an optimization approach to the square root Kalman filter with the right-transform analysis.

* Particularly, the right transform is precisely the inverse square root Hessian of the square root objective function.

* Therefore, one can formulate recursive linear least-squares via Newton as the Kalman filter.

  * Assuming a Gauss-Markov model in time, this likewise gives the minimum variance and maximum a posteriori statistical estimates.

========================================================
### Linear least-squares estimation and Newton's algorithm

* One additional interesting form for these equations emerges when we consider the following,

  $$\begin{align}
  \mathbf{B}_{k|k} = \boldsymbol{\Sigma}_{k|k-1}\left( \mathbf{I} + \boldsymbol{\Sigma}_{k|k-1}^\top\mathbf{H}_k^\top \mathbf{R}_k^{-1} \mathbf{H}_k\boldsymbol{\Sigma}_{k|k-1}\right)^{-1} \boldsymbol{\Sigma}_{k|k-1}^\top,
  \end{align}$$
  where this is derived from the last slide with the appropriate substitutions for the time-varying background prior, observation and posterior covariances.

* Consider then if we distribute the conjugate product through the inverse, we have equivalently,

  $$\begin{align}
  & \mathbf{B}_{k|k} = \left( \mathbf{B}_{k|k-1}^{-1} + \mathbf{H}_k^\top \mathbf{R}_k^{-1} \mathbf{H}_k\right)^{-1} \\
  \Leftrightarrow & \mathbf{B}_{k|k}^{-1} =  \mathbf{B}_{k|k-1}^{-1} + \mathbf{H}_k^\top \mathbf{R}_k^{-1} \mathbf{H}_k
  \end{align}$$

* Note that if we compute the Hessian of the direct, penalized objective function,

  $$\begin{align}
  \mathcal{J}_p (\pmb{x}) = \frac{1}{2}\parallel \overline{\pmb{x}}_{k|k-1} - \pmb{x} \parallel_{\mathbf{B}_{k|k-1}}^2 + \frac{1}{2}\parallel \pmb{y}_k - \mathbf{H}_k \pmb{x} \parallel_{\mathbf{R}_k}^2
  \end{align}$$

* we obtain,

  $$\begin{align}
  \mathbf{H}_{\mathcal{J}_p} &= \mathbf{B}^{-1}_{k|k-1} + \mathbf{H}_k\mathbf{R}_k^{-1}\mathbf{H}_k \\
  &= \mathbf{B}_{k|k}^{-1}
  \end{align}$$

========================================================
### Linear least-squares estimation and Newton's algorithm

* From the last slide we had the relationship,

  $$\begin{align}
  \mathbf{B}_{k|k} = \mathbf{H}_{\mathcal{J}_p}^{-1},
  \end{align}$$

* i.e., the posterior covariance is exactly the inverse Hessian of the direct, state-space cost function for the Gauss-Markov model.

* This is an illustration of a more widely true property.

* Particularly, the maximum likelihood estimation minus-log-likelihood cost function Hessian is the inverse covariance of the maximum likelihood estimator.

  * This is an asymptotic result that holds in a similar sense to the central limit theorem.

* In particular, when the sample size is sufficiently large, even for non-Gaussian error distributions, the maximum likelihood estimator will have a spread that is inverse-proportional to the local curvature in the state-space cost function.


text:
namespace Skylight
{
    /// <summary>
    ///     Class Show.
    /// </summary>
    public class Show
    {
        #region Fields

        /// <summary>
        ///     The _receiver
        /// </summary>
        private readonly Receiver _receiver;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="Show"/> class.
        /// </summary>
        /// <param name="in">
        /// The in.
        /// </param>
        public Show(Receiver @in)
        {
            this._receiver = @in;
        }

        #endregion

        #region Public Events

        /// <summary>
        ///     Delegates for RoomEvent. Are only invoked when commands that concern
        ///     the room's state (such as global clear, saved) for just
        ///     a few examples.
        /// </summary>
        public event Receiver.RoomEvent ShowEvent = delegate { };

        #endregion

        #region Public Methods and Operators

        /// <summary>
        ///     Called when the time doors are visible
        /// </summary>
        public void OnShow()
        {
            // Like with "hide", there is data but it is irrelevant.
            // Update relevant objects.
            this._receiver.Source.TimeDoorsVisible = true;

            // Fire the event.
            var e = new RoomEventArgs(this._receiver.Source);

            this._receiver.Source.MainReceiver.Show.ShowEvent(e);
        }

        #endregion
    }
}


text:
package org.apache.samoa.evaluation;

public interface RegressionPerformanceEvaluator extends PerformanceEvaluator {

}


text:
// Copyright 2012 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

goog.require('axs.AuditRule');

goog.provide('axs.AuditRules');

(function() {
    var auditRulesByName = {};
    var auditRulesByCode = {};

    /** @type {Object.<string, axs.AuditRule.Spec>} */
    axs.AuditRules.specs = {};

    /**
     * Instantiates and registers an audit rule.
     * If a conflicting rule is already registered then the new rule will not be added.
     * @param {axs.AuditRule.Spec} spec The object which defines the AuditRule to add.
     * @throws {Error} If the rule duplicates properties that must be unique.
     */
    axs.AuditRules.addRule = function(spec) {
        // create the auditRule before checking props as we can expect the constructor to perform the
        // first layer of sanity checking.
        var auditRule = new axs.AuditRule(spec);
        if (auditRule.code in auditRulesByCode)
            throw new Error('Can not add audit rule with same code: "' + auditRule.code + '"');
        if (auditRule.name in auditRulesByName)
            throw new Error('Can not add audit rule with same name: "' + auditRule.name + '"');
        auditRulesByName[auditRule.name] = auditRulesByCode[auditRule.code] = auditRule;
        axs.AuditRules.specs[spec.name] = spec;
    };

    /**
     * Gets the audit rule with the given name.
     * @param {string} name The name (or code) of an audit rule.
     * @return {axs.AuditRule}
     */
    axs.AuditRules.getRule = function(name) {
        return auditRulesByName[name] || auditRulesByCode[name] || null;
    };

    /**
     * Gets all registered audit rules.
     * @param {boolean=} opt_namesOnly If true then the result will contain only the rule names.
     * @return {Array.<axs.AuditRule>|Array.<string>}
     */
    axs.AuditRules.getRules = function(opt_namesOnly) {
        var ruleNames = Object.keys(auditRulesByName);
        if (opt_namesOnly)
            return ruleNames;
        return ruleNames.map(function(name) {
            return this.getRule(name);
        }, axs.AuditRules);
    };

    /**
     * Gets all registered audit rules which are not excluded by configuration.
     * @param {axs.AuditConfiguration} configuration Used to determine ignored rules.
     * @return {Array.<axs.AuditRule>}
     */
    axs.AuditRules.getActiveRules = function(configuration) {
        var auditRules;
        if (configuration.auditRulesToRun && configuration.auditRulesToRun.length > 0) {
            auditRules = configuration.auditRulesToRun;
        } else {
            auditRules = axs.AuditRules.getRules(true);
        }
        if (configuration.auditRulesToIgnore) {
            for (var i = 0; i < configuration.auditRulesToIgnore.length; i++) {
                var auditRuleToIgnore = configuration.auditRulesToIgnore[i];
                if (auditRules.indexOf(auditRuleToIgnore) < 0)
                    continue;
                auditRules.splice(auditRules.indexOf(auditRuleToIgnore), 1);
            }
        }
        return auditRules.map(axs.AuditRules.getRule);
    };
})();


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2001 World Wide Web Consortium,
(Massachusetts Institute of Technology, Institut National de
Recherche en Informatique et en Automatique, Keio University). All
Rights Reserved. This program is distributed under the W3C's Software
Intellectual Property License. This program is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See W3C License http://www.w3.org/Consortium/Legal/ for more details.
--><!DOCTYPE test SYSTEM "dom1.dtd">

<test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-1" name="nodeelementnodetype">
<metadata>
<title>nodeElementNodeType</title>
<creator>NIST</creator>
<description>
    The "getNodeType()" method for an Element Node
    returns the constant value 1.

    Retrieve the root node and invoke the "getNodeType()"
    method.   The method should return 1.
</description>
<contributor>Mary Brady</contributor>
<date qualifier="created">2001-08-17</date>
<subject resource="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-111237558"/>
</metadata>
<var name="doc" type="Document"/>
<var name="rootNode" type="Element"/>
<var name="nodeType" type="int"/>
<load var="doc" href="staff" willBeModified="false"/>
<documentElement obj="doc" var="rootNode"/>
<nodeType obj="rootNode" var="nodeType"/>
<assertEquals actual="nodeType" expected="1" id="nodeElementNodeTypeAssert1" ignoreCase="false"/>
</test>


text:
package http2

import (
	"fmt"
	"math"
	"sort"
)

// RFC 7540, Section 5.3.5: the default weight is 16.
const priorityDefaultWeight = 15 // 16 = 15 + 1

// PriorityWriteSchedulerConfig configures a priorityWriteScheduler.
type PriorityWriteSchedulerConfig struct {
	// MaxClosedNodesInTree controls the maximum number of closed streams to
	// retain in the priority tree. Setting this to zero saves a small amount
	// of memory at the cost of performance.
	//
	// See RFC 7540, Section 5.3.4:
	//   "It is possible for a stream to become closed while prioritization
	//   information ... is in transit. ... This potentially creates suboptimal
	//   prioritization, since the stream could be given a priority that is
	//   different from what is intended. To avoid these problems, an endpoint
	//   SHOULD retain stream prioritization state for a period after streams
	//   become closed. The longer state is retained, the lower the chance that
	//   streams are assigned incorrect or default priority values."
	MaxClosedNodesInTree int

	// MaxIdleNodesInTree controls the maximum number of idle streams to
	// retain in the priority tree. Setting this to zero saves a small amount
	// of memory at the cost of performance.
	//
	// See RFC 7540, Section 5.3.4:
	//   Similarly, streams that are in the "idle" state can be assigned
	//   priority or become a parent of other streams. This allows for the
	//   creation of a grouping node in the dependency tree, which enables
	//   more flexible expressions of priority. Idle streams begin with a
	//   default priority (Section 5.3.5).
	MaxIdleNodesInTree int

	// ThrottleOutOfOrderWrites enables write throttling to help ensure that
	// data is delivered in priority order. This works around a race where
	// stream B depends on stream A and both streams are about to call Write
	// to queue DATA frames. If B wins the race, a naive scheduler would eagerly
	// write as much data from B as possible, but this is suboptimal because A
	// is a higher-priority stream. With throttling enabled, we write a small
	// amount of data from B to minimize the amount of bandwidth that B can
	// steal from A.
	ThrottleOutOfOrderWrites bool
}

// NewPriorityWriteScheduler constructs a WriteScheduler that schedules
// frames by following HTTP/2 priorities as described in RFC 7340 Section 5.3.
// If cfg is nil, default options are used.
func NewPriorityWriteScheduler(cfg *PriorityWriteSchedulerConfig) WriteScheduler {
	if cfg == nil {
		// For justification of these defaults, see:
		// https://docs.google.com/document/d/1oLhNg1skaWD4_DtaoCxdSRN5erEXrH-KnLrMwEpOtFY
		cfg = &PriorityWriteSchedulerConfig{
			MaxClosedNodesInTree:     10,
			MaxIdleNodesInTree:       10,
			ThrottleOutOfOrderWrites: false,
		}
	}

	ws := &priorityWriteScheduler{
		nodes:                make(map[uint32]*priorityNode),
		maxClosedNodesInTree: cfg.MaxClosedNodesInTree,
		maxIdleNodesInTree:   cfg.MaxIdleNodesInTree,
		enableWriteThrottle:  cfg.ThrottleOutOfOrderWrites,
	}
	ws.nodes[0] = &ws.root
	if cfg.ThrottleOutOfOrderWrites {
		ws.writeThrottleLimit = 1024
	} else {
		ws.writeThrottleLimit = math.MaxInt32
	}
	return ws
}

type priorityNodeState int

const (
	priorityNodeOpen priorityNodeState = iota
	priorityNodeClosed
	priorityNodeIdle
)

// priorityNode is a node in an HTTP/2 priority tree.
// Each node is associated with a single stream ID.
// See RFC 7540, Section 5.3.
type priorityNode struct {
	q            writeQueue        // queue of pending frames to write
	id           uint32            // id of the stream, or 0 for the root of the tree
	weight       uint8             // the actual weight is weight+1, so the value is in [1,256]
	state        priorityNodeState // open | closed | idle
	bytes        int64             // number of bytes written by this node, or 0 if closed
	subtreeBytes int64             // sum(node.bytes) of all nodes in this subtree

	// These links form the priority tree.
	parent     *priorityNode
	kids       *priorityNode // start of the kids list
	prev, next *priorityNode // doubly-linked list of siblings
}

func (n *priorityNode) setParent(parent *priorityNode) {
	if n == parent {
		panic("setParent to self")
	}
	if n.parent == parent {
		return
	}
	// Unlink from current parent.
	if parent := n.parent; parent != nil {
		if n.prev == nil {
			parent.kids = n.next
		} else {
			n.prev.next = n.next
		}
		if n.next != nil {
			n.next.prev = n.prev
		}
	}
	// Link to new parent.
	// If parent=nil, remove n from the tree.
	// Always insert at the head of parent.kids (this is assumed by walkReadyInOrder).
	n.parent = parent
	if parent == nil {
		n.next = nil
		n.prev = nil
	} else {
		n.next = parent.kids
		n.prev = nil
		if n.next != nil {
			n.next.prev = n
		}
		parent.kids = n
	}
}

func (n *priorityNode) addBytes(b int64) {
	n.bytes += b
	for ; n != nil; n = n.parent {
		n.subtreeBytes += b
	}
}

// walkReadyInOrder iterates over the tree in priority order, calling f for each node
// with a non-empty write queue. When f returns true, this funcion returns true and the
// walk halts. tmp is used as scratch space for sorting.
//
// f(n, openParent) takes two arguments: the node to visit, n, and a bool that is true
// if any ancestor p of n is still open (ignoring the root node).
func (n *priorityNode) walkReadyInOrder(openParent bool, tmp *[]*priorityNode, f func(*priorityNode, bool) bool) bool {
	if !n.q.empty() && f(n, openParent) {
		return true
	}
	if n.kids == nil {
		return false
	}

	// Don't consider the root "open" when updating openParent since
	// we can't send data frames on the root stream (only control frames).
	if n.id != 0 {
		openParent = openParent || (n.state == priorityNodeOpen)
	}

	// Common case: only one kid or all kids have the same weight.
	// Some clients don't use weights; other clients (like web browsers)
	// use mostly-linear priority trees.
	w := n.kids.weight
	needSort := false
	for k := n.kids.next; k != nil; k = k.next {
		if k.weight != w {
			needSort = true
			break
		}
	}
	if !needSort {
		for k := n.kids; k != nil; k = k.next {
			if k.walkReadyInOrder(openParent, tmp, f) {
				return true
			}
		}
		return false
	}

	// Uncommon case: sort the child nodes. We remove the kids from the parent,
	// then re-insert after sorting so we can reuse tmp for future sort calls.
	*tmp = (*tmp)[:0]
	for n.kids != nil {
		*tmp = append(*tmp, n.kids)
		n.kids.setParent(nil)
	}
	sort.Sort(sortPriorityNodeSiblings(*tmp))
	for i := len(*tmp) - 1; i >= 0; i-- {
		(*tmp)[i].setParent(n) // setParent inserts at the head of n.kids
	}
	for k := n.kids; k != nil; k = k.next {
		if k.walkReadyInOrder(openParent, tmp, f) {
			return true
		}
	}
	return false
}

type sortPriorityNodeSiblings []*priorityNode

func (z sortPriorityNodeSiblings) Len() int      { return len(z) }
func (z sortPriorityNodeSiblings) Swap(i, k int) { z[i], z[k] = z[k], z[i] }
func (z sortPriorityNodeSiblings) Less(i, k int) bool {
	// Prefer the subtree that has sent fewer bytes relative to its weight.
	// See sections 5.3.2 and 5.3.4.
	wi, bi := float64(z[i].weight+1), float64(z[i].subtreeBytes)
	wk, bk := float64(z[k].weight+1), float64(z[k].subtreeBytes)
	if bi == 0 && bk == 0 {
		return wi >= wk
	}
	if bk == 0 {
		return false
	}
	return bi/bk <= wi/wk
}

type priorityWriteScheduler struct {
	// root is the root of the priority tree, where root.id = 0.
	// The root queues control frames that are not associated with any stream.
	root priorityNode

	// nodes maps stream ids to priority tree nodes.
	nodes map[uint32]*priorityNode

	// maxID is the maximum stream id in nodes.
	maxID uint32

	// lists of nodes that have been closed or are idle, but are kept in
	// the tree for improved prioritization. When the lengths exceed either
	// maxClosedNodesInTree or maxIdleNodesInTree, old nodes are discarded.
	closedNodes, idleNodes []*priorityNode

	// From the config.
	maxClosedNodesInTree int
	maxIdleNodesInTree   int
	writeThrottleLimit   int32
	enableWriteThrottle  bool

	// tmp is scratch space for priorityNode.walkReadyInOrder to reduce allocations.
	tmp []*priorityNode

	// pool of empty queues for reuse.
	queuePool writeQueuePool
}

func (ws *priorityWriteScheduler) OpenStream(streamID uint32, options OpenStreamOptions) {
	// The stream may be currently idle but cannot be opened or closed.
	if curr := ws.nodes[streamID]; curr != nil {
		if curr.state != priorityNodeIdle {
			panic(fmt.Sprintf("stream %d already opened", streamID))
		}
		curr.state = priorityNodeOpen
		return
	}

	// RFC 7540, Section 5.3.5:
	//  "All streams are initially assigned a non-exclusive dependency on stream 0x0.
	//  Pushed streams initially depend on their associated stream. In both cases,
	//  streams are assigned a default weight of 16."
	parent := ws.nodes[options.PusherID]
	if parent == nil {
		parent = &ws.root
	}
	n := &priorityNode{
		q:      *ws.queuePool.get(),
		id:     streamID,
		weight: priorityDefaultWeight,
		state:  priorityNodeOpen,
	}
	n.setParent(parent)
	ws.nodes[streamID] = n
	if streamID > ws.maxID {
		ws.maxID = streamID
	}
}

func (ws *priorityWriteScheduler) CloseStream(streamID uint32) {
	if streamID == 0 {
		panic("violation of WriteScheduler interface: cannot close stream 0")
	}
	if ws.nodes[streamID] == nil {
		panic(fmt.Sprintf("violation of WriteScheduler interface: unknown stream %d", streamID))
	}
	if ws.nodes[streamID].state != priorityNodeOpen {
		panic(fmt.Sprintf("violation of WriteScheduler interface: stream %d already closed", streamID))
	}

	n := ws.nodes[streamID]
	n.state = priorityNodeClosed
	n.addBytes(-n.bytes)

	q := n.q
	ws.queuePool.put(&q)
	n.q.s = nil
	if ws.maxClosedNodesInTree > 0 {
		ws.addClosedOrIdleNode(&ws.closedNodes, ws.maxClosedNodesInTree, n)
	} else {
		ws.removeNode(n)
	}
}

func (ws *priorityWriteScheduler) AdjustStream(streamID uint32, priority PriorityParam) {
	if streamID == 0 {
		panic("adjustPriority on root")
	}

	// If streamID does not exist, there are two cases:
	// - A closed stream that has been removed (this will have ID <= maxID)
	// - An idle stream that is being used for "grouping" (this will have ID > maxID)
	n := ws.nodes[streamID]
	if n == nil {
		if streamID <= ws.maxID || ws.maxIdleNodesInTree == 0 {
			return
		}
		ws.maxID = streamID
		n = &priorityNode{
			q:      *ws.queuePool.get(),
			id:     streamID,
			weight: priorityDefaultWeight,
			state:  priorityNodeIdle,
		}
		n.setParent(&ws.root)
		ws.nodes[streamID] = n
		ws.addClosedOrIdleNode(&ws.idleNodes, ws.maxIdleNodesInTree, n)
	}

	// Section 5.3.1: A dependency on a stream that is not currently in the tree
	// results in that stream being given a default priority (Section 5.3.5).
	parent := ws.nodes[priority.StreamDep]
	if parent == nil {
		n.setParent(&ws.root)
		n.weight = priorityDefaultWeight
		return
	}

	// Ignore if the client tries to make a node its own parent.
	if n == parent {
		return
	}

	// Section 5.3.3:
	//   "If a stream is made dependent on one of its own dependencies, the
	//   formerly dependent stream is first moved to be dependent on the
	//   reprioritized stream's previous parent. The moved dependency retains
	//   its weight."
	//
	// That is: if parent depends on n, move parent to depend on n.parent.
	for x := parent.parent; x != nil; x = x.parent {
		if x == n {
			parent.setParent(n.parent)
			break
		}
	}

	// Section 5.3.3: The exclusive flag causes the stream to become the sole
	// dependency of its parent stream, causing other dependencies to become
	// dependent on the exclusive stream.
	if priority.Exclusive {
		k := parent.kids
		for k != nil {
			next := k.next
			if k != n {
				k.setParent(n)
			}
			k = next
		}
	}

	n.setParent(parent)
	n.weight = priority.Weight
}

func (ws *priorityWriteScheduler) Push(wr FrameWriteRequest) {
	var n *priorityNode
	if id := wr.StreamID(); id == 0 {
		n = &ws.root
	} else {
		n = ws.nodes[id]
		if n == nil {
			// id is an idle or closed stream. wr should not be a HEADERS or
			// DATA frame. However, wr can be a RST_STREAM. In this case, we
			// push wr onto the root, rather than creating a new priorityNode,
			// since RST_STREAM is tiny and the stream's priority is unknown
			// anyway. See issue #17919.
			if wr.DataSize() > 0 {
				panic("add DATA on non-open stream")
			}
			n = &ws.root
		}
	}
	n.q.push(wr)
}

func (ws *priorityWriteScheduler) Pop() (wr FrameWriteRequest, ok bool) {
	ws.root.walkReadyInOrder(false, &ws.tmp, func(n *priorityNode, openParent bool) bool {
		limit := int32(math.MaxInt32)
		if openParent {
			limit = ws.writeThrottleLimit
		}
		wr, ok = n.q.consume(limit)
		if !ok {
			return false
		}
		n.addBytes(int64(wr.DataSize()))
		// If B depends on A and B continuously has data available but A
		// does not, gradually increase the throttling limit to allow B to
		// steal more and more bandwidth from A.
		if openParent {
			ws.writeThrottleLimit += 1024
			if ws.writeThrottleLimit < 0 {
				ws.writeThrottleLimit = math.MaxInt32
			}
		} else if ws.enableWriteThrottle {
			ws.writeThrottleLimit = 1024
		}
		return true
	})
	return wr, ok
}

func (ws *priorityWriteScheduler) addClosedOrIdleNode(list *[]*priorityNode, maxSize int, n *priorityNode) {
	if maxSize == 0 {
		return
	}
	if len(*list) == maxSize {
		// Remove the oldest node, then shift left.
		ws.removeNode((*list)[0])
		x := (*list)[1:]
		copy(*list, x)
		*list = (*list)[:len(x)]
	}
	*list = append(*list, n)
}

func (ws *priorityWriteScheduler) removeNode(n *priorityNode) {
	for k := n.kids; k != nil; k = k.next {
		k.setParent(n.parent)
	}
	n.setParent(nil)
	delete(ws.nodes, n.id)
}


text:
package org.apache.geronimo.st.v21.ui.wizards;

import javax.xml.bind.JAXBElement;

import org.apache.geronimo.jee.openejb.EjbRelation;
import org.apache.geronimo.jee.openejb.EjbRelationshipRole;
import org.apache.geronimo.jee.openejb.Relationships;
import org.apache.geronimo.jaxbmodel.common.operations.JAXBObjectFactory;
import org.apache.geronimo.st.ui.CommonMessages;
import org.apache.geronimo.st.ui.sections.AbstractTreeSection;
import org.apache.geronimo.st.ui.wizards.AbstractTreeWizard;
import org.apache.geronimo.jee.jaxbmodel.operations.JAXBModelUtils;
import org.apache.geronimo.jee.jaxbmodel.operations.JAXBObjectFactoryImpl;
import org.apache.geronimo.st.v21.ui.sections.EjbRelationSection;

/**
 * @version $Rev$ $Date$
 */
public class EjbRelationWizard extends AbstractTreeWizard {

    private final int EJB_RELATION = 0;
    private final int RELATIONSHIP_ROLE = 1;
    private final int CMR_FIELD_MAPPING = 2;

    public EjbRelationWizard(AbstractTreeSection section) {
        super(section, 3, 3);
        elementTypes[EJB_RELATION] = "EJB Relation";
        elementTypes[RELATIONSHIP_ROLE] = "EJB Relationship Role";
        elementTypes[CMR_FIELD_MAPPING] = "CMR Field Mapping";
    }

    public class EjbRelationWizardPage extends AbstractTreeWizardPage {

        public EjbRelationWizardPage(String pageName) {
            super(pageName);
        }

        protected void initControl () {
            if (eObject == null) {
                element.select(EJB_RELATION);
                if (EjbRelation.class.isInstance(((EjbRelationSection)section).getSelectedObject())) {
                    element.remove(elementTypes[CMR_FIELD_MAPPING]);
                }
                else if (EjbRelationshipRole.class.isInstance(((EjbRelationSection)section).getSelectedObject())) {
                    element.select(CMR_FIELD_MAPPING);
                    element.setEnabled(false);
                }
                else {
                    element.setEnabled(false);
                }
            }
            else {
                if (EjbRelation.class.isInstance(eObject)) {
                    textList.get(0).setText(((EjbRelation)eObject).getEjbRelationName());
                    textList.get(1).setText(((EjbRelation)eObject).getManyToManyTableName());
                    element.select(EJB_RELATION);
                }
                else if (EjbRelationshipRole.class.isInstance(eObject)) {
                    EjbRelationshipRole role = (EjbRelationshipRole)eObject;
                    textList.get(0).setText(role.getEjbRelationshipRoleName());
                    textList.get(1).setText(role.getRelationshipRoleSource().getEjbName());
                    textList.get(2).setText(role.getCmrField().getCmrFieldName());
                    element.select(RELATIONSHIP_ROLE);
                }
                else if (EjbRelationshipRole.RoleMapping.CmrFieldMapping.class.isInstance(eObject)) {
                    EjbRelationshipRole.RoleMapping.CmrFieldMapping fieldMapping =
                            (EjbRelationshipRole.RoleMapping.CmrFieldMapping)eObject;
                    textList.get(0).setText(fieldMapping.getKeyColumn());
                    textList.get(1).setText(fieldMapping.getForeignKeyColumn());
                    element.select(CMR_FIELD_MAPPING);
                }
                element.setEnabled(false);
            }
        }

        protected void toggleFields (boolean clearFields) {
            if (element.getText().equals(elementTypes[EJB_RELATION])) {
                for (int i = 0; i < maxTextFields; i++) {
                    labelList.get(i).setVisible(i < 2 ? true : false);
                    textList.get(i).setVisible(i < 2 ? true : false);
                    if (clearFields == true) {
                        textList.get(i).setText("");
                    }
                }
                labelList.get(0).setText(CommonMessages.name);
                labelList.get(1).setText(CommonMessages.mtmTableName);
                // if we are doing an add, then we need to make sure that the longest
                // text can be handled
                labelList.get(2).setText(CommonMessages.foreignKeyColumn);
            }
            else if (element.getText().equals(elementTypes[RELATIONSHIP_ROLE])) {
                for (int i = 0; i < maxTextFields; i++) {
                    labelList.get(i).setVisible(true);
                    textList.get(i).setVisible(true);
                    if (clearFields == true) {
                        textList.get(i).setText("");
                    }
                }
                labelList.get(0).setText(CommonMessages.name);
                labelList.get(1).setText(CommonMessages.ejbSourceName);
                labelList.get(2).setText(CommonMessages.cmrFieldName);
            }
            else if (element.getText().equals(elementTypes[CMR_FIELD_MAPPING])) {
                for (int i = 0; i < maxTextFields; i++) {
                    labelList.get(i).setVisible(i < 2 ? true : false);
                    textList.get(i).setVisible(i < 2 ? true : false);
                    if (clearFields == true) {
                        textList.get(i).setText("");
                    }
                }
                labelList.get(0).setText(CommonMessages.keyColumn);
                labelList.get(1).setText(CommonMessages.foreignKeyColumn);
            }
        }

        public String getWizardPageTitle() {
            return CommonMessages.wizardPageTitle_EjbRelation;
        }

        public String getWizardPageDescription() {
            return CommonMessages.wizardPageDescription_EjbRelation;
        }
    }

    @Override
    public void addPages() {
        addPage(new EjbRelationWizardPage("Page0"));
    }

    @Override
    public boolean performFinish() {
        EjbRelation relation;
        if (element.getText().equals(elementTypes[EJB_RELATION])) {
            relation = (EjbRelation)eObject;
            if (relation == null) {
                relation = (EjbRelation)getEFactory().create(EjbRelation.class);
                JAXBElement plan = section.getPlan();

                if (JAXBModelUtils.getEjbRelationships(plan) == null) {
                    Relationships relationships = (Relationships)getEFactory().create(Relationships.class);

                    JAXBModelUtils.setEjbRelationships(plan, relationships);
                    ((EjbRelationSection)section).resetInput(relationships);
                }
                JAXBModelUtils.getEjbRelationships(plan).add(relation);
            }
            relation.setEjbRelationName(textList.get(0).getText());
            relation.setManyToManyTableName(textList.get(1).getText());
        }
        else if (element.getText().equals(elementTypes[RELATIONSHIP_ROLE])) {
            if (isEmpty(textList.get(1).getText())) {
                return false;
            }
            EjbRelationshipRole role = (EjbRelationshipRole)eObject;
            if (role == null) {
                role = (EjbRelationshipRole)getEFactory().create(EjbRelationshipRole.class);
                relation = (EjbRelation)((EjbRelationSection)section).getSelectedObject();
                relation.getEjbRelationshipRole().add(role);
            }
            role.setEjbRelationshipRoleName(textList.get(0).getText());
            EjbRelationshipRole.RelationshipRoleSource source = role.getRelationshipRoleSource();
            if (source == null) {
                source = (EjbRelationshipRole.RelationshipRoleSource)getEFactory().create(EjbRelationshipRole.RelationshipRoleSource.class);
                role.setRelationshipRoleSource(source);
            }
            source.setEjbName(textList.get(1).getText());
            EjbRelationshipRole.CmrField cmrField = role.getCmrField();
            if (cmrField == null) {
                cmrField = (EjbRelationshipRole.CmrField)getEFactory().create(EjbRelationshipRole.CmrField.class);
                role.setCmrField(cmrField);
            }
            cmrField.setCmrFieldName(textList.get(2).getText());
        }
        else if (element.getText().equals(elementTypes[CMR_FIELD_MAPPING])) {
            if (isEmpty(textList.get(0).getText()) || isEmpty(textList.get(1).getText())) {
                return false;
            }
            EjbRelationshipRole.RoleMapping.CmrFieldMapping fieldMapping =
                    (EjbRelationshipRole.RoleMapping.CmrFieldMapping)eObject;
            if (fieldMapping == null) {
                fieldMapping = (EjbRelationshipRole.RoleMapping.CmrFieldMapping)getEFactory().create(EjbRelationshipRole.RoleMapping.CmrFieldMapping.class);
                EjbRelationshipRole role = (EjbRelationshipRole)((EjbRelationSection)section).getSelectedObject();
                EjbRelationshipRole.RoleMapping roleMapping = role.getRoleMapping();
                if (roleMapping == null) {
                    roleMapping = (EjbRelationshipRole.RoleMapping)getEFactory().create(EjbRelationshipRole.RoleMapping.class);
                    role.setRoleMapping(roleMapping);
                }
                role.getRoleMapping().getCmrFieldMapping().add(fieldMapping);
            }
            fieldMapping.setKeyColumn(textList.get(0).getText());
            fieldMapping.setForeignKeyColumn(textList.get(1).getText());
        }
        return true;
    }

    public JAXBObjectFactory getEFactory() {
        return JAXBObjectFactoryImpl.getInstance();
    }

    public String getAddWizardWindowTitle() {
        return CommonMessages.wizardNewTitle_EjbRelation;
    }

    public String getEditWizardWindowTitle() {
        return CommonMessages.wizardEditTitle_EjbRelation;
    }
}


text:
require File.expand_path('../../../helper', __FILE__)
require File.expand_path('../../../data', __FILE__)

class TestDmEvents < Test::Unit::TestCase

  context "an instance of DM::Events::Recurrence" do

    context "with yearly frequency" do
      setup do
        stub(Time).now{ now }
        @rec = ::EventRecurrence.new
        @rec.every= :year
      end

      should "work" do
        @rec.on= [1,2]
        assert_equal "year", @rec.frequency
        assert_equal [1,2], @rec.dates
      end

      should "convert string months to numbers" do
        @rec.on= ["January",3]
        assert_equal [1,3], @rec.dates
        @rec.on= ["dec",3]
        assert_equal [12,3], @rec.dates
        @rec.on= ["julY",3]
        assert_equal [7,3], @rec.dates
      end

      should "only accept up to 2 inputs" do
        @rec.on= ["Septem",1,2,3]
        assert_equal [9,1], @rec.dates
      end

      should "fail with invalid input" do
        assert_raise ArgumentError do
          @rec.on= ["invalid"]
        end
        assert_raise ArgumentError do
          @rec.on= [0]
        end
        assert_raise ArgumentError do
          @rec.on= [1000]
        end
      end

      should "ensure that the day is a valid day for the given month" do
        assert_raises ArgumentError do
          @rec.dates = ["Jan", 40]
        end
      end

      context "getting the next occurence" do

        should "without a date default to Jan 1" do
          assert_equal now.next_year.beginning_of_year, @rec.next.to_date
        end

        should "allow you to get the next occurence" do
          @rec.on = [7,1]
          assert_equal now.next_month.beginning_of_month, @rec.next.to_date
        end

        should "account for intervals" do
          @rec.dates    = ["Jan", 1]
          @rec.interval = 2
          assert_equal (now.beginning_of_year + 2.years), @rec.next.to_date
        end

      end

      should "show you all the recurrence events in a range" do
        @rec.on = [7,1]
        range   = @rec.in_range(now.beginning_of_year, now.end_of_year)
        assert_equal Time.gm(2010,7,1), range.first
        assert_equal 1, range.length
      end

    end
  end

end


text:
Mainly a collection of things I wish I could remember.

$partial("templates/post-list.html")$


text:
<?php
/**
 * @group Core
 */
class Api_Client_ServiceCustomTest extends BBDbApiTestCase
{
    protected $_initialSeedFile = 'services.xml';

    public function testServiceCustom()
    {
        $data = array(
            'order_id'    =>  9,
        );
        $result = $this->api_client->servicecustom_return_params($data);
        $this->assertEquals($data, $result);

        try {
            $this->api_client->servicecustom_non_existing($data);
            $this->fail('Method should not exist on plugin');
        } catch(Exception $e) {
            $this->assertEquals(3125, $e->getCode());
        }

        try {
            $this->api_client->servicecustom_renew($data);
            $this->fail('Renew method should be forbidden');
        } catch(Exception $e) {
            $this->assertEquals(403, $e->getCode());
        }
    }
}


text:
namespace App.Data.Models
{
    using System.ComponentModel.DataAnnotations;

    using Data.Common.Models;

    public class Country : BaseModel<int>, IListedItem
    {
        [Required]
        [MinLength(2)]
        [MaxLength(100)]
        public string Name { get; set; }
    }
}


text:
Rook is a ~2kb JavaScript library to assist with localStorage and the DOM.

You can get a great overview of localStorage in this [diveintohtml5 article](http://diveintohtml5.info/storage.html).

##Functions##

	rook().view();  // View contents of localStorage in console
	rook().wipe(); // Clear localStorage

###Set###

	rook().set(key, obj);  // Set value to key in localStorage

Examples:

	rook().set('foo', 'bar'); // String
	rook().set('foo', bar); // Variable
	rook().set('objectName',
		{"names": [{"firstName":"Joe" , "lastName":"Smith"},   // Object
		{"firstName":"Jan" , "lastName":"Doe"},
		{"firstName":"Bob" , "lastName":"Saget"}]
	});

###Set Element###

	rook(element).setEle(key); // Set text in element to localStorage key

Example:

	rook("#foo").set('bar');

###Get###

	var foo = rook().get(key) // Get value from key in localStorage

###Push Element To Array###

	rook(element).eleToArray('arrayName', limit);  // The limit keeps the user from adding past a certain amount of values

Example:

	rook('#foo').eleToArray('newArr', 5);  // Push text in DOM element to localStorage array

###Import CSV to localStorage###

	rook(element).upCSV(text, name);  // Import a CSV file into localStorage

Example (using jQuery ready and AJAX):

	$(document).ready(function() {
		$('#clkcsv').click(function() {
			$.ajax({
				type: "GET",
				url: "example.txt",
				dataType: "text",
				success: function(data) {
					rook('#foo').upCSV(data, 'myCSV');
				}
			});
		});
	});

###Order Array###

	rook().order(arrayName);  // Alphabetical
	rook().reverse(arrayName);  // Reverse

##Contributing##

Feel free to fork and submit pull requests to add features or fix bugs.  There is a lot that could be done better and in addition to what is here, so any help would be appreciated.  If you are looking for ways to help check out the Issues, but areas that are especially in need are the following:

*  CSV Parsing and Regex
*  Ordering is only lexicographical.  Need other sorting including numerically.

In addition to all the clean up and bug fixing, I would also like to implement more SQL-like functions as well.

##License##

Rook is licensed under the [MIT License](http://opensource.org/licenses/MIT).


text:
package hosung.epublib.model;

/**
 * Created by PC on 12/14/2016.
 */

public class RewindIndex {
}


text:
using System;
using Akka.Actor;
using Autofac;
using GridDomain.Common;
using GridDomain.Configuration;
using GridDomain.Configuration.MessageRouting;
using GridDomain.CQRS;
using GridDomain.Scheduling.Quartz.Configuration;
using Serilog;
using IScheduler = Quartz.IScheduler;

namespace GridDomain.Scheduling.Akka {
    public static class SchedulingExtensions
    {
        public static SchedulingExtension InitSchedulingExtension(this ActorSystem system,
                                                                  IQuartzConfig quartzConfig,
                                                                  ILogger logger,
                                                                  IPublisher publisher,
                                                                  ICommandExecutor executor)
        {
            if(system == null)
                throw new ArgumentNullException(nameof(system));

            var ext = (SchedulingExtension)system.RegisterExtension(SchedulingExtensionProvider.Provider);
            var schedulingContainer = new ContainerBuilder();
            new SchedulingConfiguration(quartzConfig, logger, publisher, executor).Register(schedulingContainer);
            var container = schedulingContainer.Build();

            ext.Scheduler = container.Resolve<IScheduler>();
            ext.SchedulingActor = system.ActorOf(Props.Create(() => new SchedulingActor()), nameof(SchedulingActor));

            system.RegisterOnTermination(() =>
                                         {
                                             try
                                             {
                                                 if(ext.Scheduler != null && ext.Scheduler.IsShutdown == false)
                                                     ext.Scheduler.Shutdown(false);
                                             }
                                             catch(Exception ex)
                                             {
                                                 system.Log.Warning($"Got error on quartz scheduler shutdown:{ex}");
                                             }
                                         });
            return ext;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using SharpOrrery;
using UnityEngine;

public class Universe : MonoBehaviour
{
    public double epochTime;
    public DateTime date;
    public double currentTime;
    public bool playing;

    public ScenarioLoader scenarioLoader;

    private readonly Ticker ticker = new Ticker();
    private Dictionary<string, CelestialBody> bodies;
    private CelestialBody centralBody;
    public Scenario scenario;

    private double size;
    private double startEpochTime;
    private bool? usePhysics = true;

    public delegate void OnCelestialBodyAddedDelegate(CelestialBody body);
    public OnCelestialBodyAddedDelegate OnCelestialBodyAdded;

    void Start()
    {
        scenarioLoader.LoadCommonBodies();
        scenarioLoader.InitScenarios();
        init();
    }

    public void init()
    {

        //name = scenario.name;
        //var initialSettings = _.extend({}, scenario.defaultGuiSettings, qstrSettings, scenario.forcedGuiSettings);
        //console.log(initialSettings);

        //Universe is, well, global
        SO.U = this;

        usePhysics = scenario.usePhysics.HasValue ? scenario.usePhysics : SO.USE_PHYSICS_BY_DEFAULT;

        /*
            		this.dateDisplay = Gui.addDate(function(){
					this.playing = false;
					this.epochTime = 0;
					this.currentTime = this.startEpochTime = this.getEpochTime(Gui.getDate());
					this.repositionBodies();
					this.scene.onDateReset();
				}.bind(this));
                 */

        var tempIsPlaying = playing;
        playing = false;
        epochTime = 0;

//        date = DateTime.Now; // bomb (needs to go on UI time)
        date = new DateTime(2014, 1, 1, 12, 0, 0, DateTimeKind.Utc);
        currentTime = startEpochTime = getEpochTime(date);
        Debug.Log(startEpochTime);

        createBodies(scenario);

        calculateDimensions();

        initBodies(scenario);
        ticker.setSecondsPerTick(scenario.secondsPerTick);
        ticker.setCalculationsPerTick(scenario.calculationsPerTick.HasValue ? scenario.calculationsPerTick.Value : SO.defaultCalculationsPerTick);

        playing = tempIsPlaying;
    }

    private void createBodies(Scenario scenario)
    {
        bodies = new Dictionary<string, CelestialBody>();

        foreach (string bodyName in scenario.common)
        {
            var body = new CelestialBody();
            body.AssignInitialValues(scenario.bodies[bodyName]);
            body.name = bodyName;
            centralBody = (centralBody != null && centralBody.mass > body.mass) ? centralBody : body;
            bodies[body.name] = body;
        }

        centralBody.isCentral = true;
    }

    private void initBodies(Scenario scenario)
    {
        foreach (string bodyName in scenario.common)
        {
            CelestialBody body = bodies[bodyName];

            if (!scenario.calculateAll && !body.isCentral)
            {
                body.mass = 1;
            }

            body.init();
            body.setPositionFromDate(currentTime, true);

            if(OnCelestialBodyAdded != null)
                OnCelestialBodyAdded.Invoke(body);
        }

        setBarycenter();

        //after all is inialized
        foreach (var celestialBodyKV in bodies)
        {
            CelestialBody body = celestialBodyKV.Value;
            //this.scene.addBody(body);

            body.afterInitialized();
            //console.log(body.name, body.isCentral);
        }

        //this.scene.setCentralBody(this.centralBody);

        ticker.setBodies(bodies.Values.ToList());
    }

    /* balance the system by calculating the masses of the non-central bodies and placing the central body to balance it.*/

    private void setBarycenter()
    {
        CelestialBody central = centralBody;
        if (!usePhysics.Value || central.isStill || scenario.useBarycenter == false)
            return;

        double massRatio = 0.0;

        double massCenter_mass = 0.0;
        var massCenter_pos = new Vector3d();
        var massCenter_momentum = new Vector3d();

        foreach (var celestialBodyKV in bodies)
        {
            CelestialBody b = celestialBodyKV.Value;

            if (b == central)
                continue;
            massCenter_mass += b.mass;
            massRatio = b.mass/massCenter_mass;
            massCenter_pos = (massCenter_pos + b.getPosition())* massRatio;
            massCenter_momentum = (massCenter_momentum + b.getVelocity())* b.mass;
        }

        massCenter_momentum *=  (1/massCenter_mass);

        massRatio = massCenter_mass/central.mass;
        central.velocity = massCenter_momentum* (massRatio*-1);
        central.position = massCenter_pos* (massRatio*-1);

        foreach (var celestialBodyKV in bodies)
        {
            CelestialBody b = celestialBodyKV.Value;

            if (b == central || (b.relativeTo != null && b.relativeTo != central))
                continue;

            b.velocity += central.velocity;
            //if central body's mass is way bigger than the object, we assume that the central body is the center of rotation. Otherwise, it's the barycenter
            if (central.mass/b.mass > 10e10)
            {
                b.position += central.position;
            }
            else if (b.relativeTo == central)
            {
                b.relativeTo = null;
            }
        }
    }

    private void repositionBodies()
    {
        foreach (CelestialBody body in bodies.Values)
        {
            body.reset();
            body.setPositionFromDate(currentTime, true);
        }

        ticker.tick(false, currentTime);

        setBarycenter();

        //adjust position depending on other bodies' position (for example a satellite is relative to its main body)
        foreach (CelestialBody body in bodies.Values)
        {
            body.afterInitialized();
        }
    }

    // Original code used null name to represent central body
    public CelestialBody getBody(CelestialBody body = null)
    {
        if (body == null)
        {
            return centralBody;
        }

        if (!bodies.ContainsKey(body.name))
            return null;

        return bodies[body.name];
    }

    // Original code used null name to represent central body
    public CelestialBody getBody(string bodyName)
    {
        if (bodyName == null)
        {
            return centralBody;
        }

        if (!bodies.ContainsKey(bodyName))
            return null;

        return bodies[bodyName];
    }

    private void calculateDimensions()
    {
        string centralBodyName = getBody().name;

        //find the largest radius in km among all bodies
        double largestRadius = bodies.Values.Max(b => b.radius);
        // bomb - This needs to be verified

        //find the largest semi major axis in km among all bodies

        double? largestSMA = bodies.Values.Where(b => !b.isCentral && b.orbit != null).Max(b => b.orbit.baseElements.a);

        double? smallestSMA = bodies.Values.Where(b => !b.isCentral && b.orbit != null && (b.relativeTo == null || b.relativeTo == centralBody)).Max(b => b.orbit.baseElements.a);

        smallestSMA *= SO.KM;
        largestSMA *= SO.KM;
        largestRadius *= SO.KM;

        //console.log('universe size', largestSMA, ' m');

        size = largestSMA.Value;
        //this.scene.setDimension(largestSMA, smallestSMA, largestRadius);
    }

    void Update()
    {
        tick();
    }

    private void tick()
    {
        if (playing)
        {
            epochTime += ticker.getDeltaT();
            currentTime = startEpochTime + epochTime;
            ticker.tick(usePhysics.Value, currentTime);

            //this.scene.updateCamera();
            //this.scene.draw();
            //this.showDate();
        }

        //requestAnimFrame(this.ticker);
    }

/*

			getScene : function(){
				return this.scene;
			},
*/

    public double getEpochTime(DateTime userDate)
    {
        return (userDate.GetTime() - SO.J2000) / 1000;
    }

    public bool isPlaying()
    {
        return playing;
    }

    public void stop()
    {
        playing = false;
        //this.scene.updateCamera();
        //this.scene.draw();
    }
}


text:
      addywaddy

        {% include navigation.html %}

      {% if site.show_social_icons %}
        {% include social_links.html %}
      {% endif %}


text:
jopy.thermo package
===================

.. automodule:: jopy.thermo
    :members:
    :undoc-members:
    :show-inheritance:

Submodules
----------

jopy.thermo.utils module
------------------------

.. automodule:: jopy.thermo.utils
    :members:
    :undoc-members:
    :show-inheritance: