text:
package org.olat.core.commons.fullWebApp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.olat.core.CoreSpringFactory;
import org.olat.core.commons.chiefcontrollers.ChiefControllerMessageEvent;
import org.olat.core.commons.chiefcontrollers.LanguageChangedEvent;
import org.olat.core.commons.fullWebApp.util.GlobalStickyMessage;
import org.olat.core.configuration.PersistedProperties;
import org.olat.core.gui.GUIInterna;
import org.olat.core.gui.GUIMessage;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.WindowManager;
import org.olat.core.gui.WindowSettings;
import org.olat.core.gui.components.Component;
import org.olat.core.gui.components.Window;
import org.olat.core.gui.components.htmlheader.jscss.CustomCSS;
import org.olat.core.gui.components.htmlheader.jscss.CustomJSComponent;
import org.olat.core.gui.components.link.Link;
import org.olat.core.gui.components.link.LinkFactory;
import org.olat.core.gui.components.panel.OncePanel;
import org.olat.core.gui.components.panel.Panel;
import org.olat.core.gui.components.text.TextFactory;
import org.olat.core.gui.components.velocity.VelocityContainer;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.Event;
import org.olat.core.gui.control.VetoableCloseController;
import org.olat.core.gui.control.WindowBackOffice;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.control.WindowControlInfoImpl;
import org.olat.core.gui.control.controller.BasicController;
import org.olat.core.gui.control.creator.ControllerCreator;
import org.olat.core.gui.control.generic.dtabs.Activateable2;
import org.olat.core.gui.control.generic.dtabs.DTab;
import org.olat.core.gui.control.generic.dtabs.DTabImpl;
import org.olat.core.gui.control.generic.dtabs.DTabs;
import org.olat.core.gui.control.guistack.GuiStack;
import org.olat.core.gui.control.info.WindowControlInfo;
import org.olat.core.gui.control.navigation.BornSiteInstance;
import org.olat.core.gui.control.navigation.SiteInstance;
import org.olat.core.gui.control.util.ZIndexWrapper;
import org.olat.core.gui.themes.Theme;
import org.olat.core.id.OLATResourceable;
import org.olat.core.id.context.BusinessControl;
import org.olat.core.id.context.BusinessControlFactory;
import org.olat.core.id.context.ContextEntry;
import org.olat.core.id.context.HistoryModule;
import org.olat.core.id.context.HistoryPoint;
import org.olat.core.id.context.HistoryPointImpl;
import org.olat.core.id.context.StateEntry;
import org.olat.core.id.context.StateSite;
import org.olat.core.logging.AssertException;
import org.olat.core.util.StringHelper;
import org.olat.core.util.event.GenericEventListener;
import org.olat.core.util.prefs.Preferences;
import org.olat.core.util.resource.OresHelper;

/**
 * Description:

 * The BaseFullWebappController defines the outer most part of the main layout
 *

 * Initial Date: 20.07.2007

 *
 * @author patrickb, Felix Jost, Florian Gnägi
 */
public class BaseFullWebappController extends BasicController implements GenericEventListener {
	private static final String PRESENTED_AFTER_LOGIN_WORKFLOW = "presentedAfterLoginWorkflow";

	// STARTED
	private GuiStack currentGuiStack;
	private Panel main;
	private Panel modalPanel;
	private GUIMessage guiMessage;
	private OncePanel guimsgPanel;
	private Panel guimsgHolder;
	private Panel currentMsgHolder;
	private VelocityContainer guimsgVc;

	private VelocityContainer mainVc, navVc;

	// NEW FROM FullChiefController
	private Controller headerCtr, topnavCtr, footerCtr;
	private SiteInstance curSite;
	private DTab curDTab;

	private final List<TabState> siteAndTabs = new ArrayList<TabState>();

	// the dynamic tabs list
	private List<DTab> dtabs;
	private List<String> dtabsLinkNames;
	private List<Controller> dtabsControllers;
	private Map<DTab,HistoryPoint> dtabToBusinessPath = new HashMap<DTab,HistoryPoint>();
	// used as link id which is load url safe (e.g. replayable
	private int dtabCreateCounter = 0;
	// the sites list
	private List<SiteInstance> sites;
	private Map<SiteInstance, BornSiteInstance> siteToBornSite = new HashMap<SiteInstance, BornSiteInstance>();
	private int navLinkCounter = 1;
	//fxdiff BAKS-7 Resume function
	private Map<SiteInstance,HistoryPoint> siteToBusinessPath = new HashMap<SiteInstance,HistoryPoint>();

	//
	private BaseFullWebappControllerParts baseFullWebappControllerParts;
	protected Controller contentCtrl;
	private Panel initialPanel;
	private DTabs myDTabsImpl;
	private static Integer MAX_TAB;
	private WindowSettings wSettings;

	public BaseFullWebappController(UserRequest ureq, WindowControl ouisc_wControl,
			BaseFullWebappControllerParts baseFullWebappControllerParts) {
		// only-use-in-super-call, since we define our own
		super(ureq, null);

		this.baseFullWebappControllerParts = baseFullWebappControllerParts;

		guiMessage = new GUIMessage();
		guimsgPanel = new OncePanel("guimsgPanel");

		// define the new windowcontrol
		final WindowControl origWCo = ouisc_wControl;

		WindowControl myWControl = new WindowControl() {
			private WindowControlInfo wci;

			{
				wci = new WindowControlInfoImpl(BaseFullWebappController.this, origWCo.getWindowControlInfo());
			}

			/**
			 * @see org.olat.core.gui.control.WindowControl#pushToMainArea(org.olat.core.gui.components.Component)
			 */
			@SuppressWarnings("synthetic-access")
			public void pushToMainArea(Component newMainArea) {
				currentGuiStack.pushContent(newMainArea);
			}

			/**
			 * @see org.olat.core.gui.control.WindowControl#pushAsModalDialog(java.lang.String,
			 *      org.olat.core.gui.components.Component)
			 */

			@SuppressWarnings("synthetic-access")
			public void pushAsModalDialog(Component newModalDialog) {
				currentGuiStack.pushModalDialog(newModalDialog);
			}

			@Override
			public void pushAsCallout(Component comp, String targetId) {
				currentGuiStack.pushCallout(comp, targetId);
			}

			/**
			 * @see org.olat.core.gui.control.WindowControl#pop()
			 */
			@SuppressWarnings("synthetic-access")
			public void pop() {
				// reactivate latest dialog from stack, dumping current one
				currentGuiStack.popContent();
			}

			/**
			 * @see org.olat.core.gui.control.WindowControl#setInfo(java.lang.String)
			 */
			@SuppressWarnings("synthetic-access")
			public void setInfo(String info) {
				guiMessage.setInfo(info);
				guimsgPanel.setContent(guimsgVc);

				// setInfo is called input guimsgPanel into the correct place
			}

			/**
			 * @see org.olat.core.gui.control.WindowControl#setError(java.lang.String)
			 */
			@SuppressWarnings("synthetic-access")
			public void setError(String error) {
				guiMessage.setError(error);
				guimsgPanel.setContent(guimsgVc);
			}

			/**
			 * @see org.olat.core.gui.control.WindowControl#setWarning(java.lang.String)
			 */
			@SuppressWarnings("synthetic-access")
			public void setWarning(String warning) {
				guiMessage.setWarn(warning);
				guimsgPanel.setContent(guimsgVc);
			}

			public WindowControlInfo getWindowControlInfo() {
				return wci;
			}

			public void makeFlat() {
				throw new AssertException("should never be called!");
			}

			public BusinessControl getBusinessControl() {
				return origWCo.getBusinessControl();
			}

			public WindowBackOffice getWindowBackOffice() {
				return origWCo.getWindowBackOffice();
			}

		};
		overrideWindowControl(myWControl);

		/*
		 * BaseFullWebappController provides access to Dynamic Tabs
		 * on the same window and not on all Windows!
		 * TODO:pb discuss with HJZ multi window concept.
		 */

		// detach DTabs implementation from the controller - DTabs may be fetched from the window and locked on (synchronized access).
		// if this is controller the controller is locked instead of only the DTabs part.
		myDTabsImpl = new DTabs() {

			@Override
			public void activate(UserRequest ureq, DTab dTab, List<ContextEntry> entries) {
				BaseFullWebappController.this.activate(ureq, dTab, null, entries);
			}

			@Override
			public void activateStatic(UserRequest ureq, String className, List<ContextEntry> entries) {
				BaseFullWebappController.this.activateStatic(ureq, className, null, entries);
			}

			public boolean addDTab(UserRequest ureq, DTab dt) {
				return BaseFullWebappController.this.addDTab(ureq, dt);
			}
			//fxdiff BAKS-7 Resume function
			public DTab createDTab(OLATResourceable ores, String title) {
				return BaseFullWebappController.this.createDTab(ores, null, title);
			}

			public DTab createDTab(OLATResourceable ores, OLATResourceable initialOres, String title) {
				return BaseFullWebappController.this.createDTab(ores, initialOres, title);
			}

			public DTab getDTab(OLATResourceable ores) {
				return BaseFullWebappController.this.getDTab(ores);
			}

			public void removeDTab(UserRequest ureq, DTab dt) {
				BaseFullWebappController.this.removeDTab(ureq, dt);
			}

		};

		Window myWindow = myWControl.getWindowBackOffice().getWindow();
		myWindow.setDTabs(myDTabsImpl);
		//REVIEW:PB remove if back support is desired
		myWindow.addListener(this);//to be able to report BACK / FORWARD / RELOAD

		/*
		 * does all initialisation, moved to method because of possibility to react
		 * on LanguageChangeEvents -> resets and rebuilds footer, header, topnav, sites, content etc.
		 */
		initialize(ureq);

		initialPanel = putInitialPanel(mainVc);
		// ------ all the frame preparation is finished ----

		if (CoreSpringFactory.containsBean("fullWebApp.AfterLoginInterceptionControllerCreator")){
        		// present an overlay with configured afterlogin-controllers or nothing if none configured.
        		// presented only once per session.
        		Boolean alreadySeen = ((Boolean)ureq.getUserSession().getEntry(PRESENTED_AFTER_LOGIN_WORKFLOW));
        		if (ureq.getUserSession().isAuthenticated() && alreadySeen == null) {
        			Controller aftLHookCtr = ((ControllerCreator) CoreSpringFactory.getBean("fullWebApp.AfterLoginInterceptionControllerCreator")).createController(ureq, getWindowControl());
        			listenTo(aftLHookCtr);
        			aftLHookCtr.getInitialComponent();
        			ureq.getUserSession().putEntry(PRESENTED_AFTER_LOGIN_WORKFLOW, Boolean.TRUE);
        		}
		}

		/*
		 * register for cycle event to be able to adjust the guimessage place
		 */
		getWindowControl().getWindowBackOffice().addCycleListener(this);
		/*
		 * register for locale change events ->
		 */
		//move to a i18nModule? languageManger? languageChooserController?
		OLATResourceable wrappedLocale = OresHelper.createOLATResourceableType(Locale.class);
		ureq.getUserSession().getSingleUserEventCenter().registerFor(this, getIdentity(), wrappedLocale);
		/*
		 * register for global sticky message changed events
		 */
		GlobalStickyMessage.registerForGlobalStickyMessage(this, ureq.getIdentity());

	}

	private void initialize(UserRequest ureq) {
		mainVc = createVelocityContainer("fullwebapplayout");
		// use separate container for navigation to prevent full page refresh in ajax mode on site change
		// nav is not a controller part because it is a fundamental part of the BaseFullWebAppConroller.
		navVc = createVelocityContainer("nav");
		mainVc.put("navComponent", navVc);

		// GUI messages
		guimsgVc = createVelocityContainer("guimsg");
		// FIXME fg: create controller that uses monolog controller after monolog
		// controller refactoring. is all the same...

		guimsgVc.contextPut("guiMessage", guiMessage);
		guimsgHolder = new Panel("guimsgholder");
		guimsgHolder.setContent(guimsgPanel);
		currentMsgHolder = guimsgHolder;

		mainVc.put("guimessage", guimsgHolder);

		dtabs = new ArrayList<DTab>();
		dtabsLinkNames = new ArrayList<String>();
		dtabsControllers = new ArrayList<Controller>();

		// -- sites -- by definition the first site is activated at the beginning
		sites = baseFullWebappControllerParts.getSiteInstances(ureq, getWindowControl());
		if (sites != null && sites.size() == 0) {
			sites = null;
		}
		// either sites is null or contains at least one SiteInstance.
		if (sites != null) {
			// create the links for the sites
			for (Iterator<SiteInstance> iterator = sites.iterator(); iterator.hasNext();) {
				SiteInstance si = iterator.next();
				Link link = LinkFactory.createCustomLink("t" + navLinkCounter, "t", "", Link.NONTRANSLATED, navVc, this);
				link.setCustomDisplayText(si.getNavElement().getTitle());
				link.setTitle(si.getNavElement().getDescription());
				link.setUserObject(si);
				Character accessKey = si.getNavElement().getAccessKey();
				if (accessKey != null && StringHelper.containsNonWhitespace(accessKey.toString())) {
					link.setAccessKey(accessKey.toString());
				}
				navLinkCounter++;
			}
		}

		navVc.contextPut("sites", sites);
		navVc.contextPut("dtabs", dtabs);
		navVc.contextPut("dtabsLinkNames", dtabsLinkNames);
		navVc.contextPut("tabhelper", this);

		// header, optional (e.g. for logo, advertising )
		headerCtr = baseFullWebappControllerParts.createHeaderController(ureq, getWindowControl());
		if (headerCtr != null) {
			listenTo(headerCtr); // cleanup on dispose
			Component headerCmp = headerCtr.getInitialComponent();
			mainVc.put("headerComponent", headerCmp);
		}

		// topnav, optional (e.g. for imprint, logout)
		topnavCtr = baseFullWebappControllerParts.createTopNavController(ureq, getWindowControl());
		if (topnavCtr != null) {
			listenTo(topnavCtr); // cleanup on dispose
			Component topNavCmp = topnavCtr.getInitialComponent();
			mainVc.put("topnavComponent", topNavCmp);
		}

		// panel for modal overlays, placed right after the olat-header-div
		modalPanel = new Panel("ccmodalpanel");
		mainVc.put("modalpanel", modalPanel);

		// main, mandatory (e.g. a LayoutMain3ColsController)
		main = new Panel("main");
		mainVc.put("main", main);

		// footer, optional (e.g. for copyright, powered by)
		footerCtr = baseFullWebappControllerParts.createFooterController(ureq, getWindowControl());
		if (footerCtr != null) {
			listenTo(footerCtr); // cleanup on dispose
			Component footerCmp = footerCtr.getInitialComponent();
			mainVc.put("footerComponent", footerCmp);
		}

		contentCtrl = baseFullWebappControllerParts.getContentController(ureq, getWindowControl());
		if (contentCtrl != null) {
			listenTo(contentCtrl);
			GuiStack gs = getWindowControl().getWindowBackOffice().createGuiStack(contentCtrl.getInitialComponent());
			setGuiStack(gs);
			main.setContent(contentCtrl.getInitialComponent());
		}
		if (sites != null) {
			// ------ activate now main
			SiteInstance s = sites.get(0);
			if (contentCtrl == null) {
				//activate site only if no content was set -> allow content before activation of default site.
				activateSite(s, ureq, null, null, false);
				updateBusinessPath(ureq, s);
			}
		}
		if (sites == null && contentCtrl == null) {
		  // fxdiff: FXOLAT-190  RS if no sites displayed... show empty page instead
			main.setContent(TextFactory.createTextComponentFromString("empty", "", null, false, null));
			//set a guistack for the after login interceptor
			GuiStack gs = getWindowControl().getWindowBackOffice().createGuiStack(new Panel("dummy"));
			setGuiStack(gs);
		}

		// set maintenance message
		String stickyMessage = GlobalStickyMessage.getGlobalStickyMessage();
		mainVc.contextPut("hasStickyMessage", (stickyMessage == null ? Boolean.FALSE : Boolean.TRUE));
		mainVc.contextPut("stickyMessage", stickyMessage);

		setWindowSettings(getWindowControl().getWindowBackOffice().getWindowSettings());

		addCustomThemeJS();
	}

	private void setWindowSettings(WindowSettings wSettings) {
		if((this.wSettings == null && wSettings != null)
				|| (this.wSettings != null && !this.wSettings.equals(wSettings))) {
			this.wSettings = wSettings;
			navVc.setVisible(wSettings == null || !wSettings.isHideNavigation());
			if (topnavCtr != null) {
				topnavCtr.getInitialComponent().setVisible(wSettings == null || !wSettings.isHideHeader());
			}
			if (footerCtr != null) {
				footerCtr.getInitialComponent().setVisible(wSettings == null || !wSettings.isHideFooter());
			}
			mainVc.setDirty(true);
		}
	}

	/**
	 * adds the custom js-code to the mainVc
	 * FXOLAT-310
	 */
	private void addCustomThemeJS() {
		Theme currentTheme = getWindowControl().getWindowBackOffice().getWindow().getGuiTheme();
		if (currentTheme.hasCustomJS()) {
			String relPath = currentTheme.getRelPathToCustomJS();
			CustomJSComponent customJS = new CustomJSComponent("customThemejs", new String[] { relPath });
			if (isLogDebugEnabled())
				logDebug("injecting custom javascript from current OLAT-Theme", relPath);
			mainVc.put(customJS.getComponentName(), customJS);
		}
	}

	@Override
	protected void event(UserRequest ureq, Component source, Event event) {
		if (source instanceof Link) {
			Link link = (Link) source;
			String mC = link.getCommand().substring(0, 1);
			if (mC.equals("t")) { // activate normal tab
				SiteInstance s = (SiteInstance) link.getUserObject();
				//fix the state of the last tab/site
				updateBusinessPath(ureq);

				HistoryPoint point = null;
				if(siteToBusinessPath.containsKey(s)) {
					point = siteToBusinessPath.get(s);
				}
				activateSite(s, ureq, null, null, true);
				if(point != null) {
					BusinessControlFactory.getInstance().addToHistory(ureq, point);
				}
				updateBusinessPath(ureq, s);
			} else if (mC.equals("a")) { // activate dyntab
				DTab dt = (DTab) link.getUserObject();
				//fix the state of the last tab/site
				updateBusinessPath(ureq);

				HistoryPoint point = null;
				if(dtabToBusinessPath.containsKey(dt)) {
					point = dtabToBusinessPath.get(dt);
				}

				doActivateDTab(dt);
				if(point != null) {
					BusinessControlFactory.getInstance().addToHistory(ureq, point);
				}
			} else if (mC.equals("c")) { // close dyntab
				DTab dt = (DTab) link.getUserObject();
				requestCloseTab(ureq, dt);
			}
		} else if (source == getWindowControl().getWindowBackOffice().getWindow()) {
			if (event == Window.OLDTIMESTAMPCALL) {
				if (GUIInterna.isLoadPerformanceMode()) {
					getLogger().info("loadtestMode RELOAD");
				} else {
					getLogger().info("RELOAD");
				}

				if(isBackEnabled(ureq)) {
					HistoryPoint point = ureq.getUserSession().popLastHistoryEntry();
					if(point != null) {
						back(ureq, point);
					}
				}
			}
		}
	}

	private boolean isBackEnabled(UserRequest ureq) {
		HistoryModule historyModule = (HistoryModule)CoreSpringFactory.getBean("historyModule");
		if(historyModule.isBackEnabled()) {
			Preferences prefs =  ureq.getUserSession().getGuiPreferences();
			Boolean be = (Boolean)prefs.get(WindowManager.class, "back-enabled");
			if (be != null) {
				return be.booleanValue();
			}
			else {
				return historyModule.isBackDefaultSetting();
			}
		}
		return false;
	}

	protected void back(UserRequest ureq, HistoryPoint cstate) {
		List<ContextEntry> entries = cstate.getEntries();
		if(entries.isEmpty()) return;

		entries = new ArrayList<ContextEntry>(entries);

		ContextEntry state = entries.remove(0);
		if(state == null) return;//no red screen for this

		OLATResourceable ores = state.getOLATResourceable();
		DTab dt = getDTab(ores);
		if(dt != null) {
			doActivateDTab(dt);
			if(dt.getController() instanceof Activateable2) {
				((Activateable2)dt.getController()).activate(ureq, entries, null);
			}
			updateBusinessPath(ureq, dt);
		} else {
			StateEntry s = state.getTransientState();
			if(s instanceof StateSite && ((StateSite)s).getSite() != null && sites != null) {
				SiteInstance site = ((StateSite)s).getSite();
				for(SiteInstance savedSite:sites) {
					if(savedSite != null && site.getClass().equals(savedSite.getClass())) {
						activateSite(savedSite, ureq, null, entries, false);
						//updateBusinessPath(ureq, savedSite);
					}
				}
			}
		}
	}

	@Override
	protected void event(UserRequest ureq, Controller source, Event event) {
		int tabIndex = dtabsControllers.indexOf(source);
		if (tabIndex > -1) {
			// Event comes from a controller in a dtab. Check if the controller is
			// finished and close the tab. Cancel and failed is interpreted as
			// finished.
			if (event == Event.DONE_EVENT || event == Event.CANCELLED_EVENT || event == Event.FAILED_EVENT) {
				DTab tab = dtabs.get(tabIndex);
				removeDTab(ureq, tab);//disposes also tab and controllers
			}
		}

	}

	@Override
	protected void doDispose() {
		// deregister for chief global sticky messages events
		GlobalStickyMessage.deregisterForGlobalStickyMessage(this);
		// dispose sites and tabs

		if (dtabs != null) {
			for (DTab tab : dtabs) {
				tab.dispose();
			}
			for (BornSiteInstance bornSite : siteToBornSite.values()) {
				bornSite.dispose();
			}
			dtabs = null;
			dtabsControllers = null;
			sites = null;
			siteToBornSite = null;
			siteToBusinessPath = null;
			dtabToBusinessPath = null;
		}
		//clear the DTabs Service
		Window myWindow = getWindowControl().getWindowBackOffice().getWindow();
		myDTabsImpl = null;
		myWindow.setDTabs(null);

		getWindowControl().getWindowBackOffice().removeCycleListener(this);
	}

	private void setGuiStack(GuiStack guiStack) {
		currentGuiStack = guiStack;
		Panel guiStackPanel = currentGuiStack.getPanel();
		main.setContent(guiStackPanel);
		// place for modal dialogs, which are overlayd over the normal layout (using
		// css alpha blending)
		// maybe null if no current modal dialog -> clears the panel
		Panel modalStackP = currentGuiStack.getModalPanel();
		modalPanel.setContent(modalStackP);
	}

	// FROM FULLCHIEFCONTROLLER
	//fxdiff BAKS-7 Resume function
	private void activateSite(SiteInstance s, UserRequest ureq, String viewIdentifier,
			List<ContextEntry> entries, boolean forceReload) {
		BornSiteInstance bs = siteToBornSite.get(s);
		GuiStack gs;
		Controller resC;
		//PB//WindowControl site_wControl;
		if (bs != null && s != curSite) {
			// single - click -> fetch guistack from cache
			gs = bs.getGuiStackHandle();
			resC = bs.getController();
		} else if (bs != null && s == curSite && !forceReload) {
			//via activate, don't force the reload
			gs = bs.getGuiStackHandle();
			resC = bs.getController();
		} else {
			// bs == null (not yet in cache) || s == curSite
			// double click or not yet in cache.
			// dispose old controller
			if (bs != null) {
				// already in cache -> dispose old
				bs.getController().dispose();
			}
			// reset site and create new controller
			s.reset();
			resC = s.createController(ureq, getWindowControl());
			gs = getWindowControl().getWindowBackOffice().createGuiStack(resC.getInitialComponent());
			//PB//site_wControl = bwControl;
			//PB//siteToBornSite.put(s, new BornSiteInstance(gs, resC, bwControl));
			siteToBornSite.put(s, new BornSiteInstance(gs, resC));
		}
		doActivateSite(s, gs);
		//fxdiff BAKS-7 Resume function
		if(resC instanceof Activateable2) {
			((Activateable2)resC).activate(ureq, entries, null);
		}
		//fxdiff perhaps has activation changed the gui stack and it need to be updated
		setGuiStack(gs);
	}

	private void doActivateSite(SiteInstance s, GuiStack gs) {
		removeCurrentCustomCSSFromView();

		// set curSite
		setCurrent(s, null);

		setGuiStack(gs);
		navVc.contextPut("pageTitle", s.getNavElement().getTitle());
		navVc.setDirty(true);
		// add css for this site
		BornSiteInstance bs = siteToBornSite.get(s);
		if (bs != null)	addCurrentCustomCSSToView(bs.getCustomCSS());
	}

	private void doActivateDTab(DTab dtabi) {
		removeCurrentCustomCSSFromView();

		//set curDTab
		setCurrent(null, dtabi);
		setGuiStack(dtabi.getGuiStackHandle());
		// set description as page title, getTitel() might contain trucated values
		//TODO:gs:a html escaping or removing should be done everywhere where text input fields are written to velocity. Best would be to not allow it in the input fields or escape it there
		navVc.contextPut("pageTitle", dtabi.getNavElement().getDescription());
		navVc.setDirty(true);
		// add css for this tab
		addCurrentCustomCSSToView(dtabi.getCustomCSS());
	}

	/**
	 * Remove the current custom css from the view
	 */
	protected void removeCurrentCustomCSSFromView() {
		Window myWindow = getWindowControl().getWindowBackOffice().getWindow();
		CustomCSS currentCustomCSS = myWindow.getCustomCSS();
		if (currentCustomCSS != null) {
			// remove css and js from view
			mainVc.remove(currentCustomCSS.getJSAndCSSComponent());
			myWindow.setCustomCSS(null);
		}
	}

	/**
	 * Add a custom css to the view and mark it as the curent custom CSS.
	 *
	 * @param customCSS
	 */
	protected void addCurrentCustomCSSToView(CustomCSS customCSS) {
		if (customCSS == null) return;
		// The current CSS is stored as a window attribute so that is can be
		// accessed by the IFrameDisplayController
		Window myWindow = getWindowControl().getWindowBackOffice().getWindow();
		myWindow.setCustomCSS(customCSS);
		// add css component to view
		mainVc.put("jsAndCss", customCSS.getJSAndCSSComponent());

		addCustomThemeJS();
	}

	/**
	 * @param pos
	 * @return the dtab at pos pos
	 */
	public DTab getDTabAt(int pos) {
		return dtabs.get(pos);
	}

	public void removeDTab(UserRequest ureq, DTab delt) {
		// remove from tab list and mapper table
		synchronized (dtabs) {//o_clusterOK dtabs are per user session only - user session is always in the same vm
			// make dtabs and dtabsControllers access synchronized
			int dtabIndex = dtabs.indexOf(delt);
			if(dtabIndex == -1){
				// OLAT-3343 :: although one session only is implemented, a user can
				// open multiple "main windows" in different _browser tabs_.
				// closing one dtab in _browser tab one_ and then closing the same dtab
				// once again in the _browser tab two_ leads to the case where dtabIndex
				// is -1, e.g. not found causing the redscreen described in the issue.
				// TODO:2008-07-25: pb: define concept of "multi windowing" "main windowing"
				// and reconsider this place.
				//
				// NOTHING TO REMOVE, return
				return;
			}
			// Remove tab itself
			dtabs.remove(delt);
			dtabToBusinessPath.remove(delt);
			dtabsLinkNames.remove(dtabIndex);
			Controller tabCtr = dtabsControllers.get(dtabIndex);
			dtabsControllers.remove(tabCtr);

			for(Iterator<TabState> it=siteAndTabs.iterator(); it.hasNext(); ) {
				if(it.next().getDtab() == delt) {
					it.remove();
				}
			}

			navVc.setDirty(true);
			// remove created links for dtab out of container
			navVc.remove(navVc.getComponent("a" + delt.hashCode()));
			navVc.remove(navVc.getComponent("ca" + delt.hashCode()));
			navVc.remove(navVc.getComponent("cp" + delt.hashCode()));
			if (delt == curDTab) { // if we close the current tab -> return to the previous
				popTheTabState(ureq);
			} // else just remove the dtabs
			delt.dispose();//dispose tab and controllers in tab
		}
	}

	private void popTheTabState(UserRequest ureq) {
		if(siteAndTabs.isEmpty() && sites != null) {
			SiteInstance home = sites.get(0);
			BornSiteInstance bs = siteToBornSite.get(home);
			doActivateSite(home, bs.getGuiStackHandle());
		} else if(!siteAndTabs.isEmpty()) {
			TabState state = siteAndTabs.remove(siteAndTabs.size() - 1);
			if(state.getSite() != null) {
				// latest selected static tab
				// activate previous chosen static site -> this site has already been
				// constructed and is thus in the cache
				SiteInstance si = state.getSite();
				BornSiteInstance bs = siteToBornSite.get(si);
				// bs != null since clicked previously
				GuiStack gsh = bs.getGuiStackHandle();
				doActivateSite(si, gsh);
				if(siteToBusinessPath.containsValue(si)) {
					ureq.getUserSession().addToHistory(ureq, siteToBusinessPath.get(si));
				}
			} else if (state.getDtab() != null && !state.getDtab().getController().isDisposed()) {
				DTab tab = state.getDtab();
				doActivateDTab(tab);
				if(dtabToBusinessPath.containsKey(tab)) {
					ureq.getUserSession().addToHistory(ureq, dtabToBusinessPath.get(tab));
				}
			} else {
				popTheTabState(ureq);
			}
		}
	}

	/**
	 * @param dt
	 */
	private void requestCloseTab(UserRequest ureq, DTab delt) {

		Controller c = delt.getController(); // FIXME:fj: test
		// vetoableclosecontroller
		if (c instanceof VetoableCloseController) {
			VetoableCloseController vcc = (VetoableCloseController) c;
			// rembember current dtab, and swap to the temporary one
			DTab reTab = curDTab;
			doActivateDTab(delt);
			boolean immediateClose = vcc.requestForClose();
			if (!immediateClose) {
				return;
			} else {
				if (reTab != null) {
					doActivateDTab(reTab);
				}
				removeDTab(ureq, delt);
			}
		} else {
			removeDTab(ureq, delt);
		}
	}

	/**
	 * @see org.olat.core.gui.control.generic.dtabs.DTabs#getDTab(org.olat.core.id.OLATResourceable
	 */
	public DTab getDTab(OLATResourceable ores) {
		for (Iterator<DTab> it_dts = dtabs.iterator(); it_dts.hasNext();) {
			DTab dtab = it_dts.next();
			if (OresHelper.equals(dtab.getOLATResourceable(), ores)) return dtab;
			//fxdiff BAKS-7 Resume function
			if (OresHelper.equals(dtab.getInitialOLATResourceable(), ores)) return dtab;
		}
		return null;
	}

	/**
	 * @see org.olat.core.gui.control.generic.dtabs.DTabs#createDTab(org.olat.core.id.OLATResourceable
	 *      java.lang.String)
	 */
	//fxdiff BAKS-7 Resume function
	public DTab createDTab(OLATResourceable ores, OLATResourceable repoOres, String title) {
		// fxdiff: read from props
		if (dtabs.size() >= getMaxTabs()) {
			getWindowControl().setError(translate("warn.tabsfull"));
			return null;
		}
		DTabImpl dt = new DTabImpl(ores, repoOres, title, getWindowControl());
		return dt;
	}

	/**
	 * fxdiff: load max dTab-Amount from Properties, set default to 5
	 * @return
	 */
	private int getMaxTabs() {
		if (MAX_TAB == null) {
			PersistedProperties prop = new PersistedProperties(this);
			prop.init();
			prop.setIntPropertyDefault("max.dtabs", 5);
			MAX_TAB = prop.getIntPropertyValue("max.dtabs");
		}
		return MAX_TAB;
	}

	/**
	 * @see org.olat.core.gui.control.generic.dtabs.DTabs#addDTab(org.olat.core.gui.control.generic.dtabs.DTab)
	 */
	public boolean addDTab(UserRequest ureq, DTab dt) {
		if(isDisposed()) {
			return false;
		}

		DTab old = getDTab(dt.getOLATResourceable());
		if (old != null) {
			return true;
		}
		// add to tabs list
		synchronized (dtabs) {
			// make dtabs and dtabsControllers access synchronized
			dtabs.add(dt);
			dtabsLinkNames.add(Integer.toString(dtabCreateCounter));
			Link link = LinkFactory.createCustomLink("a" + dtabCreateCounter, "a" + dtabCreateCounter, "", Link.NONTRANSLATED, navVc, this);
			link.setCustomDisplayText(StringHelper.escapeHtml(dt.getNavElement().getTitle()));
			link.setTitle(dt.getTitle());
			link.setUserObject(dt);
			// Set accessibility access key using the 's' key. You can loop through all opened tabs by
			// pressing s repetitively (works only in IE/FF which is normally used by blind people)
			link.setAccessKey("s");
			// add close links
			Link calink = LinkFactory.createCustomLink("ca" + dtabCreateCounter, "ca" + dtabCreateCounter, "", Link.NONTRANSLATED, navVc, this);
			calink.setCustomEnabledLinkCSS("b_nav_tab_close");
			calink.setTitle(translate("close"));
			calink.setUserObject(dt);
			Link cplink = LinkFactory.createCustomLink("cp" + dtabCreateCounter, "cp" + dtabCreateCounter, "", Link.NONTRANSLATED, navVc, this);
			cplink.setCustomEnabledLinkCSS("b_nav_tab_close");
			cplink.setTitle(translate("close"));
			cplink.setUserObject(dt);

			Controller dtabCtr = dt.getController();
			dtabCtr.addControllerListener(this);
			updateBusinessPath(ureq, dt);
			// add to tabs controller lookup table for later event dispatching
			dtabsControllers.add(dtabCtr);
			// increase DTab added counter.
			dtabCreateCounter++;
		}
		return true;
	}

	/**
	 * @see org.olat.core.gui.control.generic.dtabs.DTabs#activate(org.olat.core.gui.UserRequest,
	 *      org.olat.core.gui.control.generic.dtabs.DTab, java.lang.String)
	 */
	public void activate(final UserRequest ureq, DTab dTab, final String viewIdentifier, final List<ContextEntry> entries) {
		//update window settings if needed
		setWindowSettings(getWindowControl().getWindowBackOffice().getWindowSettings());

		// init view (e.g. kurs in run mode, repo-detail-edit...)
		// jump here via external link or just open a new tab from e.g. repository
		//fxdiff FXOLAT-113: business path in DMZ
		if(dTab == null && contentCtrl instanceof Activateable2) {
			((Activateable2)contentCtrl).activate(ureq, entries, null);
			return;
		}

		DTabImpl dtabi = (DTabImpl) dTab;
		Controller c = dtabi.getController();
		if (c == null) throw new AssertException("no controller set yet! " + dTab + ", view: " + viewIdentifier);
		doActivateDTab(dtabi);
		//fxdiff BAKS-7 Resume function
		if(entries != null && !entries.isEmpty() && c instanceof Activateable2) {
			final Activateable2 activateable = ((Activateable2) c);
			activateable.activate(ureq, entries, null);
		}
		updateBusinessPath(ureq, dtabi);

		//fxdiff BAKS-7 Resume function
		//update the panels after activation
		setGuiStack(dtabi.getGuiStackHandle());

		// activating a tab is like focusing a new window - we need to adjust the
		// guipath since e.g. the button triggering the activation is not
		// part of the guipath, but rather the new tab in its initial state.
		// in all other cases the "focus of interest" (where the calculation of the
		// guipath is started) matches the controller which listens to the
		// event caused by a user interaction.
		// WindowBackOffice wboNew = getWindowControl().getWindowBackOffice(); //
		// this is the starting point.
		// getWindowControl().getWindowBackOffice().adjustGuiPathCenter(getWindowControl().getWindowControlInfo());
	}

	/**
	 * FIXME:fj: change className to class
	 *
	 * @see org.olat.core.gui.control.generic.dtabs.DTabs#activateStatic(org.olat.core.gui.UserRequest,
	 *      java.lang.String, java.lang.String)
	 */
	// brasato:: remove
	//fxdiff BAKS-7 Resume function
	public void activateStatic(UserRequest ureq, String className, String viewIdentifier, List<ContextEntry> entries) {
		for (Iterator<SiteInstance> it_sites = sites.iterator(); it_sites.hasNext();) {
			SiteInstance site = it_sites.next();
			String cName = site.getClass().getName();
			if (cName.equals(className)) {
				activateSite(site, ureq, viewIdentifier, entries, false);
				return;
			}
		}
	}

	public void event(Event event) {
		if (event == Window.AFTER_VALIDATING) {
			// now update the guimessage

			List<ZIndexWrapper> places = getWindowControl().getWindowBackOffice().getGuiMessages();
			Panel winnerP = null;
			int maxZ = -1;
			if (places != null) {
				// we have places where we can put the gui message
				for (Iterator<ZIndexWrapper> it_places = places.iterator(); it_places.hasNext();) {
					ZIndexWrapper ziw = it_places.next();
					int cind = ziw.getZindex();
					if (cind > maxZ) {
						maxZ = cind;
						winnerP = ziw.getPanel();
					}
				}
			} else {
				winnerP = guimsgHolder;
			}

			if (winnerP != null && winnerP != currentMsgHolder) {
				currentMsgHolder.setContent(null);
				winnerP.setContent(guimsgPanel);
				currentMsgHolder = winnerP;
			} else {
				currentMsgHolder = guimsgHolder;
				currentMsgHolder.setContent(guimsgPanel);
			}
		} else if(event instanceof LanguageChangedEvent){
			LanguageChangedEvent lce = (LanguageChangedEvent)event;
			getTranslator().setLocale(lce.getNewLocale());
			initialize(lce.getCurrentUreq());
			initialPanel.popContent();
			initialPanel.pushContent(mainVc);
			//
		} else if (event instanceof ChiefControllerMessageEvent) {
			// msg can be set to show only on one node or on all nodes
			String msg = GlobalStickyMessage.getGlobalStickyMessage();//either null, or the global message or the per-node-message
			Boolean hasStickyMessage = Boolean.valueOf(msg != null);
			mainVc.contextPut("hasStickyMessage", hasStickyMessage);
			mainVc.contextPut("stickyMessage", msg != null ? msg : "");		}
	}

	/**
	 * [used by velocity] helper for velocity
	 *
	 */
	public boolean isSiteActive(SiteInstance si) {
		return curSite != null && si == curSite;
	}

	/**
	 *
	 * [used by velocity]
	 *
	 * @return
	 */
	public boolean isDTabActive(DTab dtab) {
		return curDTab != null && dtab == curDTab;
	}

	/**
	 * Invitee have only one dynamic tab. They are not allowed
	 * to close it.
	 * [used by velocity]
	 *
	 * @return
	 */
	public boolean isCanCloseDTab(DTab dtab) {
		//can close
		return (sites != null && !sites.isEmpty()) || (dtabs != null && dtabs.size() > 1);
	}

	private void setCurrent(SiteInstance site, DTab tab) {
		curSite = site;
		curDTab = tab;
		siteAndTabs.add(new TabState(tab, site));

		//limite the size
		if(siteAndTabs.size() > 30) {
			while(siteAndTabs.size() > 30) {
				siteAndTabs.remove(0);
			}
		}
	}

	private void updateBusinessPath(UserRequest ureq) {
		if(siteAndTabs.isEmpty()) return;

		TabState tabState = siteAndTabs.get(siteAndTabs.size() - 1);
		if(tabState.getSite() != null) {
			updateBusinessPath(ureq, tabState.getSite());
		} else if (tabState.getDtab() != null) {
			updateBusinessPath(ureq, tabState.getDtab());
		}
	}

	private void updateBusinessPath(UserRequest ureq, SiteInstance site) {
		if(site == null) return;

		String businessPath = siteToBornSite.get(site).getController().getWindowControlForDebug().getBusinessControl().getAsString();
		HistoryPoint point = ureq.getUserSession().getLastHistoryPoint();
		int index = businessPath.indexOf(':');
		if(index > 0 && point != null && point.getBusinessPath() != null) {
			String start = businessPath.substring(0, index);
			if(!point.getBusinessPath().startsWith(start)) {
				//if a controller has not set its business path, don't pollute the mapping
				List<ContextEntry> entries = siteToBornSite.get(site).getController().getWindowControlForDebug().getBusinessControl().getEntries();
				siteToBusinessPath.put(site, new HistoryPointImpl(ureq.getUuid(), businessPath, entries));
				return;
			}
		}

		siteToBusinessPath.put(site, point);
	}

	private void updateBusinessPath(UserRequest ureq, DTab tab) {
		//dtabToBusinessPath is null if the controller is disposed
		if(tab == null || dtabToBusinessPath == null) return;

		String businessPath = tab.getController().getWindowControlForDebug().getBusinessControl().getAsString();
		HistoryPoint point = ureq.getUserSession().getLastHistoryPoint();
		int index = businessPath.indexOf(']');
		if(index > 0 && point != null && point.getBusinessPath() != null) {
			String start = businessPath.substring(0, index);
			if(!point.getBusinessPath().startsWith(start)) {
				//if a controller has not set its business path, don't pollute the mapping
				List<ContextEntry> entries = tab.getController().getWindowControlForDebug().getBusinessControl().getEntries();
				dtabToBusinessPath.put(tab, new HistoryPointImpl(ureq.getUuid(), businessPath, entries));
				return;
			}
		}
		dtabToBusinessPath.put(tab, point);
	}

	private static class TabState {
		private final DTab dtab;
		private final SiteInstance site;

		private TabState(DTab dtab, SiteInstance site) {
			this.dtab = dtab;
			this.site = site;
		}

		public DTab getDtab() {
			return dtab;
		}

		public SiteInstance getSite() {
			return site;
		}
	}
}


text:
@interface DD2TalkToUsViewController () <MFMailComposeViewControllerDelegate>

@end

@implementation DD2TalkToUsViewController

@synthesize customBackgroundColor = _customBackgroundColor;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    //track screen with GA
    [DD2GlobalHelper sendViewToGAWithViewName:@"Talk To Us Shown"];
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    if(![[NSUserDefaults standardUserDefaults] boolForKey:NOT_USE_VOICE_HINTS]) {
        // Play 'rate me please' in Talk to us voice message (file dds_8_3.m4a or 8.2 ?)
        // appington id 26
        if (LOG_VOICE_HINTS) NSLog(@"Play rate me please message");
    }
}

- (IBAction) rateInStore:(id)sender
{
    static NSString *const iOSAppStoreURLFormat = @"itms-apps://itunes.apple.com/app/id%@";
    static NSString *const iOS7AppStoreURLFormat = @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%@";

    NSString * appStoreID = @"590239077";

    NSURL *urlToOpen = [NSURL URLWithString:[NSString stringWithFormat:([[UIDevice currentDevice].systemVersion floatValue] >= 7.0f)? iOS7AppStoreURLFormat: iOSAppStoreURLFormat, appStoreID]];
    // Would contain the right link

    [[UIApplication sharedApplication] openURL:urlToOpen];

    //track screen with GA
    [DD2GlobalHelper sendViewToGAWithViewName:[NSString stringWithFormat:@"RateApp triggered"]];

    // appington conversion id 26
    if (LOG_VOICE_HINTS) NSLog(@"AFFECT: Rated button pressed");
}

#pragma mark - Sending an Email

- (IBAction) sendEmail: (id) sender
{
	BOOL	bCanSendMail = [MFMailComposeViewController canSendMail];
    //    BOOL	bCanSendMail = NO; //for testing the no email alert

    //track screen with GA
    [DD2GlobalHelper sendViewToGAWithViewName:[NSString stringWithFormat:@"SendEmail triggered"]];

	if (!bCanSendMail)
	{
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"No Email Account"
                                                        message: @"You must set up an email account for your device before you can send mail."
                                                       delegate: nil
                                              cancelButtonTitle: nil
                                              otherButtonTitles: @"OK", nil];
		[alert show];
	}
	else
	{
		MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];

		picker.mailComposeDelegate = self;

		[picker setToRecipients: [NSArray arrayWithObject: @"dydifeedback@gmail.com"]];
		[picker setSubject: @"DD's Dictionary Feedback"];
		[picker setMessageBody: [NSString stringWithFormat:@"What do you like about DD's Dictionary? \r\n\r\n What would you like to see improved? \r\n\r\n How did you find the App? \r\n\r\n Any other thoughts? \r\n\r\n\r\n\r\n Thank you so much for taking the time to give us your feedback.\r\n\r\n Best regards Alison.\r\n (from Version: %@ on an %@)",[DD2GlobalHelper version], [DD2GlobalHelper deviceType]] isHTML: NO];

        [self presentViewController: picker animated: YES completion:nil];
	}
}

- (void) mailComposeController: (MFMailComposeViewController *) controller
           didFinishWithResult: (MFMailComposeResult) result
                         error: (NSError *) error
{
    [self dismissViewControllerAnimated: YES completion:nil];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.

    [self.view setOpaque:NO];
    self.view.backgroundColor = self.customBackgroundColor;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

redpajama_set_name: RedPajamaGithub


text:
use vec::Vec;
use boxed::Box;

#[derive(Clone)]
/// Represents an owned C style string
///
/// This type generates compatible C-strings from Rust. It guarantees that
/// there is no null bytes in the string and that the string is ended by a null
/// byte.
pub struct CString {
    data: Box<[u8]>,
}

impl CString {
    /// Creates a new C style string
    ///
    /// This will ensure that no null byte is present in the string or return
    /// and error if that's the case. It will also add the final null byte.
    pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, ()> {
        let mut v = t.into();

        for b in &v {
            if *b == 0 {
                return Err(());
            }
        }

        v.push(0);

        Ok(CString {
            data: v.into_boxed_slice(),
        })
    }

    /// Return the raw representation of the string without the trailing null
    /// byte
    pub fn as_bytes(&self) -> &[u8] {
        &self.data[..self.data.len() - 1]
    }

    /// Return the raw representation of the string.
    ///
    /// This buffer is guaranteed without intermediate null bytes and includes
    /// the trailing null byte.
    pub fn as_bytes_with_nul(&self) -> &[u8] {
        &*self.data
    }
}


text:
local pango = require("pango")
local cairo = require("cairo")
local RADIUS = 200
local N_WORDS = 8
local FONT_WITH_MANUAL_SIZE = "Times new roman,Sans"
local FONT_SIZE = 36
local DEVICE_DPI = 72
--local TWEAKABLE_SCALE = 0.1
local PANGO_SCALE = 1024
local draw_text = function(cr)
  --cr:translate (RADIUS, RADIUS)
  local layout = pango.PangoCairo.createPangoLayout(cr)
  local text8 = "Ленивый рыжий кот شَدَّة latin العَرَبِية";
  layout:setText(text8, -1)
  local desc = pango.Font.fontDescriptionFromString(FONT_WITH_MANUAL_SIZE)
  desc:setAbsoluteSize( FONT_SIZE * DEVICE_DPI * PANGO_SCALE / (72.0))

  local w,_ = layout:getSize()
  layout:setFontDescription(desc)

  cr:setSourceRgb(0.0, 0.0, 0.0)
  pango.PangoCairo.updatePangoLayout(cr, layout)

  cr:moveTo (10,10)
  pango.PangoCairo.showPangoLayout(cr, layout)
end

local xcb = require("xcb")
local conn = xcb.connect()
local screen = conn:getSetup():setupRootsIterator().data

local window = conn:createWindow({
  parent=screen.root,
  visual=screen.root_visual,
  x=20, y=20, w=650, h=150, border=10,
  class = xcb.WindowClass.InputOutput,
  mask=xcb.CW.BackPixel | xcb.CW.EventMask,
  value0=screen.white_pixel,
  value1=xcb.EventMask.Exposure | xcb.EventMask.KeyPress
})
conn:mapWindow(window)
conn:flush()
local visual = cairo.findVisual(conn, screen.root_visual)
local surface = cairo.xcbSurfaceCreate(conn, window.id, visual, 650, 150)
local cr = surface:cairoCreate()
--cr:scale(1 * TWEAKABLE_SCALE, 1 * TWEAKABLE_SCALE)
conn:flush()

local e = conn:waitForEvent()
while (e) do
  local response_type = e.response_type
  if (response_type == xcb.EventType.Expose) then
    cr:setSourceRgb(.9, .9, .9)
    cr:paint()
    draw_text (cr)
    surface:flush()
    conn:flush()
  elseif (response_type == xcb.EventType.KeyPress) then
    break
  elseif (response_type == 0) then
    if (e.error_code) then
      print(string.format("Event error code:%i", e.error_code))
    else
      print("Event error code:null")
    end
  end
  e = conn:waitForEvent()
end
conn:disconnect()


text:
namespace permissions {

NotificationPermissionUiSelector::Decision::Decision(
    base::Optional<QuietUiReason> quiet_ui_reason,
    base::Optional<WarningReason> warning_reason)
    : quiet_ui_reason(quiet_ui_reason), warning_reason(warning_reason) {}
NotificationPermissionUiSelector::Decision::~Decision() = default;

NotificationPermissionUiSelector::Decision::Decision(const Decision&) = default;
NotificationPermissionUiSelector::Decision&
NotificationPermissionUiSelector::Decision::operator=(const Decision&) =
    default;

// static
NotificationPermissionUiSelector::Decision
NotificationPermissionUiSelector::Decision::UseNormalUiAndShowNoWarning() {
  return Decision(UseNormalUi(), ShowNoWarning());
}

}  // namespace permissions


text:
<?php

namespace Nette\Database\Reflection;

use Nette;

/**
 * Reflection metadata class with discovery for a database.
 *
 * @author     Jan Skrasek
 * @property-write Nette\Database\Connection $connection
 */
class DiscoveredReflection extends Nette\Object implements Nette\Database\IReflection
{
	/** @var Nette\Caching\Cache */
	protected $cache;

	/** @var Nette\Caching\IStorage */
	protected $cacheStorage;

	/** @var Nette\Database\Connection */
	protected $connection;

	/** @var array */
	protected $structure = array(
		'primary' => array(),
		'hasMany' => array(),
		'belongsTo' => array(),
	);

	/**
	 * Create autodiscovery structure.
	 * @param  Nette\Caching\IStorage
	 */
	public function __construct(Nette\Caching\IStorage $storage = NULL)
	{
		$this->cacheStorage = $storage;
	}

	public function setConnection(Nette\Database\Connection $connection)
	{
		$this->connection = $connection;
		if ($this->cacheStorage) {
			$this->cache = new Nette\Caching\Cache($this->cacheStorage, 'Nette.Database.' . md5($connection->getDsn()));
			$this->structure = $this->cache->load('structure') ?: $this->structure;
		}
	}

	public function __destruct()
	{
		if ($this->cache) {
			$this->cache->save('structure', $this->structure);
		}
	}

	public function getPrimary($table)
	{
		$primary = & $this->structure['primary'][$table];
		if (isset($primary)) {
			return $primary;
		}

		$columns = $this->connection->getSupplementalDriver()->getColumns($table);
		$primaryCount = 0;
		foreach ($columns as $column) {
			if ($column['primary']) {
				$primary = $column['name'];
				$primaryCount++;
			}
		}

		if ($primaryCount !== 1)
			return NULL;

		return $primary;
	}

	public function getHasManyReference($table, $key, $refresh = TRUE)
	{
		$reference = $this->structure['hasMany'];
		if (!empty($reference[$table])) {
			foreach ($reference[$table] as $targetTable => $targetColumn) {
				if (strpos($targetTable, strtolower($key)) !== FALSE) {
					return array(
						$targetTable,
						$targetColumn,
					);
				}
			}
		}

		if (!$refresh) {
			throw new \PDOException("No reference found for \${$table}->related({$key}).");
		}

		$this->reloadAllForeignKeys();
		return $this->getHasManyReference($table, $key, FALSE);
	}

	public function getBelongsToReference($table, $key, $refresh = TRUE)
	{
		$reference = $this->structure['belongsTo'];
		if (!empty($reference[$table])) {
			foreach ($reference[$table] as $column => $targetTable) {
				if (strpos($column, strtolower($key)) !== FALSE) {
					return array(
						$targetTable,
						$column,
					);
				}
			}
		}

		if (!$refresh) {
			throw new \PDOException("No reference found for \${$table}->{$key}.");
		}

		$this->reloadForeignKeys($table);
		return $this->getBelongsToReference($table, $key, FALSE);
	}

	protected function reloadAllForeignKeys()
	{
		foreach ($this->connection->getSupplementalDriver()->getTables() as $table) {
			if ($table['view'] == FALSE) {
				$this->reloadForeignKeys($table['name']);
			}
		}

		foreach (array_keys($this->structure['hasMany']) as $table) {
			uksort($this->structure['hasMany'][$table], function($a, $b) {
				return strlen($a) - strlen($b);
			});
		}
	}

	protected function reloadForeignKeys($table)
	{
		foreach ($this->connection->getSupplementalDriver()->getForeignKeys($table) as $row) {
			$this->structure['belongsTo'][$table][strtolower($row['local'])] = $row['table'];
			$this->structure['hasMany'][strtolower($row['table'])][$table] = $row['local'];
		}

		if (isset($this->structure['belongsTo'][$table])) {
			uksort($this->structure['belongsTo'][$table], function($a, $b) {
				return strlen($a) - strlen($b);
			});
		}
	}

}


text:
@class XHTumblrMenu;
@class XHTumblrMenuItem;

typedef void (^XHTumblrMenuViewSelectedBlock)(XHTumblrMenu *tumblrMenu, XHTumblrMenuItem *tumblrMenuItem);

typedef NS_ENUM(NSInteger, XHTumblrMenuDissmissAnimationType) {
    kXHFade = 0,
    kXHZoom
};

#endif


text:
class GtoPointReader : public Gto::Reader
{
public:
    typedef std::vector<float> PointData;

    //
    //  A matrix struct so we get default constructor to make identity
    //

    struct Matrix
    {
        Matrix()
        {
            memset(elements, 0, sizeof(float) * 16);
            elements[0]  = 1.0;
            elements[5]  = 1.0;
            elements[10] = 1.0;
            elements[15] = 1.0;
        }

        float elements[16];
    };

    struct ObjectData
    {
        Matrix      globalMatrix;
        PointData   points;
        size_t      numPoints;
        size_t      dimensions;
    };

    typedef std::map<std::string,ObjectData> ObjectMap;

    GtoPointReader() : Reader() {}

    const ObjectMap& objectMap() const { return m_objectMap; }

protected:
    virtual Request object(const std::string& name,
                           const std::string& protocol,
                           unsigned int protocolVersion,
                           const ObjectInfo &header);

    virtual Request component(const std::string& name,
                              const std::string& interp,
                              const ComponentInfo &header);

    virtual Request property(const std::string& name,
                             const std::string& interp,
                             const PropertyInfo &header);

    void* data(const PropertyInfo& info, size_t bytes);

private:
    ObjectMap m_objectMap;
};

#endif // __GtoDeformer__GtoPointReader__h__


text:
layout: page
title: Archive
description: Page with links to all old articles of the blog
theme: green
---

			Coming Soon


text:
from sort import *

##################################################################################################################
#                                                                                #
#                                       CASE 2: GEMINI NETWORK FUNCTIONS                                         #
#                                                                                #
#                            Used in copying data from internal Gemini network                                   #
#                                                                                #
##################################################################################################################

def start(tel, sort, over, copy, program, date):
    """Copy and sort data based on command line input. Data copied from Internal Gemini
    network (used ONLY within Gemini).

    Args:
        tel (boolean):  Specified with -t at command line. If False no
                        telluric corrections will be executed. Default: True.
        over (boolean): Specified with -o at command line. If True
                        old files will be overwritten during data reduction. Default: False.
        sort (boolean): Specified with -s or --sort at command line. If False data will not be
                        sorted. Default: True.
        copy (boolean): Specified with -c or --copy at command line. If True data
                        will be copied from Gemini network. Default: False.
        program:        Specified with -p at command line. Eg GN-2013B-Q-109. Used only within Gemini network.
        date:           Specified with -d at command line. YYYYMMDD. Used only within Gemini network.

    """

    FORMAT = '%(asctime)s %(message)s'
    DATEFMT = datefmt()
    logging.basicConfig(filename='Nifty.log',format=FORMAT,datefmt=DATEFMT,level=logging.DEBUG)
    log = os.getcwd()+'/Nifty.log'

    path = os.getcwd()

    # Copy from Gemini Internal Network AND sort. This will be executed IF ONLY -c True is
    # specified at command line. MUST provide a program id or date with -d or -p.

    if copy and sort:
        # Copy data from archives and sort ONLY IF a program is given with -p.
        if program:
            allfilelist, filelist, skyFrameList, telskyFrameList = getProgram(program, date, over)
            arclist, arcdarklist, flatlist, flatdarklist, ronchilist, obsidDateList  = getCals(filelist, over)
            objDateGratingList, objDirList, obsDirList, telDirList = sortObsGem(allfilelist, skyFrameList, telskyFrameList)
            calDirList = sortCalsGem(arcdarklist, arclist, flatlist, flatdarklist, ronchilist, objDateGratingList, objDirList, obsidDateList)
            # If a telluric correction will be performed sort the science and telluric images based on time between observations.
            # This will ONLY NOT be executed if -t False is specified at command line.
            if tel:
                telSort(telDirList, obsDirList)
        # Copy data from archives and sort ONLY IF a date is given with -d.
        elif date:
            allfilelist, filelist, skyFrameList, telskyFrameList = getScience(date, over)
            arclist, arcdarklist, flatlist, flatdarklist, ronchilist, obsidDateList = getCals(filelist, over)
            objDateGratingList, objDirList, obsDirList, telDirList = sortObsGem(allfilelist, skyFrameList, telskyFrameList)
            calDirList = sortCalsGem(arcdarklist, arclist, flatlist, flatdarklist, ronchilist, objDateGratingList, objDirList, obsidDateList)
            # If telluric correction will be performed sort the science and telluric images based on time between observations.
            # This will ONLY NOT be executed if -t False is specified at command line.
            if tel:
                telSort(telDirList, obsDirList)
            # Exit if a program or date was not probided with -p or -d at command line.
            else:
                print "\n Error in sort.py. Please enter a program ID or observation date with -p or -d at command line.\n"
                raise SystemExit

    # Copy from Gemini Internal network and DON'T sort. This will be executed IF -c True and -s False are specified at command line. MUST provide a program id or date with -d or -p.
    elif copy and not sort:
        # When a program is given (looks for program using /net/mko-nfs/sci/dataflow)
        if program:
            allfilelist, filelist, skyFrameList, telskyFrameList = getProgram(program, date, over)
            arclist, arcdarklist, flatlist, flatdarklist, ronchilist, obsidDateList  = getCals(filelist, over)
            allfilelist, arclist, arcdarklist, flatlist, flatdarklist, ronchilist, objDateGratingList, skyFrameList, telskyFrameList, obsidDateList = makeSortFiles(dir)
            obsDirList, calDirList, telDirList = getPaths(allfilelist, objDateGratingList, dir)
        # When a date is given (looks for data using /net/mko-nfs/sci/dataflow)
        elif date:
            allfilelist, filelist, skyFrameList, telskyFrameList = getScience(date, over)
            arclist, arcdarklist, flatlist, flatdarklist, ronchilist, obsidDateList  = getCals(filelist, over)
            allfilelist, arclist, arcdarklist, flatlist, flatdarklist, ronchilist, objDateGratingList, skyFrameList, telskyFrameList, obsidDateList = makeSortFiles(dir)
            obsDirList, calDirList, telDirList = getPaths(allfilelist, objDateGratingList, dir)
        # Exit if a program or date was not provided with -p or -d at command line.
        else:
            print "\n Error in sort.py. Please enter a program ID or observation date with -p or -d at command line.\n"
            raise SystemExit

    # Sort data ALREADY copied from Gemini Network. Specified if -s and -c are NOT specified at command line.
    elif not copy and sort:
        allfilelist, arclist, arcdarklist, flatlist, flatdarklist, ronchilist, objDateGratingList, skyFrameList, telskyFrameList, obsidDateList = makeSortFiles(dir)
        # Sort and get data from Gemini Internal Network
        if program or date:
            objDateGratingList, objDirList, obsDirList, telDirList = sortObsGem(allfilelist, skyFrameList, telskyFrameList)
            calDirList = sortCalsGem(arcdarklist, arclist, flatlist, flatdarklist, ronchilist, objDateGratingList, objDirList, obsidDateList)
        # if a telluric correction will be performed sort the science and telluric images based on time between observations
        if tel:
            telSort(telDirList, obsDirList)

    # Exit if no or incorrectly formatted input is given
    else:
        print "\n Enter a program ID, observation date, or directory where the raw files are located.\n"
        raise SystemExit

    os.chdir(path)

    return obsDirList, calDirList, telDirList

##################################################################################################################
#                                                                                #
#                                                   FUNCTIONS                                                    #
#                                                                                #
##################################################################################################################

def sortObsGem(allfilelist, skyFrameList, telskyFrameList):

    """Sorts the science images, tellurics and acquisitions into the appropriate directories based
    on date, grating, obsid, obsclass; called when sorting in the Gemini network.
    """

    path = os.getcwd()
    Raw = path+'/Raw'
    pathlist = []
    pathlist2 = []
    objDirList = []
    objDateGratingList = []
    obsDirList = []
    telDirList = []

    fitsKeyWords = ['OBSID', 'OBJECT', 'OBSCLASS', 'DATE', 'GRATING', 'POFFSET', 'QOFFSET']

    for entry in allfilelist:
        header = getFitsHeader(entry, fitsKeyWords)
        header[2] = header[2].replace(' ', '')
        DATE = header[4].replace('-','')
        if header[3]=='science':
            # create the object directory (name of target) in the current directory
            if not os.path.exists(path+'/'+header[2]):
                os.mkdir(path+'/'+header[2])
                objDir = path+'/'+header[2]
            # append object directory list (used in sortCalsGem)
                if not objDirList or not objDirList[-1]==objDir:
                    objDirList.append(objDir)
            else:
                objDir = path+'/'+header[2]
                if not objDirList or not objDirList[-1]==objDir:
                     objDirList.append(objDir)

    # append object date list of the form objDateGratingList = [[obj1, DATE1],[obj2, DATE1]...] (used in sortCalsGem)
    for entry in allfilelist:
        header = getFitsHeader(entry, fitsKeyWords)
        DATE = header[4].replace('-','')
        obj = header[2]
        if header[3]=='science':
            list1 = [obj, DATE]
            if not objDateGratingList or not objDateGratingList[-1]==list1:
                objDateGratingList.append(list1)

    for entry in allfilelist:
        header = getFitsHeader(entry, fitsKeyWords)
        DATE = header[4].replace('-','')
        objDir = path+'/'+header[2]
        obsid = header[1][-3:].replace('-','')
        if header[3]=='science':
            # create a directory for each observation date (YYYYMMDD) in objDir/
            if not os.path.exists(objDir+'/'+DATE):
                os.mkdir(objDir+'/'+DATE)
            # create a directory for each grating used in objDir/YYYYMMDD/
            if not os.path.exists(objDir+'/'+DATE+'/'+header[5][0]):
                os.mkdir(objDir+'/'+DATE+'/'+header[5][0])
            # create a directory for each obsid (eg. obs25) in objDir/YYYYMMDD/grating/
            if not os.path.exists(objDir+'/'+DATE+'/'+header[5][0]+'/obs'+obsid):
                os.mkdir(objDir+'/'+DATE+'/'+header[5][0]+'/obs'+obsid)
            # append obsid directory list; a list of all the different observation directories (used in nifsScience.py and nifsMerge.py)
                obsDirList.append(objDir+'/'+DATE+'/'+header[5][0]+'/obs'+obsid)
            elif not obsDirList or not obsDirList[-1]==objDir+'/'+DATE+'/'+header[5][0]+'/obs'+obsid:
                obsDirList.append(objDir+'/'+DATE+'/'+header[5][0]+'/obs'+obsid)

    # copy science, telluric, and acquisition images to the appropriate folder
    for i in range(len(allfilelist)):
        header = getFitsHeader(allfilelist[i], fitsKeyWords)
        DATE = header[4].replace('-','')
        obsid = header[1][-3:].replace('-','')
        if header[3]=='science':
            objDir = path+'/'+header[2]
            shutil.copy(Raw+'/'+allfilelist[i], objDir+'/'+DATE+'/'+header[5][0]+'/obs'+obsid+'/')
            # make an objlist in the relevant directory
            if allfilelist[i] not in skyFrameList:
                writeList(allfilelist[i], 'objlist', objDir+'/'+DATE+'/'+header[5][0]+'/obs'+obsid+'/')
            # make a skyFrameList in the relevant directory
            if allfilelist[i] in skyFrameList:
               writeList(allfilelist[i], 'skyFrameList', objDir+'/'+DATE+'/'+header[5][0]+'/obs'+obsid+'/')

        if header[3]=='partnerCal':
            # create a Tellurics directory in objDir/YYYYMMDD/grating
            for objDir in objDirList:
                if not os.path.exists(objDir+'/'+DATE+'/'+header[5][0]+'/Tellurics'):
                    os.mkdir(objDir+'/'+DATE+'/'+header[5][0]+'/Tellurics')
                if not os.path.exists(objDir+'/'+DATE+'/'+header[5][0]+'/Tellurics/obs'+obsid):
                    os.mkdir(objDir+'/'+DATE+'/'+header[5][0]+'/Tellurics/obs'+obsid)
                    telDirList.append(objDir+'/'+DATE+'/'+header[5][0]+'/Tellurics/obs'+obsid)
                elif not telDirList or not telDirList[-1]==objDir+'/'+DATE+'/'+header[5][0]+'/Tellurics/obs'+obsid:
                    telDirList.append(objDir+'/'+DATE+'/'+header[5][0]+'/Tellurics/obs'+obsid)
                shutil.copy(Raw+'/'+allfilelist[i], objDir+'/'+DATE+'/'+header[5][0]+'/Tellurics/obs'+obsid+'/')
                # make a tellist in the relevant directory
                if allfilelist[i] not in telskyFrameList:
                    writeList(allfilelist[i], 'tellist', objDir+'/'+DATE+'/'+header[5][0]+'/Tellurics/obs'+obsid+'/')
                # make a skyFrameList in the relevant telluric directory
                if allfilelist[i] in telskyFrameList:
                    writeList(allfilelist[i], 'skyFrameList', objDir+'/'+DATE+'/'+header[5][0]+'/Tellurics/obs'+obsid+'/')

        if i!=(len(allfilelist)-1):
            header2= getFitsHeader(allfilelist[i+1], fitsKeyWords)
        if header[3]=='acq' and header2[3]=='science': #or header[3]=='acqCal' and header2[3]=='partnerCal':
            # create an Acquisitions directory in objDir/YYYYMMDD/grating
            if not os.path.exists(header2[2]+'/'+DATE+'/'+header[5][0]+'/Acquisitions/'):
                os.mkdir(header2[2]+'/'+DATE+'/'+header[5][0]+'/Acquisitions/')
            shutil.copy(Raw+'/'+allfilelist[i], header2[2]+'/'+DATE+'/'+header[5][0]+'/Acquisitions/')

    os.chdir(path)

    return objDateGratingList, objDirList, obsDirList, telDirList

#----------------------------------------------------------------------------------------#

def sortCalsGem(arcdarklist, arclist, flatlist, flatdarklist, ronchilist, dateObjList, objDirList, obsidDateList):

    """Sort calibrations into the appropriate directory based on date.
    """
    calDirList = []

    path = os.getcwd()
    Raw = path+'/Raw'

    fitsKeyWords = ['OBSID', 'OBSCLASS', 'DATE']

    # create Calibrations directories in each of the observation date directories (ie. YYYYMMDD/Calibrations)
    for item in dateObjList:
        if not os.path.exists(path+'/'+item[0]+'/'+item[1]+'/Calibrations'):
            os.mkdir(path+'/'+item[0]+'/'+item[1]+'/Calibrations')
            calDirList.append(path+'/'+item[0]+'/'+item[1]+'/Calibrations')
        elif not calDirList or not calDirList[-1]==path+'/'+item[0]+'/'+item[1]+'/Calibrations':
            calDirList.append(path+'/'+item[0]+'/'+item[1]+'/Calibrations')

    # sort lamps on flats
    for entry in flatlist:
        header = getFitsHeader(entry, fitsKeyWords)
        DATE = header[3].replace('-','')
        for obj in objDirList:
            if obsidDateList:
                for item in obsidDateList:
                    if header[1] in item:
                        DATE = item[0]
            path1 = obj+'/'+DATE+'/Calibrations/'
            shutil.copy(Raw+'/'+entry, path1)
            # create a flatlist in the relevant directory
            writeList(entry, 'flatlist', path1)

    # sort lamps off flats
    for entry in flatdarklist:
        header = getFitsHeader(entry, fitsKeyWords)
        DATE = header[3].replace('-','')
        for obj in objDirList:
            if obsidDateList:
                for item in obsidDateList:
                    if header[1] in item:
                        DATE = item[0]
            path1 = obj+'/'+DATE+'/Calibrations/'
            shutil.copy(Raw+'/'+entry, path1)
            # create a flatdarklist in the relevant directory
            writeList(entry, 'flatdarklist', path1)

    # sort ronchi flats
    for entry in ronchilist:
        header = getFitsHeader(entry, fitsKeyWords)
        DATE = header[3].replace('-','')
        for obj in objDirList:
            if obsidDateList:
                for item in obsidDateList:
                    if header[1] in item:
                        DATE = item[0]
            path1 = obj+'/'+DATE+'/Calibrations/'
            shutil.copy(Raw+'/'+entry, path1)
            # create a ronchilist in the relevant directory
            writeList(entry, 'ronchilist', path1)

    # sort arcs
    for entry in arclist:
        header = getFitsHeader(entry, fitsKeyWords)
        DATE = header[3].replace('-','')
        for obj in objDirList:
            path1 = obj+'/'+DATE+'/Calibrations/'
            shutil.copy(Raw+'/'+entry,path1)
            # create an arclist in the relevant directory
            writeList(entry, 'arclist', path1)

    # sort arc darks
    for entry in arcdarklist:
        header = getFitsHeader(entry, fitsKeyWords)
        DATE = header[3].replace('-','')
        for obj in objDirList:
            if obsidDateList:
                for item in obsidDateList:
                    if header[1] in item:
                        DATE = item[0]
            path1 = obj+'/'+DATE+'/Calibrations/'
            shutil.copy(Raw+'/'+entry,path1)
            # create an arcdarklist in the relevant directory
            writeList(entry, 'arcdarklist', path1)

    os.chdir(path)

    return calDirList

#----------------------------------------------------------------------------------------#

def getProgram(program, date, over):

    """Copies all the science, acquisition, and telluric images for a given program to the Raw directory.
    """
    rawfiles = []
    missingRaw = []
    filelist = []
    skyFrameList = []
    telskyFrameList = []

    if date:
        url = '/net/mko-nfs/sci/dataflow/'+program+'/'+date+'/OBJECT'
    else:
        # internal site where observations can be found
        url = '/net/mko-nfs/sci/dataflow/'+program+'/OBJECT'

    # find and create a list of all the .fits files from a given night
    allfilelist = checkQAPIreq(getUrlFiles(url, 'file'))

    if allfilelist:
        # check to make sure that the program ID matches the OBSID in the science headers
        checkEntry(program, 'program', allfilelist)
    else:
        print '\n Either no files found or the PI and QI requirements have not been met. \n'
        raise SystemExit

    # check to make sure that all telluric and acquisition files were taken on the same night as science data and removes the ones that weren't
    removelist = checkDate(allfilelist)
    if removelist:
        for entry in removelist:
            allfilelist.remove(entry)

    # make a directory called Raw if one does not already exist
    path = os.getcwd()

    if not os.path.exists(path+'/Raw'):
        os.mkdir(path+'/Raw')
    Raw = path+'/Raw'

    # copy the files in allfilelist to the Raw directory, first checking if over is set and if the files have already been copied
    checkOverCopy(allfilelist, Raw, over)

    # make a list of all images excluding acq images (getCals cannot use acq images)
    for entry in allfilelist:
        fitsKeyWords= ["OBSCLASS", "DATE"]
        headerList = getFitsHeader(entry,fitsKeyWords)
        if not headerList[1]=='acq':
            filelist.append(entry)

    # make a list of all the sky images (science and telluric)
    for entry in allfilelist:
        fitsKeyWords = ['OBSCLASS', 'POFFSET', 'QOFFSET']
        header = getFitsHeader(entry, fitsKeyWords)
        if header[1] == 'science':
            rad = math.sqrt(header[2]**2 + header[3]**2)
            if rad > 3.0:
                skyFrameList.append(entry)
        if header[1] == 'partnerCal':
            rad = math.sqrt(header[2]**2 + header[3]**2)
            if rad > 2.5:
                telskyFrameList.append(entry)

    return allfilelist, filelist, skyFrameList, telskyFrameList

#----------------------------------------------------------------------------------------#

def getScience(date, over):

    """Copies all the science, acquisition, and telluric images for a given date to the Raw directory.
    """
    allfilelist = []
    filelist = []
    templist = []
    datelist = []
    skyFrameList = []
    telskyFrameList = []

    # internal site where observations can be found
    url = 'http://fits/xmlfilelist/summary/'+date+'/NIFS/OBJECT'

    # find and create a list of all the .fits files from a given night, checking the QA and PI requirements
    templist = checkQAPIreq(getUrlFiles(url, 'file'))

    # identify the images by obsclass makes a listed list of filename, obsclass, and obsid
    fitsKeyWords = ['OBSCLASS', 'OBSID', 'DATE', 'OBJECT']
    for entry in templist:
        header = getFitsHeader(entry, fitsKeyWords)
        if header[1] == 'science':
            obsid = header[2]
            break

    url2 = 'http://fits/xmlfilelist/summary/'+date+'/NIFS/OBJECT/'+obsid[:-2]
    allfilelist = checkQAPIreq(getUrlFiles(url, 'file'))

    # check to make sure that all telluric and acquisition files were taken on the same night as science data and removes the ones that weren't
    removelist = checkDate(allfilelist)
    if removelist:
        for entry in removelist:
            allfilelist.remove(entry)

    # make a list of all the sky images
    for entry in allfilelist:
        fitsKeyWords = ['OBSCLASS', 'POFFSET', 'QOFFSET']
        header = getFitsHeader(entry, fitsKeyWords)
        if header[1] == 'science':
            rad = math.sqrt(header[2]**2 + header[3]**2)
            if rad > 3.0:
                skyFrameList.append(entry)
        if header[1] == 'partnerCal':
            rad = math.sqrt(header[2]**2 + header[3]**2)
            if rad > 2.5:
                telskyFrameList.append(entry)
        if header[1]!='acq':
            filelist.append(entry)

    # path to data archive
    raw = '/net/mko-nfs/sci/dataflow'

    # make a directory called Raw if one does not already exist
    path = os.getcwd()

    if not os.path.exists(path+'/Raw'):
        Raw = os.mkdir(path+'/Raw')

    Raw = path+'/Raw'

    # copy all science images from a given night into ./Raw/
    checkOverCopy(allfilelist, Raw, over)

    return allfilelist, filelist, skyFrameList, telskyFrameList

#----------------------------------------------------------------------------------------#

def getCals(filelist, over):

    """Copies the necessary calibration files to the Raw directory using
    http://fits/calmgr to match calibrations frames to science frames.
    """
    # path to data archive
    raw = '/net/mko-nfs/sci/dataflow'

    # make a directory called Raw if one does not already exist
    path = os.getcwd()

    if os.path.exists(path+'/Raw'):
        Raw = path+'/Raw'
    else:
       Raw = os.mkdir(path+'/Raw')

    # find lamps on, lamps off, and ronchi flats
    flatlist, flatdarklist, ronchilist, obsidlist, obsidDateList = getFlat(filelist)
    # copy flats and  to Calibrations
    checkOverCopy(flatlist, Raw, over)
    checkOverCopy(flatdarklist, Raw, over)
    checkOverCopy(ronchilist, Raw, over)

    # find arc and arc darks
    arclist, arcdarklist = getArc(filelist, obsidlist)
    # copy arc to Calibrations
    checkOverCopy(arclist, Raw, over)
    checkOverCopy(arcdarklist, Raw, over)

    templist = flatlist+flatdarklist
    flatlist = []
    flatdarklist = []
    for entry in templist:
        header = astropy.io.fits.open(Raw+'/'+entry)

        obstype = header[0].header['OBSTYPE'].strip()  # used to sort out the acqs and acqCals in the trap
        aper = header[0].header['APERTURE']

        if obstype == 'FLAT' and not aper=='Ronchi_Screen_G5615':
            # open the image and store pixel values in an array
            array = astropy.io.fits.getdata(Raw+'/'+entry)
            # then this takes the mean of all of them
            mean_counts = np.mean(array)

            # once we've stored that to the variable we can use this conditional
            # to check whether the frame is a sky or an object based on the counts
            # 2000.0 is an arbitrary threshold that appears to work well.
            if mean_counts < 2000.0:
                flatdarklist.append(entry)
            else:
                flatlist.append(entry)

    return arclist, arcdarklist, flatlist, flatdarklist, ronchilist, obsidDateList

#----------------------------------------------------------------------------------------#

def getArc(filelist, obsidlist):

    """Finds and returns a list of arcs and arc darks to use to reduce the science data.
    """
    templist = []
    arclist = []
    arcdarklist = []
    obsid2list = []

    # find all the different obsid's
    for i in range(len(filelist)):
        url = 'http://fits/calmgr/arc/'+filelist[i]
        file1 = getUrlFiles(url, 'calibration')
        if i==0 or not arclist[-1]==file1[0]:
            arclist.append(file1[0])

    fitsKeyWords= ["OBSID", "RAWPIREQ","RAWGEMQA", 'DATE']

    # find all the obsid's and dates of the arcs
    for entry in templist:
        headerList = getFitsHeader(entry,fitsKeyWords)
        obsid2 = headerList[1]
        obsid2list.append(obsid2)
        datelist.append(headerList[4].replace('-',''))

    # check to make sure that the arcs meet the PI and QA requirements
    for entry in arclist:
        headerList = getFitsHeader(entry, fitsKeyWords)
        rawPIreq = headerList[2]
        rawGemQA = headerList[3]
        if rawPIreq in ["YES","UNKNOWN"] and rawGemQA in ["USABLE","UNKNOWN"]:
            pass
        else:
            print 'Arc\'s QA not PASS or UNKNOWN so skipped'

    # find arc darks
    # first check if there are arc darks in the same observing program as the arc(s)
    for obsid2 in obsid2list:
        for date in datelist:
            url = 'http://fits/xmlfilelist/summary/'+obsid2+'/DARK/'+date
            tempdarklist = getUrlFiles(url, 'file')
            for item in tempdarklist:
                arcdarklist.append(item)

    # if not arc darks were found above, use the arc darks taken in the daycal program
    if not arcdarklist:
        for obsid in obsidlist:
            url = 'http://fits/xmlfilelist/summary/'+obsid+'/DARK'
            tempdarklist = getUrlFiles(url, 'file')
            for item in tempdarklist:
                arcdarklist.append(item)

    return arclist, arcdarklist

#----------------------------------------------------------------------------------------#

def getFlat(filelist):

    """Finds and returns a list of flats (lamps on, lamps off, and ronchi) to use to
    reduce the science data.
    """

    templist = []
    flatlist = []
    flatdarklist = []
    obsidlist = []
    ronchilist = []
    flattemp = []
    obsidDateList = []

    fitsKeyWords = ['DATE', 'OBSID']

    #find first flat for each image and record the obsids of the science image and the flat
    for i in range(len(filelist)):
        url = 'http://fits/calmgr/flat/'+filelist[i]
        file1 = str(getUrlFiles(url, 'calibration'))
        file1 = file1[2:-2]
        if i==0 or not templist[-1]==file1:
            templist.append(file1)
        header1 = getFitsHeader(filelist[i], fitsKeyWords)
        header2 = getFitsHeader(file1, fitsKeyWords)
        date = header1[1]
        obsid = header2[2]
        list1 = [date.replace('-',''), obsid]
        if date!=header2[2]:
            if not obsidDateList or not obsidDateList[-1]==list1:
                obsidDateList.append(list1)

    for entry in templist:
        fitsKeyWords = ['OBSID', 'GCALSHUT', 'OBSCLASS']
        headerList = getFitsHeader(entry, fitsKeyWords)
        obsid = headerList[1]
        obsidlist.append(obsid)
        url2 = 'http://fits/xmlfilelist/summary/'+obsid+'/FLAT'
        tempflatlist = getUrlFiles(url2, 'file')
        for item in tempflatlist:
            flattemp.append(item)

    # use the obsid of the first flat to find the other lamps on flats and lamps off flats
    for entry in flattemp:
       fitsKeyWords = ['GCALSHUT']
       header = getFitsHeader(entry, fitsKeyWords)
       # differentiate between lamps on and lamps off flats by looking for "OPEN"(lamps on) or "CLOSED"(lamps off) for GCALSHUT in the fits header
       if header[1] == 'OPEN':
           flatlist.append(entry)
       else:
           flatdarklist.append(entry)

    # use the obsid to find ronchi flats
    for obsid in obsidlist:
        url3 = 'http://fits/xmlfilelist/summary/'+obsid+'/RONCHI'
        tempronchilist = getUrlFiles(url3, 'file')
        for item in tempronchilist:
            ronchilist.append(item)

    return flatlist, flatdarklist, ronchilist, obsidlist, obsidDateList

#----------------------------------------------------------------------------------------#

if __name__ == '__main__':
    print "gemini_sort"


text:
package org.ow2.chameleon.rose.zookeeper;

import static org.apache.zookeeper.CreateMode.EPHEMERAL;
import static org.osgi.service.log.LogService.LOG_DEBUG;
import static org.osgi.service.log.LogService.LOG_INFO;
import static org.osgi.service.log.LogService.LOG_WARNING;
import static org.ow2.chameleon.rose.RoseMachine.ENDPOINT_LISTENER_INTEREST;
import static org.ow2.chameleon.rose.zookeeper.ZookeeperManager.computePath;
import static org.ow2.chameleon.rose.RoseMachine.EndpointListerInterrest.LOCAL;
import java.util.Dictionary;
import java.util.Hashtable;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.log.LogService;
import org.osgi.service.remoteserviceadmin.EndpointDescription;
import org.osgi.service.remoteserviceadmin.EndpointListener;
import org.ow2.chameleon.json.JSONService;

public class RoseLocalEndpointListener implements EndpointListener {

	private final ZookeeperManager bridge;
	private final ServiceRegistration registration;

	public RoseLocalEndpointListener(ZookeeperManager zbridge,String filter,BundleContext context) {
		bridge = zbridge;

		Dictionary<String, Object> props = null;
		props=new Hashtable<String, Object>();
		props.put(ENDPOINT_LISTENER_INTEREST, LOCAL); //track only local EndpointDescription

		if (filter!=null){
			props.put(ENDPOINT_LISTENER_SCOPE, filter); //scope filter

		}

		registration = context.registerService(EndpointListener.class.getName(), this, props);
		logger().log(LOG_INFO, "The zookeeper ExportedEndpointListener service has been registered.");
	}

	/*----------------------------*
	 * EndpointListener call-back *
	 * (WB pattern)               *
	 *----------------------------*/

	/*
	 * (non-Javadoc)
	 * @see org.osgi.service.remoteserviceadmin.EndpointListener#endpointAdded(org.osgi.service.remoteserviceadmin.EndpointDescription, java.lang.String)
	 */
	public void endpointAdded(EndpointDescription endpoint, String matchedFilter) {
		//Convert the endpoint into a json object
		String desc = json().toJSON(endpoint.getProperties());
		try {
			String path = keeper().create(computePath(endpoint), desc.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, EPHEMERAL);
			logger().log(LOG_DEBUG,"The endpoint :"+endpoint.getId()+" has been published on the zookeeper node of path "+path);
		} catch (KeeperException e) {
			logger().log(LOG_WARNING, "Cannot publish through zookeeper the endpoint of id: "+endpoint.getId(),e);
		} catch (InterruptedException e) {
			logger().log(LOG_WARNING, "Cannot publish through zookeeper the endpoint of id: "+endpoint.getId(),e);
		}
	}

	/*
	 * (non-Javadoc)
	 * @see org.osgi.service.remoteserviceadmin.EndpointListener#endpointRemoved(org.osgi.service.remoteserviceadmin.EndpointDescription, java.lang.String)
	 */
	public void endpointRemoved(EndpointDescription endpoint, String matchedFilter) {
		final String path = computePath(endpoint);
		try {
			keeper().delete(path, -1); //-1 match any nodes version
			logger().log(LOG_DEBUG,"The endpoint :"+endpoint.getId()+" has been removed from zookeeper, node :"+path);
		} catch (InterruptedException e) {
			logger().log(LOG_WARNING, "Cannot remove from zookeeper the endpoint of id: "+endpoint.getId(),e);
		} catch (KeeperException e) {
			logger().log(LOG_WARNING, "Cannot remove from zookeeper the endpoint of id: "+endpoint.getId(),e);
		}

	}

	/**
	 * Unregister this {@link LocalEndpointListener}.
	 */
	public void destroy(){
		registration.unregister();
		logger().log(LOG_INFO, "The zookeeper ExportedEndpointListener service has been unregistered.");
	}

	/**
	 * @return The {@link LogService}
	 */
	private LogService logger(){
		return bridge.getLogger();
	}

	/**
	 * @return The {@link ZooKeeper} client
	 */
	private ZooKeeper keeper(){
		return bridge.getKeeper();
	}

	/**
	 * @return The {@link JSONService}
	 */
	private JSONService json(){
		return bridge.getJson();
	}
}


text:
package org.perfcake.ide.editor.swing.icons.control;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.image.BufferedImage;
import org.perfcake.ide.editor.actions.ActionType;

/**
 * This class has been automatically generated using
 * Flamingo SVG transcoder.
 */
public class PlusIcon extends AbstractControlIcon {

    public static final int DEFAULT_WIDTH = 8;
    public static final int DEFAULT_HEIGHT = 8;
    /**
     * The rendered image.
     */
    private BufferedImage image;

    /**
     * Creates a new transcoded SVG image.
     *
     * @param color color
     */
    public PlusIcon(Color color) {
        this(DEFAULT_WIDTH, DEFAULT_HEIGHT, color);
    }

    /**
     * Creates a new transcoded SVG image.
     *
     * @param width  width of the icon
     * @param height heigth of the icon
     * @param color  color
     */
    public PlusIcon(int width, int height, Color color) {
        super(width, height, color, ActionType.ADD);
    }

    /**
     * Creates new plus icon.
     *
     * @param iconWidth width
     * @param iconHeight height
     */
    public PlusIcon(int iconWidth, int iconHeight) {
        super(iconWidth, iconHeight, null);
    }

    @Override
    public int getIconHeight() {
        return height;
    }

    @Override
    public int getIconWidth() {
        return width;
    }

    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        //store location
        this.x = x;
        this.y = y;

        if (isRenderNeeded()) {
            image = new BufferedImage(getIconWidth(), getIconHeight(), BufferedImage.TYPE_INT_ARGB);
            double coef = Math.min((double) width / (double) DEFAULT_WIDTH, (double) height / (double) DEFAULT_HEIGHT);

            Graphics2D g2d = image.createGraphics();
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.scale(coef, coef);
            paint(g2d);
            g2d.dispose();
        }

        g.drawImage(image, x, y, null);
    }

    /**
     * Paints the transcoded SVG image on the specified graphics context.
     *
     * @param g Graphics context.
     */
    private void paint(Graphics2D g) {
        Shape shape = null;

        float origAlpha = 1.0f;

        java.util.LinkedList<AffineTransform> transformations = new java.util.LinkedList<AffineTransform>();

        //

        // _0

        // _0_0
        shape = new GeneralPath();
        ((GeneralPath) shape).moveTo(3.0, 0.0);
        ((GeneralPath) shape).lineTo(3.0, 3.0);
        ((GeneralPath) shape).lineTo(0.0, 3.0);
        ((GeneralPath) shape).lineTo(0.0, 5.0);
        ((GeneralPath) shape).lineTo(3.0, 5.0);
        ((GeneralPath) shape).lineTo(3.0, 8.0);
        ((GeneralPath) shape).lineTo(5.0, 8.0);
        ((GeneralPath) shape).lineTo(5.0, 5.0);
        ((GeneralPath) shape).lineTo(8.0, 5.0);
        ((GeneralPath) shape).lineTo(8.0, 3.0);
        ((GeneralPath) shape).lineTo(5.0, 3.0);
        ((GeneralPath) shape).lineTo(5.0, 0.0);
        ((GeneralPath) shape).lineTo(3.0, 0.0);
        ((GeneralPath) shape).closePath();

        g.setPaint(color);
        g.fill(shape);
    }
}


text:
.class Lcom/android/server/location/RemoteListenerHelper$LinkedListener;
.super Ljava/lang/Object;
.source "RemoteListenerHelper.java"

# interfaces
.implements Landroid/os/IBinder$DeathRecipient;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/location/RemoteListenerHelper;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "LinkedListener"
.end annotation

# instance fields
.field private final mListener:Landroid/os/IInterface;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "TT",
            "Listener;"
        }
    .end annotation
.end field

.field final synthetic this$0:Lcom/android/server/location/RemoteListenerHelper;

# direct methods
.method public constructor <init>(Lcom/android/server/location/RemoteListenerHelper;Landroid/os/IInterface;)V
    .locals 0
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(TT",
            "Listener;",
            ")V"
        }
    .end annotation

    iput-object p1, p0, Lcom/android/server/location/RemoteListenerHelper$LinkedListener;->this$0:Lcom/android/server/location/RemoteListenerHelper;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    iput-object p2, p0, Lcom/android/server/location/RemoteListenerHelper$LinkedListener;->mListener:Landroid/os/IInterface;

    return-void
.end method

# virtual methods
.method public binderDied()V
    .locals 3

    iget-object v0, p0, Lcom/android/server/location/RemoteListenerHelper$LinkedListener;->this$0:Lcom/android/server/location/RemoteListenerHelper;

    invoke-static {v0}, Lcom/android/server/location/RemoteListenerHelper;->-get0(Lcom/android/server/location/RemoteListenerHelper;)Ljava/lang/String;

    move-result-object v0

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v2, "Remote Listener died: "

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    iget-object v2, p0, Lcom/android/server/location/RemoteListenerHelper$LinkedListener;->mListener:Landroid/os/IInterface;

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-static {v0, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    iget-object v0, p0, Lcom/android/server/location/RemoteListenerHelper$LinkedListener;->this$0:Lcom/android/server/location/RemoteListenerHelper;

    iget-object v1, p0, Lcom/android/server/location/RemoteListenerHelper$LinkedListener;->mListener:Landroid/os/IInterface;

    invoke-virtual {v0, v1}, Lcom/android/server/location/RemoteListenerHelper;->removeListener(Landroid/os/IInterface;)V

    return-void
.end method

.method public getUnderlyingListener()Landroid/os/IInterface;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()TT",
            "Listener;"
        }
    .end annotation

    iget-object v0, p0, Lcom/android/server/location/RemoteListenerHelper$LinkedListener;->mListener:Landroid/os/IInterface;

    return-object v0
.end method


text:
#include <algorithm>
#include <map>
#include <memory>
#include <string>
#include <tuple>
#include <utility>

#include "llvm/ADT/StringRef.h"
#include "llvm/Support/SourceMgr.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"  // from @llvm-project
#include "mlir/Parser/Parser.h"  // from @llvm-project
#include "mlir/Pass/Pass.h"  // from @llvm-project
#include "mlir/Pass/PassManager.h"  // from @llvm-project
#include "mlir/Transforms/Passes.h"  // from @llvm-project
#include "tensorflow/compiler/mlir/quantization/tensorflow/passes/passes.h"
#include "tensorflow/compiler/mlir/quantization/tensorflow/passes/quantized_function_library.h"
#include "tensorflow/compiler/mlir/quantization/tensorflow/quantization_options.pb.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_dialect.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h"

namespace mlir {
namespace quant {
namespace {

class InsertQuantizedFunctionsPass
    : public PassWrapper<InsertQuantizedFunctionsPass,
                         OperationPass<ModuleOp>> {
 public:
  MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(InsertQuantizedFunctionsPass)

  explicit InsertQuantizedFunctionsPass() {}
  explicit InsertQuantizedFunctionsPass(QuantizationMethod quantization_method,
                                        const OpSet& op_set) {
    quantization_method_ = quantization_method;
    op_set_ = op_set;
  }
  InsertQuantizedFunctionsPass(const InsertQuantizedFunctionsPass& other) {
    quantization_method_ = other.quantization_method_;
    op_set_ = other.op_set_;
  }

  StringRef getArgument() const final {
    // This is the argument used to refer to the pass in the textual format (on
    // the commandline for example).
    return "quant-insert-quantized-functions";
  }

  StringRef getDescription() const final {
    // This is a brief description of the pass.
    return "Insert quantized functions into the module";
  }

  void getDependentDialects(DialectRegistry& registry) const override {
    registry.insert<TF::TensorFlowDialect, func::FuncDialect>();
  }

 private:
  void runOnOperation() override;

  // Returns the function library for the given quantization method and opset
  // pair.
  llvm::StringRef GetFunctionLibrary(QuantizationMethod quantization_method,
                                     OpSet op_set);

  Option<QuantizationMethod> quantization_method_{
      *this, "quantization-method",
      llvm::cl::init(QuantizationMethod::kPostTrainingQuantization),
      llvm::cl::desc("Choose quantization method."),
      llvm::cl::values(
          clEnumValN(QuantizationMethod::kPostTrainingQuantization, "ptq",
                     "Post-training static-range quantization"),
          clEnumValN(QuantizationMethod::kDynamicRangeQuantization, "drq",
                     "Post-training dynamic-range quantizaiton"))};

  Option<OpSet> op_set_{
      *this, "target-opset", llvm::cl::init(OpSet::TF),
      llvm::cl::desc("Choose target opset."),
      llvm::cl::values(
          clEnumValN(OpSet::TF, "TF",
                     "Uses TF ops that mimic quantization behavior"),
          clEnumValN(OpSet::XLA, "XLA", "Uses TF XLA ops"),
          clEnumValN(OpSet::UNIFORM_QUANTIZED, "UNIFORM_QUANTIZED",
                     "Uses TF Uniform Quantized ops"))};
};

llvm::StringRef InsertQuantizedFunctionsPass::GetFunctionLibrary(
    QuantizationMethod quantization_method, OpSet op_set) {
  absl::flat_hash_map<OpSet, llvm::StringRef> function_library_map;
  if (quantization_method == QuantizationMethod::kDynamicRangeQuantization) {
    function_library_map = {
        {OpSet::UNIFORM_QUANTIZED,
         kQuantizedFunctionLibraryInMLIR_UNIFORM_QUANTIZED_DRQ},
        {OpSet::TF, kQuantizedFunctionLibraryInMLIR_TF_DRQ}};
  } else {
    function_library_map = {{OpSet::TF, kQuantizedFunctionLibraryInMLIR},
                            {OpSet::XLA, kQuantizedFunctionLibraryInMLIR}};
  }

  auto it = function_library_map.find(op_set);
  if (it != function_library_map.end()) {
    return it->second;
  }
  return llvm::StringRef();
}

static PassRegistration<InsertQuantizedFunctionsPass> pass;

void InsertQuantizedFunctionsPass::runOnOperation() {
  ModuleOp module = getOperation();
  SymbolTable symbol_table(module);

  std::unique_ptr<llvm::MemoryBuffer> mem_buffer;
  llvm::StringRef quantized_function_library =
      GetFunctionLibrary(quantization_method_, op_set_);

  if (quantized_function_library.empty()) {
    emitError(module.getLoc())
        << "Failed to get function library for the opset.";
    signalPassFailure();
    return;
  }

  mem_buffer =
      llvm::MemoryBuffer::getMemBuffer(quantized_function_library,
                                       /*BufferName=*/"",
                                       /*RequiresNullTerminator=*/false);

  llvm::SourceMgr source_mgr;
  source_mgr.AddNewSourceBuffer(std::move(mem_buffer), llvm::SMLoc());
  OwningOpRef<ModuleOp> module_ref =
      parseSourceFile<ModuleOp>(source_mgr, module.getContext());
  // Inline and optimize loaded functions.
  MLIRContext* context = &getContext();
  PassManager pm(context);
  pm.addPass(createInlinerPass());
  pm.addNestedPass<func::FuncOp>(createCanonicalizerPass());
  pm.addNestedPass<func::FuncOp>(createCSEPass());

  StatusScopedDiagnosticHandler diagnostic_handler(context);
  if (failed(pm.run(*module_ref))) {
    emitError(module.getLoc())
        << "failed to apply the optimization: "
        << diagnostic_handler.ConsumeStatus().error_message();
    signalPassFailure();
    return;
  }

  // Copy all functions used by this signature to the final MLIR module.
  for (func::FuncOp func : module_ref->getOps<func::FuncOp>()) {
    // Do nothing if the function already exists.
    if (symbol_table.lookup(func.getSymName()) != nullptr) continue;

    // Set the function to private and insert to the module.
    func::FuncOp new_func = func.clone();
    new_func.setPrivate();
    symbol_table.insert(new_func);
  }
}

}  // namespace

// Creates an instance of the pass for inserting quantized functions.
std::unique_ptr<OperationPass<ModuleOp>> CreateInsertQuantizedFunctionsPass(
    QuantizationMethod quantization_method, const OpSet& op_set) {
  return std::make_unique<InsertQuantizedFunctionsPass>(quantization_method,
                                                        op_set);
}

}  // namespace quant
}  // namespace mlir