text:
package ca.wimsc.client.common.select;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import ca.wimsc.client.common.model.AbstractModelListener;
import ca.wimsc.client.common.model.Model;
import ca.wimsc.client.common.model.Route;
import ca.wimsc.client.common.model.RouteList;
import ca.wimsc.client.common.model.Stop;
import ca.wimsc.client.common.util.Constants;
import ca.wimsc.client.common.util.IClosable;
import ca.wimsc.client.common.util.IPropertyChangeListener;
import ca.wimsc.client.common.widgets.HtmlBr;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

/**
 * A panel containing controls suitable for selecting a new route / stop
 */
public class ChooseRoutesAndStopsPanel extends FlowPanel implements IClosable {

	private static final String DEFAULT_ROUTE = "501";
	private List<Widget> myActionLink = new ArrayList<Widget>();
	private ChooseRoutesAndStopActionsPanel myActionsPanel;
	private IPropertyChangeListener myModelListener;
	private MyRoutePanelPropertyChangeListener myRoutePanelListener = new MyRoutePanelPropertyChangeListener();
	private final Set<String> mySelectedRouteTags = new TreeSet<String>();
	private final Set<String> mySelectedStopTags = new HashSet<String>();
	private final List<IProvidesRoutesAndStops> mySelectionBoxesPanels = new ArrayList<IProvidesRoutesAndStops>();
	private boolean myUpdateNeeded;
	private int myExtraComponentsAtBottom;

	/**
	 * Constructor
	 */
	public ChooseRoutesAndStopsPanel(ChooseRoutesAndStopActionsPanel theActionsPanel) {

		myActionsPanel = theActionsPanel;
		myModelListener = new IPropertyChangeListener() {

			@Override
			public void propertyChanged(String thePropertyName, Object theOldValue, Object theNewValue) {

				if (thePropertyName == Model.SELECTED_ROUTE_PROPERTY) {
					mySelectedRouteTags.clear();
					@SuppressWarnings("unchecked")
					Collection<String> value = (Collection<String>) theNewValue;
					mySelectedRouteTags.addAll(value);
				}

				if (thePropertyName == Model.SELECTED_STOP_PROPERTY) {
					mySelectedStopTags.clear();
					@SuppressWarnings("unchecked")
					Collection<String> value = (Collection<String>) theNewValue;
					mySelectedStopTags.addAll(value);
				}

				updateUiLater();
			}

		};
		Model.INSTANCE.addPropertyChangeListener(Model.SELECTED_STOP_PROPERTY, myModelListener);
		Model.INSTANCE.addPropertyChangeListener(Model.SELECTED_ROUTE_PROPERTY, myModelListener);

		Set<String> selectedRouteTags = Model.INSTANCE.getSelectedRouteTags();
		Set<String> selectedStopTags = Model.INSTANCE.getSelectedStopTags();

		HTML addAnotherRouteButton = new HTML("<img src='images/tag_blue_add-16x16.png'" + ChooseRoutesAndStopActionsPanel.HW16 + "/> Add Another Route");
		addAnotherRouteButton.setStyleName("leftAddAnotherRouteButton");
		addAnotherRouteButton.addClickHandler(new MyAddAnotherRouteClickHandler());
		myActionLink.add(addAnotherRouteButton);

		if (selectedRouteTags != null) {
			mySelectedRouteTags.addAll(selectedRouteTags);
			mySelectedStopTags.addAll(selectedStopTags);

			updateUiLater();
		}
	}

	public void insertActionLink(Widget theActionLink) {
		myActionLink.add(0, theActionLink);
	}

	public void addRoute() {

		Model.INSTANCE.getRouteList(new AbstractModelListener<RouteList>() {
			@Override
			public void objectLoaded(RouteList theObject, boolean theRequiredAsyncLoad) {

				// Find a stop which is already selected, to help with selecting the next one
				Stop firstSelectedStop = null;
				for (IProvidesRoutesAndStops nextRouteBox : mySelectionBoxesPanels) {
					firstSelectedStop = nextRouteBox.getFirstSelectedStopIfAny();
					if (firstSelectedStop != null) {
						break;
					}
				}

				// Look for a route which isn't already selected
				for (Route next : theObject.getList()) {

					boolean foundMatch = false;
					for (IProvidesRoutesAndStops nextPanel : mySelectionBoxesPanels) {
						foundMatch |= nextPanel.getSelectedRoutesTags().contains(next.getTag());
					}

					if (foundMatch == false) {
						ChooseStopsForSingleRoutePanel panel = createSelectionBoxesPanel(next.getTag(), null);
						panel.preSelectStopsClosestTo(firstSelectedStop);
						mySelectionBoxesPanels.add(panel);
						ChooseRoutesAndStopsPanel.this.insert(panel, ChooseRoutesAndStopsPanel.this.getWidgetCount() - (myExtraComponentsAtBottom));

						updateSelectedRoutesAndStops();
						myActionsPanel.enableSelectButton();
						return;
					}

				}

			}
		});

	}

	private void closeChildren() {
		for (int i = 0; i < getWidgetCount(); i++) {
			Widget next = getWidget(i);
			if (next instanceof IClosable) {
				((IClosable) next).closeNow();
			}
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void closeNow() {
		Model.INSTANCE.removePropertyChangeListener(Model.SELECTED_STOP_PROPERTY, myModelListener);
		Model.INSTANCE.removePropertyChangeListener(Model.SELECTED_ROUTE_PROPERTY, myModelListener);
		closeChildren();
	}

	private ChooseStopsForSingleRoutePanel createSelectionBoxesPanel(String theRouteTag, String theStopTag) {
		ChooseStopsForSingleRoutePanel panel;
		panel = new ChooseStopsForSingleRoutePanel(this, theRouteTag, theStopTag);
		panel.addPropertyChangeListener(ChooseStopsForSingleRoutePanel.ROUTE_REMOVED_PROPERTY, myRoutePanelListener);
		panel.addPropertyChangeListener(ChooseStopsForSingleRoutePanel.STOP_SELECTION_PROPERTY, myRoutePanelListener);
		panel.addPropertyChangeListener(ChooseStopsForSingleRoutePanel.ROUTE_SELECTION_PROPERTY, myRoutePanelListener);
		panel.addStyleName("leftStopPanel");
		return panel;
	}

	public Set<String> getSelectedRouteTags() {
		return mySelectedRouteTags;
	}

	public Set<String> getSelectedStopTags() {
		return mySelectedStopTags;
	}

	public void resetStops() {
		mySelectedRouteTags.clear();
		mySelectedRouteTags.add(DEFAULT_ROUTE);
		mySelectedStopTags.clear();
		myUpdateNeeded = true;
		updateUi();
	}

	private void updateSelectedRoutesAndStops() {
		mySelectedRouteTags.clear();
		mySelectedStopTags.clear();
		for (IProvidesRoutesAndStops next : mySelectionBoxesPanels) {
			mySelectedRouteTags.addAll(next.getSelectedRoutesTags());
			mySelectedStopTags.addAll(next.getSelectedStopTags());
		}
	}

	/**
	 * Remove all components and add new panels for each selected route
	 */
	public void updateUi() {

		if (myUpdateNeeded == false) {
			return;
		}
		myUpdateNeeded = false;

		if (mySelectedRouteTags.isEmpty()) {
			return;
		}

		closeChildren();
		this.clear();

		ArrayList<IProvidesRoutesAndStops> existingSelectionBoxesPanels = new ArrayList<IProvidesRoutesAndStops>(mySelectionBoxesPanels);
		mySelectionBoxesPanels.clear();

		for (String nextRouteTag : mySelectedRouteTags) {

			ChooseStopsForSingleRoutePanel panel = null;
			for (int i = 0; i < existingSelectionBoxesPanels.size(); i++) {
				IProvidesRoutesAndStops nextExisting = existingSelectionBoxesPanels.get(i);
				if (nextExisting instanceof ChooseStopsForSingleRoutePanel) {
					ChooseStopsForSingleRoutePanel nextExistingCasted = (ChooseStopsForSingleRoutePanel) nextExisting;
					if (nextExistingCasted.getSelectedRouteTag().equals(nextRouteTag)) {
						panel = nextExistingCasted;
						existingSelectionBoxesPanels.remove(i);
						break;
					}
				}
			}

			if (panel == null) {
				panel = createSelectionBoxesPanel(nextRouteTag, null);
			}

			mySelectionBoxesPanels.add(panel);

			this.add(panel);

		}

		for (IProvidesRoutesAndStops next : existingSelectionBoxesPanels) {
			if (next instanceof IClosable) {
				((IClosable) next).closeNow();
			}
		}

		addActionLinks();

		myActionsPanel.disableSelectButton();

	}

	private void addActionLinks() {

		int extraComponents = 0;
		for (int i = 0; i < myActionLink.size(); i++) {
			if (i > 0) {
				this.add(new HtmlBr());
				extraComponents++;
			}
			this.add(myActionLink.get(i));
			extraComponents++;
		}

		if (getSelectedStopTags().size() == Constants.MAX_STOPS_AT_ONCE) {
			this.add(new Label("Note: No more than two stops may be selected at a time"));
			extraComponents++;
		}

		myExtraComponentsAtBottom = extraComponents;

	}

	private void removeActionLinks() {
		for (int i = 0; i < myActionLink.size(); i++) {
			this.remove(myActionLink.get(i));
		}
	}

	public void updateUiLater() {
		myUpdateNeeded = true;
		Scheduler.get().scheduleDeferred(new ScheduledCommand() {

			@Override
			public void execute() {
				updateUi();
			}
		});
	}

	private final class MyAddAnotherRouteClickHandler implements ClickHandler {
		@Override
		public void onClick(ClickEvent theEvent) {
			addRoute();
		}
	}

	private class MyRoutePanelPropertyChangeListener implements IPropertyChangeListener {

		@Override
		public void propertyChanged(String thePropertyName, Object theOldValue, Object theNewValue) {
			if (thePropertyName == ChooseStopsForSingleRoutePanel.ROUTE_REMOVED_PROPERTY) {
				assert theOldValue != null && theNewValue == null;
				mySelectionBoxesPanels.remove(theOldValue);
				ChooseRoutesAndStopsPanel.this.remove((Widget) theOldValue);

				if (mySelectionBoxesPanels.isEmpty()) {
					addRoute();
				}

			}

			updateSelectedRoutesAndStops();

			myActionsPanel.enableSelectButton();
		}

	}

	public boolean hasRoutesWithNoStopsSelected() {
		for (IProvidesRoutesAndStops next : mySelectionBoxesPanels) {
			if (next.getSelectedRoutesTags().isEmpty() == false && next.getSelectedStopTags().isEmpty() == true) {
				return true;
			}
		}
		return false;
	}
}


text:
<?php

require_once('../vendor/autoload.php');
$examplesDir = dirname(__FILE__);
$examplesConfig = require_once($examplesDir . '/_examples-config.php');

$druidHost = $examplesConfig['druid-host'];
$druidPort = $examplesConfig['druid-port'];
$druidDataSource = $examplesConfig['druid-dataSource'];

date_default_timezone_set('America/Denver');

$c = new \DruidFamiliar\QueryExecutor\DruidNodeDruidQueryExecutor($druidHost, $druidPort);

$q = new \DruidFamiliar\QueryGenerator\TimeBoundaryDruidQueryGenerator();
$p = new \DruidFamiliar\QueryParameters\TimeBoundaryQueryParameters($druidDataSource);
$r = $c->executeQuery($q, $p, new DruidFamiliar\ResponseHandler\JsonFormattingResponseHandler());

var_dump( $r );

//array(1) {
//    [0]=>
//  array(2) {
//        ["timestamp"]=>
//    string(24) "2011-06-01T00:00:11.000Z"
//        ["result"]=>
//    array(2) {
//            ["minTime"]=>
//      string(24) "2011-06-01T00:00:11.000Z"
//            ["maxTime"]=>
//      string(24) "2011-11-30T23:55:34.000Z"
//    }
//  }
//}

$q = new \DruidFamiliar\QueryGenerator\TimeBoundaryDruidQueryGenerator($druidDataSource);
$p = new \DruidFamiliar\QueryParameters\TimeBoundaryQueryParameters($druidDataSource);
$r = $c->executeQuery($q, $p, new DruidFamiliar\ResponseHandler\TimeBoundaryResponseHandler());

var_dump( $r );

//object(DruidFamiliar\Response\TimeBoundaryResponse)#11 (2) {
//  ["minTime"]=>
//  string(24) "2008-02-06T11:47:39.000Z"
//  ["maxTime"]=>
//  string(24) "2008-12-31T19:36:48.000Z"
//}

redpajama_set_name: RedPajamaGithub


text:
This article is comprised of three sections: The first section explains how to install Seattle on the Nokia N800 Internet Tablet. The second section (optional) explains how to run the Seattle unit tests on the Nokia N800 Internet Tablet. The third section describes the modification necessary to run Seattle on the N810.
----

----

## Setting up Seattle

### Tools Required
In order to run Seattle, you will need: Python, and root access to the system in the tablet. These can be obtained through the Application Manager.

 1. In the top menu, go to Tools -> Application Catalog.
 1. Select the "maemo extras" entry and Edit.
 1. Uncheck the "disabled" box.
 1. Refresh the installable package list, and packages that are required should now show up.

#### Python
For Python, you will need to install the "maemo-python-env" package. This will install Python 2.5 onto the tablet.

#### Root access
This is only required for the installation of Seattle. In particular, root access is required to configure Seattle to run on startup. There are several ways to obtain the root shell access. This article will describe two easy ways by which root shell access can be obtained.

##### rootsh
Find and install the "rootsh" package. The root shell package allows the user to gain root access through a simple command: "sudo gainroot" or simply "root".

##### openssh
Find and install "openssh" package. During installation the first time, you will be prompted for a new password. Enter your password of choice and remember it for later. Root shell access can be obtained using "ssh root@localhost". You will be prompted for the password you entered during installation.

### Installation
 1. Download the Seattle tarball (Installer for Linux) [here](https://betabox.cs.washington.edu/geni/download/tukwila/).
 1. Next, extract the tarball, and navigate to the Seattle directory.
 1. Install Seattle.
  1. You will need root access to configure Seattle to run on startup properly during installation. See above on how to gain root access.
  2. To install, run **./install.sh**. Seattle will be configured to run on startup. In addition, Seattle will be started after installation.
  3. To check that it is running, run the command
```
ps -f | grep nmmain.py | grep -v grep
```
 1. To stop Seattle, run **./stop_seattle.sh**. Run **./start_seattle.sh** to restart it. You will not need root access for either of these.
 1. Uninstallation:
  1. You will again need root access to uninstall properly. This stops Seattle from running on startup.
  1. Run **./uninstall.sh**.

----
## Running Seattle Unit Tests (Optional)
Note: This part is **optional** and not required for the installation of Seattle.

### Directions
 1. The tarball for the unit tests can be obtained [here](https://seattle.poly.edu/static/nokiadev/seattle_testnokia-r3516.tgz). The tarball contains all of the repy files necessary to run the unit tests as a standalone.
 2. Untar the file by doing the following:
```
tar zxf seattle_testnokia-r3516.tgz
```
 3. Change into the seattle directory, and run the unit tests by doing:
```
python utf.py -m repytests
```
 4. The unit tests should take about an hour. In the end it will report the number of passes/failures.

----
## Notes for Nokia N810 Tablet
This section describes the difference between the above N800, and the N810 installation.

### Python

For Python, you will need to install the "maemo-python-device-env" package; however, this Python package lacks some important modules which Seattle uses. You must add these modules manually.

For Python 2.5.2, you might not be able to install Seattle due to two missing packages: compiler.py and getpass.py. To overcome this setback:

 1. Visit http://www.python.org/download/releases/2.5.2/ and download the 2.5.2 release for other platforms;
 2. unpack the downloaded file;
 3. locate the files compiler.py and getpass.py and copy them to where maemo-python-device-env was installed on N810 (somewhere on your pythonpath).
 4. Install Seattle as usual.

### N810 Notes:

 1. You will just locate the files you need from the release downloaded from the Python official website and copy them. Do not install the release!

 b. to check where maemo-python-device-env was installed you could use the following lines in Python interactive mode:

```
import sys
print sys.path
```


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Moonlit.Caching;
using Moonlit.Mvc.Maintenance.Domains;
using Newtonsoft.Json;

namespace Moonlit.Mvc.Maintenance.Services
{
    public class MaintDomainService : IMaintDomainService
    {
        static Locker _locker = new Locker();
        private readonly CacheKeyManager _cacheKeyManager;
        private readonly IMaintDbRepository _maintDbRepository;
        private readonly ICacheManager _cacheManager;
        private const string CacheKeySystemSettings = "MaintDomainService::SystemSettings";
        private const string CacheKeyCultures = "MaintDomainService::Cultures";
        private const string CacheKeyCultureTexts = "MaintDomainService::CultureTexts";
        public MaintDomainService(CacheKeyManager cacheKeyManager, ICacheManager cacheManager, IMaintDbRepository maintDbRepository)
        {
            _cacheKeyManager = cacheKeyManager;
            _maintDbRepository = maintDbRepository;
            _cacheManager = cacheManager;

            _cacheKeyManager.RegisterCacheKey(CacheKeySystemSettings);
            _cacheKeyManager.RegisterCacheKey(CacheKeyCultures);
            _cacheKeyManager.RegisterCacheKey(CacheKeyCultureTexts);
        }

        private TimeSpan _timeout = TimeSpan.FromHours(1);

        public List<SystemSetting> GetSystemSettings()
        {
            var systemSettings = _cacheManager.Get<List<SystemSetting>>(CacheKeySystemSettings);

            if (systemSettings == null)
            {
                var db = _maintDbRepository;
                systemSettings = db.SystemSettings.ToList();
                _cacheManager.Set(CacheKeySystemSettings, systemSettings, _timeout);
            }
            return systemSettings;
        }
        public List<Culture> GetCultures()
        {
            var cultures = _cacheManager.Get<List<Culture>>(CacheKeyCultures);

            if (cultures == null)
            {
                var db = _maintDbRepository;
                cultures = db.Cultures.Where(x => x.IsEnabled).ToList();
                _cacheManager.Set(CacheKeyCultures, cultures, _timeout);
            }
            return cultures;
        }
        public List<CultureText> GetCultureTexts()
        {
            var cultureTexts = _cacheManager.Get<List<CultureText>>(CacheKeyCultureTexts);

            if (cultureTexts == null)
            {
                var db = _maintDbRepository;

                cultureTexts = db.CultureTexts.ToList();
                _cacheManager.Set(CacheKeyCultureTexts, cultureTexts, _timeout);

            }
            return cultureTexts;
        }

        public void ClearCultureTextsCache()
        {
            _cacheManager.Remove(CacheKeyCultureTexts);
        }

        public void ClearSystemSettingsCache()
        {
            _cacheManager.Remove(CacheKeySystemSettings);
        }
    }

    public interface IMaintDomainService
    {
        List<SystemSetting> GetSystemSettings();
        List<Culture> GetCultures();
        List<CultureText> GetCultureTexts();
        void ClearCultureTextsCache();
        void ClearSystemSettingsCache();
    }
}


text:
package globalnamespaceaccess

import (
	"encoding/base32"
	"fmt"
	"strings"

	"github.com/rancher/norman/api/access"
	"github.com/rancher/norman/httperror"
	"github.com/rancher/norman/types"
	"github.com/rancher/norman/types/convert"
	"github.com/rancher/norman/types/set"
	"github.com/rancher/norman/types/slice"
	"github.com/rancher/rancher/pkg/ref"
	v3 "github.com/rancher/types/apis/management.cattle.io/v3"
	managementschema "github.com/rancher/types/apis/management.cattle.io/v3/schema"
	client "github.com/rancher/types/client/management/v3"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
)

type MemberAccess struct {
	Users              v3.UserInterface
	RoleTemplateLister v3.RoleTemplateLister
	PrtbLister         v3.ProjectRoleTemplateBindingLister
	CrtbLister         v3.ClusterRoleTemplateBindingLister
	GrbLister          v3.GlobalRoleBindingLister
	GrLister           v3.GlobalRoleLister
	Prtbs              v3.ProjectRoleTemplateBindingInterface
	Crtbs              v3.ClusterRoleTemplateBindingInterface
	ProjectLister      v3.ProjectLister
	ClusterLister      v3.ClusterLister
}

const (
	ImpersonateUserHeader  = "Impersonate-User"
	ImpersonateGroupHeader = "Impersonate-Group"
	OwnerAccess            = "owner"
	ReadonlyAccess         = "read-only"
	localPrincipalPrefix   = "local://"
)

func (ma *MemberAccess) CheckCallerAccessToTargets(request *types.APIContext, targets []string, resourceType string, into interface{}) error {
	for _, targetID := range targets {
		if err := access.ByID(request, &managementschema.Version, resourceType, targetID, into); err != nil {
			return err
		}
	}
	return nil
}

func (ma *MemberAccess) IsAdmin(callerID string) (bool, error) {
	u, err := ma.Users.Controller().Lister().Get("", callerID)
	if err != nil {
		return false, err
	}
	if u == nil {
		return false, fmt.Errorf("No user found with ID %v", callerID)
	}
	// Get globalRoleBinding for this user
	grbs, err := ma.GrbLister.List("", labels.NewSelector())
	if err != nil {
		return false, err
	}
	var callerRole string
	for _, grb := range grbs {
		if grb.UserName == callerID {
			callerRole = grb.GlobalRoleName
			break
		}
	}
	gr, err := ma.GrLister.Get("", callerRole)
	if err != nil {
		return false, err
	}
	if gr != nil {
		for _, rule := range gr.Rules {
			// admin roles have all resources and all verbs allowed
			if slice.ContainsString(rule.Resources, "*") && slice.ContainsString(rule.APIGroups, "*") && slice.ContainsString(rule.Verbs, "*") {
				// caller is global admin
				return true, nil
			}
		}
	}
	return false, nil
}

func (ma *MemberAccess) EnsureRoleInTargets(targetProjects, roleTemplates []string, callerID string) error {
	isAdmin, err := ma.IsAdmin(callerID)
	if err != nil {
		return err
	}
	if isAdmin {
		for _, t := range targetProjects {
			if err := ma.checkProjectExists(t); err != nil {
				return err
			}
		}
		// relax memberAccess check for the global admin
		return nil
	}
	newProjectRoleTemplateMap := make(map[string]*v3.RoleTemplate)
	newClusterRoleTemplateMap := make(map[string]*v3.RoleTemplate)
	clusters := make(map[string]bool)
	for _, r := range roleTemplates {
		rt, err := ma.RoleTemplateLister.Get("", r)
		if err != nil {
			if apierrors.IsNotFound(err) {
				return httperror.WrapAPIError(err, httperror.InvalidBodyContent, "Role "+r+" does not exist")
			}
			return err
		}
		switch rt.Context {
		case "project":
			if _, ok := newProjectRoleTemplateMap[r]; !ok {
				newProjectRoleTemplateMap[r] = rt
			}
		case "cluster":
			if _, ok := newClusterRoleTemplateMap[r]; !ok {
				newClusterRoleTemplateMap[r] = rt
			}
		}
	}
	clustersCallerIsOwnerOf := make(map[string]bool)
	errMsg := "User does not have "
	roleMissing := false
	for _, t := range targetProjects {
		if err := ma.checkProjectExists(t); err != nil {
			return err
		}
		cname, pname := ref.Parse(t)
		if !clusters[cname] {
			clusters[cname] = true
		}
		projectRoleTemplateFoundCount := 0
		projectRoleTemplateFoundMap := make(map[string]bool)
		callerIsProjectOwner := false
		callerIsProjectMember := false
		callerIsClusterOwner := false
		prtbs, err := ma.PrtbLister.List(pname, labels.NewSelector())
		if err != nil {
			return err
		}
		for _, prtb := range prtbs {
			if prtb.UserName == callerID {
				if _, ok := newProjectRoleTemplateMap[prtb.RoleTemplateName]; ok {
					projectRoleTemplateFoundMap[prtb.RoleTemplateName] = true
					projectRoleTemplateFoundCount++
				}
				if callerIsProjectOwner && callerIsProjectMember {
					continue
				}
				rt, err := ma.RoleTemplateLister.Get("", prtb.RoleTemplateName)
				if err != nil {
					return err
				}
				if rt.ProjectCreatorDefault && rt.Builtin {
					callerIsProjectOwner = true
				}
				if rt.Name == "project-member" {
					callerIsProjectMember = true
				}
			}
		}
		if projectRoleTemplateFoundCount != len(newProjectRoleTemplateMap) {
			// user does not have prtbs for all input roles in this project, find the roles for which there are no prtbs
			customRolesFound := false
			inputRolesContainProjectOwnerRole := false
			projectRolesToAddMap := make(map[string]bool)
			for role := range newProjectRoleTemplateMap {
				projectRolesToAddMap[role] = true
			}
			_, rolesNotFound, _ := set.Diff(projectRoleTemplateFoundMap, projectRolesToAddMap)
			// find if any of the roles for which prtbs aren't found are custom
			for _, r := range rolesNotFound {
				if rt, ok := newProjectRoleTemplateMap[r]; ok {
					if !rt.Builtin {
						customRolesFound = true
					}
					if rt.ProjectCreatorDefault && rt.Builtin {
						// this is the "project-owner" role
						inputRolesContainProjectOwnerRole = true
					}
				}
			}
			// check if caller is project-owner, project-member or cluster-owner
			if callerIsProjectOwner && !customRolesFound {
				// project-owner should be allowed to add any built-in project roles
				continue
			}
			if callerIsProjectMember && !customRolesFound && !inputRolesContainProjectOwnerRole {
				// project-member should be allowed to add any built-in project role, EXCEPT the project-owner role
				continue
			}

			// check if caller is cluster-owner
			crtbs, err := ma.CrtbLister.List(cname, labels.NewSelector())
			if err != nil {
				return err
			}
			for _, crtb := range crtbs {
				if crtb.UserName == callerID {
					rt, err := ma.RoleTemplateLister.Get("", crtb.RoleTemplateName)
					if err != nil {
						return err
					}
					if rt.ClusterCreatorDefault && rt.Builtin {
						// caller is the owner of the cluster that this project belongs to, no need to check other crtbs
						callerIsClusterOwner = true
						clustersCallerIsOwnerOf[cname] = true
						break
					}
				}
			}
			if callerIsClusterOwner && !customRolesFound {
				// cluster-owner should be allowed to add any built-in roles
				continue
			}
			// either the user is not one of these: project-owner, project-member or cluster-owner, OR
			// the passed in roles have some custom roles which the user does not have prtbs/crtbs for
			p, err := ma.ProjectLister.Get(cname, pname)
			if err != nil {
				return err
			}
			projectName := pname
			if p.Spec.DisplayName != "" {
				projectName = p.Spec.DisplayName
			}
			// get display name of cluster
			c, err := ma.ClusterLister.Get("", cname)
			if err != nil {
				return err
			}
			clusterName := cname
			if c.Spec.DisplayName != "" {
				clusterName = c.Spec.DisplayName
			}
			roleMissing = true
			missingRoles := strings.Join(rolesNotFound, ",")
			projErr := fmt.Sprintf("roles %v in project %v of cluster %v, ", missingRoles, projectName, clusterName)
			errMsg += projErr
		}
	}

	if len(newClusterRoleTemplateMap) == 0 && !roleMissing {
		return nil
	}
	for cname := range clusters {
		clusterRoleTemplateFoundCount := 0
		clusterRoleTemplateFoundMap := make(map[string]bool)
		clusterOwner := clustersCallerIsOwnerOf[cname]
		crtbs, err := ma.CrtbLister.List(cname, labels.NewSelector())
		if err != nil {
			return err
		}
		for _, crtb := range crtbs {
			if crtb.UserName == callerID {
				if _, ok := newClusterRoleTemplateMap[crtb.RoleTemplateName]; ok {
					clusterRoleTemplateFoundMap[crtb.RoleTemplateName] = true
					clusterRoleTemplateFoundCount++
				}
				if clusterOwner {
					// we already found a crtb with roletemplate cluster-owner for the caller in this cluster
					continue
				}
				rt, err := ma.RoleTemplateLister.Get("", crtb.RoleTemplateName)
				if err != nil {
					return err
				}
				if rt.ClusterCreatorDefault && rt.Builtin {
					clusterOwner = true
				}
			}
		}
		if clusterRoleTemplateFoundCount != len(newClusterRoleTemplateMap) {
			customRolesFound := false
			clusterRolesToAddMap := make(map[string]bool)
			for role := range newClusterRoleTemplateMap {
				clusterRolesToAddMap[role] = true
			}
			_, rolesNotFound, _ := set.Diff(clusterRoleTemplateFoundMap, clusterRolesToAddMap)
			// find if any of the roles for which prtbs aren't found are builtin
			for _, r := range rolesNotFound {
				if rt, ok := newProjectRoleTemplateMap[r]; ok {
					if !rt.Builtin {
						customRolesFound = true
					}
				}
			}
			if clusterOwner && !customRolesFound {
				// caller is cluster-owner of current cluster, relax this check
				continue
			}

			// get cluster's displayName
			c, err := ma.ClusterLister.Get("", cname)
			if err != nil {
				return err
			}
			clusterName := cname
			if c.Spec.DisplayName != "" {
				clusterName = c.Spec.DisplayName
			}
			roleMissing = true
			missingRoles := strings.Join(rolesNotFound, ",")
			clusErr := fmt.Sprintf("roles %v in cluster %v, ", missingRoles, clusterName)
			errMsg += clusErr
		}
	}
	if roleMissing {
		errMsg := strings.TrimRight(errMsg, ", ")
		return httperror.NewAPIError(httperror.PermissionDenied, errMsg)
	}
	return nil
}

// CheckAccessToUpdateMembers checks if the request is updating members list, and if the caller has permission to do so
func CheckAccessToUpdateMembers(members []v3.Member, data map[string]interface{}, ownerAccess bool) error {
	var requestUpdatesMembers bool
	// Check if members are being updated, if yes, make sure only member with owner permission is making this update request
	newMembers := convert.ToMapSlice(data[client.GlobalDnsFieldMembers])
	originalMembers := members
	if len(newMembers) != len(originalMembers) && !ownerAccess {
		return fmt.Errorf("only members with owner access can update members")
	}

	newMemberAccessType := make(map[string]string)
	for _, m := range newMembers {
		if userPrincipalName, ok := m[client.MemberFieldUserPrincipalID]; ok && userPrincipalName != nil {
			newMemberAccessType[convert.ToString(m[client.MemberFieldUserPrincipalID])] = convert.ToString(m[client.MemberFieldAccessType])
		}
		if groupPrincipalName, ok := m[client.MemberFieldGroupPrincipalID]; ok && groupPrincipalName != nil {
			newMemberAccessType[convert.ToString(m[client.MemberFieldGroupPrincipalID])] = convert.ToString(m[client.MemberFieldAccessType])
		}
	}

	originalMemberAccessType := make(map[string]string)
	originalMembersFoundInRequest := make(map[string]bool) // map to check whether all existing members are present in the current request, if not then this request is trying to update members list
	for _, m := range originalMembers {
		if m.UserPrincipalName != "" {
			originalMemberAccessType[m.UserPrincipalName] = m.AccessType
		}
		if m.GroupPrincipalName != "" {
			originalMemberAccessType[m.GroupPrincipalName] = m.AccessType
		}
	}

	// go through all members in the current request, check if each exists in the original global DNS
	// if it exists, check that the access type hasn't changed, if it has changed, this means the req is updating members
	// if the member from req doesn't exist in original global DNS, this means the new request is adding a new member, hence updating members list
	for key, accessType := range newMemberAccessType {
		if val, ok := originalMemberAccessType[key]; ok {
			if val != accessType {
				requestUpdatesMembers = true
				break
			}
			// mark this original member as present in the current request
			originalMembersFoundInRequest[key] = true
		} else {
			requestUpdatesMembers = true
			break
		}
	}
	if requestUpdatesMembers && !ownerAccess {
		return fmt.Errorf("only members with owner access can add new members")
	}

	// at this point, all members in the new request have been found in the original global DNS with the same access type
	// but we need to check if all members from the original global DNS are also present in the current request
	for member := range originalMemberAccessType {
		// if any member is not found, this means the current request is updating members list by deleting this member
		if !originalMembersFoundInRequest[member] && !ownerAccess {
			return fmt.Errorf("only members with owner access can delete existing members")
		}
	}
	return nil
}

func (ma *MemberAccess) GetAccessTypeOfCaller(callerID, creatorID, name string, members []v3.Member) (string, error) {
	var username string
	isAdmin, err := ma.IsAdmin(callerID)
	if err != nil {
		return "", err
	}
	if isAdmin {
		// global admins should be allowed to update mcapp, irrespective of their accessType if they're added as member, or
		// even if they aren't added as member at all
		return OwnerAccess, nil
	}
	if callerID == creatorID {
		return OwnerAccess, nil
	}
	for _, m := range members {
		if m.UserName == "" && m.UserPrincipalName != "" {
			user, err := ma.getUserFromUserPrincipalID(m.UserPrincipalName)
			if err != nil {
				return "", err
			}
			if user == nil {
				return "", fmt.Errorf("no user found for principal %v", m.UserPrincipalName)
			}
			if user.Name == callerID {
				username = user.Name
			}
		} else if m.UserName == callerID {
			username = m.UserName
		}
		if username != "" { // found the caller
			return m.AccessType, nil
		}
		if m.GroupPrincipalName == "*" {
			return m.AccessType, nil
		}
	}
	return "", fmt.Errorf("user %v is not in members list", callerID)
}

func (ma *MemberAccess) getUserFromUserPrincipalID(userPrincipalID string) (*v3.User, error) {
	encodedPrincipalID := base32.HexEncoding.WithPadding(base32.NoPadding).EncodeToString([]byte(userPrincipalID))
	if len(encodedPrincipalID) > 63 {
		encodedPrincipalID = encodedPrincipalID[:63]
	}
	set := labels.Set(map[string]string{encodedPrincipalID: "hashed-principal-name"})
	usersList, err := ma.Users.List(v1.ListOptions{LabelSelector: set.String()})
	if err != nil {
		return nil, err
	}

	if len(usersList.Items) == 0 {
		// check for local auth principals
		if strings.HasPrefix(userPrincipalID, localPrincipalPrefix) {
			userID := strings.TrimPrefix(userPrincipalID, localPrincipalPrefix)
			user, err := ma.Users.Controller().Lister().Get("", userID)
			return user, err
		}
		return nil, nil
	}

	var match *v3.User
	for _, u := range usersList.Items {
		if slice.ContainsString(u.PrincipalIDs, userPrincipalID) {
			if match != nil {
				// error out on duplicates
				return nil, fmt.Errorf("can't find unique user for principal %v", userPrincipalID)
			}
			match = &u
		}
	}
	return match, nil
}

func (ma *MemberAccess) RemoveRolesFromTargets(targetProjects, rolesToRemove []string, mcappName string, removeAllRoles bool) error {
	systemUserPrincipalID := fmt.Sprintf("system://%s", mcappName)
	// from given targets, remove prtbs/crtbs created for user with system account's userID
	rolesToRemoveMap := make(map[string]bool)
	if !removeAllRoles {
		for _, role := range rolesToRemove {
			rolesToRemoveMap[role] = true
		}
	}

	for _, target := range targetProjects {
		split := strings.SplitN(target, ":", 2)
		if len(split) != 2 {
			errMsg := fmt.Sprintf("Invalid project ID: %v", target)
			return httperror.NewAPIError(httperror.InvalidBodyContent, errMsg)
		}
		clusterName, projectName := split[0], split[1]
		clustersCovered := make(map[string]bool)
		prtbs, err := ma.PrtbLister.List(projectName, labels.NewSelector())
		if err != nil {
			return err
		}
		for _, prtb := range prtbs {
			if prtb.UserPrincipalName == systemUserPrincipalID {
				if removeAllRoles || rolesToRemoveMap[prtb.RoleTemplateName] {
					if err = ma.Prtbs.DeleteNamespaced(projectName, prtb.Name, &v1.DeleteOptions{}); err != nil && !apierrors.IsNotFound(err) && !apierrors.IsGone(err) {
						return err
					}
				}
			}
		}

		if !clustersCovered[clusterName] {
			crtbs, err := ma.CrtbLister.List(clusterName, labels.NewSelector())
			if err != nil {
				return err
			}
			for _, crtb := range crtbs {
				if crtb.UserPrincipalName == systemUserPrincipalID {
					if removeAllRoles || rolesToRemoveMap[crtb.RoleTemplateName] {
						if err = ma.Crtbs.DeleteNamespaced(clusterName, crtb.Name, &v1.DeleteOptions{}); err != nil && !apierrors.IsNotFound(err) && !apierrors.IsGone(err) {
							return err
						}
					}
				}
			}
			clustersCovered[clusterName] = true
		}
	}
	return nil
}

func (ma *MemberAccess) checkProjectExists(target string) error {
	split := strings.SplitN(target, ":", 2)
	if len(split) != 2 {
		return httperror.NewAPIError(httperror.InvalidFormat, fmt.Sprintf("invalid project ID %s", target))
	}
	_, err := ma.ProjectLister.Get(split[0], split[1])
	if err != nil {
		if apierrors.IsNotFound(err) {
			return httperror.NewAPIError(httperror.InvalidOption, fmt.Sprintf("project is not found %s", target))
		}
		return httperror.NewAPIError(httperror.InvalidOption, fmt.Sprintf("error getting project %s: %v", target, err))
	}
	return nil
}


text:
module Drive
  class DiscetteUpdater
    def self.update_discette discette, drive_dir
      files_hash = { "css" => [] , "js" => [] }
      drive_files = Dir.glob(drive_dir + "/assets/*")
      drive_files.each do |drive_file|
        if File.extname(drive_file) == ".css"
          files_hash["css"].push( File.split(drive_file)[1] )
        elsif File.extname(drive_file) == ".js"
          files_hash["js"].push( File.split(drive_file)[1] )
        end
      end
      discette.meta = discette.meta || {}
      discette.meta["files"] = files_hash
      discette.save!
    end

    def self.read_in_discettes
      drive_dirs = Dir["#{Rails.root}/plugins/discourse-drive/public/drives/**"]
      drive_dirs.each do |drive_dir|
        drive_name = File.split(drive_dir)[1]
        discette = Drive::Discette.where(:slug => drive_name).first
        if discette
          Drive::DiscetteUpdater.update_discette discette, drive_dir
        end
      end
      # binding.pry
    end

  end
end

Drive::DiscetteUpdater.read_in_discettes

# temporary hack to get madrid topics available in section
# Category.where(:name => "Madrid").first.topics.each do |topic|
#   if topic.archetype == "regular"
#     topic.archetype = "discette"
#     topic.save!
#   end
# end


text:
<?php

namespace EXSyst\Component\Security\Exception;

class InvalidArgumentException extends SecurityException
{
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="JavadocGenerationManager">
    <option name="OUTPUT_DIRECTORY" value="$PROJECT_DIR$/docs" />
    <option name="OPTION_SCOPE" value="protected" />
    <option name="OPTION_HIERARCHY" value="true" />
    <option name="OPTION_NAVIGATOR" value="true" />
    <option name="OPTION_INDEX" value="true" />
    <option name="OPTION_SEPARATE_INDEX" value="true" />
    <option name="OPTION_DOCUMENT_TAG_USE" value="false" />
    <option name="OPTION_DOCUMENT_TAG_AUTHOR" value="false" />
    <option name="OPTION_DOCUMENT_TAG_VERSION" value="false" />
    <option name="OPTION_DOCUMENT_TAG_DEPRECATED" value="true" />
    <option name="OPTION_DEPRECATED_LIST" value="true" />
    <option name="OTHER_OPTIONS" />
    <option name="HEAP_SIZE" />
    <option name="LOCALE" />
    <option name="OPEN_IN_BROWSER" value="true" />
    <option name="OPTION_INCLUDE_LIBS" value="false" />
  </component>
  <component name="NullableNotNullManager">
    <option name="myDefaultNullable" value="android.support.annotation.Nullable" />
    <option name="myDefaultNotNull" value="android.support.annotation.NonNull" />
    <option name="myNullables">
      <value>
        <list size="12">
          <item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.Nullable" />
          <item index="1" class="java.lang.String" itemvalue="javax.annotation.Nullable" />
          <item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.Nullable" />
          <item index="3" class="java.lang.String" itemvalue="android.support.annotation.Nullable" />
          <item index="4" class="java.lang.String" itemvalue="javax.annotation.CheckForNull" />
          <item index="5" class="java.lang.String" itemvalue="androidx.annotation.Nullable" />
          <item index="6" class="java.lang.String" itemvalue="android.annotation.Nullable" />
          <item index="7" class="java.lang.String" itemvalue="androidx.annotation.RecentlyNullable" />
          <item index="8" class="java.lang.String" itemvalue="org.checkerframework.checker.nullness.qual.Nullable" />
          <item index="9" class="java.lang.String" itemvalue="org.checkerframework.checker.nullness.compatqual.NullableDecl" />
          <item index="10" class="java.lang.String" itemvalue="org.checkerframework.checker.nullness.compatqual.NullableType" />
          <item index="11" class="java.lang.String" itemvalue="com.android.annotations.Nullable" />
        </list>
      </value>
    </option>
    <option name="myNotNulls">
      <value>
        <list size="11">
          <item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.NotNull" />
          <item index="1" class="java.lang.String" itemvalue="javax.annotation.Nonnull" />
          <item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.NonNull" />
          <item index="3" class="java.lang.String" itemvalue="android.support.annotation.NonNull" />
          <item index="4" class="java.lang.String" itemvalue="androidx.annotation.NonNull" />
          <item index="5" class="java.lang.String" itemvalue="android.annotation.NonNull" />
          <item index="6" class="java.lang.String" itemvalue="androidx.annotation.RecentlyNonNull" />
          <item index="7" class="java.lang.String" itemvalue="org.checkerframework.checker.nullness.qual.NonNull" />
          <item index="8" class="java.lang.String" itemvalue="org.checkerframework.checker.nullness.compatqual.NonNullDecl" />
          <item index="9" class="java.lang.String" itemvalue="org.checkerframework.checker.nullness.compatqual.NonNullType" />
          <item index="10" class="java.lang.String" itemvalue="com.android.annotations.NonNull" />
        </list>
      </value>
    </option>
  </component>
  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
    <output url="file://$PROJECT_DIR$/build/classes" />
  </component>
  <component name="ProjectType">
    <option name="id" value="Android" />
  </component>
</project>


text:
package com.ce.game.myapplication.act;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;

import com.ce.game.myapplication.R;
import com.ce.game.myapplication.util.AboutPhoneU;
import com.ce.game.myapplication.util.BitmapU;
import com.ce.game.myapplication.util.ThreadPoolU;

public class DecorViewWithColorDrawableActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);

        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
//                        | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                        | View.SYSTEM_UI_FLAG_IMMERSIVE);

        setContentView(R.layout.activity_decor_view_with_color_drawable);

        final Context context = getApplicationContext();

//        final View testView = findViewById(R.id.test_view);

//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.wallpaper_01)
//                .copy(Bitmap.Config.ARGB_8888, true);

        ThreadPoolU.execute(new Runnable() {
            @Override
            public void run() {
                Bitmap originalB = BitmapU.drawableToBitmap(getWindow().getDecorView().getBackground());

                Canvas canvas = new Canvas();

                //Get the width and height of the screen
                DisplayMetrics d = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(d);
                int width  = d.widthPixels;
                int height = d.heightPixels;

                Paint paint = new Paint();
                paint.setColor(Color.parseColor("#80000000"));
                paint.setStyle(Paint.Style.FILL);

                canvas.drawRect(0, 0, width, height, paint);

                Path path = new Path();
                canvas.drawARGB(128,125,0,0);

                int navHeight = new AboutPhoneU().getNavH(getApplicationContext());
                if (navHeight != 0) {
                    int screenHeight = new AboutPhoneU().getRealScreenHeightIncludeVirtualButtonBar(context);
                    int startY = screenHeight - navHeight;

                    path.moveTo(0, startY);
                    path.lineTo(canvas.getWidth(), startY);
                    path.lineTo(canvas.getWidth(), screenHeight);
                    path.lineTo(0, canvas.getHeight());

                    canvas.drawPath(path, paint);
                }

//                getWindow().getDecorView().setBackgroundDrawable(new BitmapDrawable(getResources(), originalB));
                getWindow().getDecorView().draw(canvas);

//                testView.draw(canvas);
            }
        });

    }

    public class MyCanvas extends View {
        public MyCanvas(Context context) {
            super(context);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);

            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.wallpaper_01)
                    .copy(Bitmap.Config.ARGB_8888, true);

            Paint pBackground = new Paint();

            pBackground.setColor(Color.WHITE);

            canvas.drawBitmap(bitmap, 0, 0, pBackground);

            canvas.drawARGB(128, 0, 0, 0);

            canvas.drawColor(Color.parseColor("#80000000"), PorterDuff.Mode.ADD);

//            canvas.drawRect(0, 0, 512, 512, pBackground);
            Paint pText = new Paint();
            pText.setColor(Color.BLACK);
            pText.setTextSize(20);
            canvas.drawText("Sample Text", 100, 100, pText);
        }
    }

}


text:
<!DOCTYPE html>

    <title></title>

Description:

This sample showcases one-shot speech recognition using a custom list-based grammar.

                <select id="languageSelect" class="win-dropdown"></select>

                <button id="btnListenUI" disabled class="win-button"> with UI</button>
                <button id="btnListen" disabled class="win-button"> without UI</button>


text:
create class test_class (col_set SEQUENCE bigint);

insert into test_class(col_set) values ({-9223372036854775808, 9223372036854775807});
insert into test_class(col_set) values ({-100, 100});
insert into test_class(col_set) values ({0, -0});
insert into test_class(col_set) values ({NULL, NULL});
insert into test_class(col_set) values ({-9223372036854775808, 9223372036854775807, 9223372036854775807});
insert into test_class(col_set) values ({-100, 100, -100});
insert into test_class(col_set) values ({NULL, NULL, null});
insert into test_class(col_set) values ({-100, -10, 100, 10, 0});

select * from test_class order by 1;
select * from test_class where col_set seteq {-100, 100} order by 1;
select * from test_class where col_set seteq {NULL, NULL} order by 1;

select * from test_class where col_set setneq {-100, 100} order by 1;
select * from test_class where col_set setneq {NULL, NULL} order by 1;

select * from test_class where col_set superset {100};
select * from test_class where col_set superset {NULL};

select * from test_class where col_set superseteq {-100, 100};
select * from test_class where col_set superseteq {NULL};

select * from test_class where col_set subset {-100, 100, 0};
select * from test_class where col_set subset {NULL, 0};

select * from test_class where col_set subseteq {-100, 100, 0};
select * from test_class where col_set subseteq {NULL, 0};

drop class test_class;


text:
package com.opengamma.strata.basics.index;

import java.io.Serializable;
import java.time.LocalDate;
import java.util.Map;
import java.util.NoSuchElementException;

import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.ImmutableBean;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaBean;
import org.joda.beans.MetaProperty;
import org.joda.beans.gen.BeanDefinition;
import org.joda.beans.gen.PropertyDefinition;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import org.joda.beans.impl.direct.DirectPrivateBeanBuilder;

import com.opengamma.strata.basics.ReferenceData;
import com.opengamma.strata.basics.currency.Currency;

/**
 * Defines the observation of a rate of interest from a single Ibor index.
 *

 * An interest rate determined directly from an Ibor index.
 * For example, a rate determined from 'GBP-LIBOR-3M' on a single fixing date.
 */
@BeanDefinition(builderScope = "private", constructorScope = "package")
public final class IborIndexObservation
    implements IndexObservation, ImmutableBean, Serializable {

  /**
   * The Ibor index.
   *

   * The rate to be paid is based on this index.
   * It will be a well known market index such as 'GBP-LIBOR-3M'.
   */
  @PropertyDefinition(validate = "notNull", overrideGet = true)
  private final IborIndex index;
  /**
   * The date of the index fixing.
   *

   * This is an adjusted date with any business day rule applied.
   * Valid business days are defined by {@link IborIndex#getFixingCalendar()}.
   */
  @PropertyDefinition(validate = "notNull")
  private final LocalDate fixingDate;
  /**
   * The effective date of the investment implied by the fixing date.
   *

   * This is an adjusted date with any business day rule applied.
   * This must be equal to {@link IborIndex#calculateEffectiveFromFixing(LocalDate, ReferenceData)}.
   */
  @PropertyDefinition(validate = "notNull")
  private final LocalDate effectiveDate;
  /**
   * The maturity date of the investment implied by the fixing date.
   *

   * This is an adjusted date with any business day rule applied.
   * This must be equal to {@link IborIndex#calculateMaturityFromEffective(LocalDate, ReferenceData)}.
   */
  @PropertyDefinition(validate = "notNull")
  private final LocalDate maturityDate;
  /**
   * The year fraction of the investment implied by the fixing date.
   *

   * This is calculated using the day count of the index.
   * It represents the fraction of the year between the effective date and the maturity date.
   * Typically the value will be close to 1 for one year and close to 0.5 for six months.
   */
  @PropertyDefinition(validate = "notNull")
  private final double yearFraction;

  //-------------------------------------------------------------------------
  /**
   * Creates an instance from an index and fixing date.
   *

   * The reference data is used to find the maturity date from the fixing date.
   *
   * @param index  the index
   * @param fixingDate  the fixing date
   * @param refData  the reference data to use when resolving holiday calendars
   * @return the rate observation
   */
  public static IborIndexObservation of(
      IborIndex index,
      LocalDate fixingDate,
      ReferenceData refData) {

    LocalDate effectiveDate = index.calculateEffectiveFromFixing(fixingDate, refData);
    LocalDate maturityDate = index.calculateMaturityFromEffective(effectiveDate, refData);
    double yearFraction = index.getDayCount().yearFraction(effectiveDate, maturityDate);
    return new IborIndexObservation(index, fixingDate, effectiveDate, maturityDate, yearFraction);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the currency of the Ibor index.
   *
   * @return the currency of the index
   */
  public Currency getCurrency() {
    return index.getCurrency();
  }

  //------------------------- AUTOGENERATED START -------------------------
  /**
   * The meta-bean for {@code IborIndexObservation}.
   * @return the meta-bean, not null
   */
  public static IborIndexObservation.Meta meta() {
    return IborIndexObservation.Meta.INSTANCE;
  }

  static {
    MetaBean.register(IborIndexObservation.Meta.INSTANCE);
  }

  /**
   * The serialization version id.
   */
  private static final long serialVersionUID = 1L;

  /**
   * Creates an instance.
   * @param index  the value of the property, not null
   * @param fixingDate  the value of the property, not null
   * @param effectiveDate  the value of the property, not null
   * @param maturityDate  the value of the property, not null
   * @param yearFraction  the value of the property, not null
   */
  IborIndexObservation(
      IborIndex index,
      LocalDate fixingDate,
      LocalDate effectiveDate,
      LocalDate maturityDate,
      double yearFraction) {
    JodaBeanUtils.notNull(index, "index");
    JodaBeanUtils.notNull(fixingDate, "fixingDate");
    JodaBeanUtils.notNull(effectiveDate, "effectiveDate");
    JodaBeanUtils.notNull(maturityDate, "maturityDate");
    JodaBeanUtils.notNull(yearFraction, "yearFraction");
    this.index = index;
    this.fixingDate = fixingDate;
    this.effectiveDate = effectiveDate;
    this.maturityDate = maturityDate;
    this.yearFraction = yearFraction;
  }

  @Override
  public IborIndexObservation.Meta metaBean() {
    return IborIndexObservation.Meta.INSTANCE;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the Ibor index.
   *

   * The rate to be paid is based on this index.
   * It will be a well known market index such as 'GBP-LIBOR-3M'.
   * @return the value of the property, not null
   */
  @Override
  public IborIndex getIndex() {
    return index;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the date of the index fixing.
   *

   * This is an adjusted date with any business day rule applied.
   * Valid business days are defined by {@link IborIndex#getFixingCalendar()}.
   * @return the value of the property, not null
   */
  public LocalDate getFixingDate() {
    return fixingDate;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the effective date of the investment implied by the fixing date.
   *

   * This is an adjusted date with any business day rule applied.
   * This must be equal to {@link IborIndex#calculateEffectiveFromFixing(LocalDate, ReferenceData)}.
   * @return the value of the property, not null
   */
  public LocalDate getEffectiveDate() {
    return effectiveDate;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the maturity date of the investment implied by the fixing date.
   *

   * This is an adjusted date with any business day rule applied.
   * This must be equal to {@link IborIndex#calculateMaturityFromEffective(LocalDate, ReferenceData)}.
   * @return the value of the property, not null
   */
  public LocalDate getMaturityDate() {
    return maturityDate;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the year fraction of the investment implied by the fixing date.
   *

   * This is calculated using the day count of the index.
   * It represents the fraction of the year between the effective date and the maturity date.
   * Typically the value will be close to 1 for one year and close to 0.5 for six months.
   * @return the value of the property, not null
   */
  public double getYearFraction() {
    return yearFraction;
  }

  //-----------------------------------------------------------------------
  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (obj != null && obj.getClass() == this.getClass()) {
      IborIndexObservation other = (IborIndexObservation) obj;
      return JodaBeanUtils.equal(index, other.index) &&
          JodaBeanUtils.equal(fixingDate, other.fixingDate) &&
          JodaBeanUtils.equal(effectiveDate, other.effectiveDate) &&
          JodaBeanUtils.equal(maturityDate, other.maturityDate) &&
          JodaBeanUtils.equal(yearFraction, other.yearFraction);
    }
    return false;
  }

  @Override
  public int hashCode() {
    int hash = getClass().hashCode();
    hash = hash * 31 + JodaBeanUtils.hashCode(index);
    hash = hash * 31 + JodaBeanUtils.hashCode(fixingDate);
    hash = hash * 31 + JodaBeanUtils.hashCode(effectiveDate);
    hash = hash * 31 + JodaBeanUtils.hashCode(maturityDate);
    hash = hash * 31 + JodaBeanUtils.hashCode(yearFraction);
    return hash;
  }

  @Override
  public String toString() {
    StringBuilder buf = new StringBuilder(192);
    buf.append("IborIndexObservation{");
    buf.append("index").append('=').append(JodaBeanUtils.toString(index)).append(',').append(' ');
    buf.append("fixingDate").append('=').append(JodaBeanUtils.toString(fixingDate)).append(',').append(' ');
    buf.append("effectiveDate").append('=').append(JodaBeanUtils.toString(effectiveDate)).append(',').append(' ');
    buf.append("maturityDate").append('=').append(JodaBeanUtils.toString(maturityDate)).append(',').append(' ');
    buf.append("yearFraction").append('=').append(JodaBeanUtils.toString(yearFraction));
    buf.append('}');
    return buf.toString();
  }

  //-----------------------------------------------------------------------
  /**
   * The meta-bean for {@code IborIndexObservation}.
   */
  public static final class Meta extends DirectMetaBean {
    /**
     * The singleton instance of the meta-bean.
     */
    static final Meta INSTANCE = new Meta();

    /**
     * The meta-property for the {@code index} property.
     */
    private final MetaProperty<IborIndex> index = DirectMetaProperty.ofImmutable(
        this, "index", IborIndexObservation.class, IborIndex.class);
    /**
     * The meta-property for the {@code fixingDate} property.
     */
    private final MetaProperty<LocalDate> fixingDate = DirectMetaProperty.ofImmutable(
        this, "fixingDate", IborIndexObservation.class, LocalDate.class);
    /**
     * The meta-property for the {@code effectiveDate} property.
     */
    private final MetaProperty<LocalDate> effectiveDate = DirectMetaProperty.ofImmutable(
        this, "effectiveDate", IborIndexObservation.class, LocalDate.class);
    /**
     * The meta-property for the {@code maturityDate} property.
     */
    private final MetaProperty<LocalDate> maturityDate = DirectMetaProperty.ofImmutable(
        this, "maturityDate", IborIndexObservation.class, LocalDate.class);
    /**
     * The meta-property for the {@code yearFraction} property.
     */
    private final MetaProperty<Double> yearFraction = DirectMetaProperty.ofImmutable(
        this, "yearFraction", IborIndexObservation.class, Double.TYPE);
    /**
     * The meta-properties.
     */
    private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap(
        this, null,
        "index",
        "fixingDate",
        "effectiveDate",
        "maturityDate",
        "yearFraction");

    /**
     * Restricted constructor.
     */
    private Meta() {
    }

    @Override
    protected MetaProperty<?> metaPropertyGet(String propertyName) {
      switch (propertyName.hashCode()) {
        case 100346066:  // index
          return index;
        case 1255202043:  // fixingDate
          return fixingDate;
        case -930389515:  // effectiveDate
          return effectiveDate;
        case -414641441:  // maturityDate
          return maturityDate;
        case -1731780257:  // yearFraction
          return yearFraction;
      }
      return super.metaPropertyGet(propertyName);
    }

    @Override
    public BeanBuilder<? extends IborIndexObservation> builder() {
      return new IborIndexObservation.Builder();
    }

    @Override
    public Class<? extends IborIndexObservation> beanType() {
      return IborIndexObservation.class;
    }

    @Override
    public Map<String, MetaProperty<?>> metaPropertyMap() {
      return metaPropertyMap$;
    }

    //-----------------------------------------------------------------------
    /**
     * The meta-property for the {@code index} property.
     * @return the meta-property, not null
     */
    public MetaProperty<IborIndex> index() {
      return index;
    }

    /**
     * The meta-property for the {@code fixingDate} property.
     * @return the meta-property, not null
     */
    public MetaProperty<LocalDate> fixingDate() {
      return fixingDate;
    }

    /**
     * The meta-property for the {@code effectiveDate} property.
     * @return the meta-property, not null
     */
    public MetaProperty<LocalDate> effectiveDate() {
      return effectiveDate;
    }

    /**
     * The meta-property for the {@code maturityDate} property.
     * @return the meta-property, not null
     */
    public MetaProperty<LocalDate> maturityDate() {
      return maturityDate;
    }

    /**
     * The meta-property for the {@code yearFraction} property.
     * @return the meta-property, not null
     */
    public MetaProperty<Double> yearFraction() {
      return yearFraction;
    }

    //-----------------------------------------------------------------------
    @Override
    protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
      switch (propertyName.hashCode()) {
        case 100346066:  // index
          return ((IborIndexObservation) bean).getIndex();
        case 1255202043:  // fixingDate
          return ((IborIndexObservation) bean).getFixingDate();
        case -930389515:  // effectiveDate
          return ((IborIndexObservation) bean).getEffectiveDate();
        case -414641441:  // maturityDate
          return ((IborIndexObservation) bean).getMaturityDate();
        case -1731780257:  // yearFraction
          return ((IborIndexObservation) bean).getYearFraction();
      }
      return super.propertyGet(bean, propertyName, quiet);
    }

    @Override
    protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
      metaProperty(propertyName);
      if (quiet) {
        return;
      }
      throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
    }

  }

  //-----------------------------------------------------------------------
  /**
   * The bean-builder for {@code IborIndexObservation}.
   */
  private static final class Builder extends DirectPrivateBeanBuilder<IborIndexObservation> {

    private IborIndex index;
    private LocalDate fixingDate;
    private LocalDate effectiveDate;
    private LocalDate maturityDate;
    private double yearFraction;

    /**
     * Restricted constructor.
     */
    private Builder() {
    }

    //-----------------------------------------------------------------------
    @Override
    public Object get(String propertyName) {
      switch (propertyName.hashCode()) {
        case 100346066:  // index
          return index;
        case 1255202043:  // fixingDate
          return fixingDate;
        case -930389515:  // effectiveDate
          return effectiveDate;
        case -414641441:  // maturityDate
          return maturityDate;
        case -1731780257:  // yearFraction
          return yearFraction;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
    }

    @Override
    public Builder set(String propertyName, Object newValue) {
      switch (propertyName.hashCode()) {
        case 100346066:  // index
          this.index = (IborIndex) newValue;
          break;
        case 1255202043:  // fixingDate
          this.fixingDate = (LocalDate) newValue;
          break;
        case -930389515:  // effectiveDate
          this.effectiveDate = (LocalDate) newValue;
          break;
        case -414641441:  // maturityDate
          this.maturityDate = (LocalDate) newValue;
          break;
        case -1731780257:  // yearFraction
          this.yearFraction = (Double) newValue;
          break;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
      return this;
    }

    @Override
    public IborIndexObservation build() {
      return new IborIndexObservation(
          index,
          fixingDate,
          effectiveDate,
          maturityDate,
          yearFraction);
    }

    //-----------------------------------------------------------------------
    @Override
    public String toString() {
      StringBuilder buf = new StringBuilder(192);
      buf.append("IborIndexObservation.Builder{");
      buf.append("index").append('=').append(JodaBeanUtils.toString(index)).append(',').append(' ');
      buf.append("fixingDate").append('=').append(JodaBeanUtils.toString(fixingDate)).append(',').append(' ');
      buf.append("effectiveDate").append('=').append(JodaBeanUtils.toString(effectiveDate)).append(',').append(' ');
      buf.append("maturityDate").append('=').append(JodaBeanUtils.toString(maturityDate)).append(',').append(' ');
      buf.append("yearFraction").append('=').append(JodaBeanUtils.toString(yearFraction));
      buf.append('}');
      return buf.toString();
    }

  }

  //-------------------------- AUTOGENERATED END --------------------------
}


text:
package com.bladecoder.engineeditor.qa;

import com.bladecoder.engine.model.BaseActor;

public interface ActorVisitor extends Visitor {
	public void visit(BaseActor a);
}


text:
'use strict';

const moment = require('moment');

const Message = require('../../../app/models/Message');
const Conversation = require('../../../app/models/Conversation');

const conversationFactory = require('../factories/conversation');
const messageFactory = require('../factories/message');

module.exports.seed = {};

exports.seed.messages = async function messages(qty = 1) {
  let generated = 0;
  const limit = 10;
  const messageObjects = [];

  while (generated < qty && generated < limit) {
    messageObjects.push(messageFactory.getRawMessageData());
    generated += 1;
  }
  return Message.create(messageObjects);
};

exports.seed.conversations = async function conversations(qty = 1) {
  let generated = 0;
  const limit = 10;
  const conversationObjects = [];

  while (generated < qty && generated < limit) {
    conversationObjects.push(conversationFactory.getRawConversationData());
    generated += 1;
  }
  return Conversation.create(conversationObjects);
};

/**
 * conversationMessages - Creates a conversation with it's corresponding inbound and outbound
 * messages.
 *
 * @return {Object}  Object with conversation, inboundMessage, and outboundMessage properties.
 */
exports.seed.conversationMessages = async function conversationMessages() {
  const conversation = conversationFactory.getValidConversation();
  const inboundMessage = messageFactory.getValidMessage();
  const outboundMessage = messageFactory.getValidOutboundReplyMessage();

  // Link outbound message to conversation
  conversation.lastOutboundMessage = outboundMessage;

  // Link Conversation to messages
  inboundMessage.conversationId = conversation;
  outboundMessage.conversationId = conversation;

  // Make sure outbound has a queuedAt metadata property
  // TODO: I think this should be done directly in the factory
  outboundMessage.metadata = {
    delivery: {
      queuedAt: moment().subtract(3, 'days').format(),
    },
  };

  await conversation.save();
  await inboundMessage.save();
  await outboundMessage.save();

  return { conversation, inboundMessage, outboundMessage };
};


text:
#ifndef QPIXMAPDATA_X11_P_H
#define QPIXMAPDATA_X11_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include <QtGui/private/qpixmapdata_p.h>
#include <QtGui/private/qpixmapdatafactory_p.h>

#include "QtGui/qx11info_x11.h"

QT_BEGIN_NAMESPACE

class QX11PaintEngine;

struct QXImageWrapper;

class Q_GUI_EXPORT QX11PixmapData : public QPixmapData
{
public:
    QX11PixmapData(PixelType type);
//     QX11PixmapData(PixelType type, int width, int height);
//     QX11PixmapData(PixelType type, const QImage &image,
//                    Qt::ImageConversionFlags flags);
    ~QX11PixmapData();

    QPixmapData *createCompatiblePixmapData() const;

    void resize(int width, int height);
    void fromImage(const QImage &image, Qt::ImageConversionFlags flags);
    void copy(const QPixmapData *data, const QRect &rect);
    bool scroll(int dx, int dy, const QRect &rect);

    void fill(const QColor &color);
    QBitmap mask() const;
    void setMask(const QBitmap &mask);
    bool hasAlphaChannel() const;
    void setAlphaChannel(const QPixmap &alphaChannel);
    QPixmap alphaChannel() const;
    QPixmap transformed(const QTransform &transform,
                        Qt::TransformationMode mode) const;
    QImage toImage() const;
    QImage toImage(const QRect &rect) const;
    QPaintEngine* paintEngine() const;

    Qt::HANDLE handle() const { return hd; }
    Qt::HANDLE x11ConvertToDefaultDepth();

    static Qt::HANDLE createBitmapFromImage(const QImage &image);

    void* gl_surface;
#ifndef QT_NO_XRENDER
    void convertToARGB32(bool preserveContents = true);
#endif

protected:
    int metric(QPaintDevice::PaintDeviceMetric metric) const;

private:
    friend class QPixmap;
    friend class QBitmap;
    friend class QX11PaintEngine;
    friend class QX11WindowSurface;
    friend class QRasterWindowSurface;
    friend class QGLContextPrivate; // Needs to access xinfo, gl_surface & flags
    friend class QEglContext; // Needs gl_surface
    friend class QGLContext; // Needs gl_surface
    friend class QX11GLPixmapData; // Needs gl_surface
    friend class QMeeGoLivePixmapData; // Needs gl_surface and flags
    friend bool  qt_createEGLSurfaceForPixmap(QPixmapData*, bool); // Needs gl_surface

    void release();

    QImage toImage(const QXImageWrapper &xi, const QRect &rect) const;

    QBitmap mask_to_bitmap(int screen) const;
    static Qt::HANDLE bitmap_to_mask(const QBitmap &, int screen);
    void bitmapFromImage(const QImage &image);

    bool canTakeQImageFromXImage(const QXImageWrapper &xi) const;
    QImage takeQImageFromXImage(const QXImageWrapper &xi) const;

    Qt::HANDLE hd;

    enum Flag {
         NoFlags = 0x0,
         Uninitialized = 0x1,
         Readonly = 0x2,
         InvertedWhenBoundToTexture = 0x4,
         GlSurfaceCreatedWithAlpha = 0x8
    };
    uint flags;

    QX11Info xinfo;
    Qt::HANDLE x11_mask;
    Qt::HANDLE picture;
    Qt::HANDLE mask_picture;
    Qt::HANDLE hd2; // sorted in the default display depth
    QPixmap::ShareMode share_mode;

    QX11PaintEngine *pengine;
};

QT_END_NAMESPACE

#endif // QPIXMAPDATA_X11_P_H


text:
package com.cosmos.utils.converter.impls;

import com.cosmos.utils.converter.ConvertException;
import com.cosmos.utils.converter.Converter;

public class StringAndIntegerConverter implements Converter<String, Integer>{

	@Override
	public Integer to(String obj) throws ConvertException {
		Integer result = null;
		try {
			if(obj != null){
				result = new Integer(obj);
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
			throw new ConvertException("无法由String:" + obj + "转换为Integer");
		}
		return result;
	}

	@Override
	public String from(Integer obj) throws ConvertException {
		return obj == null ? null :obj.toString();
	}

	@Override
	public void initialize(Object obj) throws ConvertException {

	}

}


text:
package org.apache.flink.client.deployment.application;

import org.apache.flink.annotation.Internal;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.client.ClientUtils;
import org.apache.flink.client.deployment.application.executors.EmbeddedExecutor;
import org.apache.flink.client.deployment.application.executors.EmbeddedExecutorServiceLoader;
import org.apache.flink.client.program.PackagedProgram;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.ExecutionOptions;
import org.apache.flink.core.execution.PipelineExecutorServiceLoader;
import org.apache.flink.runtime.concurrent.ScheduledExecutor;
import org.apache.flink.runtime.dispatcher.AbstractDispatcherBootstrap;
import org.apache.flink.runtime.dispatcher.Dispatcher;
import org.apache.flink.runtime.dispatcher.DispatcherBootstrap;
import org.apache.flink.runtime.dispatcher.DispatcherGateway;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobmaster.JobResult;
import org.apache.flink.runtime.messages.Acknowledge;
import org.apache.flink.util.SerializedThrowable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.apache.flink.util.Preconditions.checkNotNull;

/**
 * A {@link DispatcherBootstrap} used for running the user's {@code main()} in "Application Mode" (see FLIP-85).
 *
 *
This dispatcher bootstrap submits the recovered {@link JobGraph job graphs} for re-execution
 * (in case of recovery from a failure), and then submits the remaining jobs of the application for execution.
 *
 *
To achieve this, it works in conjunction with the
 * {@link EmbeddedExecutor EmbeddedExecutor} which decides
 * if it should submit a job for execution (in case of a new job) or the job was already recovered and is running.
 */
@Internal
public class ApplicationDispatcherBootstrap extends AbstractDispatcherBootstrap {

	private static final Logger LOG = LoggerFactory.getLogger(ApplicationDispatcherBootstrap.class);

	private final PackagedProgram application;

	private final Collection<JobGraph> recoveredJobs;

	private final Configuration configuration;

	private CompletableFuture<Void> applicationCompletionFuture;

	private ScheduledFuture<?> applicationExecutionTask;

	public ApplicationDispatcherBootstrap(
			final PackagedProgram application,
			final Collection<JobGraph> recoveredJobs,
			final Configuration configuration) {
		this.configuration = checkNotNull(configuration);
		this.recoveredJobs = checkNotNull(recoveredJobs);
		this.application = checkNotNull(application);
	}

	@Override
	public void initialize(final Dispatcher dispatcher, ScheduledExecutor scheduledExecutor) {
		checkNotNull(dispatcher);
		launchRecoveredJobGraphs(dispatcher, recoveredJobs);

		runApplicationAndShutdownClusterAsync(
				dispatcher,
				scheduledExecutor);
	}

	@Override
	public void stop() {
		if (applicationExecutionTask != null) {
			applicationExecutionTask.cancel(true);
		}

		if (applicationCompletionFuture != null) {
			applicationCompletionFuture.cancel(true);
		}
	}

	@VisibleForTesting
	ScheduledFuture<?> getApplicationExecutionFuture() {
		return applicationExecutionTask;
	}

	/**
	 * Runs the user program entrypoint using {@link #runApplicationAsync(DispatcherGateway,
	 * ScheduledExecutor, boolean)} and shuts down the given dispatcher when the application
	 * completes (either succesfully or in case of failure).
	 */
	@VisibleForTesting
	CompletableFuture<Acknowledge> runApplicationAndShutdownClusterAsync(
			final DispatcherGateway dispatcher,
			final ScheduledExecutor scheduledExecutor) {

		applicationCompletionFuture = runApplicationAsync(dispatcher, scheduledExecutor, false);

		return applicationCompletionFuture
				.handle((r, t) -> {
					if (t != null) {
						LOG.warn("Application FAILED: ", t);
					} else {
						LOG.info("Application completed SUCCESSFULLY");
					}
					return dispatcher.shutDownCluster();
				})
				.thenCompose(Function.identity());
	}

	/**
	 * Runs the user program entrypoint by scheduling a task on the given {@code scheduledExecutor}.
	 * The returned {@link CompletableFuture} completes when all jobs of the user application
	 * succeeded. if any of them fails, or if job submission fails.
	 */
	@VisibleForTesting
	CompletableFuture<Void> runApplicationAsync(
			final DispatcherGateway dispatcher,
			final ScheduledExecutor scheduledExecutor,
			final boolean enforceSingleJobExecution) {
		final CompletableFuture<List<JobID>> applicationExecutionFuture = new CompletableFuture<>();

		// we need to hand in a future as return value because we need to get those JobIs out
		// from the scheduled task that executes the user program
		applicationExecutionTask = scheduledExecutor.schedule(
				() -> runApplicationEntrypoint(
						applicationExecutionFuture,
						dispatcher,
						scheduledExecutor,
						enforceSingleJobExecution),
				0L,
				TimeUnit.MILLISECONDS);

		return applicationExecutionFuture.thenCompose(
				jobIds -> getApplicationResult(dispatcher, jobIds, scheduledExecutor));
	}

	/**
	 * Runs the user program entrypoint and completes the given {@code jobIdsFuture} with the {@link
	 * JobID JobIDs} of the submitted jobs.
	 *
	 *
This should be executed in a separate thread (or task).
	 */
	private void runApplicationEntrypoint(
			final CompletableFuture<List<JobID>> jobIdsFuture,
			final DispatcherGateway dispatcher,
			final ScheduledExecutor scheduledExecutor,
			final boolean enforceSingleJobExecution) {
		try {
			final List<JobID> applicationJobIds =
					new ArrayList<>(getRecoveredJobIds(recoveredJobs));

			final PipelineExecutorServiceLoader executorServiceLoader =
					new EmbeddedExecutorServiceLoader(
							applicationJobIds, dispatcher, scheduledExecutor);

			ClientUtils.executeProgram(
					executorServiceLoader,
					configuration,
					application,
					enforceSingleJobExecution,
					true /* suppress sysout */);

			if (applicationJobIds.isEmpty()) {
				jobIdsFuture.completeExceptionally(
						new ApplicationExecutionException(
								"The application contains no execute() calls."));
			} else {
				jobIdsFuture.complete(applicationJobIds);
			}
		} catch (Throwable t) {
			jobIdsFuture.completeExceptionally(
					new ApplicationExecutionException("Could not execute application.", t));
		}
	}

	private CompletableFuture<Void> getApplicationResult(
			final DispatcherGateway dispatcherGateway,
			final Collection<JobID> applicationJobIds,
			final ScheduledExecutor executor) {
		final CompletableFuture<?>[] jobResultFutures = applicationJobIds
				.stream()
				.map(jobId ->
						unwrapJobResultException(getJobResult(dispatcherGateway, jobId, executor)))
				.toArray(CompletableFuture<?>[]::new);

		final CompletableFuture<Void> allStatusFutures = CompletableFuture.allOf(jobResultFutures);
		Stream.of(jobResultFutures)
				.forEach(f -> f.exceptionally(e -> {
					allStatusFutures.completeExceptionally(e);
					return null;
				}));
		return allStatusFutures;
	}

	private CompletableFuture<JobResult> getJobResult(
			final DispatcherGateway dispatcherGateway,
			final JobID jobId,
			final ScheduledExecutor scheduledExecutor) {

		final Time timeout = Time.milliseconds(configuration.get(ExecutionOptions.EMBEDDED_RPC_TIMEOUT).toMillis());
		final Time retryPeriod = Time.milliseconds(configuration.get(ExecutionOptions.EMBEDDED_RPC_RETRY_PERIOD).toMillis());

		return JobStatusPollingUtils.getJobResult(
						dispatcherGateway, jobId, scheduledExecutor, timeout, retryPeriod);
	}

	/**
	 * If the given {@link JobResult} indicates success, this passes through the {@link JobResult}.
	 * Otherwise, this returns a future that is finished exceptionally (potentially with an
	 * exception from the {@link JobResult}.
	 */
	private CompletableFuture<JobResult> unwrapJobResultException(
			CompletableFuture<JobResult> jobResult) {
		return jobResult.thenApply(result -> {
			if (result.isSuccess()) {
				return result;
			}

			Optional<SerializedThrowable> serializedThrowable = result.getSerializedThrowable();
			if (serializedThrowable.isPresent()) {
				Throwable throwable =
						serializedThrowable
								.get()
								.deserializeError(application.getUserCodeClassLoader());
				throw new CompletionException(throwable);
			}
			throw new RuntimeException("Job execution failed for unknown reason.");
		});
	}

	private List<JobID> getRecoveredJobIds(final Collection<JobGraph> recoveredJobs) {
		return recoveredJobs
				.stream()
				.map(JobGraph::getJobID)
				.collect(Collectors.toList());
	}
}


text:
using System.Collections.Generic;

using Amazon.IdentityManagement.Model;
using Amazon.Runtime.Internal.Transform;

namespace Amazon.IdentityManagement.Model.Internal.MarshallTransformations
{
     /// <summary>
     ///   ListServerCertificatesResult Unmarshaller
     /// </summary>
    internal class ListServerCertificatesResultUnmarshaller : IUnmarshaller<ListServerCertificatesResult, XmlUnmarshallerContext>
    {
        public ListServerCertificatesResult Unmarshall(XmlUnmarshallerContext context)
        {
            ListServerCertificatesResult listServerCertificatesResult = new ListServerCertificatesResult();
            int originalDepth = context.CurrentDepth;
            int targetDepth = originalDepth + 1;
            if (context.IsStartOfDocument)
               targetDepth += 2;

            while (context.Read())
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                    if (context.TestExpression("ServerCertificateMetadataList/member", targetDepth))
                    {
                        listServerCertificatesResult.ServerCertificateMetadataList.Add(ServerCertificateMetadataUnmarshaller.GetInstance().Unmarshall(context));

                        continue;
                    }
                    if (context.TestExpression("IsTruncated", targetDepth))
                    {
                        listServerCertificatesResult.IsTruncated = BoolUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                    if (context.TestExpression("Marker", targetDepth))
                    {
                        listServerCertificatesResult.Marker = StringUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                }
                else if (context.IsEndElement && context.CurrentDepth < originalDepth)
                {
                    return listServerCertificatesResult;
                }
            }

            return listServerCertificatesResult;
        }

        private static ListServerCertificatesResultUnmarshaller instance;

        public static ListServerCertificatesResultUnmarshaller GetInstance()
        {
            if (instance == null)
               instance = new ListServerCertificatesResultUnmarshaller();

            return instance;
        }
    }
}


text:
package org.apache.ignite.internal.util.future;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.internal.IgniteFutureCancelledCheckedException;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.NodeStoppingException;
import org.apache.ignite.internal.cluster.ClusterTopologyCheckedException;
import org.apache.ignite.internal.processors.cache.distributed.near.consistency.IgniteConsistencyViolationException;
import org.apache.ignite.internal.transactions.IgniteTxOptimisticCheckedException;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.C1;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteInClosure;
import org.apache.ignite.lang.IgniteReducer;
import org.jetbrains.annotations.Nullable;

/**
 * Future composed of multiple inner futures.
 */
public class GridCompoundFuture<T, R> extends GridFutureAdapter<R> implements IgniteInClosure<IgniteInternalFuture<T>> {
    /** */
    private static final long serialVersionUID = 0L;

    /** Initialization flag. */
    private static final int INIT_FLAG = 0x1;

    /** Flags updater. */
    private static final AtomicIntegerFieldUpdater<GridCompoundFuture> FLAGS_UPD =
        AtomicIntegerFieldUpdater.newUpdater(GridCompoundFuture.class, "initFlag");

    /** Listener calls updater. */
    private static final AtomicIntegerFieldUpdater<GridCompoundFuture> LSNR_CALLS_UPD =
        AtomicIntegerFieldUpdater.newUpdater(GridCompoundFuture.class, "lsnrCalls");

    /** Possible values: null (no future), IgniteInternalFuture instance (single future) or List of futures  */
    private volatile Object futs;

    /** Reducer. */
    @GridToStringInclude
    private final IgniteReducer<T, R> rdc;

    /** Initialization flag. Updated via {@link #FLAGS_UPD}. */
    @SuppressWarnings("unused")
    private volatile int initFlag;

    /** Listener calls. Updated via {@link #LSNR_CALLS_UPD}. */
    @SuppressWarnings("unused")
    private volatile int lsnrCalls;

    /**
     * Default constructor.
     */
    public GridCompoundFuture() {
        this(null);
    }

    /**
     * @param rdc Reducer.
     */
    public GridCompoundFuture(@Nullable IgniteReducer<T, R> rdc) {
        this.rdc = rdc;
    }

    /** {@inheritDoc} */
    @Override public final void apply(IgniteInternalFuture<T> fut) {
        try {
            T t = fut.get();

            try {
                if (rdc != null && !rdc.collect(t))
                    onDone(rdc.reduce());
            }
            catch (RuntimeException e) {
                logError(null, "Failed to execute compound future reducer: " + this, e);

                // Exception in reducer is a bug, so we bypass checkComplete here.
                onDone(e);
            }
            catch (AssertionError e) {
                logError(null, "Failed to execute compound future reducer: " + this, e);

                // Bypass checkComplete because need to rethrow.
                onDone(e);

                throw e;
            }
        }
        catch (IgniteTxOptimisticCheckedException | IgniteFutureCancelledCheckedException |
            ClusterTopologyCheckedException | IgniteConsistencyViolationException e) {
            if (!processFailure(e, fut))
                onDone(e);
        }
        catch (IgniteCheckedException e) {
            if (!processFailure(e, fut)) {
                if (e instanceof NodeStoppingException)
                    logDebug(logger(), "Failed to execute compound future reducer, node stopped.");
                else
                    logError(null, "Failed to execute compound future reducer: " + this, e);

                onDone(e);
            }
        }
        catch (RuntimeException e) {
            logError(null, "Failed to execute compound future reducer: " + this, e);

            onDone(e);
        }
        catch (AssertionError e) {
            logError(null, "Failed to execute compound future reducer: " + this, e);

            // Bypass checkComplete because need to rethrow.
            onDone(e);

            throw e;
        }

        LSNR_CALLS_UPD.incrementAndGet(this);

        checkComplete();
    }

    /** {@inheritDoc} */
    @Override public boolean cancel() throws IgniteCheckedException {
        if (onCancelled()) {
            for (IgniteInternalFuture<T> fut : futures())
                fut.cancel();

            return true;
        }

        return false;
    }

    /**
     * Gets collection of futures.
     *
     * @return Collection of futures.
     */
    public final synchronized Collection<IgniteInternalFuture<T>> futures() {
        if (futs == null)
            return Collections.emptyList();

        if (futs instanceof IgniteInternalFuture)
            return Collections.singletonList((IgniteInternalFuture<T>)futs);

        return new ArrayList<>((Collection<IgniteInternalFuture<T>>)futs);
    }

    /**
     * Checks if this compound future should ignore this particular exception.
     *
     * @param err Exception to check.
     * @return {@code True} if this error should be ignored.
     */
    protected boolean ignoreFailure(Throwable err) {
        return false;
    }

    /**
     * Processes error thrown by some of the inner futures.
     *
     * @param err Thrown exception.
     * @param fut Failed future.
     * @return {@code True} if this error should be ignored.
     */
    protected boolean processFailure(Throwable err, IgniteInternalFuture<T> fut) {
        return ignoreFailure(err);
    }

    /**
     * Checks if there are pending futures. This is not the same as
     * {@link #isDone()} because child classes may override {@link #onDone(Object, Throwable)}
     * call and delay completion.
     *
     * @return {@code True} if there are pending futures.
     */
    protected final boolean hasPending() {
        synchronized (this) {
            int size = futuresCountNoLock();

            // Avoid iterator creation and collection copy.
            for (int i = 0; i < size; i++) {
                IgniteInternalFuture<T> fut = future(i);

                if (!fut.isDone())
                    return true;
            }
        }

        return false;
    }

    /**
     * Adds a future to this compound future.
     *
     * @param fut Future to add.
     */
    public final GridCompoundFuture<T, R> add(IgniteInternalFuture<T> fut) {
        assert fut != null;

        synchronized (this) {
            if (futs == null)
                futs = fut;
            else if (futs instanceof IgniteInternalFuture) {
                Collection<IgniteInternalFuture> futs0 = new ArrayList<>(4);

                futs0.add((IgniteInternalFuture)futs);
                futs0.add(fut);

                futs = futs0;
            }
            else
                ((Collection<IgniteInternalFuture>)futs).add(fut);
        }

        fut.listen(this);

        if (isCancelled()) {
            try {
                fut.cancel();
            }
            catch (IgniteCheckedException e) {
                onDone(e);
            }
        }

        return this;
    }

    /**
     * Clear futures.
     */
    protected final synchronized void clear() {
        futs = null;
    }

    /**
     * @return {@code True} if this future was initialized. Initialization happens when {@link #markInitialized()}
     * method is called on future.
     */
    public final boolean initialized() {
        return initFlag == INIT_FLAG;
    }

    /**
     * Mark this future as initialized.
     */
    public final GridCompoundFuture<T, R> markInitialized() {
        if (FLAGS_UPD.compareAndSet(this, 0, INIT_FLAG))
            checkComplete();

        return this;
    }

    /**
     * Check completeness of the future.
     */
    private void checkComplete() {
        if (initialized() && !isDone() && lsnrCalls == futuresCount()) {
            try {
                onDone(rdc != null ? rdc.reduce() : null);
            }
            catch (RuntimeException e) {
                logError(logger(), "Failed to execute compound future reducer: " + this, e);

                onDone(e);
            }
            catch (AssertionError e) {
                logError(logger(), "Failed to execute compound future reducer: " + this, e);

                onDone(e);

                throw e;
            }
        }
    }

    /**
     * @param log IgniteLogger.
     * @param msg ShortMessage.
     * @param e Exception.
     */
    protected void logError(IgniteLogger log, String msg, Throwable e) {
        U.error(log, msg, e);
    }

    /**
     * @param log IgniteLogger.
     * @param msg ShortMessage.
     */
    protected void logDebug(IgniteLogger log, String msg) {
        if (log != null && log.isDebugEnabled())
            log.debug(msg);
    }

    /**
     * Returns future at the specified position in this list.
     *
     * @param idx - index index of the element to return
     * @return Future.
     */
    @SuppressWarnings("unchecked")
    protected final IgniteInternalFuture<T> future(int idx) {
        assert Thread.holdsLock(this);
        assert futs != null && idx >= 0 && idx < futuresCountNoLock();

        if (futs instanceof IgniteInternalFuture) {
            assert idx == 0;

            return (IgniteInternalFuture<T>)futs;
        }
        else
            return ((List<IgniteInternalFuture>)futs).get(idx);
    }

    /**
     * @return Futures size.
     */
    protected final int futuresCountNoLock() {
        assert Thread.holdsLock(this);

        if (futs == null)
            return 0;

        if (futs instanceof IgniteInternalFuture)
            return 1;

        return ((Collection<IgniteInternalFuture>)futs).size();
    }

    /**
     * @return Futures size.
     */
    private synchronized int futuresCount() {
        return futuresCountNoLock();
    }

    /**
     * @return {@code True} if has at least one future.
     */
    protected final synchronized boolean hasFutures() {
        return futs != null;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(GridCompoundFuture.class, this,
            "done", isDone(),
            "cancelled", isCancelled(),
            "err", error(),
            "futs",
            F.viewReadOnly(futures(), new C1<IgniteInternalFuture<T>, String>() {
                @Override public String apply(IgniteInternalFuture<T> f) {
                    return Boolean.toString(f.isDone());
                }
            })
        );
    }
}


text:
<template name="visPieChart">

</template>

<template name="visPieChartForm">

      Chart Type

        <input type="hidden" name="chartType" value={{settings.chartType}}>

        select

Pie

Donut

      Category Field
      {{> dropdown name="categoryField" value=settings.categoryField items=fields}}

      Value Field
      {{> dropdown name="valueField" value=settings.valueField items=fields}}

      Settings

        <input type="checkbox" name="showValue:boolean" checked={{settings.showValue}}>
        show value

</template>