text:
"""Testing for the VotingClassifier"""

import numpy as np
from sklearn.utils.testing import assert_almost_equal, assert_array_equal
from sklearn.utils.testing import assert_equal, assert_true, assert_false
from sklearn.utils.testing import assert_raise_message
from sklearn.utils.testing import assert_warns_message
from sklearn.exceptions import NotFittedError
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import VotingClassifier
from sklearn.model_selection import GridSearchCV
from sklearn import datasets
from sklearn.model_selection import cross_val_score
from sklearn.datasets import make_multilabel_classification
from sklearn.svm import SVC
from sklearn.multiclass import OneVsRestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.base import BaseEstimator, ClassifierMixin

# Load the iris dataset and randomly permute it
iris = datasets.load_iris()
X, y = iris.data[:, 1:3], iris.target

def test_estimator_init():
    eclf = VotingClassifier(estimators=[])
    msg = ('Invalid `estimators` attribute, `estimators` should be'
           ' a list of (string, estimator) tuples')
    assert_raise_message(AttributeError, msg, eclf.fit, X, y)

    clf = LogisticRegression(random_state=1)

    eclf = VotingClassifier(estimators=[('lr', clf)], voting='error')
    msg = ('Voting must be \'soft\' or \'hard\'; got (voting=\'error\')')
    assert_raise_message(ValueError, msg, eclf.fit, X, y)

    eclf = VotingClassifier(estimators=[('lr', clf)], weights=[1, 2])
    msg = ('Number of classifiers and weights must be equal'
           '; got 2 weights, 1 estimators')
    assert_raise_message(ValueError, msg, eclf.fit, X, y)

    eclf = VotingClassifier(estimators=[('lr', clf), ('lr', clf)],
                            weights=[1, 2])
    msg = "Names provided are not unique: ['lr', 'lr']"
    assert_raise_message(ValueError, msg, eclf.fit, X, y)

    eclf = VotingClassifier(estimators=[('lr__', clf)])
    msg = "Estimator names must not contain __: got ['lr__']"
    assert_raise_message(ValueError, msg, eclf.fit, X, y)

    eclf = VotingClassifier(estimators=[('estimators', clf)])
    msg = "Estimator names conflict with constructor arguments: ['estimators']"
    assert_raise_message(ValueError, msg, eclf.fit, X, y)

def test_predictproba_hardvoting():
    eclf = VotingClassifier(estimators=[('lr1', LogisticRegression()),
                                        ('lr2', LogisticRegression())],
                            voting='hard')
    msg = "predict_proba is not available when voting='hard'"
    assert_raise_message(AttributeError, msg, eclf.predict_proba, X)

def test_notfitted():
    eclf = VotingClassifier(estimators=[('lr1', LogisticRegression()),
                                        ('lr2', LogisticRegression())],
                            voting='soft')
    msg = ("This VotingClassifier instance is not fitted yet. Call \'fit\'"
           " with appropriate arguments before using this method.")
    assert_raise_message(NotFittedError, msg, eclf.predict_proba, X)

def test_majority_label_iris():
    """Check classification by majority label on dataset iris."""
    clf1 = LogisticRegression(random_state=123)
    clf2 = RandomForestClassifier(random_state=123)
    clf3 = GaussianNB()
    eclf = VotingClassifier(estimators=[
                ('lr', clf1), ('rf', clf2), ('gnb', clf3)],
                voting='hard')
    scores = cross_val_score(eclf, X, y, cv=5, scoring='accuracy')
    assert_almost_equal(scores.mean(), 0.95, decimal=2)

def test_tie_situation():
    """Check voting classifier selects smaller class label in tie situation."""
    clf1 = LogisticRegression(random_state=123)
    clf2 = RandomForestClassifier(random_state=123)
    eclf = VotingClassifier(estimators=[('lr', clf1), ('rf', clf2)],
                            voting='hard')
    assert_equal(clf1.fit(X, y).predict(X)[73], 2)
    assert_equal(clf2.fit(X, y).predict(X)[73], 1)
    assert_equal(eclf.fit(X, y).predict(X)[73], 1)

def test_weights_iris():
    """Check classification by average probabilities on dataset iris."""
    clf1 = LogisticRegression(random_state=123)
    clf2 = RandomForestClassifier(random_state=123)
    clf3 = GaussianNB()
    eclf = VotingClassifier(estimators=[
                            ('lr', clf1), ('rf', clf2), ('gnb', clf3)],
                            voting='soft',
                            weights=[1, 2, 10])
    scores = cross_val_score(eclf, X, y, cv=5, scoring='accuracy')
    assert_almost_equal(scores.mean(), 0.93, decimal=2)

def test_predict_on_toy_problem():
    """Manually check predicted class labels for toy dataset."""
    clf1 = LogisticRegression(random_state=123)
    clf2 = RandomForestClassifier(random_state=123)
    clf3 = GaussianNB()

    X = np.array([[-1.1, -1.5],
                  [-1.2, -1.4],
                  [-3.4, -2.2],
                  [1.1, 1.2],
                  [2.1, 1.4],
                  [3.1, 2.3]])

    y = np.array([1, 1, 1, 2, 2, 2])

    assert_equal(all(clf1.fit(X, y).predict(X)), all([1, 1, 1, 2, 2, 2]))
    assert_equal(all(clf2.fit(X, y).predict(X)), all([1, 1, 1, 2, 2, 2]))
    assert_equal(all(clf3.fit(X, y).predict(X)), all([1, 1, 1, 2, 2, 2]))

    eclf = VotingClassifier(estimators=[
                            ('lr', clf1), ('rf', clf2), ('gnb', clf3)],
                            voting='hard',
                            weights=[1, 1, 1])
    assert_equal(all(eclf.fit(X, y).predict(X)), all([1, 1, 1, 2, 2, 2]))

    eclf = VotingClassifier(estimators=[
                            ('lr', clf1), ('rf', clf2), ('gnb', clf3)],
                            voting='soft',
                            weights=[1, 1, 1])
    assert_equal(all(eclf.fit(X, y).predict(X)), all([1, 1, 1, 2, 2, 2]))

def test_predict_proba_on_toy_problem():
    """Calculate predicted probabilities on toy dataset."""
    clf1 = LogisticRegression(random_state=123)
    clf2 = RandomForestClassifier(random_state=123)
    clf3 = GaussianNB()
    X = np.array([[-1.1, -1.5], [-1.2, -1.4], [-3.4, -2.2], [1.1, 1.2]])
    y = np.array([1, 1, 2, 2])

    clf1_res = np.array([[0.59790391, 0.40209609],
                         [0.57622162, 0.42377838],
                         [0.50728456, 0.49271544],
                         [0.40241774, 0.59758226]])

    clf2_res = np.array([[0.8, 0.2],
                         [0.8, 0.2],
                         [0.2, 0.8],
                         [0.3, 0.7]])

    clf3_res = np.array([[0.9985082, 0.0014918],
                         [0.99845843, 0.00154157],
                         [0., 1.],
                         [0., 1.]])

    t00 = (2*clf1_res[0][0] + clf2_res[0][0] + clf3_res[0][0]) / 4
    t11 = (2*clf1_res[1][1] + clf2_res[1][1] + clf3_res[1][1]) / 4
    t21 = (2*clf1_res[2][1] + clf2_res[2][1] + clf3_res[2][1]) / 4
    t31 = (2*clf1_res[3][1] + clf2_res[3][1] + clf3_res[3][1]) / 4

    eclf = VotingClassifier(estimators=[
                            ('lr', clf1), ('rf', clf2), ('gnb', clf3)],
                            voting='soft',
                            weights=[2, 1, 1])
    eclf_res = eclf.fit(X, y).predict_proba(X)

    assert_almost_equal(t00, eclf_res[0][0], decimal=1)
    assert_almost_equal(t11, eclf_res[1][1], decimal=1)
    assert_almost_equal(t21, eclf_res[2][1], decimal=1)
    assert_almost_equal(t31, eclf_res[3][1], decimal=1)

    try:
        eclf = VotingClassifier(estimators=[
                                ('lr', clf1), ('rf', clf2), ('gnb', clf3)],
                                voting='hard')
        eclf.fit(X, y).predict_proba(X)

    except AttributeError:
        pass
    else:
        raise AssertionError('AttributeError for voting == "hard"'
                             ' and with predict_proba not raised')

def test_multilabel():
    """Check if error is raised for multilabel classification."""
    X, y = make_multilabel_classification(n_classes=2, n_labels=1,
                                          allow_unlabeled=False,
                                          random_state=123)
    clf = OneVsRestClassifier(SVC(kernel='linear'))

    eclf = VotingClassifier(estimators=[('ovr', clf)], voting='hard')

    try:
        eclf.fit(X, y)
    except NotImplementedError:
        return

def test_gridsearch():
    """Check GridSearch support."""
    clf1 = LogisticRegression(random_state=1)
    clf2 = RandomForestClassifier(random_state=1)
    clf3 = GaussianNB()
    eclf = VotingClassifier(estimators=[
                ('lr', clf1), ('rf', clf2), ('gnb', clf3)],
                voting='soft')

    params = {'lr__C': [1.0, 100.0],
              'voting': ['soft', 'hard'],
              'weights': [[0.5, 0.5, 0.5], [1.0, 0.5, 0.5]]}

    grid = GridSearchCV(estimator=eclf, param_grid=params, cv=5)
    grid.fit(iris.data, iris.target)

def test_parallel_fit():
    """Check parallel backend of VotingClassifier on toy dataset."""
    clf1 = LogisticRegression(random_state=123)
    clf2 = RandomForestClassifier(random_state=123)
    clf3 = GaussianNB()
    X = np.array([[-1.1, -1.5], [-1.2, -1.4], [-3.4, -2.2], [1.1, 1.2]])
    y = np.array([1, 1, 2, 2])

    eclf1 = VotingClassifier(estimators=[
        ('lr', clf1), ('rf', clf2), ('gnb', clf3)],
        voting='soft',
        n_jobs=1).fit(X, y)
    eclf2 = VotingClassifier(estimators=[
        ('lr', clf1), ('rf', clf2), ('gnb', clf3)],
        voting='soft',
        n_jobs=2).fit(X, y)

    assert_array_equal(eclf1.predict(X), eclf2.predict(X))
    assert_array_equal(eclf1.predict_proba(X), eclf2.predict_proba(X))

def test_sample_weight():
    """Tests sample_weight parameter of VotingClassifier"""
    clf1 = LogisticRegression(random_state=123)
    clf2 = RandomForestClassifier(random_state=123)
    clf3 = SVC(probability=True, random_state=123)
    eclf1 = VotingClassifier(estimators=[
        ('lr', clf1), ('rf', clf2), ('svc', clf3)],
        voting='soft').fit(X, y, sample_weight=np.ones((len(y),)))
    eclf2 = VotingClassifier(estimators=[
        ('lr', clf1), ('rf', clf2), ('svc', clf3)],
        voting='soft').fit(X, y)
    assert_array_equal(eclf1.predict(X), eclf2.predict(X))
    assert_array_equal(eclf1.predict_proba(X), eclf2.predict_proba(X))

    sample_weight = np.random.RandomState(123).uniform(size=(len(y),))
    eclf3 = VotingClassifier(estimators=[('lr', clf1)], voting='soft')
    eclf3.fit(X, y, sample_weight)
    clf1.fit(X, y, sample_weight)
    assert_array_equal(eclf3.predict(X), clf1.predict(X))
    assert_array_equal(eclf3.predict_proba(X), clf1.predict_proba(X))

    clf4 = KNeighborsClassifier()
    eclf3 = VotingClassifier(estimators=[
        ('lr', clf1), ('svc', clf3), ('knn', clf4)],
        voting='soft')
    msg = ('Underlying estimator \'knn\' does not support sample weights.')
    assert_raise_message(ValueError, msg, eclf3.fit, X, y, sample_weight)

def test_sample_weight_kwargs():
    """Check that VotingClassifier passes sample_weight as kwargs"""
    class MockClassifier(BaseEstimator, ClassifierMixin):
        """Mock Classifier to check that sample_weight is received as kwargs"""
        def fit(self, X, y, *args, **sample_weight):
            assert_true('sample_weight' in sample_weight)

    clf = MockClassifier()
    eclf = VotingClassifier(estimators=[('mock', clf)], voting='soft')

    # Should not raise an error.
    eclf.fit(X, y, sample_weight=np.ones((len(y),)))

def test_set_params():
    """set_params should be able to set estimators"""
    clf1 = LogisticRegression(random_state=123, C=1.0)
    clf2 = RandomForestClassifier(random_state=123, max_depth=None)
    clf3 = GaussianNB()
    eclf1 = VotingClassifier([('lr', clf1), ('rf', clf2)], voting='soft',
                             weights=[1, 2])
    eclf1.fit(X, y)
    eclf2 = VotingClassifier([('lr', clf1), ('nb', clf3)], voting='soft',
                             weights=[1, 2])
    eclf2.set_params(nb=clf2).fit(X, y)
    assert_false(hasattr(eclf2, 'nb'))

    assert_array_equal(eclf1.predict(X), eclf2.predict(X))
    assert_array_equal(eclf1.predict_proba(X), eclf2.predict_proba(X))
    assert_equal(eclf2.estimators[0][1].get_params(), clf1.get_params())
    assert_equal(eclf2.estimators[1][1].get_params(), clf2.get_params())

    eclf1.set_params(lr__C=10.0)
    eclf2.set_params(nb__max_depth=5)

    assert_true(eclf1.estimators[0][1].get_params()['C'] == 10.0)
    assert_true(eclf2.estimators[1][1].get_params()['max_depth'] == 5)
    assert_equal(eclf1.get_params()["lr__C"],
                 eclf1.get_params()["lr"].get_params()['C'])

def test_set_estimator_none():
    """VotingClassifier set_params should be able to set estimators as None"""
    # Test predict
    clf1 = LogisticRegression(random_state=123)
    clf2 = RandomForestClassifier(random_state=123)
    clf3 = GaussianNB()
    eclf1 = VotingClassifier(estimators=[('lr', clf1), ('rf', clf2),
                                         ('nb', clf3)],
                             voting='hard', weights=[1, 0, 0.5]).fit(X, y)

    eclf2 = VotingClassifier(estimators=[('lr', clf1), ('rf', clf2),
                                         ('nb', clf3)],
                             voting='hard', weights=[1, 1, 0.5])
    eclf2.set_params(rf=None).fit(X, y)
    assert_array_equal(eclf1.predict(X), eclf2.predict(X))

    assert_true(dict(eclf2.estimators)["rf"] is None)
    assert_true(len(eclf2.estimators_) == 2)
    assert_true(all([not isinstance(est, RandomForestClassifier) for est in
                     eclf2.estimators_]))
    assert_true(eclf2.get_params()["rf"] is None)

    eclf1.set_params(voting='soft').fit(X, y)
    eclf2.set_params(voting='soft').fit(X, y)
    assert_array_equal(eclf1.predict(X), eclf2.predict(X))
    assert_array_equal(eclf1.predict_proba(X), eclf2.predict_proba(X))
    msg = ('All estimators are None. At least one is required'
           ' to be a classifier!')
    assert_raise_message(
        ValueError, msg, eclf2.set_params(lr=None, rf=None, nb=None).fit, X, y)

    # Test soft voting transform
    X1 = np.array([[1], [2]])
    y1 = np.array([1, 2])
    eclf1 = VotingClassifier(estimators=[('rf', clf2), ('nb', clf3)],
                             voting='soft', weights=[0, 0.5]).fit(X1, y1)

    eclf2 = VotingClassifier(estimators=[('rf', clf2), ('nb', clf3)],
                             voting='soft', weights=[1, 0.5])
    eclf2.set_params(rf=None).fit(X1, y1)
    assert_array_equal(eclf1.transform(X1), np.array([[[0.7, 0.3], [0.3, 0.7]],
                                                      [[1., 0.], [0., 1.]]]))
    assert_array_equal(eclf2.transform(X1), np.array([[[1., 0.], [0., 1.]]]))
    eclf1.set_params(voting='hard')
    eclf2.set_params(voting='hard')
    assert_array_equal(eclf1.transform(X1), np.array([[0, 0], [1, 1]]))
    assert_array_equal(eclf2.transform(X1), np.array([[0], [1]]))

def test_estimator_weights_format():
    # Test estimator weights inputs as list and array
    clf1 = LogisticRegression(random_state=123)
    clf2 = RandomForestClassifier(random_state=123)
    eclf1 = VotingClassifier(estimators=[
                ('lr', clf1), ('rf', clf2)],
                weights=[1, 2],
                voting='soft')
    eclf2 = VotingClassifier(estimators=[
                ('lr', clf1), ('rf', clf2)],
                weights=np.array((1, 2)),
                voting='soft')
    eclf1.fit(X, y)
    eclf2.fit(X, y)
    assert_array_equal(eclf1.predict_proba(X), eclf2.predict_proba(X))

def test_transform():
    """Check transform method of VotingClassifier on toy dataset."""
    clf1 = LogisticRegression(random_state=123)
    clf2 = RandomForestClassifier(random_state=123)
    clf3 = GaussianNB()
    X = np.array([[-1.1, -1.5], [-1.2, -1.4], [-3.4, -2.2], [1.1, 1.2]])
    y = np.array([1, 1, 2, 2])

    eclf1 = VotingClassifier(estimators=[
        ('lr', clf1), ('rf', clf2), ('gnb', clf3)],
        voting='soft').fit(X, y)
    eclf2 = VotingClassifier(estimators=[
        ('lr', clf1), ('rf', clf2), ('gnb', clf3)],
        voting='soft',
        flatten_transform=True).fit(X, y)
    eclf3 = VotingClassifier(estimators=[
        ('lr', clf1), ('rf', clf2), ('gnb', clf3)],
        voting='soft',
        flatten_transform=False).fit(X, y)

    warn_msg = ("'flatten_transform' default value will be "
                "changed to True in 0.21."
                "To silence this warning you may"
                " explicitly set flatten_transform=False.")
    res = assert_warns_message(DeprecationWarning, warn_msg,
                               eclf1.transform, X)
    assert_array_equal(res.shape, (3, 4, 2))
    assert_array_equal(eclf2.transform(X).shape, (4, 6))
    assert_array_equal(eclf3.transform(X).shape, (3, 4, 2))
    assert_array_equal(res.swapaxes(0, 1).reshape((4, 6)),
                       eclf2.transform(X))
    assert_array_equal(eclf3.transform(X).swapaxes(0, 1).reshape((4, 6)),
                       eclf2.transform(X))


text:
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE

using System.Collections.Generic;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.RP.Objects.Interface;
using OpenTK;
using OpenTK.Graphics;
using IHasEndTime = osu.Game.Rulesets.RP.Objects.Interface.IHasEndTime;

namespace osu.Game.Rulesets.RP.Objects
{
    /// <summary>
    ///     包住RP物件的容器
    /// </summary>
    public class RpContainerLineGroup : BaseRpObject, IHasID, IHasEndTime, IHasPosition, IHasRotation, IHasColor, IHasLength, IHasContainList<RpContainerLine>, IHasScale
    {
        //ID
        public int ID { get; set; }

        //end time
        public double EndTime { get; set; }

        //Duration
        public double Duration
        {
            get => EndTime - StartTime;
            set { }
        }

        //position
        public Vector2 Position { get; set; }

        //X anix
        public float X => Position.X;

        //Y anix
        public float Y => Position.Y;

        //rotation
        public float Rotation { get; set; }

        //Color
        public Color4 Color { get; set; }

        //length
        public float Lenght
        {
            get { return 512; }
            set { }
        }

        //list Contain Object
        public List<RpContainerLine> ListContainObject { get; set; }

        //scale
        public float Scale { get; set; }

        //Object type
        public override ObjectType ObjectType => ObjectType.ContainerGroup;

        /// <summary>
        ///     Initialize
        /// </summary>
        /// <param name="startTime"></param>
        public RpContainerLineGroup(double startTime)
            : base(startTime)
        {
        }

        /// <summary>
        ///     初始化物件參數
        /// </summary>
        protected override void InitialDefaultValue()
        {
            base.InitialDefaultValue();

            Scale = 1;
            //顏色
            Color = new Color4(0, 0, 0, 255);
            //速度
            Velocity = 1f;
            //預設試3秒後結束
            EndTime = StartTime + 3000;
            //初始化layout
            InitialLayer();
        }

        protected void InitialLayer()
        {
            ListContainObject = new List<RpContainerLine>();
            //每個Container裡面至少會有一層Layout
            ListContainObject.Add(new RpContainerLine(this));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
(function(permissions) {//dependent on PermissionsTable class
    "use strict";
    permissions.ContainerAppTable = function($table, is_user_admin, $navigation_links) {
        permissions.PermissionsTable.call(this, $table, is_user_admin, $navigation_links);
        this.list_url = "/api/containerapps/";
        this.registerLinkColumn("Name", "", "name", "absolute_url");
        this.registerColumn("Description", "description");
        this.registerColumn("Inputs", "inputs");
        this.registerColumn("Outputs", "outputs");
    };
    permissions.ContainerAppTable.prototype = Object.create(permissions.PermissionsTable.prototype);
    permissions.ContainerAppTable.prototype.extractRows = function(response) {
        var rows = response.results;
        for(var i in rows) {
            if (rows[i].name === '') {
                rows[i].name = '[default]';
            }
        }
        return rows;
    };
})(permissions);


text:
package com.artemzin.android.wail.api.lastfm.model.response;

import com.artemzin.android.bytes.common.StringUtil;
import com.artemzin.android.wail.api.lastfm.LFApiException;

import org.json.JSONObject;

public abstract class LFBaseResponseModel {

    private JSONObject jsonObject;
    private Error error;

    public JSONObject getJsonObject() {
        return jsonObject;
    }

    protected LFBaseResponseModel(String json) throws LFApiException {
        try {
            jsonObject = new JSONObject(json);
        } catch (Exception e) {
            throw LFApiException.newDataFormatErrorInstance(null, e.getMessage());
        }

        error = Error.optFromJSONObject(jsonObject);

        if (error != null) {
            throw LFApiException.newIntance(error.error, error.message);
        }
    }

    private static class Error {

        private String error;
        private String message;

        public String getError() {
            return error;
        }

        public String getMessage() {
            return message;
        }

        public static Error optFromJSONObject(JSONObject jsonObject) {
            final String errorValue = jsonObject.optString("error");

            if (!StringUtil.isNullOrEmpty(errorValue)) {
                final Error error = new Error();
                error.error = errorValue;
                error.message = jsonObject.optString("message");
                return error;
            }

            return null;
        }
    }

}


text:
package com.google.gapid.widgets;

import com.google.gapid.util.Events;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Text;

/**
 * Clipboard helper to handle copy-paste operations on various widgets.
 */
public class CopyPaste {
  private static final String SOURCE_DATA_KEY = CopyPaste.class.getName() + ".source";

  private final Events.ListenerCollection<Listener> listeners = Events.listeners(Listener.class);
  private final Display display;
  private final Clipboard clipboard;
  private final org.eclipse.swt.widgets.Listener focusListener;
  private boolean copyState = false;

  public CopyPaste(Display display) {
    this.display = display;
    this.clipboard = new Clipboard(display);
    this.focusListener = e -> updateCopyState();

    display.addFilter(SWT.FocusIn, focusListener);
    display.addFilter(SWT.FocusOut, focusListener);
  }

  public void dispose() {
    display.removeFilter(SWT.FocusIn, focusListener);
    display.removeFilter(SWT.FocusOut, focusListener);
    clipboard.dispose();
  }

  public void registerCopySource(Control focusReceiver, CopySource source) {
    focusReceiver.setData(SOURCE_DATA_KEY, source);
  }

  public void updateCopyState() {
    boolean newState = getCurrentCopier().hasCopyData();
    if (newState != copyState) {
      copyState = newState;
      listeners.fire().onCopyEnabled(copyState);
    }
  }

  public void doCopy() {
    getCurrentCopier().copy();
  }

  private Copier getCurrentCopier() {
    Control focus = display.getFocusControl();
    if (focus == null) {
      return Copier.NULL_COPIER;
    }

    CopySource source = (CopySource)focus.getData(SOURCE_DATA_KEY);
    if (source == null) {
      if (focus instanceof Text || focus instanceof StyledText) {
        return new Copier() {
          @Override
          public boolean hasCopyData() {
            return true;
          }

          @Override
          public void copy() {
            if (focus instanceof Text) {
              ((Text)focus).copy();
            } else if (focus instanceof StyledText) {
              ((StyledText)focus).copy();
            }
          }
        };
      }
      return Copier.NULL_COPIER;
    }

    return new Copier() {
      @Override
      public boolean hasCopyData() {
        return source.hasCopyData();
      }

      @Override
      public void copy() {
        doCopy(source);
      }
    };
  }

  protected void doCopy(CopySource source) {
    if (!source.hasCopyData()) {
      return;
    }

    CopyData[] data = source.getCopyData();
    if (data.length == 0) {
      return;
    }

    Object[] objs = new Object[data.length];
    Transfer[] transfers = new Transfer[data.length];
    for (int i = 0; i < data.length; i++) {
      objs[i] = data[i].data;
      transfers[i] = data[i].transfer;
    }
    clipboard.setContents(objs, transfers);
  }

  public void addListener(Listener listener) {
    listeners.addListener(listener);
  }

  public void removeListener(Listener listener) {
    listeners.removeListener(listener);
  }

  /**
   * A source from which data can be copied to the clipboard.
   */
  public static interface CopySource {
    /**
     * @return whether the source currently contains any copiable (selected) data.
     */
    public boolean hasCopyData();

    /**
     * @return the current copiable data.
     */
    public CopyData[] getCopyData();
  }

  /**
   * Data to be copied to the clipboard.
   */
  public static class CopyData {
    public final Object data;
    public final Transfer transfer;

    public CopyData(Object data, Transfer transfer) {
      this.data = data;
      this.transfer = transfer;
    }

    public static CopyData text(String text) {
      return new CopyData(text, TextTransfer.getInstance());
    }
  }

  @SuppressWarnings("unused")
  public static interface Listener extends Events.Listener {
    /**
     * Event that indicates whether the copy action (such as in the menu) should be enabled.
     */
    public default void onCopyEnabled(boolean enabled) { /* empty */ }
  }

  /**
   * Handles copying to the clipboard.
   */
  private static interface Copier {
    public static final Copier NULL_COPIER = new Copier() {
      @Override
      public boolean hasCopyData() {
        return false;
      }

      @Override
      public void copy() {
        // Do nothing.
      }
    };

    /**
     * @return whether the copier currently contains any copiable data.
     */
    public boolean hasCopyData();

    /**
     * Performs the copy operation.
     */
    public void copy();
  }
}


text:
#import "ZXBitArray.h"
#import "ZXBitMatrix.h"
#import "ZXBoolArray.h"
#import "ZXIntArray.h"

@interface ZXBitMatrix ()

@property (nonatomic, assign, readonly) int bitsSize;

@end

@implementation ZXBitMatrix

- (id)initWithDimension:(int)dimension {
  return [self initWithWidth:dimension height:dimension];
}

- (id)initWithWidth:(int)width height:(int)height {
  if (self = [super init]) {
    if (width < 1 || height < 1) {
      @throw [NSException exceptionWithName:NSInvalidArgumentException
                                     reason:@"Both dimensions must be greater than 0"
                                   userInfo:nil];
    }
    _width = width;
    _height = height;
    _rowSize = (_width + 31) / 32;
    _bitsSize = _rowSize * _height;
    _bits = (int32_t *)malloc(_bitsSize * sizeof(int32_t));
    [self clear];
  }

  return self;
}

- (id)initWithWidth:(int)width height:(int)height rowSize:(int)rowSize bits:(int32_t *)bits {
  if (self = [super init]) {
    _width = width;
    _height = height;
    _rowSize = rowSize;
    _bitsSize = _rowSize * _height;
    _bits = (int32_t *)malloc(_bitsSize * sizeof(int32_t));
    memcpy(_bits, bits, _bitsSize * sizeof(int32_t));
  }

  return self;
}

- (void)dealloc {
  if (_bits != NULL) {
    free(_bits);
    _bits = NULL;
  }
}

+ (ZXBitMatrix *)parse:(NSString *)stringRepresentation
             setString:(NSString *)setString
           unsetString:(NSString *)unsetString {
  if (!stringRepresentation) {
    @throw [NSException exceptionWithName:@"IllegalArgumentException"
                                   reason:@"stringRepresentation is required"
                                 userInfo:nil];
  }

  ZXBoolArray *bits = [[ZXBoolArray alloc] initWithLength:(unsigned int)stringRepresentation.length];
  int bitsPos = 0;
  int rowStartPos = 0;
  int rowLength = -1;
  int nRows = 0;
  int pos = 0;
  while (pos < stringRepresentation.length) {
    if ([stringRepresentation characterAtIndex:pos] == '\n' ||
        [stringRepresentation characterAtIndex:pos] == '\r') {
      if (bitsPos > rowStartPos) {
        if(rowLength == -1) {
          rowLength = bitsPos - rowStartPos;
        } else if (bitsPos - rowStartPos != rowLength) {
          @throw [NSException exceptionWithName:@"IllegalArgumentException"
                                         reason:@"row lengths do not match"
                                       userInfo:nil];
        }
        rowStartPos = bitsPos;
        nRows++;
      }
      pos++;
    } else if ([[stringRepresentation substringWithRange:NSMakeRange(pos, setString.length)] isEqualToString:setString]) {
      pos += setString.length;
      bits.array[bitsPos] = YES;
      bitsPos++;
    } else if ([[stringRepresentation substringWithRange:NSMakeRange(pos, unsetString.length)] isEqualToString:unsetString]) {
      pos += unsetString.length;
      bits.array[bitsPos] = NO;
      bitsPos++;
    } else {
      @throw [NSException exceptionWithName:@"IllegalArgumentException"
                                     reason:[NSString stringWithFormat:@"illegal character encountered: %@", [stringRepresentation substringFromIndex:pos]]
                                   userInfo:nil];
    }
  }

  // no EOL at end?
  if (bitsPos > rowStartPos) {
    if (rowLength == -1) {
      rowLength = bitsPos - rowStartPos;
    } else if (bitsPos - rowStartPos != rowLength) {
      @throw [NSException exceptionWithName:@"IllegalArgumentException"
                                     reason:@"row lengths do not match"
                                   userInfo:nil];
    }
    nRows++;
  }

  ZXBitMatrix *matrix = [[ZXBitMatrix alloc] initWithWidth:rowLength height:nRows];
  for (int i = 0; i < bitsPos; i++) {
    if (bits.array[i]) {
      [matrix setX:i % rowLength y:i / rowLength];
    }
  }
  return matrix;
}

- (BOOL)getX:(int)x y:(int)y {
  NSInteger offset = y * self.rowSize + (x / 32);
  return ((_bits[offset] >> (x & 0x1f)) & 1) != 0;
}

- (void)setX:(int)x y:(int)y {
  NSInteger offset = y * self.rowSize + (x / 32);
  _bits[offset] |= 1 << (x & 0x1f);
}

- (void)unsetX:(int)x y:(int)y {
  int offset = y * self.rowSize + (x / 32);
  _bits[offset] &= ~(1 << (x & 0x1f));
}

- (void)flipX:(int)x y:(int)y {
  NSUInteger offset = y * self.rowSize + (x / 32);
  _bits[offset] ^= 1 << (x & 0x1f);
}

- (void)xor:(ZXBitMatrix *)mask {
  if (self.width != mask.width || self.height != mask.height
      || self.rowSize != mask.rowSize) {
    @throw [NSException exceptionWithName:NSInvalidArgumentException
                                   reason:@"input matrix dimensions do not match"
                                 userInfo:nil];
  }
  ZXBitArray *rowArray = [[ZXBitArray alloc] initWithSize:self.width];
  for (int y = 0; y < self.height; y++) {
    int offset = y * self.rowSize;
    int32_t *row = [mask rowAtY:y row:rowArray].bits;
    for (int x = 0; x < self.rowSize; x++) {
      self.bits[offset + x] ^= row[x];
    }
  }
}

- (void)clear {
  NSInteger max = self.bitsSize;
  memset(_bits, 0, max * sizeof(int32_t));
}

- (void)setRegionAtLeft:(int)left top:(int)top width:(int)aWidth height:(int)aHeight {
  if (aHeight < 1 || aWidth < 1) {
    @throw [NSException exceptionWithName:NSInvalidArgumentException
                                   reason:@"Height and width must be at least 1"
                                 userInfo:nil];
  }
  NSUInteger right = left + aWidth;
  NSUInteger bottom = top + aHeight;
  if (bottom > self.height || right > self.width) {
    @throw [NSException exceptionWithName:NSInvalidArgumentException
                                   reason:@"The region must fit inside the matrix"
                                 userInfo:nil];
  }
  for (NSUInteger y = top; y < bottom; y++) {
    NSUInteger offset = y * self.rowSize;
    for (NSInteger x = left; x < right; x++) {
      _bits[offset + (x / 32)] |= 1 << (x & 0x1f);
    }
  }
}

- (ZXBitArray *)rowAtY:(int)y row:(ZXBitArray *)row {
  if (row == nil || [row size] < self.width) {
    row = [[ZXBitArray alloc] initWithSize:self.width];
  } else {
    [row clear];
  }
  int offset = y * self.rowSize;
  for (int x = 0; x < self.rowSize; x++) {
    [row setBulk:x * 32 newBits:_bits[offset + x]];
  }

  return row;
}

- (void)setRowAtY:(int)y row:(ZXBitArray *)row {
  for (NSUInteger i = 0; i < self.rowSize; i++) {
    _bits[(y * self.rowSize) + i] = row.bits[i];
  }
}

- (void)rotate180 {
  int width = self.width;
  int height = self.height;
  ZXBitArray *topRow = [[ZXBitArray alloc] initWithSize:width];
  ZXBitArray *bottomRow = [[ZXBitArray alloc] initWithSize:width];
  for (int i = 0; i < (height+1) / 2; i++) {
    topRow = [self rowAtY:i row:topRow];
    bottomRow = [self rowAtY:height - 1 - i row:bottomRow];
    [topRow reverse];
    [bottomRow reverse];
    [self setRowAtY:i row:bottomRow];
    [self setRowAtY:height - 1 - i row:topRow];
  }
}

- (ZXIntArray *)enclosingRectangle {
  int left = self.width;
  int top = self.height;
  int right = -1;
  int bottom = -1;

  for (int y = 0; y < self.height; y++) {
    for (int x32 = 0; x32 < self.rowSize; x32++) {
      int32_t theBits = _bits[y * self.rowSize + x32];
      if (theBits != 0) {
        if (y < top) {
          top = y;
        }
        if (y > bottom) {
          bottom = y;
        }
        if (x32 * 32 < left) {
          int32_t bit = 0;
          while ((theBits << (31 - bit)) == 0) {
            bit++;
          }
          if ((x32 * 32 + bit) < left) {
            left = x32 * 32 + bit;
          }
        }
        if (x32 * 32 + 31 > right) {
          int bit = 31;
          while ((theBits >> bit) == 0) {
            bit--;
          }
          if ((x32 * 32 + bit) > right) {
            right = x32 * 32 + bit;
          }
        }
      }
    }
  }

  NSInteger width = right - left + 1;
  NSInteger height = bottom - top + 1;

  if (width < 0 || height < 0) {
    return nil;
  }

  return [[ZXIntArray alloc] initWithInts:left, top, width, height, -1];
}

- (ZXIntArray *)topLeftOnBit {
  int bitsOffset = 0;
  while (bitsOffset < self.bitsSize && _bits[bitsOffset] == 0) {
    bitsOffset++;
  }
  if (bitsOffset == self.bitsSize) {
    return nil;
  }
  int y = bitsOffset / self.rowSize;
  int x = (bitsOffset % self.rowSize) * 32;

  int32_t theBits = _bits[bitsOffset];
  int32_t bit = 0;
  while ((theBits << (31 - bit)) == 0) {
    bit++;
  }
  x += bit;
  return [[ZXIntArray alloc] initWithInts:x, y, -1];
}

- (ZXIntArray *)bottomRightOnBit {
  int bitsOffset = self.bitsSize - 1;
  while (bitsOffset >= 0 && _bits[bitsOffset] == 0) {
    bitsOffset--;
  }
  if (bitsOffset < 0) {
    return nil;
  }

  int y = bitsOffset / self.rowSize;
  int x = (bitsOffset % self.rowSize) * 32;

  int32_t theBits = _bits[bitsOffset];
  int32_t bit = 31;
  while ((theBits >> bit) == 0) {
    bit--;
  }
  x += bit;

  return [[ZXIntArray alloc] initWithInts:x, y, -1];
}

- (BOOL)isEqual:(NSObject *)o {
  if (!([o isKindOfClass:[ZXBitMatrix class]])) {
    return NO;
  }
  ZXBitMatrix *other = (ZXBitMatrix *)o;
  for (int i = 0; i < self.bitsSize; i++) {
    if (_bits[i] != other.bits[i]) {
      return NO;
    }
  }
  return self.width == other.width && self.height == other.height && self.rowSize == other.rowSize && self.bitsSize == other.bitsSize;
}

- (NSUInteger)hash {
  NSInteger hash = self.width;
  hash = 31 * hash + self.width;
  hash = 31 * hash + self.height;
  hash = 31 * hash + self.rowSize;
  for (NSUInteger i = 0; i < self.bitsSize; i++) {
    hash = 31 * hash + _bits[i];
  }
  return hash;
}

// string representation using "X" for set and " " for unset bits
- (NSString *)description {
  return [self descriptionWithSetString:@"X " unsetString:@"  "];
}

- (NSString *)descriptionWithSetString:(NSString *)setString unsetString:(NSString *)unsetString {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  return [self descriptionWithSetString:setString unsetString:unsetString lineSeparator:@"\n"];
#pragma GCC diagnostic pop
}

- (NSString *)descriptionWithSetString:(NSString *)setString unsetString:(NSString *)unsetString
                         lineSeparator:(NSString *)lineSeparator {
  NSMutableString *result = [NSMutableString stringWithCapacity:self.height * (self.width + 1)];
  for (int y = 0; y < self.height; y++) {
    for (int x = 0; x < self.width; x++) {
      [result appendString:[self getX:x y:y] ? setString : unsetString];
    }
    [result appendString:lineSeparator];
  }
  return result;
}

- (id)copyWithZone:(NSZone *)zone {
  return [[ZXBitMatrix allocWithZone:zone] initWithWidth:self.width height:self.height rowSize:self.rowSize bits:self.bits];
}

@end


text:
using ICSharpCode.AvalonEdit.CodeCompletion;
using ICSharpCode.AvalonEdit.Highlighting;
using Innovator.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Documents;
using System.Windows.Media;

namespace InnovatorAdmin.Editor
{
  public class RegexHelper : PlainTextEditorHelper
  {
    private InsightWindow _currentInsight;

    public override string BlockCommentEnd { get { return ")"; } }
    public override string BlockCommentStart { get { return "(?#"; } }
    public override string LineComment { get { return "#"; } }

    public override ICSharpCode.AvalonEdit.Highlighting.IHighlightingDefinition GetHighlighting()
    {
      return _highlighter;
    }

    public override void HandleTextEntered(EditorWinForm control, string insertText)
    {
      switch (insertText)
      {
        case "\\":
          ShowCompletions(control);
          break;
        case "{":
        case "(":
        case "[":
          if (_currentInsight != null)
            _currentInsight.Hide();

          var overload = new OverloadInsightWindow(control.Editor.TextArea);
          if (insertText == "{")
            overload.Provider = _quantifiers;
          else if (insertText == "(")
            overload.Provider = _groups;
          else
            overload.Provider = _charClass;
          overload.Show();
          _currentInsight = overload;
          break;
        case "}":
        case ")":
        case "]":
          if (_currentInsight != null)
            _currentInsight.Hide();

          _currentInsight = null;
          break;
      }
    }

    private static OverloadList _quantifiers = new OverloadList()
    {
      {"{n}", "Exactly n times"},
      {"{n,}", "At least n times"},
      {"{n,}?", "At least n times as few times as possible"},
      {"{n,m}", "At least n, but no more than m times"},
      {"{n,m}?", "At least n, but no more than m times as few times as possible"}
    };

    private static OverloadList _groups = new OverloadList()
    {
      {"(subexpression)", "Captures the matched subexpression and assigns it a one-based ordinal number."},
      {"(?: subexpression)", "Defines a noncapturing group."},
      {"(?= subexpression)", "Zero-width positive lookahead assertion."},
      {"(?! subexpression)", "Zero-width negative lookahead assertion."},
      {"(?<= subexpression)", "Zero-width positive lookbehind assertion."},
      {"(?> subexpression)", "Nonbacktracking (or \"greedy\") subexpression."},
      {"(?# comment)", "Inline comment"}
    };

    private static OverloadList _charClass = new OverloadList()
    {
      {"[character_group]", "Matches the listed characters."},
      {"[^character_group]", "Matches characters which aren't listed."}
    };

    private static string[][] _completionInfo = new string[][] {
      new string[] { "a", "Bell Character (\\u0007)"},
      new string[] { "b", "Backspace (in a character class) (\\u0008)"},
      new string[] { "t", "Tab (\\u0009)"},
      new string[] { "r", "Carriage Return (\\u000d)"},
      new string[] { "v", "Vertical Tab (\\u000b)"},
      new string[] { "f", "Form Feed (\\u000c)"},
      new string[] { "n", "New Line (\\u000a)"},
      new string[] { "e", "Escape (\\u001b)"},
      new string[] { "w", "Word character ([a-zA-Z0-9_])"},
      new string[] { "W", "Non-word character ([^a-zA-Z0-9_])"},
      new string[] { "s", "White-space character"},
      new string[] { "S", "Non-white-space character"},
      new string[] { "d", "Digit ([0-9])"},
      new string[] { "D", "Non-digit ([^0-9])"},
      new string[] { "A", "Match occurs at the start of the string"},
      new string[] { "Z", "Match occurs at the end of the string or line"},
      new string[] { "z", "Match occurs at the end of the string or line"},
      new string[] { "G", "Match occurs where previous match ended"},
      new string[] { "b", "Match occurs on a boundary between a \\w and \\W character"},
      new string[] { "B", "Match does not occur on a \\b boundary"}
    };

    public override Innovator.Client.IPromise<CompletionContext> ShowCompletions(EditorWinForm control)
    {
      var length = control.Editor.Document.TextLength;
      var caret = control.Editor.CaretOffset;
      var data = new CompletionContext();

      if (caret > 0 && control.Editor.Document.GetCharAt(caret - 1) == '\\')
      {
        data.Items = _completionInfo
          .OrderBy(i => i[0].ToLowerInvariant())
          .ThenBy(i => i[1])
          .Select(i => new BasicCompletionData() {
            Content = FormatText.Span(FormatText.Text(i[0] + " "), FormatText.MutedText(i[1])),
            Text = i[0],
            Action = () => i[0]
          });
      }

      if (data.Items.Any())
      {
        var items = data.Items.ToArray();
        var contextItems = items.OfType<IContextCompletions>();
        foreach (var contextItem in contextItems)
        {
          contextItem.SetContext(this, control);
        }

        control.ShowCompletionWindow(items, data.Overlap);
      }

      return Promises.Resolved(data);
    }

    internal static IHighlightingDefinition _highlighter;

    static RegexHelper()
    {
      using (var stream = System.Reflection.Assembly.GetExecutingAssembly()
        .GetManifestResourceStream("InnovatorAdmin.resources.Regex.xshd"))
      {
        using (var reader = new System.Xml.XmlTextReader(stream))
        {
          _highlighter =
              ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(reader,
              ICSharpCode.AvalonEdit.Highlighting.HighlightingManager.Instance);
        }
      }
    }
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>MIPS Pipelined Scoreboard Machine Simulator: DataSegment Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

MIPS Pipelined Scoreboard Machine Simulator
    1.4

Public Member Functions |
Protected Member Functions |
Protected Attributes |
List of all members

DataSegment Class Reference

Simulates a data segment in memory.
 More...

#include <DataSegment.hpp>

Inheritance diagram for DataSegment:

  <map id="DataSegment_map" name="DataSegment_map">
<area href="class_segment.html" title="Simulates an abstract segment in memory. " alt="Segment" shape="rect" coords="0,0,86,24"/>
</map>

Public Member Functions

 	DataSegment ()

 	Default constructor.

 	DataSegment (address baseAddress, address maxAddress)

qword 	readNumber (address at, int size)

string 	readString (address at)

void 	writeNumber (address to, qword data, int size)

void 	writeString (address to, vector< byte > data)

Protected Member Functions

byte 	getByte (address at)

qword 	getBytes (address at, int size)

void 	writeBytes (address to, qword data, int size)

Protected Attributes

map< address, byte > 	memoryUnit

 	the range of memory allocated to the segment as a map of dwords to bytes

address 	baseAddress

 	the minimum address the segment has access too

address 	maxAddress

 	the maximum address the segment has access too

int 	size

 	the size of the segment

Detailed Description

Simulates a data segment in memory.

Constructor & Destructor Documentation

§ DataSegment()

          DataSegment::DataSegment
          (
          address
          baseAddress,

          address
          maxAddress

          )

Constructor to create a DataSegment at the given address

Parameters

baseAddress	the minimum address this segment will be able to access

maxAddress	the maximum address this segment has access to

Member Function Documentation

§ getByte()

          byte Segment::getByte
          (
          address
          at	)

protectedinherited

Attempts to retrieve the byte stored at address, if this address hasn't been initialized, returns 0

Parameters

at	the physcial address of memory to read from

Returns

the byte stored at address

§ getBytes()

          qword Segment::getBytes
          (
          address
          at,

          int
          size

          )

protectedinherited

Attempts to fill a qword with a piece of data of a given size

Parameters

at	the address to read data from

size	the number of bytes to read

§ readNumber()

          qword DataSegment::readNumber
          (
          address
          at,

          int
          size

          )

Reads the number stored at a virtual address

Parameters

at	the virtual address to read from

size	the size of the number in bytes

Returns

the number of a size stored at at

§ readString()

          string DataSegment::readString
          (
          address
          at	)

Reads the string stored at a virtual address

Parameters

at	the virtual address to read from

Returns

the string starting at at

§ writeBytes()

          void Segment::writeBytes
          (
          address
          to,

          qword
          data,

          int
          size

          )

protectedinherited

Attempts write a qword with a piece of data of a given size

Parameters

to	the address to write data to

data	the data to write to memory

size	the number of bytes to write

§ writeNumber()

          void DataSegment::writeNumber
          (
          address
          to,

          qword
          data,

          int
          size

          )

Writes a number to a virtual memory address

Parameters

to	the virtual address to write to

data	the number to write

§ writeString()

          void DataSegment::writeString
          (
          address
          to,

          vector< byte >
          data

          )

Writes a string to a virtual memory address

Parameters

to	the virtual address to write to

data	the array of bytes containing the string data

The documentation for this class was generated from the following files:

Simulator/CPU/Memory/DataSegment.hpp

Simulator/CPU/Memory/DataSegment.cpp

<address class="footer">
Generated by

 1.8.12
</address>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

001
002
007
008package org.jsimpledb.ant;
009
010import java.io.BufferedInputStream;
011import java.io.BufferedOutputStream;
012import java.io.File;
013import java.io.FileInputStream;
014import java.io.FileOutputStream;
015import java.io.IOException;
016import java.util.HashSet;
017
018import org.apache.tools.ant.AntClassLoader;
019import org.apache.tools.ant.BuildException;
020import org.apache.tools.ant.Task;
021import org.apache.tools.ant.types.Path;
022import org.apache.tools.ant.types.Reference;
023import org.jsimpledb.DefaultStorageIdGenerator;
024import org.jsimpledb.JSimpleDBFactory;
025import org.jsimpledb.StorageIdGenerator;
026import org.jsimpledb.annotation.JFieldType;
027import org.jsimpledb.core.Database;
028import org.jsimpledb.core.FieldType;
029import org.jsimpledb.kv.simple.SimpleKVDatabase;
030import org.jsimpledb.schema.SchemaModel;
031import org.jsimpledb.spring.JSimpleDBClassScanner;
032import org.jsimpledb.spring.JSimpleDBFieldTypeScanner;
033
034/**
035 * Ant task for schema XML generation and/or verification.
036 *
037 * <p>
038 * This task scans the configured classpath for classes with {@link org.jsimpledb.annotation.JSimpleClass &#64;JSimpleClass}
039 * and {@link org.jsimpledb.annotation.JFieldType &#64;JFieldType} annotations and either writes the generated schema
040 * to an XML file, or verifies the schema from an existing XML file.
041 * </p>
042 *
043 * <p>
044 * The following tasks are supported:
045 * </p>
046 *
047 * <div style="margin-left: 20px;">
048 * <table border="1" cellpadding="3" cellspacing="0" summary="Supported Tasks">
049 * <tr style="bgcolor:#ccffcc">
050 *  <th align="left">Attribute</th>
051 *  <th align="left">Required?</th>
052 *  <th align="left">Description</th>
053 * </tr>
054 * <tr>
055 *  <td>{@code mode}</td>
056 *  <td>No</td>
057 *  <td>
058 *      <p>
059 *      Set to {@code generate} to generate a new XML file, or {@code verify} to verify an existing XML file.
060 *      </p>
061 *
062 *      <p>
063 *      Default is {@code verify}.
064 *      </p>
065 * </td>
066 * </tr>
067 * <tr>
068 *  <td>{@code file}</td>
069 *  <td>Yes</td>
070 *  <td>
071 *      <p>
072 *      The XML file to generate or verify.
073 *      </p>
074 * </td>
075 * </tr>
076 * <tr>
077 *  <td>{@code matchNames}</td>
078 *  <td>No</td>
079 *  <td>
080 *      <p>
081 *      Whether to verify not only schema compatibility but also that the two schemas are identical, i.e.,
082 *      the same names are used for object types, fields, and composite indexes.
083 *      </p>
084 *
085 *      <p>
086 *      Two schemas that are equivalent except for names are considered compatible, because the core API uses
087 *      storage ID's, not names. However, if names change then some JSimpleDB layer operations, such as index
088 *      queries and reference path inversion, may need to be updated.
089 *      </p>
090 *
091 *      <p>
092 *      Default is {@code true}. Ignored unless {@code mode} is {@code verify}.
093 *      </p>
094 * </td>
095 * </tr>
096 * <tr>
097 *  <td>{@code failOnError}</td>
098 *  <td>No</td>
099 *  <td>
100 *      <p>
101 *      Whether to fail if verification fails.
102 *      </p>
103 *
104 *      <p>
105 *      Default is {@code true}. Ignored unless {@code mode} is {@code verify}.
106 *      </p>
107 * </td>
108 * </tr>
109 * <tr>
110 *  <td>{@code verifiedProperty}</td>
111 *  <td>No</td>
112 *  <td>
113 *      <p>
114 *      The name of an ant property to set to {@code true} or {@code false} depending on whether
115 *      verification succeeded or failed. Useful when {@code failOnError} is set to {@code false}
116 *      and you want to handle the failure elsewhere in the build file.
117 *      </p>
118 *
119 *      <p>
120 *      Default is to not set any property.
121 *      </p>
122 * </td>
123 * </tr>
124 * <tr>
125 *  <td>{@code classpath} or {@code classpathref}</td>
126 *  <td>Yes</td>
127 *  <td>
128 *      <p>
129 *      Specifies the search path for classes with {@link org.jsimpledb.annotation.JSimpleClass &#64;JSimpleClass}
130 *      annotations.
131 *      </p>
132 * </td>
133 * </tr>
134 * <tr>
135 *  <td>{@code packages}</td>
136 *  <td>Yes</td>
137 *  <td>
138 *      <p>
139 *      Specifies one or more Java package names (separated by commas and/or whitespace) under which to look
140 *      for classes with {@link org.jsimpledb.annotation.JSimpleClass &#64;JSimpleClass}
141 *      and {@link org.jsimpledb.annotation.JFieldType &#64;JFieldType} annotations.
142 *      </p>
143 * </td>
144 * </tr>
145 * <tr>
146 *  <td>{@code storageIdGeneratorClass}</td>
147 *  <td>No</td>
148 *  <td>
149 *      <p>
150 *      Specifies the name of an optional custom {@link StorageIdGenerator} class.
151 *      </p>
152 *
153 *      <p>
154 *      By default, a {@link DefaultStorageIdGenerator} is used.
155 *      </p>
156 * </td>
157 * </tr>
158 * </table>
159 * </div>
160 *
161 * <p>
162 * Example:
163 * <pre>
164 *  &lt;project xmlns:jsimpledb="urn:org.dellroad.jsimpledb" ... &gt;
165 *      ...
166 *      &lt;taskdef uri="urn:org.dellroad.jsimpledb" name="schema"
167 *        classname="org.jsimpledb.ant.SchemaGeneratorTask" classpathref="jsimpledb.classpath"/&gt;
168 *      &lt;jsimpledb:schema mode="verify" classpathref="myclasses.classpath"
169 *        file="expected-schema.xml" packages="com.example.model"/&gt;
170 * </pre>
171 *
172 * @see org.jsimpledb.JSimpleDB
173 * @see org.jsimpledb.schema.SchemaModel
174 */
175public class SchemaGeneratorTask extends Task {
176
177    public static final String MODE_VERIFY = "verify";
178    public static final String MODE_GENERATE = "generate";
179
180    private String[] packages;
181    private String mode = MODE_VERIFY;
182    private boolean matchNames = true;
183    private boolean failOnError = true;
184    private String verifiedProperty;
185    private File file;
186    private Path classPath;
187    private String storageIdGeneratorClassName = DefaultStorageIdGenerator.class.getName();
188
189    public void setPackages(String packages) {
190        this.packages = packages.split("[\\s,]");
191    }
192
193    public void setMode(String mode) {
194        this.mode = mode;
195    }
196
197    public void setMatchNames(boolean matchNames) {
198        this.matchNames = matchNames;
199    }
200
201    public void setFailOnError(boolean failOnError) {
202        this.failOnError = failOnError;
203    }
204
205    public void setVerifiedProperty(String verifiedProperty) {
206        this.verifiedProperty = verifiedProperty;
207    }
208
209    public void setFile(File file) {
210        this.file = file;
211    }
212
213    public Path createClasspath() {
214        this.classPath = new Path(this.getProject());
215        return this.classPath;
216    }
217
218    public void setClasspath(Path classPath) {
219        this.classPath = classPath;
220    }
221
222    public void setClasspathRef(Reference ref) {
223        this.classPath = (Path)ref.getReferencedObject(this.getProject());
224    }
225
226    public void setStorageIdGeneratorClass(String storageIdGeneratorClassName) {
227        this.storageIdGeneratorClassName = storageIdGeneratorClassName;
228    }
229
230    /**
231     * @throws BuildException if operation fails
232     */
233    @Override
234    public void execute() {
235
236        // Sanity check
237        if (this.file == null)
238            throw new BuildException("`file' attribute is required specifying output/verify file");
239        final boolean generate;
240        switch (this.mode) {
241        case MODE_VERIFY:
242            generate = false;
243            break;
244        case MODE_GENERATE:
245            generate = true;
246            break;
247        default:
248            throw new BuildException("`mode' attribute must be one of `" + MODE_VERIFY + "' or `" + MODE_GENERATE + "'");
249        }
250        if (this.packages == null)
251            throw new BuildException("`packages' attribute is required specifying packages to scan for Java model classes");
252        if (this.classPath == null)
253            throw new BuildException("`classpath' attribute is required specifying search path for scanned classes");
254
255        // Create directory containing file
256        if (generate && this.file.getParent() != null && !this.file.getParentFile().exists() && !this.file.getParentFile().mkdirs())
257            throw new BuildException("error creating directory `" + this.file.getParentFile() + "'");
258
259        // Set up mysterious classloader stuff
260        final AntClassLoader loader = this.getProject().createClassLoader(this.classPath);
261        final ClassLoader currentLoader = this.getClass().getClassLoader();
262        if (currentLoader != null)
263            loader.setParent(currentLoader);
264        loader.setThreadContextLoader();
265        try {
266
267            // Scan for @JSimpleClass classes
268            final HashSet<Class<?>> modelClasses = new HashSet<>();
269            for (String className : new JSimpleDBClassScanner().scanForClasses(this.packages)) {
270                this.log("adding JSimpleDB schema class " + className);
271                try {
272                    modelClasses.add(Class.forName(className, false, Thread.currentThread().getContextClassLoader()));
273                } catch (ClassNotFoundException e) {
274                    throw new BuildException("failed to load class `" + className + "'", e);
275                }
276            }
277
278            // Scan for @JFieldType classes
279            final HashSet<FieldType<?>> fieldTypes = new HashSet<>();
280            for (String className : new JSimpleDBFieldTypeScanner().scanForClasses(this.packages)) {
281                this.log("adding JSimpleDB field type class " + className);
282                try {
283                    fieldTypes.add(this.asFieldTypeClass(
284                      Class.forName(className, false, Thread.currentThread().getContextClassLoader())).newInstance());
285                } catch (Exception e) {
286                    throw new BuildException("failed to instantiate class `" + className + "'", e);
287                }
288            }
289
290            // Instantiate StorageIdGenerator
291            final StorageIdGenerator storageIdGenerator;
292            try {
293                storageIdGenerator = Class.forName(this.storageIdGeneratorClassName,
294                  false, Thread.currentThread().getContextClassLoader()).asSubclass(StorageIdGenerator.class).newInstance();
295            } catch (Exception e) {
296                throw new BuildException("failed to instantiate class `" + storageIdGeneratorClassName + "'", e);
297            }
298
299            // Set up database and configure field type classes
300            final Database db = new Database(new SimpleKVDatabase());
301            for (FieldType<?> fieldType : fieldTypes) {
302                try {
303                    db.getFieldTypeRegistry().add(fieldType);
304                } catch (Exception e) {
305                    throw new BuildException("failed to register custom field type " + fieldType.getClass().getName(), e);
306                }
307            }
308
309            // Set up factory
310            final JSimpleDBFactory factory = new JSimpleDBFactory();
311            factory.setDatabase(db);
312            factory.setSchemaVersion(1);
313            factory.setStorageIdGenerator(storageIdGenerator);
314            factory.setModelClasses(modelClasses);
315
316            // Build schema model
317            this.log("generating JSimpleDB schema from schema classes");
318            final SchemaModel schemaModel;
319            try {
320                schemaModel = factory.newJSimpleDB().getSchemaModel();
321            } catch (Exception e) {
322                throw new BuildException("schema generation failed: " + e, e);
323            }
324
325            // Verify or generate
326            if (generate) {
327
328                // Write schema model to file
329                this.log("writing JSimpleDB schema to `" + this.file + "'");
330                try (BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(this.file))) {
331                    schemaModel.toXML(output, true);
332                } catch (IOException e) {
333                    throw new BuildException("error writing schema to `" + this.file + "': " + e, e);
334                }
335            } else {
336
337                // Read file
338                this.log("verifying JSimpleDB schema matches `" + this.file + "'");
339                final SchemaModel verifyModel;
340                try (BufferedInputStream input = new BufferedInputStream(new FileInputStream(this.file))) {
341                    verifyModel = SchemaModel.fromXML(input);
342                } catch (IOException e) {
343                    throw new BuildException("error reading schema from `" + this.file + "': " + e, e);
344                }
345
346                // Compare
347                final boolean verified = matchNames ? schemaModel.equals(verifyModel) : schemaModel.isCompatibleWith(verifyModel);
348                if (this.verifiedProperty != null)
349                    this.getProject().setProperty(this.verifiedProperty, "" + verified);
350                this.log("schema verification " + (verified ? "succeeded" : "failed"));
351                if (!verified) {
352                    this.log(schemaModel.differencesFrom(verifyModel).toString());
353                    if (this.failOnError)
354                        throw new BuildException("schema verification failed");
355                }
356            }
357        } finally {
358            loader.resetThreadContextLoader();
359            loader.cleanup();
360        }
361    }
362
363    @SuppressWarnings("unchecked")
364    private Class<? extends FieldType<?>> asFieldTypeClass(Class<?> klass) {
365        try {
366            return (Class<? extends FieldType<?>>)klass.asSubclass(FieldType.class);
367        } catch (ClassCastException e) {
368            throw new BuildException("invalid @" + JFieldType.class.getSimpleName() + " annotation on "
369              + klass + ": type is not a subclass of " + FieldType.class);
370        }
371    }
372}
373


text:
from flask import Blueprint, render_template, redirect, url_for

from deployer import database as db
from deployer.utils import xhr_form
from . import models, forms

views = Blueprint('hosts', __name__, template_folder='templates')

@views.route('/')
def index():
    hosts = db.Session().query(models.Host).all()
    return render_template('hosts.html', hosts=hosts)

@views.route('/<int:host_id>/')
def host(host_id):
    host = db.get_or_abort(models.Host, host_id)
    return render_template('host.html', host=host)

@views.route('/new/', methods=['GET', 'POST'], endpoint='new')
@views.route('/<int:host_id>/edit/', methods=['GET', 'POST'])
@xhr_form
def edit(host_id=None):
    create = host_id is None
    host = None if create else db.get_or_abort(models.Host, host_id)
    form = forms.HostForm(obj=host)

    if form.validate_on_submit():
        session = db.Session()
        if create:
            host = models.Host()
        form.populate_obj(host)
        session.add(host)
        session.commit()
        return redirect(url_for('.host', host_id=host.id))

    return render_template('edit-host.html',
                           form=form, create=create, host=host)


text:
package pl.wavesoftware.examples.wildflyswarmtester;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Krzysztof Suszynski <krzysztof.suszynski@coi.gov.pl>
 * @since 04.03.16
 */
@WebServlet("/")
public class HelloServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().append("Hello from WildFly Swarm!");
    }
}


text:
package util

import (
	"fmt"
	"io"
	"os"
	"path"
	"path/filepath"

	"github.com/nuclio/nuclio/pkg/common"

	"github.com/nuclio/errors"
)

// CopyTo copies source to dest
// If source is a file and dest is a file, performs copy file
// If source is a dir and dest is a dir, performs copy dir
// If source is a file and dest is a dir, copies source to the dest dir with the same name
// If source is a dir and dest is a file, returns error
func CopyTo(source string, dest string) error {
	sourceIsFile := common.IsFile(source)
	destIsFile := common.IsFile(dest)

	// dir -> file
	if !sourceIsFile && destIsFile {
		return errors.New("Cannot copy directory to file")
	}

	// file -> file
	if sourceIsFile && destIsFile {
		return CopyFile(source, dest)
	}

	// dir -> dir
	if !sourceIsFile && !destIsFile {
		_, err := CopyDir(source, dest)
		return err
	}

	// file -> dir
	if sourceIsFile && !destIsFile {

		// get the source file name
		sourceFileName := path.Base(source)

		// dest is dest dir + source file name
		dest = path.Join(dest, sourceFileName)

		// get the destination as the dest dir +
		return CopyFile(source, dest)
	}

	return errors.New("Should not get here")
}

// CopyFile copies file source to destination dest.
func CopyFile(source string, dest string) error {
	sf, err := os.Open(source)
	if err != nil {
		return err
	}

	defer sf.Close() // nolint: errcheck

	df, err := os.Create(dest)
	if err != nil {
		return err
	}

	defer df.Close() // nolint: errcheck

	if _, err = io.Copy(df, sf); err != nil {
		return err
	}

	si, err := sf.Stat()
	if err == nil {
		return os.Chmod(dest, si.Mode())
	}

	return nil
}

// CopyDir Recursively copies a directory tree, attempting to preserve
// permissions.  Source directory must exist, destination directory must *not*
// exist.
func CopyDir(source string, dest string) (bool, error) {

	if source == dest {
		return true, nil
	}
	// get properties of source dir
	fi, err := os.Stat(source)
	if err != nil {
		return false, nil
	}

	if !fi.IsDir() {
		return false, fmt.Errorf("Source (%q) is not a directory", source)
	}

	// create dest dir
	err = os.MkdirAll(dest, fi.Mode())
	if err != nil {
		return false, err
	}

	entries, err := os.ReadDir(source)
	if err != nil {
		return false, err
	}

	for _, entry := range entries {
		sfp := filepath.Join(source, entry.Name())
		dfp := filepath.Join(dest, entry.Name())
		if entry.IsDir() {
			_, err = CopyDir(sfp, dfp)
			if err != nil {
				return false, err
			}
		} else {
			// perform copy
			err = CopyFile(sfp, dfp)
			if err != nil {
				return false, err
			}
		}

	}
	return true, nil
}


text:
function ETransformTool::getScale( %this,%axis ) {
	%obj = %this.getSelectionObj();

	if (%obj $= "")
		return;

	%scale = %obj.scale;

	if (%axis $= "x" || %axis $= "")
		%this.setFieldValueContainers("ScaleX",getWord(%scale, 0));

	if (%axis $= "y" || %axis $= "")
		%this.setFieldValueContainers("ScaleY",getWord(%scale, 1));

	if (%axis $= "z" || %axis $= "")
		%this.setFieldValueContainers("ScaleZ",getWord(%scale, 2));
}
//------------------------------------------------------------------------------
//==============================================================================
function ETransformTool::setSelScale( %this,%axis ) {
	%scaleX = %this-->ScaleX.getText();
	%scaleY = %this-->ScaleY.getText();
	%scaleZ = %this-->ScaleZ.getText();
	%scale = "0 0 0";

	if (%axis $= "x" || %axis $= "")
		%scale.x += %scaleX;

	if (%axis $= "y" || %axis $= "")
		%scale.y += %scaleY;

	if (%axis $= "z" || %axis $= "")
		%scale.z += %scaleZ;

	//EWorldEditor.transformSelection(doPosition, point, doRelativePos, doRotate,rotation, doRelativeRot, doRotLocal, scaleType, scale, isRelative,  isLocal );
	EWorldEditor.transformSelection(true,"",false,false,"",false,false,"",%scale,false,false);
}
//------------------------------------------------------------------------------
//==============================================================================
function ETransformTool::clearScale( %this,%axis ) {
	if (%axis $= "x" || %axis $= "")
		%this.setFieldValueContainers("ScaleX","0");

	if (%axis $= "y" || %axis $= "")
		%this.setFieldValueContainers("ScaleY","0");

	if (%axis $= "z" || %axis $= "")
		%this.setFieldValueContainers("ScaleZ","0");
}
//------------------------------------------------------------------------------

//==============================================================================
// OLD FUNCTIONS FOR REFERENCE
//==============================================================================
function ETransformSelection::getAbsScaleOLD( %this ) {
	%count = EWorldEditor.getSelectionSize();
	// If we have more than one SceneObject selected,
	// we must exit.
	%obj = -1;

	for( %i=0; %i<%count; %i++) {
		%test = EWorldEditor.getSelectedObject( %i );

		if( %test.isMemberOfClass("SceneObject") ) {
			if( %obj != -1 )
				return;

			%obj = %test;
		}
	}

	if( %obj == -1 ) {
		// No SceneObjects selected
		return;
	}

	%scale = %obj.scale;
	%scalex = getWord(%scale, 0);
	%this-->ScaleX.setText(%scalex);

	if( ETransformSelectionScaleProportional.getValue() == false ) {
		%this-->ScaleY.setText(getWord(%scale, 1));
		%this-->ScaleZ.setText(getWord(%scale, 2));
	} else {
		%this-->ScaleY.setText(%scalex);
		%this-->ScaleZ.setText(%scalex);
	}

	// Turn off relative as we're populating absolute values
	%this-->ScaleRelative.setValue(0);
	// Finally, set the Scale check box as active.  The user
	// likely wants this if they're getting the position.
	%this-->DoScale.setValue(1);
}

function ETransformSelection::getAbsSizeOLD( %this ) {
	%count = EWorldEditor.getSelectionSize();
	// If we have more than one SceneObject selected,
	// we must exit.
	%obj = -1;

	for( %i=0; %i<%count; %i++) {
		%test = EWorldEditor.getSelectedObject( %i );

		if( %test.isMemberOfClass("SceneObject") ) {
			if( %obj != -1 )
				return;

			%obj = %test;
		}
	}

	if( %obj == -1 ) {
		// No SceneObjects selected
		return;
	}

	%size = %obj.getObjectBox();
	%scale = %obj.getScale();
	%sizex = (getWord(%size, 3) - getWord(%size, 0)) * getWord(%scale, 0);
	%this-->SizeX.setText( %sizex );

	if( ETransformSelectionSizeProportional.getValue() == false ) {
		%this-->SizeY.setText( (getWord(%size, 4) - getWord(%size, 1)) * getWord(%scale, 1) );
		%this-->SizeZ.setText( (getWord(%size, 5) - getWord(%size, 2)) * getWord(%scale, 2) );
	} else {
		%this-->SizeY.setText( %sizex );
		%this-->SizeZ.setText( %sizex );
	}

	// Turn off relative as we're populating absolute values
	%this-->SizeRelative.setValue(0);
	// Finally, set the Size check box as active.  The user
	// likely wants this if they're getting the position.
	%this-->DoSize.setValue(1);
}


text:
\courseTemplate[
code = {COMP3301},
title = {Operating Systems Architecture},
score = 4,
prereq = {COMP2303 or CSSE2310},
contact = {1L, 1T, 2P},
coordinator = {Dr Matthew D\'Souza (m.dsouza@uq.edu.au)},
assessment = {
example & example\% & example \\
},
review = {
    Not a difficult course provided you keep up with course materials, but assignments will take a good chunk of time. Matt and Tutors extremely helpful and very short response times. \\
    Through the course you will cover the different parts that make up an operating system kernel (especially a linux kernel), and assignments focus on concurrency and display (X11, but almost any display driver will be accepted). \\
    Note that while the textbook is mandatory, it is extremely useful. You will cover the entirety of the textbook throughout the course. \\
    The exam is fairly easy to prepare for, but going in without doing previous year's exams will result in failure. \\
    If you enjoyed 2310, I would highly recommend this course.
},
preparation = {
    \item thingo
}]{}


text:
{{{
  "title": "User Credentials and Logging into Control Portal",
  "date": "07-09-2014",
  "author": "Bryan Friedman",
  "attachments": [],
  "contentIsHTML": false
}}}

### Description
There are at least two different types of user credentials that you need to maintain and be aware of as a CenturyLink Cloud Control Portal user. One set of credentials is used for you or other users in your organization to gain access to the Control Portal itself. These are your CenturyLink Cloud Control Portal user credentials. You may also be responsible for maintaining a number of different administrator credentials for servers you have created within your CenturyLink Cloud account. Both credentials should use strong and secure passwords, however *they are not related to each other and should be managed and used separately.* This article discusses how to manage and use both types of credentials independently.

### Audience
CenturyLink Cloud customers

### Control Portal Credentials
1. Control Portal credentials are maintained in your Profile, which can be accessed by clicking your user name drop-down located in the upper right corner of the Dashboard and selecting **Your Profile**.
   ![Control Portal Header](../images/dashboard-header.png)

2. You are then directed to your Profile information for the Control Portal.
   ![Profile Page](../images/profile-info-page.png)

3. Clicking the password line enables you to change your password.
   ![Customize Password](../images/customize-password.png)

4. This is the password you use to login to the Control Portal.
   ![Control Portal Login](../images/control-portal-login.png)

**Note:** Your account may have SAML enabled allowing for Single Sign-On capabilities. For more information, refer to this Knowledge Base article about enabling SAML.
* [Control Portal](using-saml-for-single-sign-on-to-the-centurylink-platform-control-portal.md)
* [Control Portal with Windows 2012 R2 ](using-saml-for-single-sign-on-to-the-centurylink-platform-control-portal-with-windows-2012R2.md)

Also, if you are an Account Admin, you have the ability to see information for other user accounts that have been created within your sub account. That information is available in Users area under the Account menu. While you cannot see user passwords, your credential enable you to perform the following:
* View username and information.
* Lock the account.
* Set permissions.
* Delete the account.
* Generate a password reset email.

### Server Admin Credentials
These credentials are different from your Control Portal user credentials. Server Admin credentials are used to gain access to a server you have created within your account. These credentials are typically set at the time when you create the server and can be changed from the server details page. **Note:** The password should be secure and strong, particularly if your server is accessible via the public Internet.

For more information on changing or retrieving server administrator passwords, please reference the following two Knowledge Base articles:
* [How to Change a Server Administrator Password](../Servers/how-to-change-a-server-administrator-password.md)
* [How to Retrieve a Root/Administrator Password](../Servers/how-to-retrieve-rootadministrator-password.md)


text:
package executor

import (
	"archive/zip"
	"bytes"
	"context"
	"crypto/rand"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/BurntSushi/toml"
	"github.com/pingcap/errors"
	"github.com/pingcap/tidb/config"
	"github.com/pingcap/tidb/domain"
	"github.com/pingcap/tidb/infoschema"
	"github.com/pingcap/tidb/parser/ast"
	"github.com/pingcap/tidb/parser/model"
	"github.com/pingcap/tidb/sessionctx"
	"github.com/pingcap/tidb/sessionctx/variable"
	"github.com/pingcap/tidb/statistics/handle"
	"github.com/pingcap/tidb/util/chunk"
	"github.com/pingcap/tidb/util/logutil"
	"github.com/pingcap/tidb/util/printer"
	"github.com/pingcap/tidb/util/sqlexec"
	"go.uber.org/zap"
)

var _ Executor = &PlanReplayerSingleExec{}
var _ Executor = &PlanReplayerLoadExec{}

// PlanReplayerSingleExec represents a plan replayer executor.
type PlanReplayerSingleExec struct {
	baseExecutor
	ExecStmt ast.StmtNode
	Analyze  bool

	endFlag bool
}

type tableNamePair struct {
	DBName    string
	TableName string
}

type tableNameExtractor struct {
	curDB string
	names map[tableNamePair]struct{}
}

func (tne *tableNameExtractor) Enter(in ast.Node) (ast.Node, bool) {
	if _, ok := in.(*ast.TableName); ok {
		return in, true
	}
	return in, false
}

func (tne *tableNameExtractor) Leave(in ast.Node) (ast.Node, bool) {
	if t, ok := in.(*ast.TableName); ok {
		tp := tableNamePair{DBName: t.Schema.L, TableName: t.Name.L}
		if tp.DBName == "" {
			tp.DBName = tne.curDB
		}
		if _, ok := tne.names[tp]; !ok {
			tne.names[tp] = struct{}{}
		}
	}
	return in, true
}

// Next implements the Executor Next interface.
func (e *PlanReplayerSingleExec) Next(ctx context.Context, req *chunk.Chunk) error {
	req.GrowAndReset(e.maxChunkSize)
	if e.endFlag {
		return nil
	}
	if e.ExecStmt == nil {
		return errors.New("plan replayer: sql is empty")
	}
	res, err := e.dumpSingle(domain.GetPlanReplayerDirName())
	if err != nil {
		return err
	}
	req.AppendString(0, res)
	e.endFlag = true
	return nil
}

// dumpSingle will dump the information about a single sql.
// The files will be organized into the following format:
// |-meta.txt
// |-schema.sql
// |-stats
// |   |-stats1.json
// |   |-stats2.json
// |   |-....
// |-config.toml
// |-variables.toml
// |-bindings.sql
// |-sqls.sql
// |_explain
//     |-explain.txt
//
func (e *PlanReplayerSingleExec) dumpSingle(path string) (fileName string, err error) {
	// Create path
	err = os.MkdirAll(path, os.ModePerm)
	if err != nil {
		return "", errors.AddStack(err)
	}

	// Generate key and create zip file
	time := time.Now().UnixNano()
	b := make([]byte, 16)
	//nolint: gosec
	_, err = rand.Read(b)
	if err != nil {
		return "", err
	}
	key := base64.URLEncoding.EncodeToString(b)
	fileName = fmt.Sprintf("replayer_single_%v_%v.zip", key, time)
	zf, err := os.Create(filepath.Join(path, fileName))
	if err != nil {
		return "", errors.AddStack(err)
	}

	// Create zip writer
	zw := zip.NewWriter(zf)
	defer func() {
		err = zw.Close()
		if err != nil {
			logutil.BgLogger().Error("Closing zip writer failed", zap.Error(err), zap.String("filename", fileName))
		}
		err = zf.Close()
		if err != nil {
			logutil.BgLogger().Error("Closing zip file failed", zap.Error(err), zap.String("filename", fileName))
		}
	}()

	// Dump config
	if err = dumpConfig(zw); err != nil {
		return "", err
	}

	// Dump meta
	if err = dumpMeta(zw); err != nil {
		return "", err
	}

	// Retrieve current DB
	sessionVars := e.ctx.GetSessionVars()
	dbName := model.NewCIStr(sessionVars.CurrentDB)
	do := domain.GetDomain(e.ctx)

	// Retrieve all tables
	pairs, err := extractTableNames(e.ExecStmt, dbName.L)
	if err != nil {
		return "", errors.AddStack(errors.New(fmt.Sprintf("plan replayer: invalid SQL text, err: %v", err)))
	}

	// Dump Schema
	if err = dumpSchemas(e.ctx, zw, pairs); err != nil {
		return "", err
	}

	// Dump stats
	if err = dumpStats(zw, pairs, do); err != nil {
		return "", err
	}

	// Dump variables
	if err = dumpVariables(e.ctx, zw); err != nil {
		return "", err
	}

	// Dump sql
	sql, err := zw.Create("sqls.sql")
	if err != nil {
		return "", nil
	}
	_, err = sql.Write([]byte(e.ExecStmt.Text()))
	if err != nil {
		return "", err
	}

	// Dump session bindings
	if err = dumpSessionBindings(e.ctx, zw); err != nil {
		return "", err
	}

	// Dump global bindings
	if err = dumpGlobalBindings(e.ctx, zw); err != nil {
		return "", err
	}

	// Dump explain
	if err = dumpExplain(e.ctx, zw, e.ExecStmt.Text(), e.Analyze); err != nil {
		return "", err
	}

	return fileName, nil
}

func dumpConfig(zw *zip.Writer) error {
	cf, err := zw.Create("config.toml")
	if err != nil {
		return errors.AddStack(err)
	}
	if err := toml.NewEncoder(cf).Encode(config.GetGlobalConfig()); err != nil {
		return errors.AddStack(err)
	}
	return nil
}

func dumpMeta(zw *zip.Writer) error {
	mt, err := zw.Create("meta.txt")
	if err != nil {
		return errors.AddStack(err)
	}
	_, err = mt.Write([]byte(printer.GetTiDBInfo()))
	if err != nil {
		return errors.AddStack(err)
	}
	return nil
}

func dumpSchemas(ctx sessionctx.Context, zw *zip.Writer, pairs map[tableNamePair]struct{}) error {
	for pair := range pairs {
		err := getShowCreateTable(pair, zw, ctx)
		if err != nil {
			return err
		}
	}
	return nil
}

func dumpStats(zw *zip.Writer, pairs map[tableNamePair]struct{}, do *domain.Domain) error {
	for pair := range pairs {
		jsonTbl, err := getStatsForTable(do, pair)
		if err != nil {
			return err
		}
		statsFw, err := zw.Create(fmt.Sprintf("stats/%v.%v.json", pair.DBName, pair.TableName))
		if err != nil {
			return errors.AddStack(err)
		}
		data, err := json.Marshal(jsonTbl)
		if err != nil {
			return errors.AddStack(err)
		}
		_, err = statsFw.Write(data)
		if err != nil {
			return errors.AddStack(err)
		}
	}
	return nil
}

func dumpVariables(ctx sessionctx.Context, zw *zip.Writer) error {
	varMap := make(map[string]string)
	recordSets, err := ctx.(sqlexec.SQLExecutor).Execute(context.Background(), "show variables")
	if err != nil {
		return err
	}
	sRows, err := resultSetToStringSlice(context.Background(), recordSets[0])
	if err != nil {
		return err
	}
	vf, err := zw.Create("variables.toml")
	if err != nil {
		return errors.AddStack(err)
	}
	for _, row := range sRows {
		varMap[row[0]] = row[1]
	}
	if err := toml.NewEncoder(vf).Encode(varMap); err != nil {
		return errors.AddStack(err)
	}
	if len(recordSets) > 0 {
		if err := recordSets[0].Close(); err != nil {
			return err
		}
	}
	return nil
}

func dumpSessionBindings(ctx sessionctx.Context, zw *zip.Writer) error {
	recordSets, err := ctx.(sqlexec.SQLExecutor).Execute(context.Background(), "show bindings")
	if err != nil {
		return err
	}
	sRows, err := resultSetToStringSlice(context.Background(), recordSets[0])
	if err != nil {
		return err
	}
	bf, err := zw.Create("session_bindings.sql")
	if err != nil {
		return errors.AddStack(err)
	}
	for _, row := range sRows {
		fmt.Fprintf(bf, "%s\n", strings.Join(row, "\t"))
	}
	if len(recordSets) > 0 {
		if err := recordSets[0].Close(); err != nil {
			return err
		}
	}
	return nil
}

func dumpGlobalBindings(ctx sessionctx.Context, zw *zip.Writer) error {
	recordSets, err := ctx.(sqlexec.SQLExecutor).Execute(context.Background(), "show global bindings")
	if err != nil {
		return err
	}
	sRows, err := resultSetToStringSlice(context.Background(), recordSets[0])
	if err != nil {
		return err
	}
	bf, err := zw.Create("global_bindings.sql")
	if err != nil {
		return errors.AddStack(err)
	}
	for _, row := range sRows {
		fmt.Fprintf(bf, "%s\n", strings.Join(row, "\t"))
	}
	if len(recordSets) > 0 {
		if err := recordSets[0].Close(); err != nil {
			return err
		}
	}
	return nil
}

func dumpExplain(ctx sessionctx.Context, zw *zip.Writer, sql string, isAnalyze bool) error {
	var recordSets []sqlexec.RecordSet
	var err error
	if isAnalyze {
		// Explain analyze
		recordSets, err = ctx.(sqlexec.SQLExecutor).Execute(context.Background(), fmt.Sprintf("explain analyze %s", sql))
		if err != nil {
			return err
		}
	} else {
		// Explain
		recordSets, err = ctx.(sqlexec.SQLExecutor).Execute(context.Background(), fmt.Sprintf("explain %s", sql))
		if err != nil {
			return err
		}
	}
	sRows, err := resultSetToStringSlice(context.Background(), recordSets[0])
	if err != nil {
		return err
	}
	fw, err := zw.Create("explain.txt")
	if err != nil {
		return errors.AddStack(err)
	}
	for _, row := range sRows {
		fmt.Fprintf(fw, "%s\n", strings.Join(row, "\t"))
	}
	if len(recordSets) > 0 {
		if err := recordSets[0].Close(); err != nil {
			return err
		}
	}
	return nil
}

func extractTableNames(ExecStmt ast.StmtNode, curDB string) (map[tableNamePair]struct{}, error) {
	extractor := &tableNameExtractor{
		curDB: curDB,
		names: make(map[tableNamePair]struct{}),
	}
	ExecStmt.Accept(extractor)
	return extractor.names, nil
}

func getStatsForTable(do *domain.Domain, pair tableNamePair) (*handle.JSONTable, error) {
	is := do.InfoSchema()
	h := do.StatsHandle()
	tbl, err := is.TableByName(model.NewCIStr(pair.DBName), model.NewCIStr(pair.TableName))
	if err != nil {
		return nil, err
	}
	js, err := h.DumpStatsToJSON(pair.DBName, tbl.Meta(), nil)
	return js, err
}

func getShowCreateTable(pair tableNamePair, zw *zip.Writer, ctx sessionctx.Context) error {
	recordSets, err := ctx.(sqlexec.SQLExecutor).Execute(context.Background(), fmt.Sprintf("show create table `%v`.`%v`", pair.DBName, pair.TableName))
	if err != nil {
		return err
	}
	sRows, err := resultSetToStringSlice(context.Background(), recordSets[0])
	if err != nil {
		return err
	}
	fw, err := zw.Create(fmt.Sprintf("schema/%v.%v.schema.txt", pair.DBName, pair.TableName))
	if err != nil {
		return errors.AddStack(err)
	}
	if len(sRows) == 0 || len(sRows[0]) != 2 {
		return errors.New(fmt.Sprintf("plan replayer: get create table %v.%v failed", pair.DBName, pair.TableName))
	}
	fmt.Fprintf(fw, "create database `%v`; use `%v`;", pair.DBName, pair.DBName)
	fmt.Fprintf(fw, "%s", sRows[0][1])
	if len(recordSets) > 0 {
		if err := recordSets[0].Close(); err != nil {
			return err
		}
	}
	return nil
}

func resultSetToStringSlice(ctx context.Context, rs sqlexec.RecordSet) ([][]string, error) {
	rows, err := getRows(ctx, rs)
	if err != nil {
		return nil, err
	}
	err = rs.Close()
	if err != nil {
		return nil, err
	}
	sRows := make([][]string, len(rows))
	for i, row := range rows {
		iRow := make([]string, row.Len())
		for j := 0; j < row.Len(); j++ {
			if row.IsNull(j) {
				iRow[j] = "<nil>"
			} else {
				d := row.GetDatum(j, &rs.Fields()[j].Column.FieldType)
				iRow[j], err = d.ToString()
				if err != nil {
					return nil, err
				}
			}
		}
		sRows[i] = iRow
	}
	return sRows, nil
}

func getRows(ctx context.Context, rs sqlexec.RecordSet) ([]chunk.Row, error) {
	if rs == nil {
		return nil, nil
	}
	var rows []chunk.Row
	req := rs.NewChunk(nil)
	// Must reuse `req` for imitating server.(*clientConn).writeChunks
	for {
		err := rs.Next(ctx, req)
		if err != nil {
			return nil, err
		}
		if req.NumRows() == 0 {
			break
		}

		iter := chunk.NewIterator4Chunk(req.CopyConstruct())
		for row := iter.Begin(); row != iter.End(); row = iter.Next() {
			rows = append(rows, row)
		}
	}
	return rows, nil
}

// PlanReplayerLoadExec represents a plan replayer load executor.
type PlanReplayerLoadExec struct {
	baseExecutor
	info *PlanReplayerLoadInfo
}

// PlanReplayerLoadInfo contains file path and session context.
type PlanReplayerLoadInfo struct {
	Path string
	Ctx  sessionctx.Context
}

type planReplayerLoadKeyType int

func (k planReplayerLoadKeyType) String() string {
	return "plan_replayer_load_var"
}

// PlanReplayerLoadVarKey is a variable key for plan replayer load.
const PlanReplayerLoadVarKey planReplayerLoadKeyType = 0

// Next implements the Executor Next interface.
func (e *PlanReplayerLoadExec) Next(ctx context.Context, req *chunk.Chunk) error {
	req.GrowAndReset(e.maxChunkSize)
	if len(e.info.Path) == 0 {
		return errors.New("plan replayer: file path is empty")
	}
	val := e.ctx.Value(PlanReplayerLoadVarKey)
	if val != nil {
		e.ctx.SetValue(PlanReplayerLoadVarKey, nil)
		return errors.New("plan replayer: previous plan replayer load option isn't closed normally, please try again")
	}
	e.ctx.SetValue(PlanReplayerLoadVarKey, e.info)
	return nil
}

func loadVariables(ctx sessionctx.Context, z *zip.Reader) error {
	for _, zipFile := range z.File {
		if strings.Compare(zipFile.Name, "variables.toml") == 0 {
			varMap := make(map[string]string)
			v, err := zipFile.Open()
			if err != nil {
				return errors.AddStack(err)
			}
			//nolint: errcheck
			defer v.Close()
			_, err = toml.DecodeReader(v, &varMap)
			if err != nil {
				return errors.AddStack(err)
			}
			vars := ctx.GetSessionVars()
			for name, value := range varMap {
				sysVar := variable.GetSysVar(name)
				if sysVar == nil {
					return variable.ErrUnknownSystemVar.GenWithStackByArgs(name)
				}
				sVal, err := sysVar.Validate(vars, value, variable.ScopeSession)
				if err != nil {
					logutil.BgLogger().Debug(fmt.Sprintf("skip variable %s:%s", name, value), zap.Error(err))
					continue
				}
				err = vars.SetSystemVar(name, sVal)
				if err != nil {
					return err
				}
			}
		}
	}
	return nil
}

func createSchemaAndTables(ctx sessionctx.Context, f *zip.File) error {
	r, err := f.Open()
	if err != nil {
		return errors.AddStack(err)
	}
	//nolint: errcheck
	defer r.Close()
	buf := new(bytes.Buffer)
	_, err = buf.ReadFrom(r)
	if err != nil {
		return errors.AddStack(err)
	}
	sqls := strings.Split(buf.String(), ";")
	if len(sqls) != 3 {
		return errors.New("plan replayer: create schema and tables failed")
	}
	c := context.Background()
	// create database
	_, err = ctx.(sqlexec.SQLExecutor).Execute(c, sqls[0])
	logutil.BgLogger().Debug("plan replayer: skip error", zap.Error(err))
	// use database
	_, err = ctx.(sqlexec.SQLExecutor).Execute(c, sqls[1])
	if err != nil {
		return err
	}
	// create table
	_, err = ctx.(sqlexec.SQLExecutor).Execute(c, sqls[2])
	if err != nil {
		return err
	}
	return nil
}

func loadStats(ctx sessionctx.Context, f *zip.File) error {
	jsonTbl := &handle.JSONTable{}
	r, err := f.Open()
	if err != nil {
		return errors.AddStack(err)
	}
	//nolint: errcheck
	defer r.Close()
	buf := new(bytes.Buffer)
	_, err = buf.ReadFrom(r)
	if err != nil {
		return errors.AddStack(err)
	}
	if err := json.Unmarshal(buf.Bytes(), jsonTbl); err != nil {
		return errors.AddStack(err)
	}
	do := domain.GetDomain(ctx)
	h := do.StatsHandle()
	if h == nil {
		return errors.New("plan replayer: hanlde is nil")
	}
	return h.LoadStatsFromJSON(ctx.GetInfoSchema().(infoschema.InfoSchema), jsonTbl)
}

// Update updates the data of the corresponding table.
func (e *PlanReplayerLoadInfo) Update(data []byte) error {
	b := bytes.NewReader(data)
	z, err := zip.NewReader(b, int64(len(data)))
	if err != nil {
		return errors.AddStack(err)
	}

	// load variable
	err = loadVariables(e.Ctx, z)
	if err != nil {
		return err
	}

	// build schema and table
	for _, zipFile := range z.File {
		path := strings.Split(zipFile.Name, "/")
		if len(path) == 2 && strings.Compare(path[0], "schema") == 0 {
			err = createSchemaAndTables(e.Ctx, zipFile)
			if err != nil {
				return err
			}
		}
	}

	// load stats
	for _, zipFile := range z.File {
		path := strings.Split(zipFile.Name, "/")
		if len(path) == 2 && strings.Compare(path[0], "stats") == 0 {
			err = loadStats(e.Ctx, zipFile)
			if err != nil {
				return err
			}
		}
	}
	return nil
}