text:
package org.h2.build.doc;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.zip.CRC32;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.h2.dev.ftp.FtpClient;
import org.h2.engine.Constants;
import org.h2.store.fs.FileUtils;
import org.h2.test.utils.OutputCatcher;
import org.h2.util.IOUtils;
import org.h2.util.ScriptReader;
import org.h2.util.StringUtils;

/**
 * Upload the code coverage result to the H2 web site.
 */
public class UploadBuild {

    /**
     * This method is called when executing this application from the command
     * line.
     *
     * @param args the command line parameters
     */
    public static void main(String... args) throws Exception {
        System.setProperty("h2.socketConnectTimeout", "30000");
        String password = System.getProperty("h2.ftpPassword");
        if (password == null) {
            return;
        }
        FtpClient ftp = FtpClient.open("h2database.com");
        ftp.login("h2database", password);
        ftp.changeWorkingDirectory("/httpdocs");
        boolean coverage = new File("coverage/index.html").exists();
        boolean coverageFailed;
        if (coverage) {
            byte[] data = IOUtils.readBytesAndClose(
                    new FileInputStream("coverage/index.html"), -1);
            String index = new String(data, "ISO-8859-1");
            coverageFailed = index.contains("CLASS=\"h\"");
            while (true) {
                int idx = index.indexOf("<A HREF=\"");
                if (idx < 0) {
                    break;
                }
                int end = index.indexOf('>', idx) + 1;
                index = index.substring(0, idx) + index.substring(end);
                idx = index.indexOf("");
                index = index.substring(0, idx) + index.substring(idx + "".length());
            }
            index = StringUtils.replaceAll(index, "[all", "");
            index = StringUtils.replaceAll(index, "classes]", "");
            FileOutputStream out = new FileOutputStream("coverage/overview.html");
            out.write(index.getBytes("ISO-8859-1"));
            out.close();
            new File("details").mkdir();
            zip("details/coverage_files.zip", "coverage", true);
            zip("coverage.zip", "details", false);
            FileUtils.delete("coverage.txt");
            FileUtils.delete("details/coverage_files.zip");
            FileUtils.delete("details");
            if (ftp.exists("/httpdocs", "coverage")) {
                ftp.removeDirectoryRecursive("/httpdocs/coverage");
            }
            ftp.makeDirectory("/httpdocs/coverage");
        } else {
            coverageFailed = true;
        }
        String testOutput;
        boolean error;
        if (new File("docs/html/testOutput.html").exists()) {
            testOutput = IOUtils.readStringAndClose(
                    new FileReader("docs/html/testOutput.html"), -1);
            error = testOutput.contains(OutputCatcher.START_ERROR);
        } else if (new File("log.txt").exists()) {
            testOutput = IOUtils.readStringAndClose(new FileReader("log.txt"), -1);
            error = true;
        } else {
            testOutput = "No log.txt";
            error = true;
        }
        if (!ftp.exists("/httpdocs", "automated")) {
            ftp.makeDirectory("/httpdocs/automated");
        }
        String buildSql;
        if (ftp.exists("/httpdocs/automated", "history.sql")) {
            buildSql = new String(ftp.retrieve("/httpdocs/automated/history.sql"));
        } else {
            buildSql = "create table item(id identity, title varchar, " +
                    "issued timestamp, desc varchar);\n";
        }
        String ts = new java.sql.Timestamp(System.currentTimeMillis()).toString();
        String now = ts.substring(0, 16);
        int idx = testOutput.indexOf("Statements per second: ");
        if (idx >= 0) {
            int end = testOutput.indexOf("
", idx);
            if (end >= 0) {
                String result = testOutput.substring(idx +
                        "Statements per second: ".length(), end);
                now += " " + result + " op/s";
            }
        }
        String sql = "insert into item(title, issued, desc) values('Build " +
            now +
            (error ? " FAILED" : "") +
            (coverageFailed ? " COVERAGE" : "") +
            "', '" + ts +
            "', 'Output" +
            " - Coverage" +
            " - Jar');\n";
        buildSql += sql;
        Connection conn;
        try {
            Class.forName("org.h2.Driver");
            conn = DriverManager.getConnection("jdbc:h2:mem:");
        } catch (Exception e) {
            Class.forName("org.h2.upgrade.v1_1.Driver");
            conn = DriverManager.getConnection("jdbc:h2v1_1:mem:");
        }
        conn.createStatement().execute(buildSql);
        String newsfeed = IOUtils.readStringAndClose(
                new FileReader("src/tools/org/h2/build/doc/buildNewsfeed.sql"), -1);
        ScriptReader r = new ScriptReader(new StringReader(newsfeed));
        Statement stat = conn.createStatement();
        ResultSet rs = null;
        while (true) {
            String s = r.readStatement();
            if (s == null) {
                break;
            }
            if (stat.execute(s)) {
                rs = stat.getResultSet();
            }
        }
        rs.next();
        String content = rs.getString("content");
        conn.close();
        ftp.store("/httpdocs/automated/history.sql",
                new ByteArrayInputStream(buildSql.getBytes()));
        ftp.store("/httpdocs/automated/news.xml",
                new ByteArrayInputStream(content.getBytes()));
        ftp.store("/httpdocs/html/testOutput.html",
                new ByteArrayInputStream(testOutput.getBytes()));
        String jarFileName = "bin/h2-" + Constants.getVersion() + ".jar";
        if (FileUtils.exists(jarFileName)) {
            ftp.store("/httpdocs/automated/h2-latest.jar",
                    new FileInputStream(jarFileName));
        }
        if (coverage) {
            ftp.store("/httpdocs/coverage/overview.html",
                    new FileInputStream("coverage/overview.html"));
            ftp.store("/httpdocs/coverage/coverage.zip",
                    new FileInputStream("coverage.zip"));
            FileUtils.delete("coverage.zip");
        }
        ftp.close();
    }

    private static void zip(String destFile, String directory, boolean storeOnly)
            throws IOException {
        OutputStream out = new FileOutputStream(destFile);
        ZipOutputStream zipOut = new ZipOutputStream(out);
        if (storeOnly) {
            zipOut.setMethod(ZipOutputStream.STORED);
        }
        zipOut.setLevel(Deflater.BEST_COMPRESSION);
        addFiles(new File(directory), new File(directory), zipOut);
        zipOut.finish();
        zipOut.close();
    }

    private static void addFiles(File base, File file, ZipOutputStream out)
            throws IOException {
        if (file.isDirectory()) {
            for (File f : file.listFiles()) {
                addFiles(base, f, out);
            }
        } else {
            String path = file.getAbsolutePath().substring(base.getAbsolutePath().length());
            path = path.replace('\\', '/');
            if (path.startsWith("/")) {
                path = path.substring(1);
            }
            byte[] data = IOUtils.readBytesAndClose(new FileInputStream(file), -1);
            ZipEntry entry = new ZipEntry(path);
            CRC32 crc = new CRC32();
            crc.update(data);
            entry.setSize(file.length());
            entry.setCrc(crc.getValue());
            out.putNextEntry(entry);
            out.write(data);
            out.closeEntry();
        }
    }

}


text:
import abc
import ast
from distutils.version import StrictVersion as V
import random
import six

from cfgm_common import analytics_client
from cfgm_common import svc_info
from sandesh_common.vns import constants
from vnc_api.vnc_api import NoIdError

from svc_monitor.config_db import *

from sandesh_common.vns.constants import \
     ANALYTICS_API_SERVER_DISCOVERY_SERVICE_NAME as analytics_svc_name

@six.add_metaclass(abc.ABCMeta)
class VRouterScheduler(object):

    def __init__(self, vnc_lib, nova_client, disc, logger, args):
        self._vnc_lib = vnc_lib
        self._args = args
        self._nc = nova_client
        self._disc = disc
        self._logger = logger
        self._analytics_client_list = self._get_analytics_clients()

    def _get_analytics_clients(self):
        analytics_client_list = []
        analytics_servers = self._args.analytics_server_list[:]
        analytics_server_list = analytics_servers.split()
        for analytics_server in analytics_server_list or []:
            endpoint = "http://%s" % analytics_server
            obj = analytics_client.Client(endpoint)
            analytics_client_list.append(obj)
        return analytics_client_list

    @abc.abstractmethod
    def schedule(self, plugin, context, router_id, candidates=None):
        """Schedule the virtual machine to an active vrouter agent.

        Schedule the virtual machine only if it is not already scheduled and
        there is no other virtual machines of the same service instance already
        scheduled on the vrouter.
        """
        pass

    def _get_az_vrouter_list(self):
        if not self._args.netns_availability_zone:
            return None
        az_list = self._nc.oper('availability_zones', 'list',
                                self._args.admin_tenant_name,
                                detailed=True)
        if not az_list:
            self._logger.error("Failed fetching azs from nova")
            return None

        az_vr_list = []
        for az in az_list:
            try:
                # check:
                # 1. If az is mentioned in config
                # 2. If the az is enabled & active
                # 3. If it has any hosts
                if az.zoneName not in self._args.netns_availability_zone or \
                   not az.zoneState['available'] or not az.hosts:
                    continue

                # check if hosts are active & enabled
                for host,host_status in az.hosts.iteritems():
                    if (('nova-compute' in host_status) and \
                        host_status['nova-compute']['available'] and \
                        host_status['nova-compute']['active']):
                        az_vr_list.append(host)
            except Exception as e:
                self._logger.error(str(e))
                continue

        return az_vr_list

    def query_uve(self, analytics, filter_string):
        path = "/analytics/uves/vrouter/"
        response_dict = {}
        if self._args.aaa_mode == 'no-auth':
            user_token = None
        else:
            user_token = self._vnc_lib.get_auth_token()
        response = analytics.request(path, filter_string,
                   user_token=user_token)
        for values in response['value']:
            response_dict[values['name']] = values['value']
        return response_dict

    def vrouters_running(self):
        # get az host list
        az_vrs = self._get_az_vrouter_list()

        # read all vrouter information
        client_cnt = len(self._analytics_client_list)
        analytics_client_list = random.sample(
                  self._analytics_client_list, client_cnt)
        analytics_response = False
        for analytics in analytics_client_list or []:
            try:
                vrouters_mode = self.query_uve(
                       analytics, "*?cfilt=VrouterAgent:mode")
                agents_status = self.query_uve(
                       analytics, "*?cfilt=NodeStatus:process_status")
                analytics_response = True
                break
            except Exception as e:
                error_msg = "Failed to get vrouter and agent info from " + \
                            "analytics endpoint %s" %analytics.endpoint
                self._logger.error(error_msg)
                self._logger.error(str(e))

        if not analytics_response:
            error_msg = "no response from analytics servers"
            self._logger.error(error_msg)
            return

        for vr in VirtualRouterSM.values():
            if az_vrs and vr.name not in az_vrs:
                vr.set_agent_state(False)
                continue

            if vr.name not in vrouters_mode or vr.name not in agents_status:
                vr.set_agent_state(False)
                continue

            try:
                vr_mode = vrouters_mode[vr.name]['VrouterAgent']
                if (vr_mode['mode'] != constants.VrouterAgentTypeMap[
                        constants.VrouterAgentType.VROUTER_AGENT_EMBEDDED]):
                    vr.set_agent_state(False)
                    continue
            except Exception as e:
                vr.set_agent_state(False)
                continue

            try:
                state_up = False
                for vr_status in agents_status[vr.name]['NodeStatus']['process_status'] or []:
                    if (vr_status['module_id'] != constants.MODULE_VROUTER_AGENT_NAME):
                        continue
                    if (int(vr_status['instance_id']) == 0 and
                            vr_status['state'] == 'Functional'):
                        vr.set_agent_state(True)
                        state_up = True
                        break
                if not state_up:
                    vr.set_agent_state(False)
            except Exception as e:
                vr.set_agent_state(False)
                continue

    def _get_candidates(self, si, vm):
        if vm.virtual_router:
            return [vm.virtual_router]

        vr_list = VirtualRouterSM._dict.keys()
        for vm_id in si.virtual_machines:
            if vm_id == vm.uuid:
                continue
            anti_affinity_vm = VirtualMachineSM.get(vm_id)
            if anti_affinity_vm:
                try:
                    vr_list.remove(anti_affinity_vm.virtual_router)
                except ValueError:
                    pass

        for vr in VirtualRouterSM.values():
            if not vr.agent_state:
                try:
                    vr_list.remove(vr.uuid)
                except ValueError:
                    pass
        return vr_list

class RandomScheduler(VRouterScheduler):
    """Randomly allocate a vrouter agent for virtual machine of a service
    instance."""
    def schedule(self, si, vm):
        candidates = self._get_candidates(si, vm)
        if not candidates:
            return None
        chosen_vrouter = random.choice(candidates)
        self._vnc_lib.ref_update('virtual-router', chosen_vrouter,
            'virtual-machine', vm.uuid, None, 'ADD')
        return chosen_vrouter

redpajama_set_name: RedPajamaGithub


text:
package twentysix.playr

import play.api.routing.Router
import scala.runtime.AbstractPartialFunction
import play.api.mvc.RequestHeader
import play.api.mvc.Handler

trait RouterWithPrefix extends Router { self =>

  def documentation: Seq[(String, String, String)] = Seq.empty

  def routesWithPrefix(prefix: String) = self.routes

  def withPrefix(prefix: String): Router = {
    if ((prefix == "") || (prefix == "/")) {
      self
    } else {
      new Router {
        def routes = {
          val p = if (prefix.endsWith("/")) prefix.drop(1) else prefix
          val prefixed: PartialFunction[RequestHeader, RequestHeader] = {
            case rh: RequestHeader if rh.path.startsWith(p) => {
              rh.withTarget(rh.target.withPath(rh.path.drop(p.length)))
            }
          }
          Function.unlift(prefixed.lift.andThen(_.flatMap(self.routesWithPrefix(p).lift)))
        }

        def withPrefix(prefix: String) = self.withPrefix(prefix)
        def documentation = self.documentation
      }
    }
  }
}

trait SimpleRouter extends RouterWithPrefix {
  def routeRequest(header: RequestHeader, path: String, method: String): Option[Handler]

  def routes = Function.unlift { requestHeader =>
    routeRequest(requestHeader, requestHeader.path, requestHeader.method)
  }
}


text:
package test.encoding;

import org.apache.axis.Constants;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Test deserialization of SOAP responses
 */
public class TestDeser1999 extends TestDeser {

    public TestDeser1999(String name) {
        super(name, Constants.URI_1999_SCHEMA_XSI,
                    Constants.URI_1999_SCHEMA_XSD);
    }

    public void testMapWithNulls() throws Exception {
        HashMap m = new HashMap();
        m.put(null, new Boolean("false"));
        m.put("hi", null);
        // Test map with nulls and
        // Test type references to the default namespace.
        deserialize("<result xsi:type=\"xmlsoap:Map\" " +
                    "xmlns:xmlsoap=\"http://xml.apache.org/xml-soap\"> " +
                      "<item>" +
                       "<key xsi:null=\"true\"/>" +
                       "<value xsi:type=\"boolean\" xmlns=\"" +
                         Constants.URI_1999_SCHEMA_XSD +
                         "\">false</value>" +
                      "</item><item>" +
                       "<key xsi:type=\"string\" xmlns=\"" +
                         Constants.URI_1999_SCHEMA_XSD +
                         "\">hi</key>" +
                       "<value xsi:null=\"true\"/>" +
                      "</item>" +
                    "</result>",
                    m);
    }

    public void testArrayWithNullInt() throws Exception {
        ArrayList list = new ArrayList(4);
        list.add(new Integer(1));
        list.add(null);
        list.add(new Integer(3));
        deserialize("<result xsi:type=\"soapenc:Array\" " +
                            "soapenc:arrayType=\"xsd:int[3]\"> " +
                       "<item xsi:type=\"xsd:int\">1</item>" +
                       "<item xsi:null=\"true\"/>" +
                       "<item xsi:type=\"xsd:int\">3</item>" +
                    "</result>",
                    list, true);
    }

    public void testArrayWithNullString() throws Exception {
        ArrayList list = new ArrayList(4);
        list.add("abc");
        list.add(null);
        list.add("def");
        deserialize("<result xsi:type=\"soapenc:Array\" " +
                            "soapenc:arrayType=\"xsd:string[3]\"> " +
                       "<item xsi:type=\"xsd:string\">abc</item>" +
                       "<item xsi:null=\"true\"/>" +
                       "<item xsi:type=\"xsd:string\">def</item>" +
                    "</result>",
                    list, true);
    }

    public void testNullSOAPBoolean() throws Exception {
        deserialize("<result xsi:type=\"soapenc:boolean\" xsi:null=\"true\" />",
                    null);
    }
}


text:
package org.unitime.timetable.gwt.client.rooms;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.unitime.timetable.gwt.client.ToolBox;
import org.unitime.timetable.gwt.client.aria.AriaCheckBox;
import org.unitime.timetable.gwt.client.page.UniTimePageHeader;
import org.unitime.timetable.gwt.client.widgets.ImageLink;
import org.unitime.timetable.gwt.client.widgets.P;
import org.unitime.timetable.gwt.client.widgets.UniTimeTable;
import org.unitime.timetable.gwt.client.widgets.UniTimeTableHeader;
import org.unitime.timetable.gwt.client.widgets.UniTimeTableHeader.AriaOperation;
import org.unitime.timetable.gwt.client.widgets.UniTimeTableHeader.HasColumnName;
import org.unitime.timetable.gwt.client.widgets.UniTimeTableHeader.Operation;
import org.unitime.timetable.gwt.command.client.GwtRpcService;
import org.unitime.timetable.gwt.command.client.GwtRpcServiceAsync;
import org.unitime.timetable.gwt.resources.GwtAriaMessages;
import org.unitime.timetable.gwt.resources.GwtConstants;
import org.unitime.timetable.gwt.resources.GwtMessages;
import org.unitime.timetable.gwt.resources.GwtResources;
import org.unitime.timetable.gwt.shared.RoomInterface.AttachmentTypeInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.DepartmentInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.ExamTypeInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.FeatureInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.FeatureTypeInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.GroupInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomDetailInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomPictureInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomPropertiesInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomPropertyInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomsColumn;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomsPageMode;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.TakesValue;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasHorizontalAlignment.HorizontalAlignmentConstant;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author Tomas Muller
 */
public class RoomsTable extends UniTimeTable<RoomDetailInterface>{
	protected static final GwtMessages MESSAGES = GWT.create(GwtMessages.class);
	protected static final GwtAriaMessages ARIA = GWT.create(GwtAriaMessages.class);
	protected static final GwtResources RESOURCES =  GWT.create(GwtResources.class);
	protected static final GwtConstants CONSTANTS = GWT.create(GwtConstants.class);
	protected static final GwtRpcServiceAsync RPC = GWT.create(GwtRpcService.class);

	private int iFlags = 0;
	private RoomsColumn iSortBy = null;
	private boolean iAsc = true;
	private RoomsPageMode iMode = null;
	private String iDepartment = null;
	private List<Operation> iSortOperations = new ArrayList<Operation>();
	private List<Operation> iShowHideOperations = new ArrayList<Operation>();
	private List<Operation> iDepartmentOperations = new ArrayList<Operation>();
	private List<Operation> iOtherOperations = new ArrayList<Operation>();
	private RoomPropertiesInterface iProperties = null;
	private boolean iSelectable;

	public RoomsTable(RoomsPageMode mode, boolean selectable) {
		setStyleName("unitime-Rooms");
		iMode = mode;
		iSelectable = selectable;

		addOperation(new Operation() {

			@Override
			public void execute() {
				final RoomsTable table = new RoomsTable(iMode);
				table.setProperties(iProperties);
				table.setDepartment(iDepartment);
				for (int i = 1; i < getRowCount(); i++)
					table.addRoom(getData(i));
				table.getElement().getStyle().setWidth(1040, Unit.PX);

				// Move header row to thead
				Element headerRow = table.getRowFormatter().getElement(0);
				Element tableElement = table.getElement();
				Element thead = DOM.createTHead();
				tableElement.insertFirst(thead);
				headerRow.getParentElement().removeChild(headerRow);
				thead.appendChild(headerRow);

				ToolBox.print(
						new ToolBox.Page() {
							@Override
							public String getName() { return MESSAGES.pageRooms(); }
							@Override
							public String getUser() { return UniTimePageHeader.getInstance().getMiddle().getText(); }
							@Override
							public String getSession() { return UniTimePageHeader.getInstance().getRight().getText(); }
							@Override
							public Element getBody() { return table.getElement(); }
						}
						);
			}

			@Override
			public String getName() {
				return MESSAGES.buttonPrint();
			}

			@Override
			public boolean isApplicable() {
				return getRowCount() > 1 && !iSelectable;
			}

			@Override
			public boolean hasSeparator() {
				return true;
			}
		});
	}

	public RoomsTable(RoomsPageMode mode) {
		this(mode, false);
	}

	public RoomsTable(RoomsPageMode mode, RoomPropertiesInterface properties, boolean selectable) {
		this(mode, selectable);
		setProperties(properties);
	}

	public void setProperties(RoomPropertiesInterface properties) {
		iProperties = properties;

		super.clearTable();

		List<UniTimeTableHeader> header = new ArrayList<UniTimeTableHeader>();
		for (RoomsColumn column: RoomsColumn.values()) {
			int nrCells = getNbrCells(column);
			for (int idx = 0; idx < nrCells; idx++) {
				UniTimeTableHeader h = new UniTimeTableHeader(getColumnName(column, idx), getColumnAlignment(column, idx));
				header.add(h);
			}
		}

		if (iSelectable) {
			header.get(0).addOperation(new Operation() {
				@Override
				public void execute() {
					for (int row = 1; row < getRowCount(); row++) {
						Widget w =  getWidget(row, 0);
						if (w != null && w instanceof CheckBox) {
							CheckBox ch = (CheckBox)w;
							ch.setValue(true);
						}
						setSelected(row, true);
					}
				}
				@Override
				public boolean isApplicable() {
					for (int row = 1; row < getRowCount(); row++) {
						Widget w =  getWidget(row, 0);
						if (w != null && w instanceof CheckBox) {
							CheckBox ch = (CheckBox)w;
							if (!ch.getValue()) return true;
						}
					}
					return false;
				}
				@Override
				public boolean hasSeparator() {
					return false;
				}
				@Override
				public String getName() {
					return MESSAGES.opSelectAll();
				}
			});
			header.get(0).addOperation(new Operation() {
				@Override
				public void execute() {
					for (int row = 1; row < getRowCount(); row++) {
						Widget w =  getWidget(row, 0);
						if (w != null && w instanceof CheckBox) {
							CheckBox ch = (CheckBox)w;
							ch.setValue(false);
						}
						setSelected(row, false);
					}
				}
				@Override
				public boolean isApplicable() {
					for (int row = 1; row < getRowCount(); row++) {
						Widget w =  getWidget(row, 0);
						if (w != null && w instanceof CheckBox) {
							CheckBox ch = (CheckBox)w;
							if (ch.getValue()) return true;
						}
					}
					return false;
				}
				@Override
				public boolean hasSeparator() {
					return false;
				}
				@Override
				public String getName() {
					return MESSAGES.opClearSelection();
				}
			});
		}

		if (RoomCookie.getInstance().getFlags(iMode) == 0) {
			int flags = 0;
			for (RoomsColumn column: RoomsColumn.values()) {
				if (iMode.hasColumn(column)) {
					int nrCells = getNbrCells(column);
					int cellIdx = getCellIndex(column);
					for (int idx = 0; idx < nrCells; idx++) {
						flags += (1 << (cellIdx + idx));
					}
				}
			}
			RoomCookie.getInstance().setFlags(iMode, flags);
		}

		addRow(null, header);

		iShowHideOperations.clear();
		for (final RoomsColumn column: RoomsColumn.values()) {
			int nrCells = getNbrCells(column);
			int cellIdx = getCellIndex(column);
			for (int idx = 0; idx < nrCells; idx++) {
				final int colIdx = cellIdx + idx;
				final String cName = getColumnName(column, idx).replace("
", " ");
				UniTimeTableHeader h = header.get(colIdx);
				if (hasShowHideOperation(column)) {
					Operation op = new AriaOperation() {
						@Override
						public void execute() {
							boolean visible = isColumnVisible(colIdx);
							setColumnVisible(colIdx, !visible);
							RoomCookie.getInstance().set(iMode, colIdx, !visible);
						}
						@Override
						public boolean isApplicable() {
							return (iFlags & (1 << colIdx)) != 0;
						}
						@Override
						public boolean hasSeparator() {
							if (iSelectable && column == RoomsColumn.EXTERNAL_ID) return true;
							return false;
						}
						@Override
						public String getName() { return isColumnVisible(colIdx) ? MESSAGES.opHide(cName) : MESSAGES.opShow(cName); }
						@Override
						public String getAriaLabel() { return isColumnVisible(colIdx) ? ARIA.opHide(cName) : ARIA.opShow(cName); }
					};
					iShowHideOperations.add(op);
					if (colIdx > 0) header.get(0).addOperation(op);
					RoomsColumn g = getShowHideGroup(column);
					if (g == null) {
						h.addOperation(op);
					} else {
						for (RoomsColumn c: RoomsColumn.values()) {
							if (g.equals(getShowHideGroup(c)))
								for (int i = 0; i < getNbrCells(c); i++)
									header.get(getCellIndex(c) + i).addOperation(op);
						}
					}
				}
			}
		}

		iDepartmentOperations.clear();
		for (final DeptMode d: DeptMode.values()) {
			Operation op = new Operation() {
				@Override
				public void execute() {
					RoomCookie.getInstance().setDeptMode(d.ordinal());
					refreshTable();
				}
				@Override
				public boolean isApplicable() {
					return getRowCount() > 0;
				}
				@Override
				public boolean hasSeparator() {
					return d.ordinal() == 0;
				}
				@Override
				public String getName() {
					if (RoomCookie.getInstance().getDeptMode() == d.ordinal())
						return MESSAGES.opUncheck(d.getName());
					else
						return MESSAGES.opCheck(d.getName());
				}
			};
			iDepartmentOperations.add(op);
			for (RoomsColumn c: RoomsColumn.values()) {
				if (hasDepartmentOperation(c))
					for (int i = 0; i < getNbrCells(c); i++)
						header.get(getCellIndex(c) + i).addOperation(op);
			}
		}

		iSortOperations.clear();
		for (final RoomsColumn column: RoomsColumn.values()) {
			if (RoomsComparator.isApplicable(column)) {
				final UniTimeTableHeader h = header.get(getCellIndex(column));
				Operation op = new SortOperation() {
					@Override
					public void execute() {
						if (column == iSortBy) {
							iAsc = !iAsc;
						} else {
							iSortBy = column;
							iAsc = true;
						}
						RoomCookie.getInstance().setSortRoomsBy(getSortBy());
						sort();
					}
					@Override
					public boolean isApplicable() { return getRowCount() > 1 && h.isVisible(); }
					@Override
					public boolean hasSeparator() { return true; }
					@Override
					public String getName() { return MESSAGES.opSortBy(getColumnName()); }
					@Override
					public String getColumnName() { return h.getHTML().replace("
", " "); }
				};
				iSortOperations.add(op);
				h.addOperation(op);
			}
		}

		for (Operation op: getOtherOperations())
			header.get(0).addOperation(op);

		for (int i = 0; i < getCellCount(0); i++)
			getCellFormatter().setStyleName(0, i, "unitime-ClickableTableHeader");

		resetVisibility();
		setSortBy(RoomCookie.getInstance().getRoomsSortBy());

		setVisible(false);

		if (iSelectable) {
			setAllowSelection(true);
			addMouseClickListener(new MouseClickListener<RoomDetailInterface>() {
				@Override
				public void onMouseClick(TableEvent<RoomDetailInterface> event) {
					selectRoom(event.getRow(), isSelected(event.getRow()));
				}
			});
		}
	}

	public String getColumnName(RoomsColumn column, int idx) {
		switch (column) {
		case NAME: return MESSAGES.colName();
		case TYPE: return MESSAGES.colType();
		case EXTERNAL_ID: return MESSAGES.colExternalId();
		case CAPACITY: return MESSAGES.colCapacity();
		case EXAM_CAPACITY: return MESSAGES.colExaminationCapacity();
		case AREA: return MESSAGES.colArea(CONSTANTS.roomAreaUnitsShort());
		case COORDINATES: return MESSAGES.colCoordinates();
		case DISTANCE_CHECK: return MESSAGES.colDistances();
		case ROOM_CHECK: return MESSAGES.colRoomCheck();
		case MAP: return MESSAGES.colMap();
		case PICTURES:
			if (idx == 0) return MESSAGES.colPictures();
			else return iProperties.getTableTypes().get(idx - 1).getAbbreviation();
		case PREFERENCE: return MESSAGES.colPreference();
		case AVAILABILITY: return MESSAGES.colAvailability();
		case DEPARTMENTS: return MESSAGES.colDepartments();
		case CONTROL_DEPT: return MESSAGES.colControl();
		case EXAM_TYPES: return MESSAGES.colExamTypes();
		case PERIOD_PREF: return MESSAGES.colPeriodPreferences();
		case EVENT_DEPARTMENT: return MESSAGES.colEventDepartment();
		case EVENT_STATUS: return MESSAGES.colEventStatus();
		case EVENT_AVAILABILITY: return MESSAGES.colEventAvailability();
		case EVENT_MESSAGE: return MESSAGES.colEventMessage();
		case BREAK_TIME: return MESSAGES.colBreakTime();
		case GROUPS: return MESSAGES.colGroups();
		case FEATURES:
			if (idx == 0) return MESSAGES.colFeatures();
			else return getFeatureType(idx - 1).getAbbreviation();
		default: return column.name();
		}
	}

	public void refreshTable() {
		for (int r = 1; r < getRowCount(); r++) {
			for (int c = 0; c < getCellCount(r); c++) {
				Widget w = getWidget(r, c);
				if (w instanceof HasRefresh)
					((HasRefresh)w).refresh();
			}
		}
	}

	protected HorizontalAlignmentConstant getColumnAlignment(RoomsColumn column, int idx) {
		switch (column) {
		case CAPACITY:
		case EXAM_CAPACITY:
		case AREA:
			return HasHorizontalAlignment.ALIGN_RIGHT;
		default:
			return HasHorizontalAlignment.ALIGN_LEFT;
		}
	}

	protected boolean hasShowHideOperation(RoomsColumn column) {
		switch (column) {
		case NAME:
			return false;
		default:
			return true;
		}
	}

	protected int getFlagOffset(RoomsColumn column) {
		switch (column) {
		case PICTURES:
			return countFeatureTypes();
		default:
			return 0;
		}
	}

	protected boolean hasDepartmentOperation(RoomsColumn column) {
		switch (column) {
		case DEPARTMENTS:
		case CONTROL_DEPT:
		case EVENT_DEPARTMENT:
			return true;
		default:
			return false;
		}
	}

	protected RoomsColumn getShowHideGroup(RoomsColumn column) {
		switch (column) {
		case EXTERNAL_ID:
		case TYPE:
			return RoomsColumn.EXTERNAL_ID;
		case CAPACITY:
		case EXAM_CAPACITY:
		case AREA:
		case COORDINATES:
		case DISTANCE_CHECK:
		case ROOM_CHECK:
			return RoomsColumn.CAPACITY;
		case PREFERENCE:
		case AVAILABILITY:
		case DEPARTMENTS:
		case CONTROL_DEPT:
			return RoomsColumn.PREFERENCE;
		case EVENT_DEPARTMENT:
		case EVENT_AVAILABILITY:
		case EVENT_STATUS:
		case EVENT_MESSAGE:
		case BREAK_TIME:
			return RoomsColumn.EVENT_DEPARTMENT;
		case EXAM_TYPES:
		case PERIOD_PREF:
			return RoomsColumn.EXAM_TYPES;
		case PICTURES:
			return RoomsColumn.PICTURES;
		case FEATURES:
			return RoomsColumn.FEATURES;
		default:
			return null;
		}
	}

	protected boolean hasFeatureTypes() {
		return iProperties != null && iProperties.getFeatureTypes() != null && !iProperties.getFeatureTypes().isEmpty();
	}

	protected int countFeatureTypes() {
		return iProperties == null ? 0 : iProperties.getFeatureTypes().size();
	}

	protected FeatureTypeInterface getFeatureType(int index) {
		return iProperties.getFeatureTypes().get(index);
	}

	public List<Operation> getSortOperations() {
		ArrayList<Operation> operations = new ArrayList<Operation>();
		for (Operation operation: iSortOperations)
			if (operation.isApplicable())
				operations.add(operation);
		return operations;
	}

	public List<Operation> getShowHideOperations() {
		ArrayList<Operation> operations = new ArrayList<Operation>();
		for (Operation operation: iShowHideOperations)
			if (operation.isApplicable())
				operations.add(operation);
		return operations;
	}

	public List<Operation> getDepartmentOperations() {
		ArrayList<Operation> operations = new ArrayList<Operation>();
		for (Operation operation: iDepartmentOperations)
			if (operation.isApplicable())
				operations.add(operation);
		return operations;
	}

	public List<Operation> getOtherOperations() {
		ArrayList<Operation> operations = new ArrayList<Operation>();
		for (Operation operation: iOtherOperations)
			if (operation.isApplicable())
				operations.add(operation);
		return operations;
	}

	public boolean hasSortBy() { return iSortBy != null; }
	public int getSortBy() { return iSortBy == null ? 0 : iAsc ? 1 + iSortBy.ordinal() : -1 - iSortBy.ordinal(); }
	public void setSortBy(int sortBy) {
		if (sortBy == 0) {
			iSortBy = null;
			iAsc = true;
		} else if (sortBy > 0) {
			iSortBy = RoomsColumn.values()[sortBy - 1];
			iAsc = true;
		} else {
			iSortBy = RoomsColumn.values()[-1 - sortBy];
			iAsc = false;
		}
		sort();
	}

	protected void addOperation(Operation op) {
		iOtherOperations.add(op);
	}

	public void sort() {
		if (iSortBy == null) return;
		Comparator<RoomDetailInterface> rc = null;
		if (iSelectable && iSortBy == RoomsColumn.NAME) {
			rc = new Comparator<RoomDetailInterface>() {
				private Comparator<RoomDetailInterface> iRC = new RoomsComparator(iSortBy, true);
				@Override
				public int compare(RoomDetailInterface r1, RoomDetailInterface r2) {
					boolean s1 = isRoomSelected(r1), s2 = isRoomSelected(r2);
					if (s1 != s2)
						return s1 ? -1 : 1;
					return iRC.compare(r1, r2);
				}
			};
		} else {
			rc = new RoomsComparator(iSortBy, true);
		}
		UniTimeTableHeader header = getHeader(getCellIndex(iSortBy));
		sort(header, rc, iAsc);
	}

	public void setDepartment(String department) { iDepartment = department; }

	protected int getNbrCells(RoomsColumn column) {
		switch (column) {
		case PICTURES:
			List<AttachmentTypeInterface> types = iProperties.getTableTypes();
			return 1 + (types == null ? 0 : types.size());
		case FEATURES:
			return 1 + iProperties.getFeatureTypes().size();
		default:
			return 1;
		}
	}

	protected int getCellIndex(RoomsColumn column) {
		int ret = 0;
		for (RoomsColumn c: RoomsColumn.values())
			if (c.ordinal() < column.ordinal()) ret += getNbrCells(c);
		return ret;
	}

	protected Widget getCell(final RoomDetailInterface room, final RoomsColumn column, final int idx) {
		if (iProperties == null || !iProperties.isCanSeeCourses()) {
			switch (column) {
			case ROOM_CHECK:
				if (iProperties != null && iProperties.isCanSeeEvents()) break;
			case DISTANCE_CHECK:
			case PREFERENCE:
			case AVAILABILITY:
			case DEPARTMENTS:
			case CONTROL_DEPT:
				return null;
			}
		}
		if (iProperties == null || !iProperties.isCanSeeExams()) {
			switch (column) {
			case EXAM_CAPACITY:
			case EXAM_TYPES:
			case PERIOD_PREF:
				return null;
			}
		}
		if (iProperties == null || !iProperties.isCanSeeEvents()) {
			switch (column) {
			case EVENT_DEPARTMENT:
			case EVENT_MESSAGE:
			case EVENT_AVAILABILITY:
			case EVENT_STATUS:
			case BREAK_TIME:
				return null;
			}
		}
		switch (column) {
		case NAME:
			if (iSelectable) {
				return new SelectableRoomNameCell(room);
			} else {
				return new RoomNameCell(room);
			}

		case EXTERNAL_ID:
			if (!room.hasExternalId()) return null;
			return new Label(room.getExternalId());

		case TYPE:
			return new Label(room.getRoomType().getLabel());

		case CAPACITY:
			if (room.getCapacity() == null) return null;
			return new IntegerCell(room.getCapacity());

		case EXAM_CAPACITY:
			if (room.getExamCapacity() == null) return null;
			return new IntegerCell(room.getExamCapacity());

		case AREA:
			if (room.getArea() == null) return null;
			return new RoomAreaCell(room.getArea());

		case COORDINATES:
			if (!room.hasCoordinates()) return null;
			return new Label(MESSAGES.coordinates(room.getX(), room.getY()));

		case DISTANCE_CHECK:
			Image dc = new Image(!room.isIgnoreTooFar() ? RESOURCES.on() : RESOURCES.off());
			dc.setTitle(!room.isIgnoreTooFar() ? MESSAGES.infoDistanceCheckOn() : MESSAGES.infoDistanceCheckOff());
			return dc;

		case ROOM_CHECK:
			Image rc = new Image(!room.isIgnoreRoomCheck() ? RESOURCES.on() : RESOURCES.off());
			rc.setTitle(!room.isIgnoreRoomCheck() ? MESSAGES.infoRoomCheckOn() : MESSAGES.infoRoomCheckOff());
			return rc;

		case PREFERENCE:
			boolean hasPreferences = false;
			for (DepartmentInterface department: room.getDepartments())
				if (department.getPreference() != null) {
					hasPreferences = true; break;
				}
			if (hasPreferences)
				return new PreferenceCell(room.getDepartments());
			else
				return null;

		case MAP:
			if (!room.hasMiniMapUrl()) return null;
			return new MapCell(room);

		case PICTURES:
			if (idx == 0) {
				return (room.hasPictures(null) ? new PicturesCell(room, null) : null);
			} else {
				AttachmentTypeInterface type = iProperties.getTableTypes().get(idx - 1);
				return (room.hasPictures(type) ? new PicturesCell(room, type) : null);
			}

		case AVAILABILITY:
			if (room.getAvailability() == null) return null;
			return new AvailabilityCell(room, false);

		case DEPARTMENTS:
			return new DepartmentCell(true, room.getDepartments(), room.getControlDepartment());

		case CONTROL_DEPT:
			return new DepartmentCell(true, room.getControlDepartment());

		case EXAM_TYPES:
			return new ExamTypesCell(room.getUniqueId(), room.getExamTypes());

		case PERIOD_PREF:
			if (room.getPeriodPreference() == null) return null;
			if (iDepartment != null && room.hasExamTypes())
				for (ExamTypeInterface type: room.getExamTypes())
					if (iDepartment.equals(type.getReference()))
						return new PeriodPreferenceCell(room, type);
			return null;

		case EVENT_DEPARTMENT:
			if (room.getEventDepartment() == null) return null;
			final DepartmentCell edc = new DepartmentCell(false, room.getEventDepartment());
			if (room.isCanSeeEventAvailability()) {
				edc.addMouseOverHandler(new MouseOverHandler() {
					@Override
					public void onMouseOver(MouseOverEvent event) {
						RoomSharingHint.showHint(edc.getElement(), room.getUniqueId(), true);
					}
				});
				edc.addMouseOutHandler(new MouseOutHandler() {
					@Override
					public void onMouseOut(MouseOutEvent event) {
						RoomSharingHint.hideHint();
					}
				});
			}
			return edc;

		case EVENT_STATUS:
			if (room.getEventStatus() != null || room.getDefaultEventStatus() != null)
				return new StatusCell(room.getEventStatus(), room.getDefaultEventStatus());
			else
				return null;

		case EVENT_AVAILABILITY:
			if (room.getEventAvailability() == null) return null;
			return new AvailabilityCell(room, true);

		case EVENT_MESSAGE:
			if (room.hasEventNote() || room.hasDefaultEventNote())
				return new NoteCell(room.getEventNote(), room.getDefaultEventNote());
			else
				return null;

		case BREAK_TIME:
			if (room.getBreakTime() != null || room.getDefaultBreakTime() != null)
				return new BreakTimeCell(room.getBreakTime(), room.getDefaultBreakTime());
			else
				return null;

		case GROUPS:
			if (room.getGroups().isEmpty()) return null;
			return new GroupsCell(room.getGroups());

		case FEATURES:
			if (idx == 0) {
				List<FeatureInterface> features = room.getFeatures((Long)null);
				if (features.isEmpty()) return null;
				return new FeaturesCell(features);
			} else {
				FeatureTypeInterface type = getFeatureType(idx - 1);
				List<FeatureInterface> featuresOfType = room.getFeatures(type);
				if (featuresOfType.isEmpty()) return null;
				return new FeaturesCell(featuresOfType);
			}
		}
		return null;
	}

	public int addRoom(final RoomDetailInterface room) {
		List<Widget> widgets = new ArrayList<Widget>();

		for (RoomsColumn column: RoomsColumn.values()) {
			int nbrCells = getNbrCells(column);
			for (int idx = 0; idx < nbrCells; idx ++) {
				Widget cell = getCell(room, column, idx);
				if (cell == null) {
					cell = new P();
				} else if (hasShowHideOperation(column)) {
					show(column, idx);
				}
				widgets.add(cell);
			}
		}

		int row = addRow(room, widgets);
		getRowFormatter().setStyleName(row, "row");
		for (int col = 0; col < getCellCount(row); col++)
			getCellFormatter().setStyleName(row, col, "cell");

		if (!isVisible()) setVisible(true);

		return row;
	}

	protected void resetVisibility() {
		for (RoomsColumn column: RoomsColumn.values()) {
			int nrCells = getNbrCells(column);
			int cellIdx = getCellIndex(column);
			for (int idx = 0; idx < nrCells; idx++) {
				final int colIdx = cellIdx + idx;
				setColumnVisible(colIdx, !hasShowHideOperation(column));
			}
		}
	}

	protected void show(RoomsColumn column, int idx) {
		int colIdx = getCellIndex(column) + idx;
		if (RoomCookie.getInstance().get(iMode, colIdx) && !isColumnVisible(colIdx)) setColumnVisible(colIdx, true);
		int flag = (1 << colIdx);
		if ((iFlags & flag) == 0)
			iFlags += flag;
	}

	@Override
	public void clearTable(int headerRows) {
		super.clearTable(headerRows);
		resetVisibility();
		iFlags = 0;
		setVisible(false);
	}

	public int getFlags() { return iFlags; }

	public boolean isVisible(RoomsColumn column) {
		return isColumnVisible(getCellIndex(column));
	}

	public static class IntegerCell extends Label implements UniTimeTable.HasCellAlignment, UniTimeTable.HasColSpan, TakesValue<Integer> {

		public IntegerCell(Integer value) {
			super();
			setValue(value);
		}

		@Override
		public void setValue(Integer value) {
			setText(value == null ? "" : value.toString());
		}

		@Override
		public Integer getValue() {
			return getText().isEmpty() ? null : new Integer(getText());
		}

		@Override
		public HorizontalAlignmentConstant getCellAlignment() {
			return HasHorizontalAlignment.ALIGN_RIGHT;
		}

		@Override
		public int getColSpan() {
			return 1;
		}
	}

	class RoomNameCell extends Label {
		RoomNameCell(final RoomDetailInterface room) {
			super(room.hasDisplayName() ? MESSAGES.label(room.getLabel(), room.getDisplayName()) : room.getLabel());
			addMouseOverHandler(new MouseOverHandler() {
				@Override
				public void onMouseOver(MouseOverEvent event) {
					RoomHint.showHint(RoomNameCell.this.getElement(), room.getUniqueId(), room.getPrefix(), room.getProperty("distance", null), true);
				}
			});
			addMouseOutHandler(new MouseOutHandler() {
				@Override
				public void onMouseOut(MouseOutEvent event) {
					RoomHint.hideHint();
				}
			});
			if (iDepartment != null && iProperties != null && iProperties.isCanSeeCourses()) {
				for (DepartmentInterface d: room.getDepartments()) {
					if (iDepartment.equals(d.getDeptCode()) && d.getPreference() != null) {
						getElement().getStyle().setColor(d.getPreference().getColor());
						room.setPrefix(d.getPreference().getName());
					}
				}
			}
		}
	}

	class SelectableRoomNameCell extends AriaCheckBox {
		SelectableRoomNameCell(final RoomDetailInterface room) {
			addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					event.stopPropagation();
				}
			});
			addValueChangeHandler(new ValueChangeHandler<Boolean>() {
				@Override
				public void onValueChange(ValueChangeEvent<Boolean> event) {
					setSelected(getRow(room), event.getValue());
				}
			});
			setText(room.hasDisplayName() ? MESSAGES.label(room.getLabel(), room.getDisplayName()) : room.getLabel());
			addMouseOverHandler(new MouseOverHandler() {
				@Override
				public void onMouseOver(MouseOverEvent event) {
					RoomHint.showHint(SelectableRoomNameCell.this.getElement(), room.getUniqueId(), room.getPrefix(), room.getProperty("distance", null), true);
				}
			});
			addMouseOutHandler(new MouseOutHandler() {
				@Override
				public void onMouseOut(MouseOutEvent event) {
					RoomHint.hideHint();
				}
			});
			if (iDepartment != null && iProperties != null && iProperties.isCanSeeCourses()) {
				for (DepartmentInterface d: room.getDepartments()) {
					if (iDepartment.equals(d.getDeptCode()) && d.getPreference() != null) {
						getElement().getStyle().setColor(d.getPreference().getColor());
						room.setPrefix(d.getPreference().getName());
					}
				}
			}
		}
	}

	public static class RoomAreaCell extends HTML implements UniTimeTable.HasCellAlignment {
		public RoomAreaCell(Double value) {
			super(value == null ? "" : MESSAGES.roomArea(value));
		}

		@Override
		public HorizontalAlignmentConstant getCellAlignment() {
			return HasHorizontalAlignment.ALIGN_RIGHT;
		}
	}

	public static class FeaturesCell extends P implements HasRefresh {
		Map<FeatureInterface, P> iFeatures = new HashMap<FeatureInterface, P>();

		public FeaturesCell(List<? extends FeatureInterface> features) {
			super();
			setStyleName("features");
			for (FeatureInterface feature: features) {
				P p = new P("feature");
				p.setText(feature.getLabel());
				if (feature.getTitle() != null) p.setTitle(feature.getTitle());
				if (feature.getDepartment() != null) {
					p.setText(feature.getLabel() + " (" + RoomsTable.toString(feature.getDepartment(), true) + ")");
					if (feature.getDepartment().getColor() != null)
						p.getElement().getStyle().setColor(feature.getDepartment().getColor());
				}
				iFeatures.put(feature, p);
				add(p);
			}
		}

		@Override
		public void refresh() {
			for (Map.Entry<FeatureInterface, P> e: iFeatures.entrySet()) {
				P p = e.getValue();
				FeatureInterface feature = e.getKey();
				if (feature.getDepartment() != null)
					p.setText(feature.getLabel() + " (" + RoomsTable.toString(feature.getDepartment(), true) + ")");
			}
		}
	}

	public static class GroupsCell extends P implements HasRefresh {
		Map<GroupInterface, P> iGroups = new HashMap<GroupInterface, P>();

		public GroupsCell(List<? extends GroupInterface> groups) {
			super();
			setStyleName("groups");
			for (GroupInterface group: groups) {
				P p = new P("group");
				p.setText(group.getLabel());
				if (group.getTitle() != null) p.setTitle(group.getTitle());
				if (group.getDepartment() != null) {
					p.setText(group.getLabel() + " (" + RoomsTable.toString(group.getDepartment(), true) + ")");
					if (group.getDepartment().getColor() != null)
						p.getElement().getStyle().setColor(group.getDepartment().getColor());
				}
				iGroups.put(group, p);
				add(p);
			}
		}

		@Override
		public void refresh() {
			for (Map.Entry<GroupInterface, P> e: iGroups.entrySet()) {
				P p = e.getValue();
				GroupInterface group = e.getKey();
				if (group.getDepartment() != null)
					p.setText(group.getLabel() + " (" + RoomsTable.toString(group.getDepartment(), true) + ")");
			}
		}
	}

	public static class NoteCell extends P {
		public NoteCell(String note, String defaultNote) {
			super("note");
			if (note != null) {
				setHTML(note.replace("\\n", "
"));
				setTitle(note);
			} else if (defaultNote != null) {
				addStyleName("default");
				setHTML(defaultNote.replace("\\n", "
"));
				setTitle(defaultNote);
			}
		}
	}

	public static class StatusCell extends P {
		public StatusCell(Integer status, Integer defaultStatus) {
			super("status");
			if (status != null) {
				setHTML(CONSTANTS.eventStatusAbbv()[status]);
				setTitle(CONSTANTS.eventStatusName()[status]);
			} else if (defaultStatus != null) {
				addStyleName("default");
				setText(CONSTANTS.eventStatusAbbv()[defaultStatus]);
				setTitle(CONSTANTS.eventStatusName()[defaultStatus]);
			} else {
				setHTML(CONSTANTS.eventStatusAbbv()[0]);
				setTitle(CONSTANTS.eventStatusName()[0]);
			}
		}
	}

	public static class BreakTimeCell extends P {
		public BreakTimeCell(Integer breakTime, Integer defaultBreakTime) {
			super("break");
			if (breakTime != null) {
				if (breakTime != 0)
					setText(breakTime.toString());
			} else if (defaultBreakTime != null) {
				addStyleName("default");
				if (defaultBreakTime != 0)
					setText(defaultBreakTime.toString());
			}
		}
	}

	public static String toString(DepartmentInterface d, boolean ext) {
		RoomCookie cookie = RoomCookie.getInstance();
		switch (DeptMode.values()[cookie.getDeptMode()]) {
		case ABBV:
			return ext ? d.getExtAbbreviationWhenExist() : d.getAbbreviationOrCode();
		case CODE:
			return d.getDeptCode();
		case ABBV_NAME:
			return ext ? d.getExtAbbreviationWhenExist() + " - " + d.getExtLabelWhenExist() : d.getAbbreviationOrCode() + " - " + d.getLabel();
		case CODE_NAME:
			return ext ? d.getDeptCode() + " - " + d.getExtLabelWhenExist() : d.getDeptCode() + " - " + d.getLabel();
		case NAME:
			return ext ? d.getExtLabelWhenExist() : d.getLabel();
		default:
			return d.getDeptCode();
		}
	}

	public static class DepartmentCell extends P implements HasRefresh {
		boolean iExt;
		Map<DepartmentInterface, P> iP = new HashMap<DepartmentInterface, P>();

		public DepartmentCell(boolean ext, DepartmentInterface... departments) {
			super("departments");
			iExt = ext;
			for (DepartmentInterface department: departments) {
				if (department == null) continue;
				P p = new P("department");
				p.setText(RoomsTable.toString(department, iExt));
				if (department.getTitle() != null) p.setTitle(department.getTitle());
				if (department.getColor() != null)
					p.getElement().getStyle().setColor(department.getColor());
				add(p);
				iP.put(department, p);
			}
		}

		public DepartmentCell(boolean ext, List<DepartmentInterface> departments, DepartmentInterface control) {
			super("departments");
			iExt = ext;
			for (DepartmentInterface department: departments) {
				P p = new P("department");
				p.setText(RoomsTable.toString(department, iExt));
				if (department.getTitle() != null) p.setTitle(department.getTitle());
				if (department.getColor() != null)
					p.getElement().getStyle().setColor(department.getColor());
				if (department.equals(control))
					p.addStyleName("control");
				iP.put(department, p);
				add(p);
			}
		}

		@Override
		public void refresh() {
			for (Map.Entry<DepartmentInterface, P> e: iP.entrySet())
				e.getValue().setText(RoomsTable.toString(e.getKey(), iExt));
		}
	}

	public static class PreferenceCell extends DepartmentCell {
		public PreferenceCell(List<DepartmentInterface> departments) {
			super(true);
			for (DepartmentInterface department: departments) {
				if (department.getPreference() == null) continue;
				P p = new P("department");
				p.setText(RoomsTable.toString(department, iExt));
				p.setTitle(department.getPreference().getName() + " " + department.getLabel());
				p.getElement().getStyle().setColor(department.getPreference().getColor());
				iP.put(department, p);
				add(p);
			}
		}
	}

	public static class ExamTypesCell extends P {
		public ExamTypesCell(final Long roomId, List<ExamTypeInterface> examTypes) {
			super("exam-types");
			for (final ExamTypeInterface examType: examTypes) {
				final P p = new P(examType.isFinal() ? "final" : "midterm");
				p.setText(examType.getLabel());
				p.addMouseOverHandler(new MouseOverHandler() {
					@Override
					public void onMouseOver(MouseOverEvent event) {
						PeriodPreferencesHint.showHint(p.getElement(), roomId, examType.getId());
					}
				});
				p.addMouseOutHandler(new MouseOutHandler() {
					@Override
					public void onMouseOut(MouseOutEvent event) {
						PeriodPreferencesHint.hideHint();
					}
				});
				add(p);
			}
		}
	}

	public static class RoomCell extends Label {
		public RoomCell(RoomPropertyInterface property) {
			super(property == null ? "" : property.getLabel());
			if (property != null) {
				if (property.getTitle() != null)
					setTitle(property.getTitle());
				if (property.getColor() != null)
					getElement().getStyle().setColor(property.getColor());
			}
		}
	}

	public static class PictureCell extends Image {
		public PictureCell(RoomPictureInterface picture) {
			super();
			setStyleName("picture");
			setUrl(GWT.getHostPageBaseURL() + "picture?id=" + picture.getUniqueId());
			setTitle(picture.getName() + (picture.getPictureType() == null ? "" : " (" + picture.getPictureType().getLabel() + ")"));
			setAltText(picture.getName() + (picture.getPictureType() == null ? "" : " (" + picture.getPictureType().getAbbreviation() + ")"));
		}
	}

	public static class LinkCell extends ImageLink {
		LinkCell(RoomPictureInterface picture) {
			super(new Image(RESOURCES.download()), GWT.getHostPageBaseURL() + "picture?id=" + picture.getUniqueId());
			setStyleName("link");
			setTitle(picture.getName() + (picture.getPictureType() == null ? "" : " (" + picture.getPictureType().getLabel() + ")"));
			setText(picture.getName() + (picture.getPictureType() == null ? "" : " (" + picture.getPictureType().getAbbreviation() + ")"));
	        setTarget("_blank");
	        sinkEvents(Event.ONCLICK);
	    }

		@Override
	    public void onBrowserEvent(Event event) {
	        if(event.getTypeInt() == Event.ONCLICK) {
	        	event.stopPropagation();
	        }
	        super.onBrowserEvent(event);
	    }
	}

	public static class PicturesCell extends P {
		public PicturesCell(RoomDetailInterface room) {
			super("pictures");
			if (room.hasTablePictures()) {
				for (RoomPictureInterface picture: room.getTablePictures())
					add(picture.getPictureType() == null || picture.getPictureType().isImage() ? new PictureCell(picture) : new LinkCell(picture));
			}
		}
		public PicturesCell(RoomDetailInterface room, AttachmentTypeInterface type) {
			super("pictures");
			if (room.hasPictures(type)) {
				for (RoomPictureInterface picture: room.getPictures(type))
					add(picture.getPictureType() == null || picture.getPictureType().isImage() ? new PictureCell(picture) : new LinkCell(picture));
			}
		}
	}

	public static class MapCell extends Image {
		public MapCell(RoomDetailInterface room) {
			super();
			if (room.hasMiniMapUrl()) {
				setStyleName("map");
				setUrl(room.getMiniMapUrl());
				setTitle(MESSAGES.titleRoomMap(room.getLabel()));
			}
		}
	}

	public static class AvailabilityCell extends P implements HasRefresh {
		private boolean iEvents;
		private RoomDetailInterface iRoom;

		public AvailabilityCell(RoomDetailInterface room, boolean events) {
			super("availability");
			iRoom = room;
			iEvents = events;
			addMouseOverHandler(new MouseOverHandler() {
				@Override
				public void onMouseOver(MouseOverEvent event) {
					RoomSharingHint.showHint(getElement(), iRoom.getUniqueId(), iEvents);
				}
			});
			addMouseOutHandler(new MouseOutHandler() {
				@Override
				public void onMouseOut(MouseOutEvent event) {
					RoomSharingHint.hideHint();
				}
			});
			refresh();
		}

		@Override
		public void refresh() {
			clear(); setHTML("");
			RoomCookie cookie = RoomCookie.getInstance();
			if (iEvents) {
				if (cookie.isGridAsText()) {
					if (iRoom.getEventAvailability() != null) {
						P p = new P("text");
						p.setHTML(iRoom.getEventAvailability());
						add(p);
					}
				} else {
					Image availability = new Image(GWT.getHostPageBaseURL() + "pattern?loc=" + iRoom.getUniqueId() + "&e=1&v=" + (cookie.areRoomsHorizontal() ? "0" : "1") + (cookie.hasMode() ? "&s=" + cookie.getMode() : ""));
					availability.setStyleName("grid");
					add(availability);
				}
			} else {
				if (cookie.isGridAsText()) {
					if (iRoom.getAvailability() != null && !iRoom.getAvailability().isEmpty()) {
						P p = new P("text");
						p.setHTML(iRoom.getAvailability());
						add(p);
					}
				} else {
					Image availability = new Image(GWT.getHostPageBaseURL() + "pattern?loc=" + iRoom.getUniqueId() + "&v=" + (cookie.areRoomsHorizontal() ? "0" : "1") + (cookie.hasMode() ? "&s=" + cookie.getMode() : ""));
					availability.setStyleName("grid");
					add(availability);
				}
				if (iRoom.getRoomSharingNote() != null && !iRoom.getRoomSharingNote().isEmpty()) {
					P p = new P("note");
					p.setHTML(iRoom.getRoomSharingNote());
					p.setTitle(iRoom.getRoomSharingNote());
					add(p);
				}
			}
		}
	}

	public static class PeriodPreferenceCell extends P implements HasRefresh {
		private RoomDetailInterface iRoom;
		private ExamTypeInterface iType;

		public PeriodPreferenceCell(RoomDetailInterface room, ExamTypeInterface type) {
			super("periodpref");
			iRoom = room; iType = type;
			addMouseOverHandler(new MouseOverHandler() {
				@Override
				public void onMouseOver(MouseOverEvent event) {
					PeriodPreferencesHint.showHint(getElement(), iRoom.getUniqueId(), iType.getId());
				}
			});
			addMouseOutHandler(new MouseOutHandler() {
				@Override
				public void onMouseOut(MouseOutEvent event) {
					RoomSharingHint.hideHint();
				}
			});
			refresh();
		}

		@Override
		public void refresh() {
			clear(); setHTML("");
			RoomCookie cookie = RoomCookie.getInstance();
			if (cookie.isGridAsText() || !iType.isFinal()) {
				if (iRoom.getPeriodPreference() != null)
					setHTML(iRoom.getPeriodPreference());
			} else {
				add(new Image(GWT.getHostPageBaseURL() + "pattern?loc=" + iRoom.getUniqueId() + "&xt=" + iType.getId() +
						"&v=" + (cookie.areRoomsHorizontal() ? "0" : "1") + (cookie.hasMode() ? "&s=" + cookie.getMode() : "")));
			}
		}
	}

	public interface Check {
		public boolean isChecked();
	}

	public static enum DeptMode {
		CODE(MESSAGES.fieldCode()),
		ABBV(MESSAGES.fieldAbbreviation()),
		NAME(MESSAGES.fieldName()),
		ABBV_NAME(MESSAGES.fieldAbbv() + " - " + MESSAGES.fieldName()),
		CODE_NAME(MESSAGES.fieldCode() + " - " + MESSAGES.fieldName());

		private String iName;

		DeptMode(String name) { iName = name; }

		public String getName() { return iName; }
	}

	public static interface SortOperation extends Operation, HasColumnName {}

	public static interface HasRefresh {
		public void refresh();
	}

	public RoomDetailInterface getRoom(Long roomId) {
		if (roomId == null) return null;
		for (int i = 1; i < getRowCount(); i++) {
			if (roomId.equals(getData(i).getUniqueId())) return getData(i);
		}
		return null;
	}

	public void scrollTo(Long roomId) {
		if (roomId == null) return;
		for (int i = 1; i < getRowCount(); i++) {
			if (roomId.equals(getData(i).getUniqueId())) {
				ToolBox.scrollToElement(getRowFormatter().getElement(i));
			}
		}
	}

	public RoomDetailInterface getPrevious(Long roomId) {
		if (roomId == null) return null;
		for (int i = 2; i < getRowCount(); i++) {
			if (roomId.equals(getData(i).getUniqueId()))
				return getData(i - 1);
		}
		return null;
	}

	public RoomDetailInterface getNext(Long roomId) {
		if (roomId == null) return null;
		for (int i = 1; i < getRowCount() - 1; i++) {
			if (roomId.equals(getData(i).getUniqueId()))
				return getData(i + 1);
		}
		return null;
	}

	public Boolean isRoomSelected(int row) {
		Widget w = getWidget(row, 0);
		if (w != null && w instanceof CheckBox) {
			return ((CheckBox)w).getValue();
		} else {
			return null;
		}
	}

	public boolean isRoomSelected(RoomDetailInterface room) {
		if (!iSelectable) return false;
		for (int row = 1; row < getRowCount(); row++ ) {
			if (getData(row).getUniqueId().equals(room.getUniqueId()))
				return isRoomSelected(row);
		}
		return false;
	}

	public int getRow(RoomDetailInterface room) {
		for (int row = 1; row < getRowCount(); row++ )
			if (getData(row).getUniqueId().equals(room.getUniqueId()))
				return row;
		return -1;
	}

	public void selectRoom(RoomDetailInterface room, boolean value) {
		if (!iSelectable) return;
		for (int row = 1; row < getRowCount(); row++ ) {
			if (getData(row).getUniqueId().equals(room.getUniqueId())) {
				selectRoom(row, value);
				break;
			}
		}
	}

	public void selectRoom(int row, boolean value) {
		Widget w = getWidget(row, 0);
		if (w != null && w instanceof CheckBox) {
			((CheckBox)w).setValue(value);
		}
	}

	public CheckBox getRoomSelection(int row) {
		Widget w = getWidget(row, 0);
		if (w != null && w instanceof CheckBox) {
			return (CheckBox)w;
		} else {
			return null;
		}
	}
}


text:
using blink::mojom::PermissionDescriptorPtr;
using blink::mojom::PermissionName;
using blink::mojom::PermissionStatus;

namespace content {

const std::vector<PermissionType>& GetAllPermissionTypes() {
  static const base::NoDestructor<std::vector<PermissionType>>
      kAllPermissionTypes([] {
        const int NUM_TYPES = static_cast<int>(PermissionType::NUM);
        std::vector<PermissionType> all_types;
        all_types.reserve(NUM_TYPES - 4);
        for (int i = 1; i < NUM_TYPES; ++i) {
          // Skip removed entries.
          if (i == 2 || i == 11 || i == 14 || i == 15 || i == 32)
            continue;
          all_types.push_back(static_cast<PermissionType>(i));
        }
        return all_types;
      }());
  return *kAllPermissionTypes;
}

absl::optional<PermissionType> PermissionDescriptorToPermissionType(
    const PermissionDescriptorPtr& descriptor) {
  switch (descriptor->name) {
    case PermissionName::GEOLOCATION:
      return PermissionType::GEOLOCATION;
    case PermissionName::NOTIFICATIONS:
      return PermissionType::NOTIFICATIONS;
    case PermissionName::MIDI: {
      if (descriptor->extension && descriptor->extension->is_midi() &&
          descriptor->extension->get_midi()->sysex) {
        return PermissionType::MIDI_SYSEX;
      }
      return PermissionType::MIDI;
    }
    case PermissionName::PROTECTED_MEDIA_IDENTIFIER:
#if defined(ENABLE_PROTECTED_MEDIA_IDENTIFIER_PERMISSION)
      return PermissionType::PROTECTED_MEDIA_IDENTIFIER;
#else
      NOTIMPLEMENTED();
      return absl::nullopt;
#endif  // defined(ENABLE_PROTECTED_MEDIA_IDENTIFIER_PERMISSION)
    case PermissionName::DURABLE_STORAGE:
      return PermissionType::DURABLE_STORAGE;
    case PermissionName::AUDIO_CAPTURE:
      return PermissionType::AUDIO_CAPTURE;
    case PermissionName::VIDEO_CAPTURE:
      if (descriptor->extension && descriptor->extension->is_camera_device() &&
          descriptor->extension->get_camera_device()->panTiltZoom) {
        return PermissionType::CAMERA_PAN_TILT_ZOOM;
      } else {
        return PermissionType::VIDEO_CAPTURE;
      }
    case PermissionName::BACKGROUND_SYNC:
      return PermissionType::BACKGROUND_SYNC;
    case PermissionName::SENSORS:
      return PermissionType::SENSORS;
    case PermissionName::ACCESSIBILITY_EVENTS:
      return PermissionType::ACCESSIBILITY_EVENTS;
    case PermissionName::CLIPBOARD_READ:
      return PermissionType::CLIPBOARD_READ_WRITE;
    case PermissionName::CLIPBOARD_WRITE: {
      if (descriptor->extension && descriptor->extension->is_clipboard() &&
          descriptor->extension->get_clipboard()->allowWithoutSanitization) {
        return PermissionType::CLIPBOARD_READ_WRITE;
      } else {
        return PermissionType::CLIPBOARD_SANITIZED_WRITE;
      }
    }
    case PermissionName::PAYMENT_HANDLER:
      return PermissionType::PAYMENT_HANDLER;
    case PermissionName::BACKGROUND_FETCH:
      return PermissionType::BACKGROUND_FETCH;
    case PermissionName::IDLE_DETECTION:
      return PermissionType::IDLE_DETECTION;
    case PermissionName::PERIODIC_BACKGROUND_SYNC:
      return PermissionType::PERIODIC_BACKGROUND_SYNC;
    case PermissionName::SCREEN_WAKE_LOCK:
      return PermissionType::WAKE_LOCK_SCREEN;
    case PermissionName::SYSTEM_WAKE_LOCK:
      return PermissionType::WAKE_LOCK_SYSTEM;
    case PermissionName::NFC:
      return PermissionType::NFC;
    case PermissionName::STORAGE_ACCESS:
      return PermissionType::STORAGE_ACCESS_GRANT;
    case PermissionName::WINDOW_PLACEMENT:
      return PermissionType::WINDOW_PLACEMENT;
    case PermissionName::FONT_ACCESS:
      return PermissionType::FONT_ACCESS;
    case PermissionName::DISPLAY_CAPTURE:
      return PermissionType::DISPLAY_CAPTURE;
  }

  NOTREACHED();
  return absl::nullopt;
}

}  // namespace content


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<meta name="description" content="The Page Description">

		<title>Beetle - Works 3 Columns</title>
		<link rel="stylesheet" href="css/layers.min.css" media="screen">
		<link rel="stylesheet" href="css/font-awesome.min.css" media="screen">
		<link rel="stylesheet" href="style.css" media="screen">
		<link href='http://fonts.googleapis.com/css?family=Montserrat:400,700|Open+Sans:400italic,700italic,400,700' rel='stylesheet' type='text/css'>

		<link rel="icon" href="favicon.ico">
		<link rel="apple-touch-icon" href="img/apple-touch-icon.png">
		<link rel="apple-touch-icon" sizes="76x76" href="img/apple-touch-icon-76x76.png">
		<link rel="apple-touch-icon" sizes="120x120" href="img/apple-touch-icon-120x120.png">
		<link rel="apple-touch-icon" sizes="152x152" href="img/apple-touch-icon-152x152.png">

Beetle

								Home

Generic Home Page

App Showcase

App Showcase Alternative

								Works

Four Columns Grid Style

Three Columns Grid Style

Four Columns Mosaic Style

Three Columns Mosaic Style

Lightbox Gallery

Single Work Page

								Blog

Four Columns Grid

List Style with Sidebar

Single Post

Single Post with Sidebar

Resume

								Features

Search Page

Search Page - No Results

404 - Page Not Found

										Sub Menu

Sub Sub Menu 01

Sub Sub Menu 02

Sub Sub Menu 03

Contact

The Lonely Lab

If you're any good at all, you know you can be better.

Advertising

Fun

Icons

Infographics

Lightbox

Minimal

Web design

Taj Mahal

Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Coffe addiction

Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Green Technology

Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Essentials

Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

If the music is too low

Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Sim World

Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Code School

Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Stamps

Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Summer camp

Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Holiday Gift Guide

Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Telephone love

Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

To resolve 2014

Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Older

Newer

Menu

Home

Portfolio

Blog

Resume

Contact

Archives

March 2014

April 2014

May 2014

June 2014

July 2014

Widget

Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.

Follow Us

© 2014 Mokaine. All Rights Reserved.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod.


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

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import com.twitter.heron.proto.scheduler.Scheduler;
import com.twitter.heron.spi.common.Config;
import com.twitter.heron.spi.scheduler.IScheduler;
import com.twitter.heron.spi.utils.NetworkUtils;
import com.twitter.heron.spi.utils.Runtime;
import com.twitter.heron.spi.utils.SchedulerUtils;

/**
 * {@code HttpHandler} decorator that returns an OK response unless an exception is caught, in
 * which case a NOTOK response is returned. If the delegate throws a
 * {@code TerminateSchedulerException}, the scheduler will be terminated after the response is
 * handled.
 */
class ExceptionalRequestHandler implements HttpHandler {
  private static final Logger LOG = Logger.getLogger(ExceptionalRequestHandler.class.getName());
  private HttpHandler delegate;
  private Config runtime;
  private IScheduler scheduler;

  ExceptionalRequestHandler(HttpHandler delegate, Config runtime, IScheduler scheduler) {
    this.delegate = delegate;
    this.runtime = runtime;
    this.scheduler = scheduler;
  }

  @SuppressWarnings("IllegalCatch")
  @Override
  public void handle(HttpExchange exchange) throws IOException {

    try {
      delegate.handle(exchange);
      sendResponse(exchange, true);
    } catch (TerminateSchedulerException e) {
      sendResponse(exchange, true);

      // tell the scheduler to shutdown
      LOG.info("Request handler issuing a terminate request to scheduler");
      try {
        scheduler.close();
      } finally {
        Runtime.schedulerShutdown(runtime).terminate();
      }
    } catch (Exception e) {
      handleFailure(exchange, e);
    }
  }

  private static void handleFailure(HttpExchange exchange, Exception e) {
    LOG.log(Level.SEVERE,
        String.format("Failed to handle %s request", exchange.getRequestURI()), e);
    sendResponse(exchange, false);
  }

  private static void sendResponse(HttpExchange exchange, boolean success) {
    Scheduler.SchedulerResponse response = SchedulerUtils.constructSchedulerResponse(success);
    NetworkUtils.sendHttpResponse(exchange, response.toByteArray());
  }
}


text:
namespace Microsoft.Azure.Management.ApiManagement.Models
{
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Parameters to update or create an Api Version Set Contract.
    /// </summary>
    [Rest.Serialization.JsonTransformation]
    public partial class ApiVersionSetUpdateParameters
    {
        /// <summary>
        /// Initializes a new instance of the ApiVersionSetUpdateParameters
        /// class.
        /// </summary>
        public ApiVersionSetUpdateParameters()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the ApiVersionSetUpdateParameters
        /// class.
        /// </summary>
        /// <param name="description">Description of API Version Set.</param>
        /// <param name="versionQueryName">Name of query parameter that
        /// indicates the API Version if versioningScheme is set to
        /// `query`.</param>
        /// <param name="versionHeaderName">Name of HTTP header parameter that
        /// indicates the API Version if versioningScheme is set to
        /// `header`.</param>
        /// <param name="displayName">Name of API Version Set</param>
        /// <param name="versioningScheme">An value that determines where the
        /// API Version identifer will be located in a HTTP request. Possible
        /// values include: 'Segment', 'Query', 'Header'</param>
        public ApiVersionSetUpdateParameters(string description = default(string), string versionQueryName = default(string), string versionHeaderName = default(string), string displayName = default(string), string versioningScheme = default(string))
        {
            Description = description;
            VersionQueryName = versionQueryName;
            VersionHeaderName = versionHeaderName;
            DisplayName = displayName;
            VersioningScheme = versioningScheme;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets description of API Version Set.
        /// </summary>
        [JsonProperty(PropertyName = "properties.description")]
        public string Description { get; set; }

        /// <summary>
        /// Gets or sets name of query parameter that indicates the API Version
        /// if versioningScheme is set to `query`.
        /// </summary>
        [JsonProperty(PropertyName = "properties.versionQueryName")]
        public string VersionQueryName { get; set; }

        /// <summary>
        /// Gets or sets name of HTTP header parameter that indicates the API
        /// Version if versioningScheme is set to `header`.
        /// </summary>
        [JsonProperty(PropertyName = "properties.versionHeaderName")]
        public string VersionHeaderName { get; set; }

        /// <summary>
        /// Gets or sets name of API Version Set
        /// </summary>
        [JsonProperty(PropertyName = "properties.displayName")]
        public string DisplayName { get; set; }

        /// <summary>
        /// Gets or sets an value that determines where the API Version
        /// identifer will be located in a HTTP request. Possible values
        /// include: 'Segment', 'Query', 'Header'
        /// </summary>
        [JsonProperty(PropertyName = "properties.versioningScheme")]
        public string VersioningScheme { get; set; }

    }
}


text:
{-# Language FlexibleContexts #-}

-- | Names specific to western music tradition
module Temporal.Music.Western(
    -- * Basic functions
    -- | All basic functions (composition, time stretching,
    -- dynamic changing of volume and pitch etc, etc) live in this module.
    module Temporal.Music,
    -- * Volume
    -- | Dynamics values form 9-level equally spaced grid.
    -- They are from quietest
    -- to loudest: piano pianissimo (ppp), pianissimo (pp), piano (p),
    -- mezzo piano (mp), mezzo forte (mf), forte (f), fortissimo (ff),
    -- forte fortissimo (fff).
    --  These modifiers change level relative to the current level.
    -- It means that
    --
    -- > piano . forte = id
    pppiano, ppiano, piano, mpiano, mforte, forte, fforte, ffforte,
    -- ** Shortcuts to set dynamics level.
    ppp', pp', p', mp', mf', f', ff', fff',

    -- ** Envelops
    dim, cresc,

    -- * Score
    rondo, reprise,

    -- * Tempo
    -- | Tempo terms specify not a rigid value but tempo range. So all
    -- terms are functions from relative power of term (it's value
    -- of type Double from 0 to 1) to some tempo value. Zero means
    -- the lowest value from tempo range and one means the highest value.
    -- To be used with 'bpm' function.
    Tempo,
	lento, largo, larghetto, grave, adagio, adagietto,
    andante, andantino, moderato, allegretto,
    allegro, vivace, presto, prestissimo
) where

import Temporal.Music

pppiano, ppiano, piano, mpiano, mforte, forte, fforte, ffforte ::
    (VolumeLike a) => Score a -> Score a

pppiano = quieter 4;    ppiano  = quieter 3;    piano   = quieter 2
mpiano  = quieter 1;    mforte  = louder 1;     forte   = louder 2;
fforte  = louder 3;     ffforte = louder 4;

ppp', pp', p', mp', mf', f', ff', fff' ::
    (VolumeLike a) => Score a -> Score a

ppp'    = pppiano;  pp'     = ppiano;   p'      = piano;
mp'     = mpiano;   mf'     = mforte;   f'      = forte;
ff'     = fforte;   fff'    = ffforte;

-- | diminuendo
dim :: VolumeLike a => Accent -> Score a -> Score a
dim = withAccent . (*) . negate

-- | crescendo
cresc :: VolumeLike a => Accent -> Score a -> Score a
cresc = withAccent . (*)

---------------------------------------
-- forms

-- | rondo form
--
-- >rondo a b c = mel [a, b, a, c, a]
rondo :: Score a -> Score a -> Score a -> Score a
rondo a b c = mel [a, b, a, c, a]

-- | reprise form
--
-- >reprise a b1 b2 = mel [a, b1, a, b2]
reprise :: Score a -> Score a -> Score a -> Score a
reprise a b c = mel [a, b, a, c]

---------------------------------------
-- tempo

type Tempo = Double

largoRange, larghettoRange,
	adagioRange, adagiettoRange,
    andanteRange, andantinoRange,
	moderatoRange, allegroRange,
    allegrettoRange, vivaceRange,
	prestoRange, prestissimoRange :: (Double, Double)

largoRange       = ( 40, 60)
larghettoRange   = ( 60, 66)
adagioRange      = ( 66, 76)
adagiettoRange   = ( 70, 80)
andanteRange     = ( 76, 80)
andantinoRange   = ( 80,100)
moderatoRange    = (101,110)
allegrettoRange  = (115,125)
allegroRange     = (120,139)
vivaceRange      = (135,160)
prestoRange      = (168,200)
prestissimoRange = (200,230)

getTempo :: (Tempo, Tempo) -> Double -> Tempo
getTempo (a, b) x = a + (b - a) * x

-- | very slow (40-60 bpm), like largo
lento :: Double -> Tempo
lento       = largo

-- | very slow (40-60 bpm)
largo :: Double -> Tempo
largo       = getTempo largoRange

-- | rather broadly (60-66 bpm)
larghetto :: Double -> Tempo
larghetto   = getTempo larghettoRange

-- | slow and sloemn (60 - 66 bpm)
grave :: Double -> Tempo
grave = larghetto

-- | slow and stately (literally "at ease") (66-76 bpm)
adagio :: Double -> Tempo
adagio      = getTempo adagioRange

-- | rather slow (70-80 bpm)
adagietto :: Double -> Tempo
adagietto = getTempo adagiettoRange

-- | at awalking pace (76-80 bpm)
andante :: Double -> Tempo
andante     = getTempo andanteRange

-- | slightly faster then andante (80-100 bpm)
andantino :: Double -> Tempo
andantino     = getTempo andantinoRange

-- | moderately (101-110 bpm)
moderato :: Double -> Tempo
moderato    = getTempo moderatoRange

-- | moderately fast (115-125 bpm)
allegretto :: Double -> Tempo
allegretto     = getTempo allegrettoRange

-- | fast, at 'march tempo' (120-139 bpm)
allegro :: Double -> Tempo
allegro     = getTempo allegroRange

-- | lively and fast (135-160 bpm)
vivace :: Double -> Tempo
vivace = getTempo vivaceRange

-- | very fast (168-200 bpm)
presto :: Double -> Tempo
presto      = getTempo prestoRange

-- | extremely fast (200 - 230 bpm)
prestissimo :: Double -> Tempo
prestissimo = getTempo prestissimoRange


text:
import Type from './types/type';
import BlockModel from './models/block';
import EmbedModel from './models/embed';
import Compiler from './compiler';
import HTMLParser from './parsers/html-parser';
import HTMLRenderer from './renderers/html-renderer';

/**
 * @namespace ContentKit
 * Register public ContentKit compiler modules
 */
var ContentKit = {};
ContentKit.Type = Type;
ContentKit.BlockModel = BlockModel;
ContentKit.EmbedModel = EmbedModel;
ContentKit.Compiler = Compiler;
ContentKit.HTMLParser = HTMLParser;
ContentKit.HTMLRenderer = HTMLRenderer;

export default ContentKit;


text:
module Pregame.Mtl
  ( module X
  , io
  ) where

import Control.Monad.Reader as X
  ( MonadReader
  , ask
  , reader
  , asks
  , ReaderT
  , runReaderT
  , mapReaderT
  , withReaderT
  , Reader
  , runReader
  , mapReader
  , withReader
  )
import Control.Monad.State as X
  ( MonadState
  , get
  , put
  , state
  , modify
  , modify'
  , gets
  , StateT
  , runStateT
  , evalStateT
  , execStateT
  , mapStateT
  , withStateT
  , State
  , runState
  , evalState
  , execState
  , mapState
  , withState
  )
import Control.Monad.Writer as X
  ( MonadWriter
  , writer
  , tell
  , WriterT
  , runWriterT
  , execWriterT
  , mapWriterT
  , Writer
  , runWriter
  , execWriter
  , mapWriter
  )
import Control.Monad.RWS as X
  ( MonadRWS
  , RWST
  , runRWST
  , evalRWST
  , execRWST
  , mapRWST
  , withRWST
  , RWS
  , rws
  , runRWS
  , evalRWS
  , execRWS
  , mapRWS
  , withRWS
  )
import Control.Monad.Trans as X
  ( MonadTrans
  , lift
  , MonadIO
  , liftIO
  )
import Control.Monad.List as X
  ( ListT
  , runListT
  , mapListT
  )
import Control.Monad.Except as X
  ( MonadError
  , throwError
  , catchError
  , ExceptT
  , runExceptT
  , mapExceptT
  , withExceptT
  , Except
  , runExcept
  , mapExcept
  , withExcept
  )
import Control.Monad.Cont as X
  ( MonadCont
  , callCC
  , ContT
  , runContT
  , mapContT
  , withContT
  , Cont
  , cont
  , runCont
  , mapCont
  , withCont
  )
import Pregame.GhcPrim

io :: MonadIO m => IO a -> m a
io = liftIO


text:
<input autocomplete="off"
                                                                          ng-model="query"
                                                                          ng-keyup="keyUp($event)"
                                                                          ng-keydown="keyDown($event)"/>


text:
<!----------------------------------------------------------------->
<!-- AUTOMATICALLY GENERATED CODE - PLEASE EDIT TEMPLATE INSTEAD -->
<!----------------------------------------------------------------->
<div id="chartContainer">
  <script src="/lib/d3.v3.4.8.js"></script>
  <script src="/dist/dimple.v2.1.3.js"></script>
  <script type="text/javascript">
    var svg = dimple.newSvg("#chartContainer", 590, 400);
    d3.tsv("/data/example_data.tsv", function (data) {

      // Get a unique list of dates
      var months = dimple.getUniqueValues(data, "Date");

      // Set the bounds for the charts
      var row = 0,
          col = 0,
          top = 25,
          left = 60,
          inMarg = 15,
          width = 115,
          height = 90,
          totalWidth = parseFloat(svg.attr("width"));

      // Pick the latest 12 dates
      months = months.slice(months.length - 12);

      // Draw a chart for each of the 12 dates
      months.forEach(function (month) {

          // Wrap to the row above
          if (left + ((col + 1) * (width + inMarg)) > totalWidth) {
            row += 1;
            col = 0;
          }

          // Filter for the month in the iteration
          var chartData = dimple.filterData(data, "Date", month);

          // Use d3 to draw a text label for the month
          svg
            .append("text")
                .attr("x", left + (col * (width + inMarg)) + (width / 2))
                .attr("y", top + (row * (height + inMarg)) + (height / 2) + 12)
                .style("font-family", "sans-serif")
                .style("text-anchor", "middle")
                .style("font-size", "28px")
                .style("opacity", 0.2)
                .text(chartData[0].Month.substring(0, 3));

          // Create a chart at the correct point in the trellis
          var myChart = new dimple.chart(svg, chartData);
          myChart.setBounds(
            left + (col * (width + inMarg)),
            top + (row * (height + inMarg)),
            width,
            height);

          // Add x and fix ordering so that all charts are the same
          var x = myChart.addCategoryAxis("x", "Owner");
          x.addOrderRule(["Black Mesa", "Aperture", "Tyrell Corp",
            "Rekall", "MomCorp", "LexCorp", "Stark Ind", "Wayne Ent"]);

          // Add y and fix scale so that all charts are the same
          var y = myChart.addMeasureAxis("y", "Sales Value");
          y.overrideMax = 16000000;

          // Draw the bars.  Passing null here would draw all bars with
          // the same color.  Passing owner second colors by owner, which
          // is normally bad practice in a bar chart but works in a trellis.
          // Month is only passed here so that it shows in the tooltip.
          myChart.addSeries(["Month", "Owner"], dimple.plot.bar);

          // Draw the chart
          myChart.draw();

          // Once drawn we can access the shapes
          // If this is not in the first column remove the y text
          if (col > 0) {
            y.shapes.selectAll("text").remove();
          }
          // If this is not in the last row remove the x text
          if (row < 2) {
             x.shapes.selectAll("text").remove();
          }
          // Remove the axis labels
          y.titleShape.remove();
          x.titleShape.remove();

          // Move to the next column
          col += 1;

      }, this);
    });
  </script>
</div>


text:
require 'spree_core'
require 'spree_appa/engine'


text:
function file = getDefaultDataFile( obj )
% GETDEFAULTDATAFILE Get default data files of nlsaComponent object
%
% Modified 2014/04/06

file = getDefaultFile( getDataFilelist( obj ), getPartition( obj ), 'dataX' );


text:
package com.palantir.atlasdb.keyvalue.impl;

import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.palantir.atlasdb.AtlasDbConstants;
import com.palantir.atlasdb.keyvalue.api.Cell;
import com.palantir.atlasdb.keyvalue.api.ColumnSelection;
import com.palantir.atlasdb.keyvalue.api.KeyAlreadyExistsException;
import com.palantir.atlasdb.keyvalue.api.KeyValueService;
import com.palantir.atlasdb.keyvalue.api.RangeRequest;
import com.palantir.atlasdb.keyvalue.api.RowResult;
import com.palantir.atlasdb.keyvalue.api.TableReference;
import com.palantir.atlasdb.keyvalue.api.Value;
import com.palantir.atlasdb.transaction.impl.TransactionConstants;
import com.palantir.util.paging.TokenBackedBasicResultsPage;

/**
 * This wrapper KVS should ensure that we're consistent across KVSs with:
 *   - How we apply tricks to avoid work when people make fairly stupid queries
 *     (i.e. call out to the database to read in nothing, etc)
 *   - How we validate query inputs for sanity / correctness
 *   - Not having a ton of boilerplate
 *
 * @author clockfort
 */
public class ValidatingQueryRewritingKeyValueService extends ForwardingKeyValueService implements KeyValueService {
    private static final Logger log = LoggerFactory.getLogger(ValidatingQueryRewritingKeyValueService.class);
    private static String TRANSACTION_ERROR = "shouldn't be putting into the transaction table at this level of KVS abstraction";

    public static ValidatingQueryRewritingKeyValueService create(KeyValueService delegate) {
        return new ValidatingQueryRewritingKeyValueService(delegate);
    }

    private final KeyValueService delegate;

    protected ValidatingQueryRewritingKeyValueService(KeyValueService delegate) {
        this.delegate = delegate;
    }

    @Override
    protected KeyValueService delegate() {
        return delegate;
    }

    @Override
    public void createTable(TableReference tableRef, byte[] tableMetadata) {
        sanityCheckTableName(tableRef);
        delegate.createTable(tableRef, tableMetadata);
    }

    @Override
    public void createTables(Map<TableReference, byte[]> tableRefToTableMetadata) {
        if (tableRefToTableMetadata.isEmpty()) {
            return;
        }
        if (tableRefToTableMetadata.size() == 1) {
            Entry<TableReference, byte[]> element = Iterables.getOnlyElement(tableRefToTableMetadata.entrySet());
            createTable(element.getKey(), element.getValue());
            return;
        }
        for (TableReference tableRef : tableRefToTableMetadata.keySet()) {
            sanityCheckTableName(tableRef);
        }
        delegate.createTables(tableRefToTableMetadata);
    }

    protected void sanityCheckTableName(TableReference tableRef) {
        String tableName = tableRef.getQualifiedName();
        Validate.isTrue(
                (!tableName.startsWith("_") && tableName.contains("."))
                        || AtlasDbConstants.hiddenTables.contains(tableRef)
                        || tableName.startsWith(AtlasDbConstants.NAMESPACE_PREFIX),
                "invalid tableName: " + tableName);
    }

    @Override
    public void delete(TableReference tableRef, Multimap<Cell, Long> keys) {
        if (keys.isEmpty()) {
            return;
        }
        delegate.delete(tableRef, keys);
    }

    @Override
    public Map<Cell, Value> get(TableReference tableRef, Map<Cell, Long> timestampByCell) {
        if (timestampByCell.isEmpty()) {
            return ImmutableMap.of();
        }
        return delegate.get(tableRef, timestampByCell);
    }

    @Override
    public Multimap<Cell, Long> getAllTimestamps(TableReference tableRef, Set<Cell> cells, long timestamp) {
        if (cells.isEmpty()) {
            return ImmutableSetMultimap.of();
        } else {
            return delegate.getAllTimestamps(tableRef, cells, timestamp);
        }
    }

    @Override
    public Collection<? extends KeyValueService> getDelegates() {
        return ImmutableList.of(delegate);
    }

    @Override
    public Map<RangeRequest, TokenBackedBasicResultsPage<RowResult<Value>, byte[]>> getFirstBatchForRanges(TableReference tableRef, Iterable<RangeRequest> rangeRequests, long timestamp) {
        if (Iterables.isEmpty(rangeRequests)) {
            return ImmutableMap.of();
        }
        return delegate.getFirstBatchForRanges(tableRef, rangeRequests, timestamp);
    }

    @Override
    public Map<Cell, Long> getLatestTimestamps(TableReference tableRef, Map<Cell, Long> timestampByCell) {
        if (timestampByCell.isEmpty()) {
            return ImmutableMap.of();
        }
        return delegate.getLatestTimestamps(tableRef, timestampByCell);
    }

    @Override
    public Map<Cell, Value> getRows(TableReference tableRef, Iterable<byte[]> rows, ColumnSelection columnSelection, long timestamp) {
        if (Iterables.isEmpty(rows) || columnSelection.noColumnsSelected()) {
            return ImmutableMap.of();
        }
        return delegate.getRows(tableRef, rows, columnSelection, timestamp);
    }

    @Override
    public void multiPut(Map<TableReference, ? extends Map<Cell, byte[]>> valuesByTable, long timestamp) throws KeyAlreadyExistsException {
        if (valuesByTable.isEmpty()) {
            return;
        }
        if (valuesByTable.size() == 1) {
            Entry<TableReference, ? extends Map<Cell, byte[]>> entry = Iterables.getOnlyElement(valuesByTable.entrySet());
            put(entry.getKey(), entry.getValue(), timestamp);
            return;
        }
        delegate.multiPut(valuesByTable, timestamp);
    }

    @Override
    public void put(TableReference tableRef, Map<Cell, byte[]> values, long timestamp) throws KeyAlreadyExistsException {
        Validate.isTrue(timestamp != Long.MAX_VALUE);
        Validate.isTrue(timestamp >= 0);
        Validate.isTrue(!tableRef.equals(TransactionConstants.TRANSACTION_TABLE), TRANSACTION_ERROR);
        if (values.isEmpty()) {
            return;
        }
        delegate.put(tableRef, values, timestamp);
    }

    @Override
    public void putMetadataForTables(Map<TableReference, byte[]> tableRefToMetadata) {
        if (tableRefToMetadata.isEmpty()) {
            return;
        }
        if (tableRefToMetadata.size() == 1) {
            Entry<TableReference, byte[]> entry = Iterables.getOnlyElement(tableRefToMetadata.entrySet());
            putMetadataForTable(entry.getKey(), entry.getValue());
            return;
        }
        delegate.putMetadataForTables(tableRefToMetadata);
    }

    @Override
    public void putUnlessExists(TableReference tableRef, Map<Cell, byte[]> values) throws KeyAlreadyExistsException {
        if (values.isEmpty()) {
            return;
        }
        delegate.putUnlessExists(tableRef, values);
    }

    @Override
    public void putWithTimestamps(TableReference tableRef, Multimap<Cell, Value> cellValues) throws KeyAlreadyExistsException {
        if (cellValues.isEmpty()) {
            return;
        }
        Validate.isTrue(!tableRef.equals(TransactionConstants.TRANSACTION_TABLE), TRANSACTION_ERROR);

        long lastTimestamp = -1;
        boolean allAtSameTimestamp = true;
        for (Value value : cellValues.values()) {
            long timestamp = value.getTimestamp();
            Validate.isTrue(timestamp != Long.MAX_VALUE);
            Validate.isTrue(timestamp >= 0);
            if (lastTimestamp != -1 && timestamp != lastTimestamp) {
                allAtSameTimestamp = false;
            }
            lastTimestamp = timestamp;
        }

        if (allAtSameTimestamp) {
            Multimap<Cell, byte[]> cellValuesWithStrippedTimestamp = Multimaps.transformValues(cellValues, Value.GET_VALUE);

            Map<Cell, byte[]> putMap = Maps.transformValues(cellValuesWithStrippedTimestamp.asMap(), new Function<Collection<byte[]>, byte[]>() {

                @Override
                public byte[] apply(Collection<byte[]> input) {
                    try {
                        return Iterables.getOnlyElement(input);
                    } catch (IllegalArgumentException e) {
                        log.error("Application tried to put multiple same-cell values in at same timestamp; attempting to perform last-write-wins, but ordering is not guaranteed.");
                        return Iterables.getLast(input);
                    }
                }

            });

            put(tableRef, putMap, lastTimestamp);
            return;
        }
        delegate.putWithTimestamps(tableRef, cellValues);
    }

    @Override
    public void truncateTables(Set<TableReference> tableRefs) {
        if (tableRefs.isEmpty()) {
            return;
        }
        if (tableRefs.size() == 1) {
            truncateTable(Iterables.getOnlyElement(tableRefs));
            return;
        }
        delegate.truncateTables(tableRefs);
    }
}


text:
<?php

namespace App\Http\Controllers;

use App\User;
use App\Verein;
use App\Termin;
use App\Userclub;
use App\Userappointment;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class TerminRegController extends Controller
{
    /**
     * Display terminreg view
     **/
    public function index()
    {
        $club = Verein::orderBy('created_at', 'asc')->get();

        $userclub = Userclub::orderBy('created_at', 'asc')->get();

        return view('terminreg', ['club' => $club], ['userclub' => $userclub]);
    }

    /**
     * Add a new appointment
     */

    public function newTermin(Request $request)
    {
        $validator = Validator::make($request->all(), ['name' => 'required|max:255',]);

        if ($validator->fails())
        {
            return redirect('/')
                ->withInput()
                ->withErrors($validator);
        }

        $appointment = new Termin;
        $appointment->name = $request->name;
        $appointment->date = $request->date;
        $appointment->time = $request->time;
        $appointment->place = $request->place;
        $appointment->location = $request->location;
        $appointment->leader = $request->leader;
        $appointment->save();

        $userclub = Userclub::orderBy('created_at', 'asc')->get();

        foreach($userclub as $usercluby) {
            if ($request->appointmentclub == $usercluby->fk_club) {
                $userappointment = new Userappointment;
                $userappointment->fk_users = $usercluby->fk_users;
                $userappointment->fk_appointment = $appointment->id;
                $userappointment->confirmed = true;
                $userappointment->save();

            }
        }

        $appointment = Termin::orderBy('date', 'asc')->get();

        $userappointment = Userappointment::orderBy('created_at', 'asc')->get();

        return view('home', ['appointment' => $appointment], ['userappointment' => $userappointment]);

    }

}