text:
WebInspector.SourceCode = function () {
    WebInspector.Object.call(this);

    this._pendingContentRequestCallbacks = [];

    this._originalRevision = new WebInspector.SourceCodeRevision(this, null, false);
    this._currentRevision = this._originalRevision;

    this._sourceMaps = null;
    this._formatterSourceMap = null;
};

WebInspector.SourceCode.Event = {
    ContentDidChange: "source-code-content-did-change",
    SourceMapAdded: "source-code-source-map-added",
    FormatterDidChange: "source-code-formatter-did-change"
};

WebInspector.SourceCode.prototype = Object.defineProperties({
    constructor: WebInspector.SourceCode,

    addSourceMap: function addSourceMap(sourceMap) {
        console.assert(sourceMap instanceof WebInspector.SourceMap);

        if (!this._sourceMaps) this._sourceMaps = [];

        this._sourceMaps.push(sourceMap);

        this.dispatchEventToListeners(WebInspector.SourceCode.Event.SourceMapAdded);
    },

    requestContent: function requestContent(callback) {
        console.assert(typeof callback === "function");
        if (typeof callback !== "function") return;

        this._pendingContentRequestCallbacks.push(callback);

        if (this._contentReceived) {
            // Call _servicePendingContentRequests on a timeout to force callbacks to be asynchronous.
            if (!this._servicePendingContentRequestsTimeoutIdentifier) this._servicePendingContentRequestsTimeoutIdentifier = setTimeout(this.servicePendingContentRequests.bind(this), 0);
        } else if (this.canRequestContentFromBackend()) this.requestContentFromBackendIfNeeded();
    },

    createSourceCodeLocation: function createSourceCodeLocation(lineNumber, columnNumber) {
        return new WebInspector.SourceCodeLocation(this, lineNumber, columnNumber);
    },

    createLazySourceCodeLocation: function createLazySourceCodeLocation(lineNumber, columnNumber) {
        return new WebInspector.LazySourceCodeLocation(this, lineNumber, columnNumber);
    },

    createSourceCodeTextRange: function createSourceCodeTextRange(textRange) {
        return new WebInspector.SourceCodeTextRange(this, textRange);
    },

    // Protected

    revisionContentDidChange: function revisionContentDidChange(revision) {
        if (this._ignoreRevisionContentDidChangeEvent) return;

        if (revision !== this._currentRevision) return;

        this.handleCurrentRevisionContentChange();

        this.dispatchEventToListeners(WebInspector.SourceCode.Event.ContentDidChange);
    },

    handleCurrentRevisionContentChange: function handleCurrentRevisionContentChange() {
        // Implemented by subclasses if needed.
    },

    markContentAsStale: function markContentAsStale() {
        this._contentReceived = false;
    },

    canRequestContentFromBackend: function canRequestContentFromBackend() {
        // Implemented by subclasses.
        console.error("Needs to be implemented by a subclass.");
        return false;
    },

    requestContentFromBackend: function requestContentFromBackend(callback) {
        // Implemented by subclasses.
        console.error("Needs to be implemented by a subclass.");
    },

    requestContentFromBackendIfNeeded: function requestContentFromBackendIfNeeded() {
        console.assert(this.canRequestContentFromBackend());
        if (!this.canRequestContentFromBackend()) return;

        if (!this._pendingContentRequestCallbacks.length) return;

        if (this._contentRequestResponsePending) return;

        this._contentRequestResponsePending = true;

        if (this.requestContentFromBackend(this._processContent.bind(this))) return;

        // Since requestContentFromBackend returned false, just call _processContent,
        // which will cause the pending callbacks to get null content.
        this._processContent();
    },

    servicePendingContentRequests: function servicePendingContentRequests(force) {
        if (this._servicePendingContentRequestsTimeoutIdentifier) {
            clearTimeout(this._servicePendingContentRequestsTimeoutIdentifier);
            delete this._servicePendingContentRequestsTimeoutIdentifier;
        }

        // Force the content requests to be sent. To do this correctly we also force
        // _contentReceived to be true so future calls to requestContent go through.
        if (force) this._contentReceived = true;

        console.assert(this._contentReceived);
        if (!this._contentReceived) return;

        // Move the callbacks into a local and clear _pendingContentRequestCallbacks so
        // callbacks that might call requestContent again will not modify the array.
        var callbacks = this._pendingContentRequestCallbacks;
        this._pendingContentRequestCallbacks = [];

        for (var i = 0; i < callbacks.length; ++i) callbacks[i](this, this.content, this.contentIsBase64Encoded);
    },

    // Private

    _processContent: function _processContent(error, content, base64Encoded) {
        if (error) console.error(error);

        this._contentRequestResponsePending = false;
        this._contentReceived = true;

        var revision = this.revisionForRequestedContent;

        this._ignoreRevisionContentDidChangeEvent = true;
        revision.content = content || null;
        revision.contentIsBase64Encoded = base64Encoded || false;
        delete this._ignoreRevisionContentDidChangeEvent;

        this.servicePendingContentRequests();
    }
}, {
    displayName: { // Public

        get: function get() {
            // Implemented by subclasses.
            console.error("Needs to be implemented by a subclass.");
            return "";
        },
        configurable: true,
        enumerable: true
    },
    originalRevision: {
        get: function get() {
            return this._originalRevision;
        },
        configurable: true,
        enumerable: true
    },
    currentRevision: {
        get: function get() {
            return this._currentRevision;
        },
        set: function set(revision) {
            console.assert(revision instanceof WebInspector.SourceCodeRevision);
            if (!(revision instanceof WebInspector.SourceCodeRevision)) return;

            console.assert(revision.sourceCode === this);
            if (revision.sourceCode !== this) return;

            this._currentRevision = revision;

            this.dispatchEventToListeners(WebInspector.SourceCode.Event.ContentDidChange);
        },
        configurable: true,
        enumerable: true
    },
    content: {
        get: function get() {
            return this._currentRevision.content;
        },
        configurable: true,
        enumerable: true
    },
    contentIsBase64Encoded: {
        get: function get() {
            return this._currentRevision.contentIsBase64Encoded;
        },
        configurable: true,
        enumerable: true
    },
    sourceMaps: {
        get: function get() {
            return this._sourceMaps || [];
        },
        configurable: true,
        enumerable: true
    },
    formatterSourceMap: {
        get: function get() {
            return this._formatterSourceMap;
        },
        set: function set(formatterSourceMap) {
            console.assert(this._formatterSourceMap === null || formatterSourceMap === null);
            console.assert(formatterSourceMap === null || formatterSourceMap instanceof WebInspector.FormatterSourceMap);

            this._formatterSourceMap = formatterSourceMap;

            this.dispatchEventToListeners(WebInspector.SourceCode.Event.FormatterDidChange);
        },
        configurable: true,
        enumerable: true
    },
    revisionForRequestedContent: {
        get: function get() {
            // Implemented by subclasses if needed.
            return this._originalRevision;
        },
        configurable: true,
        enumerable: true
    }
});

WebInspector.SourceCode.prototype.__proto__ = WebInspector.Object.prototype;


text:
var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/test';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);

  db.listCollections({namesOnly:true}, function(err, names) {
    console.log(names);
    db.close();
  });

});

redpajama_set_name: RedPajamaGithub


text:
export Poisson_Regression, predict, fit

type poissonRegression
    #array of weights
    w
    #w0 constnat
    w_0::Float64
    #learning rate
    eta::Float64
    #decay rate for the learning rate
    alpha::Float64
    #number of samples parsed through (will be incremnted automatically)
    n::Int64
    #number of features
    d::Int64
end

#constructor for convenience
function Poisson_Regression(;eta::Float64=0.0001, alpha::Float64=1.00, d::Int64=0)
    if d != 0
        model = poissonRegression(zeros(d), 0.0, eta, alpha, 0, d)
    else
        model = poissonRegression(nothing, 0.0, eta, alpha, 0, d)
    end

    #return the model
    model
end

#prediction using n examles (nxd matrix)
function predict(model::poissonRegression, x::Array{Float64,2})
    linear_prediction = x*model.w+model.w_0
    prediction = exp(linear_prediction)
end

#prediction using 1xd array
function predict(model::poissonRegression, x::Array{Float64,1})
    linear_prediction = x*model.w+model.w_0
    prediction = exp(linear_prediction)
end

#takes in nxd batch data as an input, conducts stochastic gradient descent
function fit(model::poissonRegression, y::Array{Float64, 1}, x::Array{Float64, 2})
    #checking if y and x match in size
    if length(y)!=size(x)[1]
        return nothing
    end

    #initiating weight array if necessary
    if model.d == 0
        model.d = size(x)[2]
        model.w = zeros(model.d)
    end

    #updating info (right now its just the number of examples parsed)
    model.n += length(y)
    num_data = length(y)

    #making prediction
    prediction = predict(model, x)

    #updating w_0
    model.w_0 = model.w_0 + model.eta*(sum(y-prediction, 1)[1]*1.0/num_data)

    #updating w
    model.w = model.w + model.eta*((transpose(x)*(y-prediction))/num_data)

    model
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
  http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- legacy, to be removed -->
<bean id="staticsModule" class="org.olat.commons.servlets.StaticsModule"
		init-method="init"
		depends-on="folderModule">
</bean>

</beans>


text:
package org.ovirt.engine.ui.uicommon.models.datacenters;
import java.util.Collections;
import org.ovirt.engine.core.compat.*;
import org.ovirt.engine.ui.uicompat.*;
import org.ovirt.engine.core.common.businessentities.*;
import org.ovirt.engine.core.common.vdscommands.*;
import org.ovirt.engine.core.common.queries.*;
import org.ovirt.engine.core.common.action.*;
import org.ovirt.engine.ui.frontend.*;
import org.ovirt.engine.ui.uicommon.*;
import org.ovirt.engine.ui.uicommon.models.*;
import org.ovirt.engine.core.common.*;

import org.ovirt.engine.ui.uicommon.models.configure.*;
import org.ovirt.engine.core.common.interfaces.*;
import org.ovirt.engine.core.common.businessentities.*;

import org.ovirt.engine.core.common.queries.*;
import org.ovirt.engine.ui.uicompat.*;
import org.ovirt.engine.ui.uicommon.*;
import org.ovirt.engine.ui.uicommon.models.*;

@SuppressWarnings("unused")
public class DataCenterListModel extends ListWithDetailsModel implements ISupportSystemTreeContext
{

	private UICommand privateNewCommand;
	public UICommand getNewCommand()
	{
		return privateNewCommand;
	}
	private void setNewCommand(UICommand value)
	{
		privateNewCommand = value;
	}
	private UICommand privateEditCommand;
	public UICommand getEditCommand()
	{
		return privateEditCommand;
	}
	private void setEditCommand(UICommand value)
	{
		privateEditCommand = value;
	}
	private UICommand privateRemoveCommand;
	public UICommand getRemoveCommand()
	{
		return privateRemoveCommand;
	}
	private void setRemoveCommand(UICommand value)
	{
		privateRemoveCommand = value;
	}
	private UICommand privateForceRemoveCommand;
	public UICommand getForceRemoveCommand()
	{
		return privateForceRemoveCommand;
	}
	private void setForceRemoveCommand(UICommand value)
	{
		privateForceRemoveCommand = value;
	}
	private UICommand privateActivateCommand;
	public UICommand getActivateCommand()
	{
		return privateActivateCommand;
	}
	private void setActivateCommand(UICommand value)
	{
		privateActivateCommand = value;
	}
	private UICommand privateGuideCommand;
	public UICommand getGuideCommand()
	{
		return privateGuideCommand;
	}
	private void setGuideCommand(UICommand value)
	{
		privateGuideCommand = value;
	}
	private UICommand privateRecoveryStorageCommand;
	public UICommand getRecoveryStorageCommand()
	{
		return privateRecoveryStorageCommand;
	}
	private void setRecoveryStorageCommand(UICommand value)
	{
		privateRecoveryStorageCommand = value;
	}

	private Model window;
	public Model getWindow()
	{
		return window;
	}
	public void setWindow(Model value)
	{
		if (window != value)
		{
			window = value;
			OnPropertyChanged(new PropertyChangedEventArgs("Window"));
		}
	}

	private Model confirmWindow;
	public Model getConfirmWindow()
	{
		return confirmWindow;
	}
	public void setConfirmWindow(Model value)
	{
		if (confirmWindow != value)
		{
			confirmWindow = value;
			OnPropertyChanged(new PropertyChangedEventArgs("ConfirmWindow"));
		}
	}

		//get { return SelectedItems == null ? new object[0] : SelectedItems.Cast<storage_pool>().Select(a => a.id).Cast<object>().ToArray(); }
	protected Object[] getSelectedKeys()
	{
		if (getSelectedItems() == null)
		{
			return new Object[0];
		}
		else
		{
			java.util.ArrayList<Object> objL = new java.util.ArrayList<Object>();
			for (storage_pool a : Linq.<storage_pool>Cast(getSelectedItems()))
			{
				objL.add(a.getId());
			}
			return objL.toArray(new Object[]{});
		}
	}

	private Object privateGuideContext;
	public Object getGuideContext()
	{
		return privateGuideContext;
	}
	public void setGuideContext(Object value)
	{
		privateGuideContext = value;
	}

	public DataCenterListModel()
	{
		setTitle("Data Centers");

		setDefaultSearchString("DataCenter:");
		setSearchString(getDefaultSearchString());

		setNewCommand(new UICommand("New", this));
		setEditCommand(new UICommand("Edit", this));
		setRemoveCommand(new UICommand("Remove", this));
		UICommand tempVar = new UICommand("ForceRemove", this);
		tempVar.setIsExecutionAllowed(true);
		setForceRemoveCommand(tempVar);
		setRecoveryStorageCommand(new UICommand("RecoveryStorage", this));
		setActivateCommand(new UICommand("Activate", this));
		setGuideCommand(new UICommand("Guide", this));

		UpdateActionAvailability();

		getSearchNextPageCommand().setIsAvailable(true);
		getSearchPreviousPageCommand().setIsAvailable(true);
	}

	public void Guide()
	{
		DataCenterGuideModel model = new DataCenterGuideModel();
		setWindow(model);
		model.setTitle("New Data Center - Guide Me");
		model.setHashName("new_data_center_-_guide_me");

		model.setEntity(getGuideContext() != null ? DataProvider.GetDataCenterById(getGuideContext() instanceof Guid ? (Guid)getGuideContext() : (Guid)getGuideContext()) : null);

		UICommand tempVar = new UICommand("Cancel", this);
		tempVar.setTitle("Configure Later");
		tempVar.setIsDefault(true);
		tempVar.setIsCancel(true);
		model.getCommands().add(tempVar);
	}

	@Override
	protected void InitDetailModels()
	{
		super.InitDetailModels();

		ObservableCollection<EntityModel> list = new ObservableCollection<EntityModel>();
		list.add(new DataCenterStorageListModel());
		list.add(new DataCenterNetworkListModel());
		list.add(new DataCenterClusterListModel());
		list.add(new PermissionListModel());
		list.add(new DataCenterEventListModel());
		setDetailModels(list);
	}

	@Override
	public boolean IsSearchStringMatch(String searchString)
	{
		return searchString.trim().toLowerCase().startsWith("datacenter");
	}

	@Override
	protected void SyncSearch()
	{
		SearchParameters tempVar = new SearchParameters(getSearchString(), SearchType.StoragePool);
		tempVar.setMaxCount(getSearchPageSize());
		super.SyncSearch(VdcQueryType.Search, tempVar);

	}

	@Override
	protected void AsyncSearch()
	{
		super.AsyncSearch();

		setAsyncResult(Frontend.RegisterSearch(getSearchString(), SearchType.StoragePool, getSearchPageSize()));
		setItems(getAsyncResult().getData());
	}

	public void New()
	{
		if (getWindow() != null)
		{
			return;
		}

		DataCenterModel model = new DataCenterModel();
		setWindow(model);
		model.setTitle("New Data Center");
		model.setHashName("new_data_center");
		model.setIsNew(true);
		model.getStorageTypeList().setSelectedItem(StorageType.NFS);

		UICommand tempVar = new UICommand("OnSave", this);
		tempVar.setTitle("OK");
		tempVar.setIsDefault(true);
		model.getCommands().add(tempVar);
		UICommand tempVar2 = new UICommand("Cancel", this);
		tempVar2.setTitle("Cancel");
		tempVar2.setIsCancel(true);
		model.getCommands().add(tempVar2);
	}

	public void Edit()
	{
		storage_pool dataCenter = (storage_pool)getSelectedItem();

		if (getWindow() != null)
		{
			return;
		}

		DataCenterModel model = new DataCenterModel();
		setWindow(model);
		model.setDataCenterId(dataCenter.getId());
		model.setTitle("Edit Data Center");
		model.setHashName("edit_data_center");
		model.getName().setEntity(dataCenter.getname());

		if (getSystemTreeSelectedItem() != null && getSystemTreeSelectedItem().getType() == SystemTreeItemType.DataCenter)
		{
			model.getName().setIsChangable(false);
			model.getName().setInfo("Cannot edit Data Center's Name in tree context");
		}

		model.getDescription().setEntity(dataCenter.getdescription());
		model.setOriginalName(dataCenter.getname());
		if (DataProvider.GetStorageDomainList(dataCenter.getId()).size() != 0)
		{
			model.getStorageTypeList().setIsChangable(false);
			model.getStorageTypeList().getChangeProhibitionReasons().add("Cannot change Repository type with Storage Domains attached to it");
		}

		model.getStorageTypeList().setSelectedItem(dataCenter.getstorage_pool_type());

		//Version
		for (Object a : model.getVersion().getItems())
		{
			Version item = (Version)a;
			if (Version.OpEquality(item, dataCenter.getcompatibility_version()))
			{
				model.getVersion().setSelectedItem(item);
				break;
			}
		}

		UICommand tempVar = new UICommand("OnSave", this);
		tempVar.setTitle("OK");
		tempVar.setIsDefault(true);
		model.getCommands().add(tempVar);
		UICommand tempVar2 = new UICommand("Cancel", this);
		tempVar2.setTitle("Cancel");
		tempVar2.setIsCancel(true);
		model.getCommands().add(tempVar2);
	}

	public void remove()
	{
		if (getWindow() != null)
		{
			return;
		}

		ConfirmationModel model = new ConfirmationModel();
		setWindow(model);
		model.setTitle("Remove Data Center(s)");
		model.setHashName("remove_data_center");
		model.setMessage("Data Center(s)");

		java.util.ArrayList<String> list = new java.util.ArrayList<String>();
		for (storage_pool a : Linq.<storage_pool>Cast(getSelectedItems()))
		{
			list.add(a.getname());
		}
		model.setItems(list);

		UICommand tempVar = new UICommand("OnRemove", this);
		tempVar.setTitle("OK");
		tempVar.setIsDefault(true);
		model.getCommands().add(tempVar);
		UICommand tempVar2 = new UICommand("Cancel", this);
		tempVar2.setTitle("Cancel");
		tempVar2.setIsCancel(true);
		model.getCommands().add(tempVar2);
	}

	public void ForceRemove()
	{
		ConfirmationModel model = new ConfirmationModel();
		setWindow(model);
		model.setTitle("Force Remove Data Center");
		model.setHashName("force_remove_data_center");
		model.setMessage("Data Center(s)");
		model.getLatch().setIsAvailable(true);
		model.getLatch().setIsChangable(true);

		java.util.ArrayList<String> list = new java.util.ArrayList<String>();
		for (storage_pool a : Linq.<storage_pool>Cast(getSelectedItems()))
		{
			list.add(a.getname());
		}
		model.setItems(list);

		UICommand tempVar = new UICommand("OnForceRemove", this);
		tempVar.setTitle("OK");
		tempVar.setIsDefault(true);
		model.getCommands().add(tempVar);
		UICommand tempVar2 = new UICommand("Cancel", this);
		tempVar2.setTitle("Cancel");
		tempVar2.setIsCancel(true);
		model.getCommands().add(tempVar2);
	}

	public void RecoveryStorage()
	{
		ConfirmationModel model = new ConfirmationModel();
		setWindow(model);
		model.setTitle("Data Center Re-Initialize");
		model.setHashName("data_center_re-initialize");
		model.getLatch().setIsAvailable(true);
		model.getLatch().setIsChangable(true);

		//IEnumerable<storage_domains> list = DataProvider.GetStorageDomainList();
		//List<EntityModel> models = list
		//    .Where(a => (a.storage_domain_type == StorageDomainType.Data && a.storage_type == ((storage_pool)SelectedItem).storage_pool_type) &&
		//         (a.storage_domain_shared_status == StorageDomainSharedStatus.Unattached)
		//        )
		//    .Select(a => new EntityModel() { Entity = a })
		//    .ToList();
		java.util.ArrayList<EntityModel> models = new java.util.ArrayList<EntityModel>();
		for (storage_domains a : DataProvider.GetStorageDomainList())
		{
			if (a.getstorage_domain_type() == StorageDomainType.Data && a.getstorage_type() == ((storage_pool)getSelectedItem()).getstorage_pool_type() && (a.getstorage_domain_shared_status() == StorageDomainSharedStatus.Unattached))
			{
				EntityModel tempVar = new EntityModel();
				tempVar.setEntity(a);
				models.add(tempVar);
			}
		}

		model.setItems(models);

		if (models.size() > 0)
		{
			EntityModel entityModel = models.size() != 0 ? models.get(0) : null;
			if (entityModel != null)
			{
				entityModel.setIsSelected(true);
			}
		}

		if (models.isEmpty())
		{
			model.setMessage("There are no compatible Storage Domains to attach to this Data Center. Please add new Storage from the Storage tab.");

			UICommand tempVar2 = new UICommand("Cancel", this);
			tempVar2.setTitle("Close");
			tempVar2.setIsDefault(true);
			tempVar2.setIsCancel(true);
			model.getCommands().add(tempVar2);
		}
		else
		{
			UICommand tempVar3 = new UICommand("OnRecover", this);
			tempVar3.setTitle("OK");
			tempVar3.setIsDefault(true);
			model.getCommands().add(tempVar3);
			UICommand tempVar4 = new UICommand("Cancel", this);
			tempVar4.setTitle("Cancel");
			tempVar4.setIsCancel(true);
			model.getCommands().add(tempVar4);
		}
	}

	public void OnRecover()
	{
		ConfirmationModel model = (ConfirmationModel)getWindow();

		if (!model.Validate())
		{
			return;
		}

		//storage_domains master = DataProvider.GetStorageDomainList(((storage_pool)SelectedItem).id).FirstOrDefault(a=>a.storage_domain_type == StorageDomainType.Master);
		storage_domains master = null;
		for (storage_domains a : DataProvider.GetStorageDomainList(((storage_pool)getSelectedItem()).getId()))
		{
			if (a.getstorage_domain_type() == StorageDomainType.Master)
			{
				master = a;
				break;
			}
		}

		java.util.ArrayList<storage_domains> items = new java.util.ArrayList<storage_domains>();
		for (EntityModel a : Linq.<EntityModel>Cast(model.getItems()))
		{
			if (a.getIsSelected())
			{
				items.add((storage_domains)a.getEntity());
			}
		}

		if (items.size() > 0)
		{
			if (model.getProgress() != null)
			{
				return;
			}

			java.util.ArrayList<VdcActionParametersBase> parameters = new java.util.ArrayList<VdcActionParametersBase>();
			for (storage_domains a : items)
			{
				parameters.add(new RecoveryStoragePoolParameters(((storage_pool)getSelectedItem()).getId(), a.getid()));
			}

			model.StartProgress(null);

			Frontend.RunMultipleAction(VdcActionType.RecoveryStoragePool, parameters,
		new IFrontendMultipleActionAsyncCallback() {
			@Override
			public void Executed(FrontendMultipleActionAsyncResult  result) {

				ConfirmationModel localModel = (ConfirmationModel)result.getState();
				localModel.StopProgress();
				Cancel();

			}
		}, model);
		}
		else
		{
			Cancel();
		}
	}

	public void Activate()
	{
		//Frontend.RunMultipleActions(VdcActionType.ActivateStoragePool,
		//    SelectedItems.Cast<storage_pool>()
		//    .Select(a => (VdcActionParametersBase)new StoragePoolParametersBase(a.id))
		//    .ToList()
		//);
	}

	public void OnRemove()
	{
		ConfirmationModel model = (ConfirmationModel)getWindow();

		if (model.getProgress() != null)
		{
			return;
		}

		java.util.ArrayList<VdcActionParametersBase> parameters = new java.util.ArrayList<VdcActionParametersBase>();
		for (storage_pool a : Linq.<storage_pool>Cast(getSelectedItems()))
		{
			parameters.add(new StoragePoolParametersBase(a.getId()));
		}

		model.StartProgress(null);

		Frontend.RunMultipleAction(VdcActionType.RemoveStoragePool, parameters,
		new IFrontendMultipleActionAsyncCallback() {
			@Override
			public void Executed(FrontendMultipleActionAsyncResult  result) {

			ConfirmationModel localModel = (ConfirmationModel)result.getState();
			localModel.StopProgress();
			Cancel();

			}
		}, model);
	}

	public void OnForceRemove()
	{
		ConfirmationModel model = (ConfirmationModel) getWindow();
		if(!model.Validate())
		{
			return;
		}
		VdcActionParametersBase parametersBase = new VdcActionParametersBase();
		StoragePoolParametersBase tempVar = new StoragePoolParametersBase(((storage_pool)getSelectedItem()).getId());
		tempVar.setForceDelete(true);
		parametersBase = tempVar;
		Frontend.RunAction(VdcActionType.RemoveStoragePool, parametersBase);
		Cancel();
	}

	public void Cancel()
	{
		CancelConfirmation();

		setGuideContext(null);
		setWindow(null);

		UpdateActionAvailability();
	}

	public void CancelConfirmation()
	{
		setConfirmWindow(null);
	}

	public void OnSave()
	{
		DataCenterModel model = (DataCenterModel)getWindow();

		if (!model.Validate())
		{
			return;
		}

		if (!model.getIsNew() && (Version)model.getVersion().getSelectedItem() != ((storage_pool)getSelectedItem()).getcompatibility_version())
		{
			ConfirmationModel confirmModel = new ConfirmationModel();
			setConfirmWindow(confirmModel);
			confirmModel.setTitle("Change Data Center Compatibility Version");
			confirmModel.setHashName("change_data_center_compatibility_version");
			confirmModel.setMessage("You are about to change the Data Center Compatibility Version. Are you sure you want to continue?");

			UICommand tempVar = new UICommand("OnSaveInternal", this);
			tempVar.setTitle("OK");
			tempVar.setIsDefault(true);
			confirmModel.getCommands().add(tempVar);
			UICommand tempVar2 = new UICommand("CancelConfirmation", this);
			tempVar2.setTitle("Cancel");
			tempVar2.setIsCancel(true);
			confirmModel.getCommands().add(tempVar2);
		}
		else
		{
			OnSaveInternal();
		}
	}

	public void OnSaveInternal()
	{
		DataCenterModel model = (DataCenterModel)getWindow();

		if (model.getProgress() != null)
		{
			return;
		}

		storage_pool dataCenter = model.getIsNew() ? new storage_pool() : (storage_pool)Cloner.clone(getSelectedItem());

		//cancel confirm window if there is
		CancelConfirmation();

		//Save changes.
		dataCenter.setname((String)model.getName().getEntity());
		dataCenter.setdescription((String)model.getDescription().getEntity());
		dataCenter.setstorage_pool_type((StorageType)model.getStorageTypeList().getSelectedItem());
		dataCenter.setcompatibility_version((Version)model.getVersion().getSelectedItem());

		model.StartProgress(null);

		Frontend.RunAction(model.getIsNew() ? VdcActionType.AddEmptyStoragePool : VdcActionType.UpdateStoragePool, new StoragePoolManagementParameter(dataCenter),
		new IFrontendActionAsyncCallback() {
			@Override
			public void Executed(FrontendActionAsyncResult  result) {

			DataCenterListModel localModel = (DataCenterListModel)result.getState();
			localModel.PostOnSaveInternal(result.getReturnValue());

			}
		}, this);
	}

	public void PostOnSaveInternal(VdcReturnValueBase returnValue)
	{
		DataCenterModel model = (DataCenterModel)getWindow();

		model.StopProgress();

		if (returnValue != null && returnValue.getSucceeded())
		{
			Cancel();

			if (model.getIsNew())
			{
				setGuideContext(returnValue.getActionReturnValue());
				UpdateActionAvailability();
				getGuideCommand().Execute();
			}
		}
	}

	@Override
	protected void OnSelectedItemChanged()
	{
		super.OnSelectedItemChanged();
		UpdateActionAvailability();
	}

	@Override
	protected void SelectedItemsChanged()
	{
		super.SelectedItemsChanged();
		UpdateActionAvailability();
	}

	@Override
	protected void ItemsCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
	{
		super.ItemsCollectionChanged(sender, e);

		//Try to select an item corresponding to the system tree selection.
		if (getSystemTreeSelectedItem() != null && getSystemTreeSelectedItem().getType() == SystemTreeItemType.DataCenter)
		{
			storage_pool dataCenter = (storage_pool)getSystemTreeSelectedItem().getEntity();

			setSelectedItem(Linq.FirstOrDefault(Linq.<storage_pool>Cast(getItems()), new Linq.DataCenterPredicate(dataCenter.getId())));
		}
	}

	@Override
	protected void SelectedItemPropertyChanged(Object sender, PropertyChangedEventArgs e)
	{
		super.SelectedItemPropertyChanged(sender, e);

		if (e.PropertyName.equals("status"))
		{
			UpdateActionAvailability();
		}
	}

	private void UpdateActionAvailability()
	{
		java.util.ArrayList<storage_pool> items = getSelectedItems() != null ? new java.util.ArrayList<storage_pool>(Linq.<storage_pool>Cast(getSelectedItems())) : new java.util.ArrayList<storage_pool>();

		boolean isAllDown = true;
		for (storage_pool item : items)
		{
			if (item.getstatus() == StoragePoolStatus.Up || item.getstatus() == StoragePoolStatus.Contend)
			{
				isAllDown = false;
				break;
			}
		}

		getEditCommand().setIsExecutionAllowed(getSelectedItem() != null && items.size() == 1);
		getRemoveCommand().setIsExecutionAllowed(items.size() > 0 && isAllDown);

		storage_pool storagePoolItem = (getSelectedItem() != null ? (storage_pool)getSelectedItem() : null);

		getForceRemoveCommand().setIsExecutionAllowed(storagePoolItem != null && items.size() == 1 && storagePoolItem.getstatus() != StoragePoolStatus.Up && storagePoolItem.getstatus() != StoragePoolStatus.Contend && storagePoolItem.getstatus() != StoragePoolStatus.Uninitialized);

		getGuideCommand().setIsExecutionAllowed(getGuideContext() != null || (getSelectedItem() != null && getSelectedItems() != null && getSelectedItems().size() == 1));

		getActivateCommand().setIsExecutionAllowed(items.size() > 0);
		if (getActivateCommand().getIsExecutionAllowed())
		{
			for (storage_pool a : items)
			{
				if (a.getstatus() == StoragePoolStatus.Up || a.getstatus() == StoragePoolStatus.Uninitialized)
				{
					getActivateCommand().setIsExecutionAllowed(false);
					break;
				}
			}
		}

		getRecoveryStorageCommand().setIsExecutionAllowed(items != null && items.size() == 1);

		//System tree dependent actions.
		boolean isAvailable = !(getSystemTreeSelectedItem() != null && getSystemTreeSelectedItem().getType() == SystemTreeItemType.DataCenter);

		getNewCommand().setIsAvailable(isAvailable);
		getRemoveCommand().setIsAvailable(isAvailable);
	}

	@Override
	public void ExecuteCommand(UICommand command)
	{
		super.ExecuteCommand(command);

		if (command == getNewCommand())
		{
			New();
		}
		else if (command == getEditCommand())
		{
			Edit();
		}
		else if (command == getRemoveCommand())
		{
			remove();
		}
		else if (command == getForceRemoveCommand())
		{
			ForceRemove();
		}
		else if (command == getActivateCommand())
		{
			Activate();
		}
		else if (command == getGuideCommand())
		{
			Guide();
		}
		else if (command == getRecoveryStorageCommand())
		{
			RecoveryStorage();
		}
		else if (StringHelper.stringsEqual(command.getName(), "OnSave"))
		{
			OnSave();
		}
		else if (StringHelper.stringsEqual(command.getName(), "Cancel"))
		{
			Cancel();
		}
		else if (StringHelper.stringsEqual(command.getName(), "OnRemove"))
		{
			OnRemove();
		}
		else if (StringHelper.stringsEqual(command.getName(), "OnForceRemove"))
		{
			OnForceRemove();
		}
		else if (StringHelper.stringsEqual(command.getName(), "OnSaveInternal"))
		{
			OnSaveInternal();
		}
		else if (StringHelper.stringsEqual(command.getName(), "CancelConfirmation"))
		{
			CancelConfirmation();
		}
		else if (StringHelper.stringsEqual(command.getName(), "OnRecover"))
		{
			OnRecover();
		}
	}

	private SystemTreeItemModel systemTreeSelectedItem;
	public SystemTreeItemModel getSystemTreeSelectedItem()
	{
		return systemTreeSelectedItem;
	}
	public void setSystemTreeSelectedItem(SystemTreeItemModel value)
	{
		if (systemTreeSelectedItem != value)
		{
			systemTreeSelectedItem = value;
			OnSystemTreeSelectedItemChanged();
		}
	}

	private void OnSystemTreeSelectedItemChanged()
	{
		UpdateActionAvailability();
	}
}


text:
<template name="menuComponent">

{{menuLabel}}

      {{#with getMenuItems}}

          {{#each this}}
            {{#if hasTemplate}}
              {{> Template.dynamic template=template data=data}}
            {{else}}

                  {{itemLabel}}
                  {{#if description}}{{_ description}}{{/if}}

            {{/if}}
          {{/each}}

      {{/with}}

        {{{icon "open"}}}
        {{{icon "close"}}}

</template>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   error.h
 * Author: czimbortibor
 *
 * Created on December 13, 2016, 1:18 AM
 */

#ifndef ERROR_H
#define ERROR_H

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

// inline, to prevent: for every file "Error.h" gets included to, a public function "error" will be created, resulting in a name clash
inline void error(const char* errorMsg) {
    perror(errorMsg);
    exit(1);
}

#endif /* ERROR_H */


text:
layout: default
---

    Welcome

    to the shipcloud developer portal where you - the developer - will hopefully get all the
    information you need to get started with integrating shipcloud into your own service, shop, app
    or other crazy idea.

    This is supposed to be your one stop for all developer needs. If you have any questions, feel free to contact us.

    If there's anything missing in this portal, you've found a typo, bug or something isn't clear, the developer
    portal is build as a public repository on github. Feel free to fork it, change things, make a pull request or
    even run your own local version of it.

    Getting started

    If you want to start testing our services fast - this is the way to go! Just follow these
    simple steps:

      First of all you

        register for our free developer plan.

      Afterwards you can

        get your api keys from our backoffice

      Start implementing your first api call using our
      api reference.

    Concepts

    Afterwards you should consider reading about a few of the

      concepts

    and principles that our api and services are adhering to. On our concepts page we're trying
    to explain stuff like authentication, versioning, timeouts and a lot more basic and important
    things you should know about when working with our api.

    Newsletter

    Always stay up to date with our

      developer journal

    where we're writing about changes and updates to our api, providing you with useful insights
    and keeping you up to date about where you can meet us to talk about the development side of
    our services.

    Not a developer?

    Don't panic! We've got you covered! There are already a hand full of

      plugins

    written by other developers for a lot of the largest online shopping software solutions.
    We're also directly integrated into a few shopping services like Gambio, Jimdo and
    VersaCommerce.

    Need help?

    If at any point you're getting the feeling that you're lost or you're simply having a
    question, because something we're describing isn't clear to you. Don't hesitate to
    contact us.


text:
[![Deploy](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy)

A Go Events CRUD API using the native net/http library and [mgo](https://github.com/go-mgo/mgo).

Feel free to use and/or make any improvements to it.

The Go gopher was designed by Renee French. (http://reneefrench.blogspot.com/) The gopher vector data was made by Takuya Ueda (http://u.hinoichi.net). Licensed under the Creative Commons 3.0 Attributions license.

## Instructions

1. Install mgo dependency.

   ```
	go get gopkg.in/mgo.v2
   ```

2. Start a MongoDB instance.

   ```
	mongod --dbpath D:/dbpath
   ```

3. Run my app!

   ```
	go run main.go -port=<port> -conn=<connectionString>
   ```

There are 2 parameters: the port represents the HTTP port to the API and the conn represents the MongoDB connection string where the event data will be persisted. The default values are "8080" and "mongodb://localhost:27017", respectively.

## Usage

There are 5 URLs that allow CRUD operations in a event resource:

- **GET events/** to get all available events.
- **GET events/:id** to get a specific event.
- **POST events/** to include a event.
- **PUT events/:id/** to update a event.
- **DELETE events/:id** to delete a event.

The event resource has the following format:

```json
{
"name": "Golang POA Meetup",
"begin": "2020-04-15T13:00:15-07:00",
"end": "2020-04-15T18:00:15-07:00",
"location":
 {
  "latitude": 30.0331,
  "longitude": 51.2300,
  "name": "Porto Alegre"
  }
}
```


text:
<?php

namespace Components\Collections\Models\Following;

use Components\Collections\Models;

require_once __DIR__ . DS . 'base.php';
require_once dirname(__DIR__) . DS . 'collection.php';

/**
 * Model class for following a collection
 */
class Collection extends Base
{
	/**
	 * Collection
	 *
	 * @var object
	 */
	private $_obj = null;

	/**
	 * File path
	 *
	 * @var string
	 */
	private $_image = null;

	/**
	 * URL
	 *
	 * @var string
	 */
	private $_baselink = null;

	/**
	 * Constructor
	 *
	 * @param   integer  $id  Collection ID
	 * @return  void
	 */
	public function __construct($oid=null)
	{
		$this->_obj = new Models\Collection($oid);

		switch ($this->_obj->get('object_type'))
		{
			case 'group':
				$group = \Hubzero\User\Group::getInstance($this->_obj->get('object_id'));
				if (!$group)
				{
					$group = new \Hubzero\User\Group();
					$group->set('gidNumber', $this->_obj->get('object_id'));
					$group->set('cn', $this->_obj->get('object_id'));
					$group->set('alias', $this->_obj->get('object_id'));
				}
				$this->_baselink = 'index.php?option=com_groups&cn=' . $group->get('cn') . '&active=collections&scope=' . $this->_obj->get('alias');
			break;

			case 'member':
			default:
				$this->_baselink = 'index.php?option=com_members&id=' . $this->_obj->get('object_id') . '&active=collections&task=' . $this->_obj->get('alias');
			break;
		}
	}

	/**
	 * Get the creator of this entry
	 *
	 * Accepts an optional property name. If provided
	 * it will return that property value. Otherwise,
	 * it returns the entire User object
	 *
	 * @param   string  $property
	 * @return  mixed
	 */
	public function creator($property=null)
	{
		switch ($this->_obj->get('object_type'))
		{
			case 'group':
				if (!isset($this->_creator) || !is_object($this->_creator))
				{
					$this->_creator = \Hubzero\User\Group::getInstance($this->_obj->get('object_id'));
				}
				if ($property)
				{
					switch ($property)
					{
						case 'name':
							return $this->_creator->get('description');
						break;
						case 'alias':
							return $this->_creator->get('cn');
						break;
						case 'id':
							return $this->_creator->get('gidNumber');
						break;
					}
				}
			break;

			case 'member':
			default:
				if (!isset($this->_creator) || !is_object($this->_creator))
				{
					$this->_creator = \User::getInstance($this->_obj->get('created_by'));
				}
				if ($property)
				{
					switch ($property)
					{
						case 'name':
							return $this->_creator->get('name');
						break;
						case 'alias':
							return $this->_creator->get('username');
						break;
						case 'id':
							return $this->_creator->get('id');
						break;
					}
				}
			break;
		}
		return $this->_creator;
	}

	/**
	 * Get an image path
	 *
	 * @return  string
	 */
	public function image()
	{
		return $this->_image;
	}

	/**
	 * Get an alias
	 *
	 * @return  string
	 */
	public function alias()
	{
		return $this->_obj->get('alias');
	}

	/**
	 * Get a title
	 *
	 * @return  string
	 */
	public function title()
	{
		return $this->_obj->get('title');
	}

	/**
	 * Get a link
	 *
	 * @param   string  $what
	 * @return  object
	 */
	public function link($what='base')
	{
		switch (strtolower(trim($what)))
		{
			case 'follow':
				return $this->_baselink . '/follow';
			break;

			case 'unfollow':
				return $this->_baselink . '/unfollow';
			break;

			case 'base':
			default:
				return $this->_baselink;
			break;
		}
	}
}


text:
@interface PodsDummy_Pods_DRYPagerViewController_Tests : NSObject
@end
@implementation PodsDummy_Pods_DRYPagerViewController_Tests
@end


text:
#include "OgreGLSLESProgramCommon.h"
#include "OgreGLSLESProgram.h"
#include "OgreGpuProgramManager.h"
#include "OgreGLUtil.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreRoot.h"
#include "OgreGLNativeSupport.h"

namespace Ogre {

    //-----------------------------------------------------------------------
    GLSLESProgramCommon::GLSLESProgramCommon(const GLShaderList& shaders)
    : GLSLProgramCommon(shaders)
    {
    }

    void GLSLESProgramCommon::bindFixedAttributes(GLuint program)
    {
        GLint maxAttribs = Root::getSingleton().getRenderSystem()->getCapabilities()->getNumVertexAttributes();

#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
        // must query active attributes on OSX to avoid warning spam
        OGRE_CHECK_GL_ERROR(glLinkProgram( program ));
#endif

        size_t numAttribs = sizeof(msCustomAttributes) / sizeof(CustomAttribute);
        for (size_t i = 0; i < numAttribs; ++i)
        {
            const CustomAttribute& a = msCustomAttributes[i];
            if (a.attrib < maxAttribs)
            {
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
                if(glGetAttribLocation(program, a.name) == -1) continue;
#endif
                OGRE_CHECK_GL_ERROR(glBindAttribLocation(program, a.attrib, a.name));
            }
        }
    }

    //-----------------------------------------------------------------------
    bool GLSLESProgramCommon::getMicrocodeFromCache(uint32 id, GLuint programHandle)
    {
        if (!GpuProgramManager::canGetCompiledShaderBuffer())
            return false;

        if (!GpuProgramManager::getSingleton().isMicrocodeAvailableInCache(id))
            return false;

        GpuProgramManager::Microcode cacheMicrocode = GpuProgramManager::getSingleton().getMicrocodeFromCache(id);

        // turns out we need this param when loading
        GLenum binaryFormat = 0;

        cacheMicrocode->seek(0);

        // get size of binary
        cacheMicrocode->read(&binaryFormat, sizeof(GLenum));

        if(!Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_CAN_GET_COMPILED_SHADER_BUFFER))
            return false;

        GLint binaryLength = static_cast<GLint>(cacheMicrocode->size() - sizeof(GLenum));

        // load binary
        OGRE_CHECK_GL_ERROR(glProgramBinaryOES(programHandle,
                           binaryFormat,
                           cacheMicrocode->getCurrentPtr(),
                           binaryLength));

        GLint success = 0;
        OGRE_CHECK_GL_ERROR(glGetProgramiv(programHandle, GL_LINK_STATUS, &success));

        return success;
    }
    void GLSLESProgramCommon::_writeToCache(uint32 id, GLuint programHandle)
    {
        if(!GpuProgramManager::canGetCompiledShaderBuffer())
            return;

        if(!GpuProgramManager::getSingleton().getSaveMicrocodesToCache())
            return;

        // Add to the microcode to the cache
        // Get buffer size
        GLint binaryLength = 0;
        OGRE_CHECK_GL_ERROR(glGetProgramiv(programHandle, GL_PROGRAM_BINARY_LENGTH_OES, &binaryLength));

        // Create microcode
        auto newMicrocode = GpuProgramManager::createMicrocode(static_cast<uint32>(binaryLength + sizeof(GLenum)));

        // Get binary
        OGRE_CHECK_GL_ERROR(glGetProgramBinaryOES(programHandle, binaryLength, NULL, (GLenum *)newMicrocode->getPtr(),
                                                  newMicrocode->getPtr() + sizeof(GLenum)));

        // Add to the microcode to the cache
        GpuProgramManager::getSingleton().addMicrocodeToCache(id, newMicrocode);
    }

#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN
    void GLSLESProgramCommon::notifyOnContextLost()
    {
        mLinked = false;
        mUniformRefsBuilt = false;
        for(auto s : mShaders)
        {
            if(s) s->getUniformCache()->clearCache();
        }
    }

    void GLSLESProgramCommon::notifyOnContextReset()
    {
        activate();
    }
#endif
} // namespace Ogre


text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the Netscape Portable Runtime (NSPR).
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998-2000
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#include "plstr.h"
#include "prmem.h"
#include <string.h>

PR_IMPLEMENT(char *)
PL_strdup(const char *s)
{
    char *rv;
    size_t n;

    if( (const char *)0 == s )
        s = "";

    n = strlen(s) + 1;

    rv = (char *)malloc(n);
    if( (char *)0 == rv ) return rv;

    (void)memcpy(rv, s, n);

    return rv;
}

PR_IMPLEMENT(void)
PL_strfree(char *s)
{
    free(s);
}

PR_IMPLEMENT(char *)
PL_strndup(const char *s, PRUint32 max)
{
    char *rv;
    size_t l;

    if( (const char *)0 == s )
        s = "";

    l = PL_strnlen(s, max);

    rv = (char *)malloc(l+1);
    if( (char *)0 == rv ) return rv;

    (void)memcpy(rv, s, l);
    rv[l] = '\0';

    return rv;
}


text:
package org.kie.workbench.common.screens.datamodeller.client.widgets.common.domain;

import java.util.List;
import javax.enterprise.event.Event;
import javax.inject.Inject;

import com.google.gwt.user.client.ui.Composite;
import org.kie.workbench.common.screens.datamodeller.client.DataModelerContext;
import org.kie.workbench.common.screens.datamodeller.client.command.DataModelCommand;
import org.kie.workbench.common.screens.datamodeller.client.command.DataModelCommandBuilder;
import org.kie.workbench.common.screens.datamodeller.client.handlers.DomainHandler;
import org.kie.workbench.common.screens.datamodeller.client.handlers.DomainHandlerRegistry;
import org.kie.workbench.common.screens.datamodeller.events.DataModelerEvent;
import org.kie.workbench.common.screens.datamodeller.events.DataModelerValueChangeEvent;

public abstract class BaseEditor extends Composite {

    protected DataModelerContext context;

    protected boolean readonly = false;

    @Inject
    protected Event<DataModelerEvent> dataModelerEvent;

    @Inject
    protected DomainHandlerRegistry handlerRegistry;

    @Inject
    protected DataModelCommandBuilder commandBuilder;

    protected BaseEditor() {
    }

    public DataModelerContext getContext() {
        return context;
    }

    public void onContextChange( DataModelerContext context ) {
        this.context = context;
    }

    public void setReadonly( boolean readonly ) {
        this.readonly = readonly;
    }

    public boolean isReadonly() {
        return readonly;
    }

    public abstract void clean();

    public abstract String getName();

    public abstract String getDomainName();

    protected void executePostCommandProcessing( DataModelCommand command ) {
        List<DomainHandler> handlers = handlerRegistry.getDomainHandlers( getDomainName() );
        for ( DomainHandler handler : handlers ) {
            handler.postCommandProcessing( command );
        }
    }

    protected void notifyChange( DataModelerEvent event ) {
        dataModelerEvent.fire( event );
        //TODO, check if the helper is still needed.
        // Notify helper directly
        getContext().getHelper().dataModelChanged( ( DataModelerValueChangeEvent)event );
    }

}


text: export class Labels {}


text:
/*
Average grade

An easy way to understand how well the students performed at this year's course is to compute the average of their final grades. If it is higher that the average for last year, that means the course was easier than last year.

Given an array with all final grades for a course

Your task is to

    write a function that computes the average of all the grades in the array and prints this number to standard output (stdout)
    the result must be rounded downwards to the nearest integer (e.g. both 7.1 and 7.9 are rounded to 7)

Note that your function will receive the following arguments:

    grades
        which is the list of grades, represented as integer numbers

Data constraints

    the length of the array given as input will not exceed 1000 elements
*/

#include <iostream>
#include <vector>

using namespace std;

void compute_average_grade(const vector<int> &grades) {
    int total = 0;
    int avg;
    std::vector<int> copy = grades;

    for(int i = 0; i < copy.size(); i++){
         total += copy[i];
    }
    avg = total/copy.size();
    cout << avg;
}


text:
<!DOCTYPE HTML>
<html>
<head onload>
<meta charset="utf-8" />
<title>This test validates that synchronously adding entries in onresourcetimingbufferfull callback results in these entries being properly handled.</title>
<link rel="author" title="Google" href="http://www.google.com/" />
<link rel="help" href="https://www.w3.org/TR/resource-timing-2/#dom-performance-onresourcetimingbufferfull"/>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="resources/resource-loaders.js"></script>
<script src="resources/buffer-full-utilities.js"></script>
</head>
<body>
<script>
promise_test(async () => {
    await fillUpTheBufferWithSingleResource();
    performance.addEventListener('resourcetimingbufferfull', () => {
        performance.setResourceTimingBufferSize(2);
        // The sync entry is added to the secondary buffer, so will be the last one there and eventually dropped.
        load.xhr_sync(scriptResources[2]);
    });
    // This resource overflows the entry buffer, and goes into the secondary buffer.
    load.script(scriptResources[1]);
    await bufferFullFirePromise;
    checkEntries(2);
}, "Test that entries synchronously added to the buffer during the callback are dropped");
</script>
</body>
</html>


text:
using System;
using System.Collections.Generic;

namespace Unidux.Example.List
{
    [Serializable]
    public class ListState : StateElement
    {
        public List<string> Texts = new List<string>();
    }
}


text:
package com.github.mikeherasimov.trie.linked;

import com.github.mikeherasimov.trie.Optimizer;
import com.github.mikeherasimov.trie.Trie;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

/**
 * LinkedTrie is one of realization of Trie interface.
 * Where each node holds references to first child and brother-node.
 * LinkedTrie uses less memory then ArrayTrie, but it algorithms has some overhead.
 * Also it can not be fully optimized to DAWG.
 */
public final class LinkedTrie implements Trie, Externalizable{

    private int size;
    private LinkedNode root;

    /**
     * Returns new LinkedTrie object, that can hold any String`s.
     * More formally its alphabet contains all UTF characters.
     */
    public LinkedTrie(){
        root = new LinkedNode();
    }

    /**
     * Returns copy of supplied LinkedTrie object.
     * More formally if copy = new LinkedTrie(trie) then

     * trie != copy and

     * trie.equals(copy) == true and

     * trie.getClass() == copy.getClass()
     *
     * @param trie  supplied LinkedTrie object
     */
    public LinkedTrie(LinkedTrie trie){
        size = trie.size;
        root = LinkedNode.newInstance(trie.root);
    }

    LinkedTrie(int size, LinkedNode root) {
        this.size = size;
        this.root = root;
    }

    /**
     * Appends specified word to this LinkedTrie.
     *
     * @param word                       word to be added to this Trie
     * @throws IllegalArgumentException  if at least one letter of word isn't supported by
     *                                   alphabet of this ArrayTrie
     */
    @Override
    public void add(String word) throws IllegalArgumentException {
        LinkedNode current = root;
        for (int i = 0, dest = word.length()-1; i < word.length(); i++){
            current = createNodeIfNeeds(current, word.charAt(i),
                    i == dest);
        }
    }

    /**
     * Makes optimization of this LinkedTrie to DAWG and returns respective DAWG object.
     * More formally makes copy of this LinkedTrie object and then makes optimization of copy to DAWG
     * and returns respective DAWG object.
     * Note that LinkedTrie can't make full optimization to DAWG that is it can't eliminate all duplicate nodes.
     * Because of its node structure, where each node contains reference to its brother and child.
     * So when checking nodes for equality LinkedTrie has to check not only all descendants of node,
     * it has to check brother-nodes too.
     *
     * @return  DAWG object
     */
    @Override
    public LinkedDAWG toDAWG() {
        LinkedTrie copy = new LinkedTrie(this);
        LinkedSubtrieConverter subtrieConverter = new LinkedSubtrieConverter(copy.root);

        Optimizer<LinkedNode> optimizer =
                new Optimizer<>(LinkedOptimizerBehaviour.INSTANCE, subtrieConverter);
        optimizer.eliminateDuplicates();
        return new LinkedDAWG(copy);
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void clear() {
        size = 0;
        root.setChild(null);
    }

    @Override
    public boolean contains(String word) {
        LinkedNode lastNode = searchNodeBySequence(word);
        return lastNode != null && lastNode.getEOW();
    }

    @Override
    public boolean isPrefix(String prefix) {
        return searchNodeBySequence(prefix) != null;
    }

    private LinkedNode searchNodeBySequence(String sequence){
        LinkedNode current = root;
        for (int i = 0; i < sequence.length(); i++) {
            if(current.getChild() == null) {
                return null;
            }
            LinkedNode temp = listScan(current.getChild(), sequence.charAt(i));
            if(temp == null) {
                return null;
            }
            current = temp;
        }
        return current;
    }

    @Override
    public int size() {
        return size;
    }

    private LinkedNode createNodeIfNeeds(LinkedNode ancestor, char letter, boolean EOW){
        LinkedNode child = listScan(ancestor.getChild(), letter);
        if (child == null){
            if (EOW){
                size++;
            }
            return addNewChild(ancestor, letter, EOW);
        } else {
            return checkNodeIfExists(child, EOW);
        }
    }

    private LinkedNode listScan(LinkedNode child, char letter){
        while(child != null) {
            if(child.getLetter() == letter) {
                return child;
            }
            child = child.getBrother();
        }
        return null;
    }

    private LinkedNode addNewChild(LinkedNode ancestor, char letter, boolean EOW){
        LinkedNode newChild = new LinkedNode(letter, EOW);
        if(ancestor.getChild() == null) {
            ancestor.setChild(newChild);
        } else {
            ancestor.getChild().getLastBrother().setBrother(newChild);
        }
        return newChild;
    }

    private LinkedNode checkNodeIfExists(LinkedNode node, boolean EOW) {
        if(EOW && !node.getEOW()) {
            size++;
            node.setAsEOW();
        }
        return node;
    }

    @Override
    public boolean equals(Object obj) {
        if(obj == this) return true;
        if(!(obj instanceof LinkedTrie)) return false;
        LinkedTrie trie = (LinkedTrie) obj;
        return size == trie.size && root.equals(trie.root);
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeInt(size);
        out.writeObject(root.serializeSubtrie());
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        this.size = in.readInt();
        char[] sequence = (char[]) in.readObject();
        this.root = LinkedNode.deserializeSubtrie(sequence);
    }

    LinkedDAWGSerializationHelper getDAWGSerializationHelper(){
        return new LinkedDAWGSerializationHelper(root);
    }
}


text:
using System;
using FluentValidation;
using ReMi.Commands.ProductRequests;
using ReMi.CommandValidators.Common;
using ReMi.Common.Cqrs.FluentValidation;

namespace ReMi.CommandValidators.ProductRequests
{
    public class CreateProductRequestRegistrationCommandValidator : RequestValidatorBase<CreateProductRequestRegistrationCommand>
    {
        public CreateProductRequestRegistrationCommandValidator()
        {
            RuleFor(o => o.Registration).NotNull();

            RuleFor(o => o.Registration.Description).NotEmpty();

            RuleFor(o => o.Registration.Description).Length(1, 1024);

            RuleFor(o => o.Registration.ExternalId).NotEqual(Guid.Empty);

            RuleFor(o => o.Registration.ProductRequestTypeId).NotEmpty();

            RuleFor(o => o.Registration)
                .SetValidator(new ProductRequestRegistrationTaskValidator());
        }
    }
}


text:
#ifndef INICPP_EXCEPTION_H
#define INICPP_EXCEPTION_H

#include <exception>
#include <iostream>
#include <string>
#include <vector>

namespace inicpp
{
	/**
	 * Generic inicpp exception.
	 */
	class exception : public std::exception
	{
	protected:
		/** Description of exception */
		std::string what_;

	public:
		/**
		 * Default constructor.
		 */
		exception() : what_("Generic inicpp exception")
		{
		}
		/**
		 * Constructor in which cause can be specified.
		 * @param what exception description
		 */
		exception(const std::string &what) : what_(what)
		{
		}

		/**
		 * Desctuctor.
		 */
		virtual ~exception()
		{
		}

		/**
		 * Return description of this exception instance.
		 * @return c-string textual description
		 */
		virtual const char *what() const noexcept
		{
			return what_.c_str();
		}
	};

	/**
	 * Occurs when parsing went wrong in some way
	 */
	class parser_exception : public exception
	{
	public:
		/**
		 * General parser_exception constructor with given description.
		 * @param message exception cause
		 */
		parser_exception(const std::string &message) : inicpp::exception(message)
		{
		}
	};

	/**
	 * Occurs when two elements cannot be successfully casted.
	 */
	class bad_cast_exception : public exception
	{
	public:
		/**
		 * General bad_cast_exception constructor with given description.
		 * @param message exception cause
		 */
		bad_cast_exception(const std::string &message) : inicpp::exception(message)
		{
		}
		/**
		 * Constructor in which casted elements can be specified.
		 * @param from type from which conversion was invoked
		 * @param to type to which conversion was invoked
		 */
		bad_cast_exception(const std::string &from, const std::string &to)
			: inicpp::exception("Bad conversion from: " + from + " to: " + to)
		{
		}
	};

	/**
	 * Element not found exception.
	 * Raised when there is no element with specified name
	 * or with specified index.
	 */
	class not_found_exception : public exception
	{
	public:
		/**
		 * Element on specified index was not found.
		 * @param index
		 */
		not_found_exception(size_t index)
			: inicpp::exception("Element on index: " + std::to_string(index) + " was not found")
		{
		}
		/**
		 * Element with specified name was not found.
		 * @param element_name
		 */
		not_found_exception(const std::string &element_name)
			: inicpp::exception("Element: " + element_name + " not found in container")
		{
		}
	};

	/**
	 * Element ambiguity exception.
	 * Raised when there are multiple elements with same name.
	 */
	class ambiguity_exception : public exception
	{
	public:
		/**
		 * There are multiple elements with specified name.
		 * @param element_name
		 */
		ambiguity_exception(const std::string &element_name)
			: inicpp::exception("Ambiguous element with name: " + element_name)
		{
		}
	};

	/**
	 * Thrown in case of validation error.
	 */
	class validation_exception : public exception
	{
	public:
		/**
		 * Default generic constructor.
		 * @param message
		 */
		validation_exception(const std::string &message) : inicpp::exception(message)
		{
		}
	};

	/**
	 * Thrown in case of bad format of input ini configuration.
	 */
	class invalid_type_exception : public exception
	{
	public:
		/**
		 * Default generic constructor.
		 * @param message
		 */
		invalid_type_exception(const std::string &message) : inicpp::exception(message)
		{
		}
	};

	/**
	 * Thrown in case of missing function implementation.
	 */
	class not_implemented_exception : public exception
	{
	public:
		/**
		 * Generic constructor.
		 */
		not_implemented_exception() : inicpp::exception("Not implemented")
		{
		}
	};
} // namespace inicpp

#endif


text:
@interface TDRegularParserTest : SenTestCase {
    NSString *s;
    PKCharacterAssembly *a;
    PKParser *p;
    TDRegexAssembler *ass;
    PKAssembly *res;
}

@end


text:
layout: post
title: Mew
modified:
categories: research
excerpt: Intelligent Query Allocation in Crowd Sensing Systems.
tags: []
img: mew-logo.PNG
image:
  feature:
date: 2016-11-26T20:28:47+05:30
---

## Background
Mobile CrowdSensing (MCS) applications rely on physical sensor
data collected by mobile devices of a large number of participants.
Participating devices are required to execute sensing tasks with
certain requirements such as geographical location or data quality.
Often, it is sufficient to execute the tasks on a subset of devices
to avoid data redundancy and improve energy efficiency. Since
mobile devices are resource-constrained, it becomes important to
ensure a load-balanced allocation of sensing tasks to this subset
of participants, which will eventually ensure longer lifetimes of
devices and therefore, higher task service rates.
To take into account the resource-constrained nature of participants,
we consider the dynamic parameters of participants (such
as battery level and link speed) and their static parameters (such
as sensor power rates and the number of sensors available) to propose
a load-balanced task allocation algorithm for MCS systems.
Our algorithm is based on the model of device 'richness' which is
a measure of their available parameter levels. Based on the richness,
we propose two variants of our algorithm - greedy allocation,
and weighted-random allocation. We compare our algorithms with
three baseline approaches using simulations. Using a quantitative
measure of inequality distribution - Gini coefficient - we show that
our algorithm achieves perfect load balancing when the participants
have homogeneous configurations. Further, using our approach,
we are able to improve the lifetime of the system by approx. X%
which eventually results in a Y% improvement in the task service
rate.

## Contributions
1. We propose a model to evaluate the richness of devices in
terms of their capabilities (resource levels). Our model is inspired
by the Linux-based Completely Fair Scheduler
(CFS) which ensures fair allocation of CPU time to processes
based on their priorities.
2. We propose two variants, NV-Greedy and NV-Weighted,
of the load-balanced task allocation algorithm based on
our device richness model and compare their performance
with three baseline algorithms - Random, RoundRobin,
and MinAST , using extensive simulations.
3. We objectively evaluate the effectiveness of our algorithm
using a quantitative measure - Gini coefficient . Gini
coefficient is commonly used in the field of economics to
measure the inequalities in income distribution of nature.
We use it to measure the inequalities in the distribution of
richness levels of devices.

## System Design
![Mew Architecture]({{ site.url }}/images/mew-arch.PNG)

## Results
Our results show that the proposed
variants improve the fairness in task allocation by upto 2-3%, which
results in an additional availability of upto 665 minutes of devices
with the system while improving the location accuracy of collected
sensor data. This is a significant gain which will increase with
the increase in number of devices available with the crowdsensing
system.

## Publications
1. Achieving Load Balanced, Dynamic Task Allocation in Mobile
Crowdsensing Systems.[pdf](http://www.mobileeducationkit.net/doc/Mek7-FULLTEXT01.pdf#page=119)


text:
<?php

require_once __DIR__.'/../vendor/autoload.php';

Dotenv::load(__DIR__.'/../');

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/

$app = new Laravel\Lumen\Application(
    realpath(__DIR__.'/../')
);

$app->withFacades();
// $app->withEloquent();

/*
|--------------------------------------------------------------------------
| Register Container Bindings
|--------------------------------------------------------------------------
|
| Now we will register a few bindings in the service container. We will
| register the exception handler and the console kernel. You may add
| your own bindings here if you like or you can make another file.
|
*/

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
*/

// $app->middleware([
//     // Illuminate\Cookie\Middleware\EncryptCookies::class,
//     // Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
//     // Illuminate\Session\Middleware\StartSession::class,
//     // Illuminate\View\Middleware\ShareErrorsFromSession::class,
//     // Laravel\Lumen\Http\Middleware\VerifyCsrfToken::class,
// ]);

// $app->routeMiddleware([

// ]);

/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/

// $app->register(App\Providers\AppServiceProvider::class);
// $app->register(App\Providers\EventServiceProvider::class);

/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/

$app->group(['namespace' => 'App\Http\Controllers'], function ($app) {
    require __DIR__.'/../app/Http/routes.php';
});

return $app;


text:
.. _config_http_filters_admission_control:

Admission Control
=================

.. attention::

  The admission control filter is experimental and is currently under active development.

See the :ref:`v3 API reference <envoy_v3_api_msg_extensions.filters.http.admission_control.v3alpha.AdmissionControl>` for details on each configuration parameter.

Overview
--------

The admission control filter probabilistically rejects requests based on the success rate of
previous requests in a configurable sliding time window. It is based on `client-side
throttling <https://landing.google.com/sre/sre-book/chapters/handling-overload/>`_ from the `Google SRE handbook <https://landing.google.com/sre/sre-book/toc/index.html>`_. The only notable difference between the admission control
filter's load shedding and load shedding defined in client-side throttling is that users may
configure how aggressively load shedding starts at a target request success rate. Users may also
configure the definition of a successful request for the purposes of the rejection probability
calculation.

The probability that the filter will reject a request is as follows:

.. math::

   P_{reject} = {(\frac{n_{total} - s}{n_{total} + 1})}^\frac{1}{aggression}

where,

.. math::

   s = \frac{n_{success}}{threshold}

- *n* refers to a request count gathered in the sliding window.
- *threshold* is a configurable value that dictates the lowest request success rate at which the
  filter will **not reject** requests. The value is normalized to [0,1] for the calculation.
- *aggression* controls the rejection probability curve such that 1.0 is a linear increase in
  rejection probability as the success rate decreases. As the **aggression** increases, the
  rejection probability will be higher for higher success rates. See `Aggression`_ for a more
  detailed explanation.

.. note::
   The success rate calculations are performed on a per-thread basis for increased performance. In
   addition, the per-thread isolation prevents decreases the blast radius of a single bad connection
   with an anomalous success rate. Therefore, the rejection probability may vary between worker
   threads.

.. note::
   Health check traffic does not count towards any of the filter's measurements.

See the :ref:`v3 API reference
<envoy_v3_api_msg_extensions.filters.http.admission_control.v3alpha.AdmissionControl>` for more
details on this parameter.

The definition of a successful request is a :ref:`configurable parameter
<envoy_v3_api_msg_extensions.filters.http.admission_control.v3alpha.AdmissionControl.SuccessCriteria>`
for both HTTP and gRPC requests.

Aggression
~~~~~~~~~~

The aggression value affects the rejection probabilities as shown in the following figures:

.. image:: images/aggression_graph.png

Since the success rate threshold in the first figure is set to 95%, the rejection probability
remains 0 until then. In the second figure, there rejection probability remains 0 until the success
rate reaches 50%. In both cases, as success rate drops to 0%, the rejection probability approaches a
value just under 100%. The aggression values dictate how high the rejection probability will be at a
given request success rate, so it will shed load more *aggressively*.

Example Configuration
---------------------
An example filter configuration can be found below. Not all fields are required and many of the
fields can be overridden via runtime settings.

.. code-block:: yaml

  name: envoy.filters.http.admission_control
  typed_config:
    "@type": type.googleapis.com/envoy.extensions.filters.http.admission_control.v3alpha.AdmissionControl
    enabled:
      default_value: true
      runtime_key: "admission_control.enabled"
    sampling_window: 120s
    sr_threshold:
      default_value: 95.0
      runtime_key: "admission_control.sr_threshold"
    aggression:
      default_value: 1.5
      runtime_key: "admission_control.aggression"
    success_criteria:
      http_criteria:
        http_success_status:
          - start: 100
            end:   400
          - start: 404
            end:   404
      grpc_criteria:
        grpc_success_status:
          - 0
          - 1

The above configuration can be understood as follows:

* Calculate the request success-rate over a 120s sliding window.
* Do not begin shedding any load until the request success-rate drops below 95% in the sliding
  window.
* HTTP requests are considered successful if they are 1xx, 2xx, 3xx, or a 404.
* gRPC requests are considered successful if they are OK or CANCELLED.

Statistics
----------
The admission control filter outputs statistics in the
*http.<stat_prefix>.admission_control.* namespace. The :ref:`stat prefix
<envoy_v3_api_field_extensions.filters.network.http_connection_manager.v3.HttpConnectionManager.stat_prefix>`
comes from the owning HTTP connection manager.

.. csv-table::
  :header: Name, Type, Description
  :widths: auto

  rq_rejected, Counter, Total requests that were not admitted by the filter.
  rq_success, Counter, Total requests that were considered a success.
  rq_failure, Counter, Total requests that were considered a failure.


text:
package spvwallet

import (
	"github.com/btcsuite/btcd/chaincfg/chainhash"
	"github.com/btcsuite/btcd/peer"
	"github.com/btcsuite/btcd/wire"
	"time"
)

var (
	maxHash              *chainhash.Hash
	MAX_UNCONFIRMED_TIME time.Duration = time.Hour * 24 * 7
)

func init() {
	h, err := chainhash.NewHashFromStr("0000000000000000000000000000000000000000000000000000000000000000")
	if err != nil {
		log.Fatal(err)
	}
	maxHash = h
}

func (w *SPVWallet) startChainDownload(p *peer.Peer) {
	defer func() {
		if r := recover(); r != nil {
			log.Error("Unhandled error in startChainDownload", r)
		}
	}()
	w.mutex.Lock()
	defer w.mutex.Unlock()
	if w.blockchain.ChainState() == SYNCING {
		height, _ := w.blockchain.db.Height()
		if height >= uint32(p.LastBlock()) {
			moar := w.peerManager.CheckForMoreBlocks(height)
			if !moar {
				log.Info("Chain download complete")
				w.blockchain.SetChainState(WAITING)
				w.Rebroadcast()
				close(w.blockQueue)
			}
			return
		}
		gBlocks := wire.NewMsgGetBlocks(maxHash)
		hashes := w.blockchain.GetBlockLocatorHashes()
		gBlocks.BlockLocatorHashes = hashes
		p.QueueMessage(gBlocks, nil)
	}
}

func (w *SPVWallet) onMerkleBlock(p *peer.Peer, m *wire.MsgMerkleBlock) {
	w.mutex.Lock()
	defer w.mutex.Unlock()
	if w.blockchain.ChainState() == SYNCING && w.peerManager.DownloadPeer() != nil && w.peerManager.DownloadPeer().ID() == p.ID() {
		queueHash := <-w.blockQueue
		headerHash := m.Header.BlockHash()
		if !headerHash.IsEqual(&queueHash) {
			log.Errorf("Peer%d is sending us blocks out of order", p.ID())
			p.Disconnect()
			return
		}
	}
	txids, err := checkMBlock(m)
	if err != nil {
		log.Errorf("Peer%d sent an invalid MerkleBlock", p.ID())
		p.Disconnect()
		return
	}
	newBlock, reorg, height, err := w.blockchain.CommitHeader(m.Header)
	if err != nil {
		log.Warning(err)
		return
	}
	if !newBlock {
		return
	}

	// We hit a reorg. Rollback the transactions and resync from the reorg point.
	if reorg != nil {
		err := w.txstore.processReorg(reorg.height)
		if err != nil {
			log.Error(err)
		}
		if w.blockchain.state != SYNCING {
			w.blockchain.SetChainState(SYNCING)
			w.blockchain.db.Put(*reorg, true)
			go w.startChainDownload(p)
			return
		}
	}

	for _, txid := range txids {
		w.peerManager.QueueTxForDownload(p, *txid, int32(height))
	}

	log.Debugf("Received Merkle Block %s at height %d\n", m.Header.BlockHash().String(), height)
	if len(w.blockQueue) == 0 && w.blockchain.ChainState() == SYNCING {
		go w.startChainDownload(p)
	}
	if w.blockchain.ChainState() == WAITING {
		txns, err := w.txstore.Txns().GetAll(false)
		if err != nil {
			log.Error(err)
			return
		}
		now := time.Now()
		for i := len(txns) - 1; i >= 0; i-- {
			if now.After(txns[i].Timestamp.Add(MAX_UNCONFIRMED_TIME)) && txns[i].Height == int32(0) {
				log.Noticef("Marking tx as dead %s", txns[i].Txid)
				h, err := chainhash.NewHashFromStr(txns[i].Txid)
				if err != nil {
					log.Error(err)
					continue
				}
				err = w.txstore.markAsDead(*h)
				if err != nil {
					log.Error(err)
					continue
				}
			}
		}
	}
}

func (w *SPVWallet) onTx(p *peer.Peer, m *wire.MsgTx) {
	w.mutex.Lock()
	height, err := w.peerManager.DequeueTx(p, m.TxHash())
	if err != nil {
		w.mutex.Unlock()
		return
	}
	w.mutex.Unlock()
	hits, err := w.txstore.Ingest(m, height)
	if err != nil {
		log.Errorf("Error ingesting tx: %s\n", err.Error())
		return
	}
	if hits == 0 {
		log.Debugf("Tx %s from Peer%d had no hits, filter false positive.", m.TxHash().String(), p.ID())
		w.fPositives <- p
		return
	}
	w.updateFilterAndSend(p)
	log.Infof("Tx %s from Peer%d ingested at height %d", m.TxHash().String(), p.ID(), height)
}

func (w *SPVWallet) onInv(p *peer.Peer, m *wire.MsgInv) {
	go func() {
		defer func() {
			if err := recover(); err != nil {
				log.Error(err)
			}
		}()
		for _, inv := range m.InvList {
			switch inv.Type {
			case wire.InvTypeBlock:
				// Kind of lame to send separate getData messages but this allows us
				// to take advantage of the timeout on the upper layer. Otherwise we
				// need separate timeout handling.
				inv.Type = wire.InvTypeFilteredBlock
				gData := wire.NewMsgGetData()
				gData.AddInvVect(inv)
				p.QueueMessage(gData, nil)
				if w.blockchain.ChainState() == SYNCING && w.peerManager.DownloadPeer() != nil && w.peerManager.DownloadPeer().ID() == p.ID() {
					w.blockQueue <- inv.Hash
				}
			case wire.InvTypeTx:
				w.peerManager.QueueTxForDownload(p, inv.Hash, 0)
				gData := wire.NewMsgGetData()
				gData.AddInvVect(inv)
				p.QueueMessage(gData, nil)
			default:
				continue
			}

		}
	}()
}

func (w *SPVWallet) onReject(p *peer.Peer, m *wire.MsgReject) {
	log.Warningf("Received reject message from peer %d: Code: %s, Hash %s, Reason: %s", int(p.ID()), m.Code.String(), m.Hash.String(), m.Reason)
}

func (w *SPVWallet) onGetData(p *peer.Peer, m *wire.MsgGetData) {
	log.Debugf("Received getdata request from Peer%d\n", p.ID())
	var sent int32
	for _, thing := range m.InvList {
		if thing.Type == wire.InvTypeTx {
			tx, _, err := w.txstore.Txns().Get(thing.Hash)
			if err != nil {
				log.Errorf("Error getting tx %s: %s", thing.Hash.String(), err.Error())
				continue
			}
			p.QueueMessageWithEncoding(tx, nil, wire.WitnessEncoding)
			sent++
			continue
		}
		// didn't match, so it's not something we're responding to
		log.Debugf("We only respond to tx requests, ignoring")

	}
	log.Debugf("Sent %d of %d requested items to Peer%d", sent, len(m.InvList), p.ID())
}

func (w *SPVWallet) fPositiveHandler(quit chan int) {
exit:
	for {
		select {
		case peer := <-w.fPositives:
			w.mutex.RLock()
			falsePostives, _ := w.fpAccumulator[peer.ID()]
			w.mutex.RUnlock()
			falsePostives++
			if falsePostives > 7 {
				w.updateFilterAndSend(peer)
				log.Debugf("Reset %d false positives for Peer%d\n", falsePostives, peer.ID())
				// reset accumulator
				falsePostives = 0
			}
			w.mutex.Lock()
			w.fpAccumulator[peer.ID()] = falsePostives
			w.mutex.Unlock()
		case <-quit:
			break exit
		}
	}
}

func (w *SPVWallet) updateFilterAndSend(p *peer.Peer) {
	filt, err := w.txstore.GimmeFilter()
	if err != nil {
		log.Errorf("Error creating filter: %s\n", err.Error())
		return
	}
	// send filter
	p.QueueMessage(filt.MsgFilterLoad(), nil)
	log.Debugf("Sent filter to Peer%d\n", p.ID())
}

func (w *SPVWallet) Rebroadcast() {
	// get all unconfirmed txs
	invMsg, err := w.txstore.GetPendingInv()
	if err != nil {
		log.Errorf("Rebroadcast error: %s", err.Error())
	}
	if len(invMsg.InvList) == 0 { // nothing to broadcast, so don't
		return
	}
	for _, peer := range w.peerManager.ConnectedPeers() {
		peer.QueueMessage(invMsg, nil)
	}
}


text:
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.Compiler.Common;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Files;
using Microsoft.DotNet.InternalAbstractions;
using Microsoft.DotNet.ProjectModel;
using Microsoft.DotNet.ProjectModel.Compilation;
using Microsoft.DotNet.ProjectModel.Files;
using Microsoft.DotNet.ProjectModel.Utilities;
using Microsoft.DotNet.Tools.Common;
using NuGet.Frameworks;

namespace Microsoft.DotNet.Tools.Publish
{
    public partial class PublishCommand
    {
        private const string PublishSubfolderName = "publish";

        public string ProjectPath { get; set; }
        public string Configuration { get; set; }
        public string BuildBasePath { get; set; }
        public string OutputPath { get; set; }
        public string Framework { get; set; }
        public string Runtime { get; set; }
        public bool NativeSubdirectories { get; set; }
        public NuGetFramework NugetFramework { get; set; }
        public BuildWorkspace Workspace { get; set; }
        public IList<ProjectContext> ProjectContexts { get; set; }
        public string VersionSuffix { get; set; }
        public int NumberOfProjects { get; private set; }
        public int NumberOfPublishedProjects { get; private set; }
        public bool ShouldBuild { get; set; }

        public bool TryPrepareForPublish()
        {
            if (Framework != null)
            {
                NugetFramework = NuGetFramework.Parse(Framework);

                if (NugetFramework.IsUnsupported)
                {
                    Reporter.Output.WriteLine($"Unsupported framework {Framework}.".Red());
                    return false;
                }
            }

            ProjectContexts = SelectContexts(ProjectPath, NugetFramework, Runtime).ToList();
            if (!ProjectContexts.Any())
            {
                string errMsg = $"'{ProjectPath}' cannot be published for '{Framework ?? "<no framework provided>"}' '{Runtime ?? "<no runtime provided>"}'";
                Reporter.Output.WriteLine(errMsg.Red());
                return false;
            }

            return true;
        }

        public void PublishAllProjects()
        {
            NumberOfPublishedProjects = 0;
            NumberOfProjects = 0;

            foreach (var project in ProjectContexts)
            {
                if (PublishProjectContext(project, BuildBasePath, OutputPath, Configuration, NativeSubdirectories))
                {
                    NumberOfPublishedProjects++;
                }

                NumberOfProjects++;
            }
        }

        /// <summary>
        /// Publish the project for given 'framework (ex - netcoreapp1.0)' and 'runtimeID (ex - win7-x64)'
        /// </summary>
        /// <param name="context">project that is to be published</param>
        /// <param name="baseOutputPath">Location of published files</param>
        /// <param name="configuration">Debug or Release</param>
        /// <param name="nativeSubdirectories"></param>
        /// <returns>Return 0 if successful else return non-zero</returns>
        private bool PublishProjectContext(ProjectContext context, string buildBasePath, string outputPath, string configuration, bool nativeSubdirectories)
        {
            var target = context.TargetFramework.DotNetFrameworkName;
            if (!string.IsNullOrEmpty(context.RuntimeIdentifier))
            {
                target = $"{target}/{context.RuntimeIdentifier}";
            }
            Reporter.Output.WriteLine($"Publishing {context.RootProject.Identity.Name.Yellow()} for {target.Yellow()}");

            var options = context.ProjectFile.GetCompilerOptions(context.TargetFramework, configuration);
            var outputPaths = context.GetOutputPaths(configuration, buildBasePath, outputPath);

            if (string.IsNullOrEmpty(outputPath))
            {
                outputPath = Path.Combine(outputPaths.RuntimeOutputPath, PublishSubfolderName);
            }

            var contextVariables = new Dictionary<string, string>
            {
                { "publish:ProjectPath", context.ProjectDirectory },
                { "publish:Configuration", configuration },
                { "publish:OutputPath", outputPath },
                { "publish:TargetFramework", context.TargetFramework.GetShortFolderName() },
                { "publish:FullTargetFramework", context.TargetFramework.DotNetFrameworkName },
                { "publish:Runtime", context.RuntimeIdentifier },
            };

            RunScripts(context, ScriptNames.PrePublish, contextVariables);

            if (!Directory.Exists(outputPath))
            {
                Directory.CreateDirectory(outputPath);
            }

            // Compile the project (and transitively, all it's dependencies)
            if (ShouldBuild && !InvokeBuildOnProject(context, buildBasePath, configuration))
            {
                return false;
            }

            // Use a library exporter to collect publish assets
            var exporter = context.CreateExporter(configuration, buildBasePath);

            // Get the output paths used by the call to `dotnet build` above (since we didn't pass `--output`, they will be different from
            // our current output paths)
            var buildOutputPaths = context.GetOutputPaths(configuration, buildBasePath);

            var exports = exporter.GetAllExports();

            var exportsLookup = exports.ToDictionary(e => e.Library.Identity.Name, StringComparer.OrdinalIgnoreCase);
            var platformExclusionList = context.GetPlatformExclusionList(exportsLookup);
            var buildExclusionList = context.GetTypeBuildExclusionList(exportsLookup);
            var allExclusionList = new HashSet<string>(platformExclusionList);
            allExclusionList.UnionWith(buildExclusionList);
            var filteredExports = exports.FilterExports(allExclusionList);

            foreach (var export in filteredExports)
            {
                Reporter.Verbose.WriteLine($"publish: Publishing {export.Library.Identity.ToString().Green().Bold()} ...");

                PublishAssetGroups(export.RuntimeAssemblyGroups, outputPath, nativeSubdirectories: false, includeRuntimeGroups: context.IsPortable);
                PublishAssetGroups(export.NativeLibraryGroups, outputPath, nativeSubdirectories, includeRuntimeGroups: context.IsPortable);

                var runtimeAssetsToCopy = export.RuntimeAssets.Where(a => ShouldCopyExportRuntimeAsset(context, buildOutputPaths, export, a));
                runtimeAssetsToCopy.StructuredCopyTo(outputPath, outputPaths.IntermediateOutputDirectoryPath);

                foreach (var resourceAsset in export.ResourceAssemblies)
                {
                    var dir = Path.Combine(outputPath, resourceAsset.Locale);
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    File.Copy(resourceAsset.Asset.ResolvedPath, Path.Combine(dir, resourceAsset.Asset.FileName), overwrite: true);
                }
            }
            foreach (var export in exports)
            {
                if (options.PreserveCompilationContext.GetValueOrDefault())
                {
                    PublishRefs(export, outputPath);
                }
            }

            if (context.ProjectFile.HasRuntimeOutput(configuration) && !context.TargetFramework.IsDesktop())
            {
                // Make executable in the new location
                var executable = new Executable(context, buildOutputPaths, outputPath, buildOutputPaths.IntermediateOutputDirectoryPath, exporter, configuration);
                var runtimeExports = filteredExports;
                var compilationExports = exports.FilterExports(buildExclusionList);

                executable.WriteConfigurationFiles(exports, runtimeExports, compilationExports, includeDevConfig: false);
            }

            var contentFiles = new ContentFiles(context);

            if (context.ProjectFile.PublishOptions != null)
            {
                var includeEntries = IncludeFilesResolver.GetIncludeFiles(
                    context.ProjectFile.PublishOptions,
                    PathUtility.EnsureTrailingSlash(outputPath),
                    diagnostics: null);

                contentFiles.StructuredCopyTo(outputPath, includeEntries);
            }
            else
            {
                contentFiles.StructuredCopyTo(outputPath);
            }

            // Publish a host if this is an application
            if (options.EmitEntryPoint.GetValueOrDefault() && !string.IsNullOrEmpty(context.RuntimeIdentifier))
            {
                Reporter.Verbose.WriteLine($"publish: Renaming native host in output to create fully standalone output.");
                RenamePublishedHost(context, outputPath, options);
            }

            RunScripts(context, ScriptNames.PostPublish, contextVariables);

            Reporter.Output.WriteLine($"publish: Published to {outputPath}".Green().Bold());

            return true;
        }

        /// <summary>
        /// Filters which export's RuntimeAssets should get copied to the output path.
        /// </summary>
        /// <returns>
        /// True if the asset should be copied to the output path; otherwise, false.
        /// </returns>
        private static bool ShouldCopyExportRuntimeAsset(ProjectContext context, OutputPaths buildOutputPaths, LibraryExport export, LibraryAsset asset)
        {
            // The current project has the host .exe in its runtime assets, but it shouldn't be copied
            // to the output path during publish. The host will come from the export that has the real host in it.

            if (context.RootProject.Identity == export.Library.Identity)
            {
                if (asset.ResolvedPath == buildOutputPaths.RuntimeFiles.Executable)
                {
                    return false;
                }
            }

            return true;
        }

        private bool InvokeBuildOnProject(ProjectContext context, string buildBasePath, string configuration)
        {
            var args = new List<string>()
            {
                "--framework",
                $"{context.TargetFramework.DotNetFrameworkName}",
                "--configuration",
                configuration,
                context.ProjectFile.ProjectDirectory
            };

            if (!string.IsNullOrEmpty(context.RuntimeIdentifier))
            {
                args.Insert(0, context.RuntimeIdentifier);
                args.Insert(0, "--runtime");
            }

            if (!string.IsNullOrEmpty(VersionSuffix))
            {
                args.Add("--version-suffix");
                args.Add(VersionSuffix);
            }

            if (!string.IsNullOrEmpty(buildBasePath))
            {
                args.Add("--build-base-path");
                args.Add(buildBasePath);
            }

            var result = Build.BuildCommand.Run(args.ToArray(), Workspace);

            return result == 0;
        }

        private static void PublishRefs(LibraryExport export, string outputPath)
        {
            var refsPath = Path.Combine(outputPath, "refs");
            if (!Directory.Exists(refsPath))
            {
                Directory.CreateDirectory(refsPath);
            }

            // Do not copy compilation assembly if it's in runtime assemblies
            var runtimeAssemblies = new HashSet<LibraryAsset>(export.RuntimeAssemblyGroups.GetDefaultAssets());
            foreach (var compilationAssembly in export.CompilationAssemblies)
            {
                if (runtimeAssemblies.Contains(compilationAssembly))
                {
                    continue;
                }
                var destFileName = Path.Combine(refsPath, Path.GetFileName(compilationAssembly.ResolvedPath));
                File.Copy(compilationAssembly.ResolvedPath, destFileName, overwrite: true);
            }
        }

        private static int RenamePublishedHost(ProjectContext context, string outputPath, CommonCompilerOptions compilationOptions)
        {
            if (context.TargetFramework.IsDesktop())
            {
                return 0;
            }

            var publishedHostFile = ResolvePublishedHostFile(outputPath);
            if (publishedHostFile == null)
            {
                Reporter.Output.WriteLine($"publish: warning: host executable not available in dependencies, using host for current platform");
                // TODO should this be an error?

                CoreHost.CopyTo(outputPath, compilationOptions.OutputName + Constants.ExeSuffix);
                return 0;
            }

            var publishedHostExtension = Path.GetExtension(publishedHostFile);
            var renamedHostName = compilationOptions.OutputName + publishedHostExtension;
            var renamedHostFile = Path.Combine(outputPath, renamedHostName);

            try
            {
                Reporter.Verbose.WriteLine($"publish: renaming published host {publishedHostFile} to {renamedHostFile}");
                File.Copy(publishedHostFile, renamedHostFile, true);
                File.Delete(publishedHostFile);
            }
            catch (Exception e)
            {
                Reporter.Error.WriteLine($"publish: Failed to rename {publishedHostFile} to {renamedHostFile}: {e.Message}");
                return 1;
            }

            return 0;
        }

        private static string ResolvePublishedHostFile(string outputPath)
        {
            var tryExtensions = new string[] { "", ".exe" };

            foreach (var extension in tryExtensions)
            {
                var hostFile = Path.Combine(outputPath, Constants.PublishedHostExecutableName + extension);
                if (File.Exists(hostFile))
                {
                    Reporter.Verbose.WriteLine($"resolved published host: {hostFile}");
                    return hostFile;
                }
            }

            Reporter.Verbose.WriteLine($"failed to resolve published host in: {outputPath}");
            return null;
        }
        private void PublishAssetGroups(IEnumerable<LibraryAssetGroup> groups, string outputPath, bool nativeSubdirectories, bool includeRuntimeGroups)
        {
            foreach (var group in groups.Where(g => includeRuntimeGroups || string.IsNullOrEmpty(g.Runtime)))
            {
                foreach (var file in group.Assets)
                {
                    var destinationDirectory = DetermineFileDestinationDirectory(file, outputPath, nativeSubdirectories);

                    if (!string.IsNullOrEmpty(group.Runtime))
                    {
                        destinationDirectory = Path.Combine(destinationDirectory, Path.GetDirectoryName(file.RelativePath));
                    }

                    if (!Directory.Exists(destinationDirectory))
                    {
                        Directory.CreateDirectory(destinationDirectory);
                    }

                    Reporter.Verbose.WriteLine($"Publishing file {Path.GetFileName(file.RelativePath)} to {destinationDirectory}");
                    File.Copy(file.ResolvedPath, Path.Combine(destinationDirectory, file.FileName), overwrite: true);
                }
            }
        }

        private static string DetermineFileDestinationDirectory(LibraryAsset file, string outputPath, bool nativeSubdirectories)
        {
            var destinationDirectory = outputPath;

            if (nativeSubdirectories)
            {
                destinationDirectory = Path.Combine(outputPath, GetNativeRelativeSubdirectory(file.RelativePath));
            }

            return destinationDirectory;
        }

        private static string GetNativeRelativeSubdirectory(string filepath)
        {
            string directoryPath = Path.GetDirectoryName(filepath);

            string[] parts = directoryPath.Split(new string[] { "native" }, 2, StringSplitOptions.None);

            if (parts.Length != 2)
            {
                throw new Exception("Unrecognized Native Directory Format: " + filepath);
            }

            string candidate = parts[1];
            candidate = candidate.TrimStart(new char[] { '/', '\\' });

            return candidate;
        }

        private IEnumerable<ProjectContext> SelectContexts(string projectPath, NuGetFramework framework, string runtime)
        {
            if (projectPath.EndsWith("project.json"))
            {
                if (File.Exists(projectPath) == false)
                    throw new InvalidProjectException($"'{projectPath}' does not exist");
            }
            else if (File.Exists(Path.Combine(projectPath, "project.json")) == false)
            {
                throw new InvalidProjectException($"'{projectPath}' does not contain a project.json file");
            }

            var contexts = Workspace.GetProjectContextCollection(projectPath)
                .EnsureValid(projectPath)
                .FrameworkOnlyContexts;

            contexts = framework == null ?
                contexts :
                contexts.Where(c => Equals(c.TargetFramework, framework));

            var rids = string.IsNullOrEmpty(runtime) ?
                DotnetRuntimeIdentifiers.InferCurrentRuntimeIdentifiers(DotnetFiles.VersionFileObject) :
                new[] { runtime };

            return contexts.Select(c => Workspace.GetRuntimeContext(c, rids));
        }

        private static void RunScripts(ProjectContext context, string name, Dictionary<string, string> contextVariables)
        {
            foreach (var script in context.ProjectFile.Scripts.GetOrEmpty(name))
            {
                ScriptExecutor.CreateCommandForScript(context.ProjectFile, script, contextVariables)
                    .ForwardStdErr()
                    .ForwardStdOut()
                    .Execute();
            }
        }
    }
}