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

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

import org.unitime.timetable.gwt.client.aria.AriaStatus;
import org.unitime.timetable.gwt.client.aria.AriaSuggestBox;
import org.unitime.timetable.gwt.client.aria.ImageButton;
import org.unitime.timetable.gwt.client.page.UniTimeNotifications;
import org.unitime.timetable.gwt.resources.GwtAriaMessages;
import org.unitime.timetable.gwt.resources.StudentSectioningConstants;
import org.unitime.timetable.gwt.resources.StudentSectioningMessages;
import org.unitime.timetable.gwt.resources.StudentSectioningResources;
import org.unitime.timetable.gwt.shared.ClassAssignmentInterface;
import org.unitime.timetable.gwt.shared.ClassAssignmentInterface.CourseAssignment;
import org.unitime.timetable.gwt.shared.CourseRequestInterface.FreeTime;
import org.unitime.timetable.gwt.shared.CourseRequestInterface.RequestedCourse;

import com.google.gwt.aria.client.Roles;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.RunAsyncCallback;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.logical.shared.HasCloseHandlers;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.SuggestOracle;
import com.google.gwt.user.client.ui.SuggestOracle.Callback;
import com.google.gwt.user.client.ui.SuggestOracle.Request;
import com.google.gwt.user.client.ui.SuggestOracle.Response;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;

/**
 * @author Tomas Muller
 */
public class CourseSelectionSuggestBox extends P implements CourseSelection {
	protected static final StudentSectioningResources RESOURCES =  GWT.create(StudentSectioningResources.class);
	protected static final StudentSectioningMessages MESSAGES = GWT.create(StudentSectioningMessages.class);
	protected static final StudentSectioningConstants CONSTANTS = GWT.create(StudentSectioningConstants.class);
	protected static final GwtAriaMessages ARIA = GWT.create(GwtAriaMessages.class);

	protected AriaSuggestBox iSuggest;
	private SimpleSuggestion iLastSuggestion;
	protected ImageButton iFinderButton;
	private Label iError;

	private String iHint = "";
	private Map<String, RequestedCourse> iValidCourseNames = new HashMap<String, RequestedCourse>();

	private DataProvider<String, Collection<CourseAssignment>> iDataProvider;
	private FreeTimeParser iFreeTimeParser = null;
	private CourseFinder iCourseFinder = null;
	private CourseFinderFactory iCourseFinderFactory = null;
	private List<Validator<CourseSelection>> iValidators = new ArrayList<Validator<CourseSelection>>();

	private boolean iShowCourses = false, iShowDefaultSuggestions = false;
	private boolean iSaved = false;

	public CourseSelectionSuggestBox() {
		this(false, false);
	}

	public CourseSelectionSuggestBox(boolean showCourses, boolean showDefaultSuggestions) {
		super("unitime-CourseSelectionBox");
		iShowCourses = showCourses;
		iShowDefaultSuggestions = showDefaultSuggestions;

		SuggestOracle courseOfferingOracle = new SuggestOracle() {
			public void requestSuggestions(Request request, Callback callback) {
				if (request.getQuery().equals(iHint)) return;
				iDataProvider.getData(request.getQuery(), new SuggestCallback(request, callback));
			}
			public void requestDefaultSuggestions(Request request, Callback callback) {
				if (iShowDefaultSuggestions)
					iDataProvider.getData("", new SuggestCallback(request, callback));
				else
					super.requestDefaultSuggestions(request, callback);

			}
			public boolean isDisplayStringHTML() { return true; }
		};

		iSuggest = new AriaSuggestBox(courseOfferingOracle);
		iSuggest.setStyleName("unitime-TextBoxHint");
		iSuggest.addStyleName("text");
		add(iSuggest);

		iFinderButton = new ImageButton(RESOURCES.search_picker(), RESOURCES.search_picker_Down(), RESOURCES.search_picker_Over(), RESOURCES.search_picker_Disabled());
		iFinderButton.setTabIndex(-1);
		iFinderButton.addStyleName("button");
		add(iFinderButton);

		iError = new Label();
		iError.setStyleName("unitime-ErrorHint");
		iError.setVisible(false);
		Roles.getPresentationRole().setAriaHiddenState(iError.getElement(), true);
		iError.addStyleName("error");
		add(iError);

		iFinderButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if (iSuggest.isEnabled()) {
					openDialogAsync();
				}
			}
		});

		iSuggest.addSelectionHandler(new SelectionHandler<Suggestion>() {
			public void onSelection(SelectionEvent<Suggestion> event) {
				iLastSuggestion = (SimpleSuggestion)event.getSelectedItem();
				if (iLastSuggestion.hasRequestedCourse())
					CourseSelectionEvent.fire(CourseSelectionSuggestBox.this, iLastSuggestion.getRequestedCourse());
				else
					CourseSelectionEvent.fire(CourseSelectionSuggestBox.this, iLastSuggestion.getReplacementString());
			}
		});
		iSuggest.getValueBox().addChangeHandler(new ChangeHandler() {
			public void onChange(ChangeEvent event) {
				String text = iSuggest.getText();
				if (iLastSuggestion != null && text.equalsIgnoreCase(iLastSuggestion.getReplacementString()) && iLastSuggestion.hasRequestedCourse()) {
					CourseSelectionEvent.fire(CourseSelectionSuggestBox.this, iLastSuggestion.getRequestedCourse());
				} else if (iValidCourseNames.containsKey(text.toLowerCase())) {
					CourseSelectionEvent.fire(CourseSelectionSuggestBox.this, iValidCourseNames.get(text.toLowerCase()));
				} else {
					CourseSelectionEvent.fire(CourseSelectionSuggestBox.this, text);
				}
			}
		});
		iSuggest.getValueBox().addKeyDownHandler(new KeyDownHandler() {
			public void onKeyDown(KeyDownEvent event) {
				if (!iSuggest.isEnabled()) return;
				if ((event.getNativeEvent().getKeyCode()=='F' || event.getNativeEvent().getKeyCode()=='f') && (event.isControlKeyDown() || event.isAltKeyDown())) {
					iSuggest.hideSuggestionList();
					openDialogAsync();
				}
				if (event.getNativeEvent().getKeyCode()==KeyCodes.KEY_ESCAPE) {
					iSuggest.hideSuggestionList();
				}
				if ((event.getNativeEvent().getKeyCode()=='L' || event.getNativeEvent().getKeyCode()=='l') && (event.isControlKeyDown() || event.isAltKeyDown())) {
					iSuggest.showSuggestionList();
				}
			}
		});
		iSuggest.getValueBox().addBlurHandler(new BlurHandler() {
			public void onBlur(BlurEvent event) {
				if (iSuggest.getText().isEmpty()) {
					if (iError.isVisible()) iError.setVisible(false);
					if (!iHint.isEmpty()) {
						iSuggest.setText(iHint);
						iSuggest.setStyleName("unitime-TextBoxHint");
					}
				}
			}
		});
		iSuggest.getValueBox().addFocusHandler(new FocusHandler() {
			public void onFocus(FocusEvent event) {
				iSuggest.setStyleName("gwt-SuggestBox");
				if (!iHint.isEmpty() && iSuggest.getText().equals(iHint)) iSuggest.setText("");
				if (!iError.getText().isEmpty())
					AriaStatus.getInstance().setText(iError.getText());
			}
		});
	}

	@Override
	public RequestedCourse getValue() {
		if (iSuggest.getText().equals(iHint) || iSuggest.getText().trim().isEmpty()) return new RequestedCourse();
		if (iLastSuggestion != null && iLastSuggestion.hasRequestedCourse() && iSuggest.getText().equalsIgnoreCase(iLastSuggestion.getReplacementString()))
			return iLastSuggestion.getRequestedCourse();
		if (iValidCourseNames.containsKey(iSuggest.getText().toLowerCase())) {
			return iValidCourseNames.get(iSuggest.getText().toLowerCase().toLowerCase());
		}
		RequestedCourse ret = new RequestedCourse();
		if (iFreeTimeParser != null) {
			try {
				ret.setFreeTime(iFreeTimeParser.parseFreeTime(iSuggest.getText()));
			} catch (IllegalArgumentException e) {
				ret.setCourseName(iSuggest.getText());
			}
		} else {
			ret.setCourseName(iSuggest.getText());
		}
		if (!isEnabled() && ret.isCourse() && isSaved()) ret.setReadOnly(true);
		return ret;
	}

	public boolean hasValue() {
		RequestedCourse value = getValue();
		return value != null && !value.isEmpty();
	}

	public String getText() {
		return iSuggest.getText().equals(iHint) ? "" : iSuggest.getText();
	}

	@Override
	public void setValue(RequestedCourse value) {
		setValue(value, false);
	}

	private void openDialogAsync() {
        GWT.runAsync(new RunAsyncCallback() {
        	public void onSuccess() {
        		openDialog();
        	}
        	public void onFailure(Throwable reason) {
        		UniTimeNotifications.error(MESSAGES.failedToLoadTheApp(reason.getMessage()));
        	}
        });
	}

	private void openDialog() {
		getCourseFinder().setValue(getValue(), true);
		getCourseFinder().findCourse();
	}

	@Override
	public void setValue(RequestedCourse value, boolean fireEvents) {
		if (value == null || value.isEmpty()) {
			iSaved = false;
			iSuggest.setText(iHint);
			if (!iHint.isEmpty())
				iSuggest.setStyleName("unitime-TextBoxHint");
			else
				iSuggest.setStyleName("gwt-SuggestBox");
			setError(null);
		} else {
			iSaved = value.isReadOnly();
			iLastSuggestion = new SimpleSuggestion(value);
			iSuggest.setText(iLastSuggestion.getReplacementString());
			if (iSuggest.getText().isEmpty()) {
				if (!iHint.isEmpty()) {
					iSuggest.setText(iHint);
					iSuggest.setStyleName("unitime-TextBoxHint");
				} else {
					iSuggest.setStyleName("gwt-SuggestBox");
				}
			} else {
				iSuggest.setStyleName("gwt-SuggestBox");
			}
		}
		if (fireEvents)
			CourseSelectionEvent.fire(CourseSelectionSuggestBox.this, value);
	}

	@Override
	public HandlerRegistration addValueChangeHandler(ValueChangeHandler<RequestedCourse> handler) {
		return addHandler(handler, ValueChangeEvent.getType());
	}

	@Override
	public void setHint(String hint) {
		if (iSuggest.getText().equals(iHint)) {
			iSuggest.setText(hint);
			if (!hint.isEmpty())
				iSuggest.setStyleName("unitime-TextBoxHint");
		}
		iHint = hint;
	}

	@Override
	public String getHint() {
		return iHint;
	}

	@Override
	public boolean isEnabled() {
		return iSuggest.isEnabled();
	}

	@Override
	public void setEnabled(boolean enabled) {
		if (enabled) {
			iSuggest.setEnabled(true);
			iFinderButton.setEnabled(true);
			iFinderButton.setTabIndex(0);
		} else {
			iSuggest.setEnabled(false);
			iFinderButton.setEnabled(false);
			iFinderButton.setTabIndex(-1);
			if (iSaved) iFinderButton.setFace(RESOURCES.search_picker_Assigned());
		}
	}

	public void setSaved(boolean saved) {
		iSaved = saved;
		if (!isEnabled())
			iFinderButton.setFace(saved ? RESOURCES.search_picker_Assigned() : RESOURCES.search_picker_Disabled());
		iFinderButton.setTitle(saved ? MESSAGES.saved(iSuggest.getValue()) : iFinderButton.getAltText());
	}

	public boolean isSaved() {
		return iSaved;
	}

	@Override
	public void setSuggestions(DataProvider<String, Collection<CourseAssignment>> provider) {
		iDataProvider = provider;
	}

	@Override
	public void setFreeTimes(FreeTimeParser parser) {
		iFreeTimeParser = parser;
		iFreeTimeParser.setValidCourseNames(iValidCourseNames);
	}

	@Override
	public FreeTimeParser getFreeTimes() {
		return iFreeTimeParser;
	}

	public boolean isAllowFreeTime() {
		return iFreeTimeParser != null;
	}

	public class SuggestCallback implements AsyncCallback<Collection<ClassAssignmentInterface.CourseAssignment>> {
		private Request iRequest;
		private Callback iCallback;

		public SuggestCallback(Request request, Callback callback) {
			iRequest = request;
			iCallback = callback;
		}

		public void onFailure(final Throwable caught) {
			iValidCourseNames.clear();
			final ArrayList<Suggestion> suggestions = new ArrayList<Suggestion>();
			if (iFreeTimeParser != null) {
				iFreeTimeParser.getData(iRequest.getQuery(), new AsyncCallback<List<FreeTime>>() {
					@Override
					public void onFailure(Throwable e) {
						if (iRequest.getQuery().toLowerCase().startsWith(CONSTANTS.freePrefix().toLowerCase())) {
							suggestions.add(new SimpleSuggestion(e));
							// setStatus(e.getMessage());
						} else {
							suggestions.add(new SimpleSuggestion(caught));
							// setStatus(caught.getMessage());
						}
					}

					@Override
					public void onSuccess(List<FreeTime> freeTimes) {
						suggestions.add(new SimpleSuggestion(freeTimes));
					}
				});
			} else {
				suggestions.add(new SimpleSuggestion(caught));
				// setStatus(caught.getMessage());
			}
			iCallback.onSuggestionsReady(iRequest, new Response(suggestions));
		}

		public void onSuccess(Collection<ClassAssignmentInterface.CourseAssignment> result) {
			ArrayList<Suggestion> suggestions = new ArrayList<Suggestion>();
			iValidCourseNames.clear();
			for (ClassAssignmentInterface.CourseAssignment course: result) {
				SimpleSuggestion suggestion = new SimpleSuggestion(course, iShowCourses);
				suggestions.add(suggestion);
				iValidCourseNames.put(suggestion.getReplacementString().toLowerCase(), suggestion.getRequestedCourse());
			}
			iCallback.onSuggestionsReady(iRequest, new Response(suggestions));
		}
	}

	public static class SimpleSuggestion implements Suggestion, AriaSuggestBox.HasStatus {
		private String iDisplay, iReplace, iStatus;
		private RequestedCourse iSuggestion = null;

		public SimpleSuggestion(Throwable error) {
			iDisplay = ""+error.getMessage()+"";
			iReplace = "";
			iStatus = error.getMessage();
		}

		public SimpleSuggestion(List<FreeTime> freeTimes) {
			iSuggestion = new RequestedCourse();
			iSuggestion.setFreeTime(freeTimes);
			iDisplay = iSuggestion.toString(CONSTANTS);
			iReplace = iDisplay;
			iStatus = ARIA.courseFinderSelectedFreeTime(iSuggestion.toAriaString(CONSTANTS));
		}

		public SimpleSuggestion(ClassAssignmentInterface.CourseAssignment suggestion, boolean showCourseTitle) {
			iDisplay = (suggestion.hasTitle() ? MESSAGES.courseNameWithTitle(suggestion.getSubject(), suggestion.getCourseNbr(), suggestion.getTitle()) : MESSAGES.courseName(suggestion.getSubject(), suggestion.getCourseNbr()));
			if (suggestion.hasUniqueName() && !showCourseTitle) {
				iReplace = MESSAGES.courseName(suggestion.getSubject(), suggestion.getCourseNbr());
			} else {
				iReplace = iDisplay;
			}
			iStatus = MESSAGES.courseName(suggestion.getSubject(), suggestion.getCourseNbr());
			if (suggestion.hasTitle()) iStatus += " " + suggestion.getTitle();
			iSuggestion = new RequestedCourse();
			iSuggestion.setCourseId(suggestion.getCourseId());
			iSuggestion.setCourseName(iReplace);
		}

		public SimpleSuggestion(RequestedCourse course) {
			if (course.isCourse()) {
				iDisplay = course.getCourseName();
				iReplace = course.getCourseName();
				iStatus = course.getCourseName();
			} else if (course.isFreeTime()) {
				iDisplay = course.toString(CONSTANTS);
				iReplace = iDisplay;
				iStatus = ARIA.courseFinderSelectedFreeTime(course.toAriaString(CONSTANTS));
			}
			iSuggestion = course;
		}

		@Override
		public String getDisplayString() {
			return iDisplay;
		}

		@Override
		public String getReplacementString() {
			return iReplace;
		}

		@Override
		public String getStatusString() {
			return iStatus;
		}

		public boolean hasRequestedCourse() {
			return iSuggestion != null;
		}

		public RequestedCourse getRequestedCourse() {
			return iSuggestion;
		}
	}

	@Override
	public void setCourseFinderFactory(CourseFinderFactory factory) {
		iCourseFinderFactory = factory;
	}

	@Override
	public CourseFinder getCourseFinder() {
		if (iCourseFinder == null) {
			iCourseFinder = iCourseFinderFactory.createCourseFinder();
			iCourseFinder.addSelectionHandler(new SelectionHandler<RequestedCourse>() {
				@Override
				public void onSelection(SelectionEvent<RequestedCourse> event) {
					setValue(event.getSelectedItem(), true);
				}
			});
			if (iCourseFinder instanceof HasCloseHandlers) {
				((HasCloseHandlers)iCourseFinder).addCloseHandler(new CloseHandler<PopupPanel>() {
					public void onClose(CloseEvent<PopupPanel> event) {
						Scheduler.get().scheduleDeferred(new ScheduledCommand() {
							public void execute() {
								iSuggest.setFocus(true);
							}
						});
					}
				});
			}
		}
		return iCourseFinder;
	}

	@Override
	public void setLabel(String title, String finderTitle) {
		iSuggest.setAriaLabel(title);
		iFinderButton.setAltText(finderTitle);
	}

	@Override
	public void hideSuggestionList() {
		iSuggest.hideSuggestionList();
	}

	@Override
	public void showSuggestionList() {
		iSuggest.showSuggestionList();
	}

	@Override
	public void setWidth(String width) {
		iSuggest.setWidth(width);
	}

	@Override
	public void setError(String error) {
		if (error == null || error.isEmpty()) {
			iError.setText("");
			iError.setVisible(false);
		} else {
			iError.setText(error);
			iError.setVisible(true);
			iSuggest.setStatus(error);
			// AriaStatus.getInstance().setText(error);
		}
	}

	@Override
	public String getError() {
		return (iError.isVisible() ? iError.getText() : null);
	}

	@Override
	public void setAccessKey(char a) {
		iSuggest.setAccessKey(a);
	}

	@Override
	public int getTabIndex() {
		return iSuggest.getTabIndex();
	}

	@Override
	public void setFocus(boolean focused) {
		iSuggest.setFocus(focused);
		if (focused) iSuggest.getValueBox().selectAll();
	}

	@Override
	public void setTabIndex(int index) {
		iSuggest.setTabIndex(index);
	}

	@Override
	public HandlerRegistration addCourseSelectionHandler(CourseSelectionHandler handler) {
		return addHandler(handler, CourseSelectionEvent.getType());
	}

	@Override
	public void addValidator(Validator<CourseSelection> validator) {
		iValidators.add(validator);
	}

	public String validate() {
		if (getValue().isEmpty()) {
			setError(null);
			return null;
		}
		if (iFreeTimeParser != null) {
			try {
				iFreeTimeParser.parseFreeTime(iSuggest.getValue());
				setError(null);
				return null;
			} catch (IllegalArgumentException e) {
				if (iSuggest.getValue().toLowerCase().startsWith(CONSTANTS.freePrefix().toLowerCase())) {
					setError(MESSAGES.invalidFreeTime());
					return e.getMessage();
				}
			}
		}
		for (Validator<CourseSelection> validator: iValidators) {
			String message = validator.validate(this);
			if (message != null) {
				setError(message);
				return message;
			}
		}
		setError(null);
		return null;
	}
}


text:
<form action="#" method="get" class="sidebar-form">

        <input type="text" name="q" class="form-control" placeholder="Search...">

            <button type="submit" name="search" id="search-btn" class="btn btn-flat"></button>

</form>

MAIN NAVIGATION

             Dashboard

            Template

                     Keyword

                    IAB Block

            Ad Unit

            Publisher

            Rules

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;

namespace osu.Game.Online.API.Requests.Responses
{
    public class CommentBundle
    {
        [JsonProperty(@"comments")]
        public List<Comment> Comments { get; set; }

        [JsonProperty(@"has_more")]
        public bool HasMore { get; set; }

        [JsonProperty(@"has_more_id")]
        public long? HasMoreId { get; set; }

        [JsonProperty(@"user_follow")]
        public bool UserFollow { get; set; }

        [JsonProperty(@"included_comments")]
        public List<Comment> IncludedComments { get; set; }

        [JsonProperty(@"pinned_comments")]
        public List<Comment> PinnedComments { get; set; }

        private List<long> userVotes;

        [JsonProperty(@"user_votes")]
        public List<long> UserVotes
        {
            get => userVotes;
            set
            {
                userVotes = value;

                Comments.ForEach(c => c.IsVoted = value.Contains(c.Id));
                IncludedComments.ForEach(c => c.IsVoted = value.Contains(c.Id));
            }
        }

        private List<APIUser> users;

        [JsonProperty(@"users")]
        public List<APIUser> Users
        {
            get => users;
            set
            {
                users = value;

                foreach (var user in value)
                {
                    foreach (var comment in Comments.Concat(IncludedComments).Concat(PinnedComments))
                    {
                        if (comment.UserId == user.Id)
                            comment.User = user;

                        if (comment.EditedById == user.Id)
                            comment.EditedUser = user;
                    }
                }
            }
        }

        [JsonProperty(@"total")]
        public int Total { get; set; }

        [JsonProperty(@"top_level_count")]
        public int TopLevelCount { get; set; }
    }
}


text:
#ifndef __MODBUSIO_H__
#define __MODBUSIO_H__

#include <errno.h>
#include <QList>
#include <QString>

#include "global.h"

class ModbusDevice;

typedef QList<const class ModbusIO *> ModbusIOPtrList;

class ModbusIO {
	public:
		ModbusIO(QString name, ModbusDevice *dev);
		virtual ~ModbusIO();

		virtual QString name() const { return mName; };
		virtual int  getValue() const { return -ENOTSUP; }
		virtual void setValue(int value) { UNUSED(value); }
	protected:
		ModbusDevice *mDev;
		QString mName;

		virtual ModbusIOPtrList *objList() { return NULL; }
};

class BitInput : public ModbusIO {
		int mBitAddr;
	public:
		BitInput(QString name, ModbusDevice *dev, int bitAddr);
		virtual ~BitInput() { }

		virtual int getValue() const;

	public:
		static const ModbusIOPtrList *elements() { return &mElements; }
	protected:
		virtual ModbusIOPtrList *objList() { return &mElements; }
	private:
		static ModbusIOPtrList mElements;
};

class BitOutput : public ModbusIO {
		int mBitAddr;
	public:
		BitOutput(QString name, ModbusDevice *dev, int bitAddr);
		virtual ~BitOutput() { }

		virtual int  getValue() const;
		virtual void setValue(int value);

	public:
		static const ModbusIOPtrList *elements() { return &mElements; }
	protected:
		virtual ModbusIOPtrList *objList() { return &mElements; }
	private:
		static ModbusIOPtrList mElements;
};

class WordInput : public ModbusIO {
		int mWordAddr;
	public:
		WordInput(QString name, ModbusDevice *dev, int wordAddr);
		virtual ~WordInput() { }

		virtual int getValue() const;

	public:
		static const ModbusIOPtrList *elements() { return &mElements; }
	protected:
		virtual ModbusIOPtrList *objList() { return &mElements; }
	private:
		static ModbusIOPtrList mElements;
};

class WordOutput : public ModbusIO {
		int mWordAddr;
	public:
		WordOutput(QString name, ModbusDevice *dev, int wordAddr);
		virtual ~WordOutput() { }

		virtual int  getValue() const;
		virtual void setValue(int value);

	public:
		static const ModbusIOPtrList *elements() { return &mElements; }
	protected:
		virtual ModbusIOPtrList *objList() { return &mElements; }
	private:
		static ModbusIOPtrList mElements;
};

class FloatInput : public ModbusIO {
		int mWordAddr;
		double mScale;
	public:
		FloatInput(QString name, ModbusDevice *dev, int wordAddr, double scale);
		virtual ~FloatInput() { }

		virtual int getValue() const;

	public:
		static const ModbusIOPtrList *elements() { return &mElements; }
	protected:
		virtual ModbusIOPtrList *objList() { return &mElements; }
	private:
		static ModbusIOPtrList mElements;
};

#endif /* __MODBUSIO_H__ */


text:
layout: default
---

Affordable ediscovery

          GoldFynch is a cloud based e-discovery review platform, designed for the modern law firm. It automatically scales to host, process, review and produce your growing ediscovery needs. Join the hundreds of lawyers and solicitors around the world, who use GoldFynch at an affordable, fixed monthly fee.

            Signup

Signup is simple and takes only a few steps.  You'll get a free case to try GoldFynch out - no sales call, no credit-card required.

            See how it works

Why GoldFynch?

Exceptional User Experience

Simple in-browser drag and drop uploads, all inclusive OCR, designed from group up and effortless workflows.

                Learn More »

Unrivaled file types support

PDF, PST, MBOX, MSG, EML, DOC, DOCX, RTF, XLS, XLSX, PPT, PPTX, POTX, ODT, TIFF, JPEG, ZIP, RAR to name a few and aways growing.

                Learn More »

Pricing which doesn't break the bank

Simple and predictable per case pricing which is affordable and offers no suprises.
                    search syntax

                Learn More »

Bank-grade security

Financial industry standard experts safeguard your data, so breathe easy that it is secure.

                Learn More »

Collaborative Ediscovery, on the go

GoldFynch runs off the cloud, which means it goes where you go.  Share cases with all your partners.

Login from Anywhere

                        Login and access your data from anywhere. GoldFynch runs on the Cloud, so work on your case wherever you are. Just login from your favorite device and you're ready to start.

Unlimited case sharing

                       Share a case with all involved peers.  Everyone can upload and review data on a shared case.  Collaborate with remote and local parties alike.

Access Control

                      Restrict and revoke access of peers at any time.  Turn users into admins, choose what you share.

All these great features and a free case to test drive GoldFynch when you sign up.  No credit-card required.

              See how it works

              Signup to see it in action

Unprecedented ease of use

Industry and UI experts came together to design GoldFynch's user interface. Getting the job done as easily as possible is our prime directive.

Drag and Drop uploads

                      Drag and drop files or folders onto GoldFynch browser window.  Files will be automatically uploaded and process them for you.

Automatic and completely unintrusive OCR processing

                      All uploaded matter is automatically processed through our processing piplines.  Any documents that may need OCR are automatically OCRed.  Have images with text?  GoldFynch will automatically detect and process such files.

Classify and Code documents like never before

                      Using GoldFynch's unified tagging system you never have to worry about or remember complex ways of coding a document.  Tagging works as the basis of effective searches, document classification and fast productions.

Affordable tools at affordable prices.  Level the playfield. Cases starting at $15 per case per month.

              See how it works

              Signup to see it in action

Tools you're used to, only better

From re-thought searches to production workflows, everything in GoldFynch has been built ground up to deliver the best possible user experience.

Simple but effective searches

                      Search like you search the internet, and progressively refine your results till you find what you need.  No complex search syntax.  GoldFynch will automatically suggest search criterion and deliver blazing fast results.

Produce like a pro

                      A simplified production workflow lets you produce as often as you like with minimum resistance.  Produce as much as you like.

Matter intelligence and linking

                      GoldFynch automatically extracts relevant enties from your matter and links it with documents so you know exactly what, where and when a particular document is talking about.

Intelligent ediscovery tools, all-inclusive at your fingertips.

              See how it works

              Signup to see it in action

What our customers are saying

They resisted the temptation to clutter the program and kept it simple. GoldFynch is software with zero learning curve.

- Kevin Caster
Shuttworth & Ingersoll

GoldFynch levels the e-discovery playing field for smaller firms. It improves attorney efficiency by 60% and offers functionality that was only previously available on expensive platforms.

- Andrew Funk
Funk - Riemann


text:
from streamlink.plugins.mrtmk import MRTmk
from tests.plugins import PluginCanHandleUrl

class TestPluginCanHandleUrlMRTmk(PluginCanHandleUrl):
    __plugin__ = MRTmk

    should_match = [
        'http://play.mrt.com.mk/live/658323455489957',
        'http://play.mrt.com.mk/live/47',
        'http://play.mrt.com.mk/play/1581',
    ]

    should_not_match = [
        'http://play.mrt.com.mk/',
        'http://play.mrt.com.mk/c/2',
    ]


text:
// Here lies the test environment's version of defineModule.
//
// This creates test friendly proxy objects for every module that gets defined.
// These proxy objects can act either as the real module would, or act as a dummy object with
// which any of the modules' exports may be manipulated as unit tests see fit.
//
// We use a fake "exports" variable here to get around the fact that there is a real
// implementation of "exports" and "require" in node.
var defineModuleStack = 0;
global.defineModule = function (key, block, definingModuleArgs) {
    // arguments.callee.caller.arguments are (exports, require, module, __filename, __dirname)
    if(undefined === definingModuleArgs) {
        definingModuleArgs = arguments.callee.caller.arguments;
    }

    var fakeModule = definingModuleArgs[2];
    var fakeExports = {};

    block(require, fakeExports);

    fakeModule.exports = fakeExports;
};

/**
 * Some of the test environment's modules really just require a real module to do
 * it's work. e.g. the test environment's kirin.js just uses the kirin-webkit module.
 * i.e. these modules masquerade as real modules.
 * This function helps define one of these modules.
 *
 * Implementation: All of the exports from the real module are copied into the
 * alias module's exports.
 * Any functions in those exports are converted into a proxy function that call the real
 * module's function. The proxy functions will then re-mirror/re-copy all of the real modules
 * exports (except the functions) into the alias module.
 */
global.defineModuleAlias = function(proxyModuleName, targetModuleName) {
    defineModule(proxyModuleName, function (require, exports) {
        var realKirinObject = require(targetModuleName);

        var proxify = function(fakeExports, realExports) {
            _.each(_.keys(realExports), function(key) {
                var value = realExports[key];

                if(_.isFunction(value)) {
                    // Create a proxy to call the real function
                    if(!fakeExports[key].__isAProxy) {
                        fakeExports[key] = function(){
                            var realFunc = value;
                            var result = realFunc.apply(this, arguments);

                            // Make sure all of the properties of the real exports are mirrored in the fake exports.
                            proxify(exports, realKirinObject);

                            return result;
                        };
                        fakeExports[key].__isAProxy = true; // Guard against proxying way too much (--> stack overflow)
                    }
                } else if("object" === typeof value && !_.isNull(value)) {
                    // Recurse into the object
                    fakeExports[key] = realExports[key];
                    proxify(fakeExports[key], realExports[key]);
                } else {
                    // It's some kind of primitive, property, or array.
                    // Make the fakeExports mirror the real exports.
                    fakeExports[key] = realExports[key];
                }
            });
        }

        _.extend(exports, realKirinObject);

        proxify(exports, realKirinObject);
    }, arguments.callee.caller.arguments);
}


text:
permalink: /flat
---
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Flat UI Free 101 Template</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="../dist/css/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="../dist/css/flat-ui.min.css" rel="stylesheet">

    <link rel="shortcut icon" href="img/favicon.ico">

Hello, world!


text:
userId = window.localStorage.getItem('stuuff:id');

Meteor.call('setUserId', userId, function(error, id) {
	userId = id;
	window.localStorage.setItem('stuuff:id', userId);
});

Meteor.subscribe('Items', userId, function() {

	// No items, not even default
	if(!Items.findOne()) {
		Items.insert({_id:userId, userId:userId, type:'list', allow:'list', title:'Welcome! Double click on me to change!'});
	}
});


text:
using GitVersion.Logging;
using GitVersion.OutputVariables;

namespace GitVersion.BuildAgents
{
    public class GitHubActions : BuildAgentBase
    {
        // https://help.github.com/en/actions/automating-your-workflow-with-github-actions/using-environment-variables#default-environment-variables

        public GitHubActions(IEnvironment environment, ILog log) : base(environment, log)
        {
        }

        public const string EnvironmentVariableName = "GITHUB_ACTIONS";
        protected override string EnvironmentVariable { get; } = EnvironmentVariableName;

        public override string GenerateSetVersionMessage(VersionVariables variables)
        {
            // There is no equivalent function in GitHub Actions.

            return string.Empty;
        }

        public override string[] GenerateSetParameterMessage(string name, string value)
        {
            // https://help.github.com/en/actions/automating-your-workflow-with-github-actions/development-tools-for-github-actions#set-an-environment-variable-set-env
            // Example
            // echo "::set-env name=action_state::yellow"

            if (!string.IsNullOrWhiteSpace(value))
            {
                var key = $"GitVersion_{name}";

                return new[]
                {
                    $"::set-env name={key}::{value}"
                };
            }

            return new string[0];
        }

        public override string GetCurrentBranch(bool usingDynamicRepos)
        {
            return Environment.GetEnvironmentVariable("GITHUB_REF");
        }

        public override bool PreventFetch() => true;
    }
}


text:
package gr.geomike.ted.api.db.entity;

import gr.geomike.ted.Views;
import com.fasterxml.jackson.annotation.JsonView;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;

@XmlRootElement(name = "Items")
public class Items {
    private List<Item> items;

    @JsonView(Views.Item.class)
    @XmlElement(name = "Item")
    public List<Item> getItems(){
        return  items;
    }
    public void setItems(List<Item> items){
        this.items = items;
    }
}


text:
// -----------------------------------------------------------------------
//  <copyright file="Program.cs" company="Asynkron HB">
//      Copyright (C) 2015-2017 Asynkron HB All rights reserved
//  </copyright>
// -----------------------------------------------------------------------

using System;
using System.Threading.Tasks;
using Proto;
using Proto.Router;

namespace RouterExample
{
    internal class Message : IHashable
    {
        public string Text;

        public string HashBy()
        {
            return Text;
        }

        public override string ToString()
        {
            return Text;
        }
    }

    internal class MyActor : IActor
    {
        public Task ReceiveAsync(IContext context)
        {
            var msg = context.Message as Message;
            if (msg != null)
            {
                Console.WriteLine($"Actor {context.Self.Id} got message '{msg.Text}'.");
            }
            return Actor.Done;
        }
    }

    internal class Program
    {
        private static readonly Props MyActorProps = Actor.FromProducer(() => new MyActor());

        private static void Main()
        {
            TestBroadcastPool();
            //TestBroadcastGroup();

            //TestRandomPool();
            //TestRandomGroup();

            //TestRoundRobinPool();
            //TestRoundRobinGroup();

            //TestConsistentHashPool();
            //TestConsistentHashGroup();

            Console.ReadLine();
        }

        private static void TestBroadcastGroup()
        {
            var props = Router.NewBroadcastGroup(
                Actor.Spawn(MyActorProps),
                Actor.Spawn(MyActorProps),
                Actor.Spawn(MyActorProps),
                Actor.Spawn(MyActorProps)
            );
            for (var i = 0; i < 10; i++)
            {
                var pid = Actor.Spawn(props);
                pid.Tell(new Message {Text = $"{i % 4}"});
            }
        }

        private static void TestBroadcastPool()
        {
            var props = Router.NewBroadcastPool(MyActorProps, 5);
            var pid = Actor.Spawn(props);
            for (var i = 0; i < 10; i++)
            {
                pid.Tell(new Message {Text = $"{i % 4}"});
            }
        }

        private static void TestConsistentHashGroup()
        {
            var props = Router.NewConsistentHashGroup(
                Actor.Spawn(MyActorProps),
                Actor.Spawn(MyActorProps),
                Actor.Spawn(MyActorProps),
                Actor.Spawn(MyActorProps)
            );
            var pid = Actor.Spawn(props);
            for (var i = 0; i < 10; i++)
            {
                pid.Tell(new Message {Text = $"{i % 4}"});
            }
        }

        private static void TestConsistentHashPool()
        {
            var props = Router.NewConsistentHashPool(MyActorProps, 5);
            var pid = Actor.Spawn(props);
            for (var i = 0; i < 10; i++)
            {
                pid.Tell(new Message {Text = $"{i % 4}"});
            }
        }

        private static void TestRoundRobinGroup()
        {
            var props = Router.NewRoundRobinGroup(
                Actor.Spawn(MyActorProps),
                Actor.Spawn(MyActorProps),
                Actor.Spawn(MyActorProps),
                Actor.Spawn(MyActorProps)
            );
            var pid = Actor.Spawn(props);
            for (var i = 0; i < 10; i++)
            {
                pid.Tell(new Message {Text = $"{i % 4}"});
            }
        }

        private static void TestRoundRobinPool()
        {
            var props = Router.NewRoundRobinPool(MyActorProps, 5);
            var pid = Actor.Spawn(props);
            for (var i = 0; i < 10; i++)
            {
                pid.Tell(new Message {Text = $"{i % 4}"});
            }
        }

        private static void TestRandomGroup()
        {
            var props = Router.NewRandomGroup(
                Actor.Spawn(MyActorProps),
                Actor.Spawn(MyActorProps),
                Actor.Spawn(MyActorProps),
                Actor.Spawn(MyActorProps)
            );
            var pid = Actor.Spawn(props);
            for (var i = 0; i < 10; i++)
            {
                pid.Tell(new Message {Text = $"{i % 4}"});
            }
        }

        private static void TestRandomPool()
        {
            var props = Router.NewRandomPool(MyActorProps, 5);
            var pid = Actor.Spawn(props);
            for (var i = 0; i < 10; i++)
            {
                pid.Tell(new Message {Text = $"{i % 4}"});
            }
        }
    }
}


text:
<link rel="import" href="bower_components/polymer/polymer.html">

<link rel="import" href="bower_components/paper-scroll-header-panel/paper-scroll-header-panel.html">
<link rel="import" href="bower_components/iron-icons/iron-icons.html">
<link rel="import" href="bower_components/paper-toolbar/paper-toolbar.html">
<link rel="import" href="bower_components/paper-material/paper-material.html">
<link rel="import" href="bower_components/paper-ripple/paper-ripple.html">
<link rel="import" href="bower_components/paper-item/paper-item.html">
<link rel="import" href="bower_components/paper-item/paper-item-body.html">
<link rel="import" href="bower_components/paper-input/paper-input.html">

<link rel="import" href="bower_components/neon-animation/neon-shared-element-animatable-behavior.html">

<dom-module id="search-page">

	<template>
		<paper-scroll-header-panel condenses>
            <paper-toolbar>

	                <paper-icon-button icon="arrow-back" class="leftIcon" on-click="backToMain"></paper-icon-button>
					<input id="searchBox" class="flex" placeholder="Search for stop names..." autofocus on-input="queryStops" on-keypress="handleKeypress">

            </paper-toolbar>

					<template is="dom-repeat" items="{{queryList}}" as="stop">

{{stop.n}}

							<iron-icon icon="arrow-forward"></iron-icon>
							<paper-ripple></paper-ripple>

					</template>

        </paper-scroll-header-panel>
	</template>
</dom-module>


text:
<?php
/* HEADER
 * 24/08/2012
 * CREATION DU FICHIER
 */

namespace MyApp\GdaBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class AnomalieForm extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder

            ->add('dateCreation','date', array(
                                                'widget' => 'single_text',
                                                'input' => 'datetime',
                                                'format' => 'dd/MM/yyyy',
                                                'attr' => array('class' => 'date'),
                                                ))
            ->add('createur', 'entity', array(
                'class'=>'MyAppGdaBundle:Utilisateur'))
            ->add('projet', 'entity', array(
                'class'=>'MyAppGdaBundle:Projet'))
            ->add('categorie', 'entity', array(
                'class'=>'MyAppGdaBundle:Categorie'))
            ->add('description', 'textarea')
        ;
    }

    public function getName()
    {
        return 'anomalieForm';
    }

}
?>


text:
module MuckComments
  module Models
    module MuckCommentable
      extend ActiveSupport::Concern

      included do
        has_many :comments, :as => :commentable, :dependent => :destroy
      end

      # Helper method to display only root threads, no children/replies
      def root_comments
        self.comments.find(:all, :conditions => {:parent_id => nil})
      end

      # Helper method that defaults the submitted time.
      def add_comment(comment)
        self.comments << comment
      end

      # Determines whether or not the give user can comment on the parent object
      def can_comment?(user)
        return true unless user.blank?
        false
      end

    end

  end
end


text:
import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {User} from '../user/user';
import {Industry} from './industry';
import {IndustryService} from './industry.service';
import {UserService} from '../user/user.service';

@Component({
	moduleId: module.id,
	selector: 'industry-select',
	templateUrl: 'industry-select.component.html',
	styleUrls: ['industry-select.component.css']
})

//TODO :
export class IndustrySelect {
	industries: Industry[];
	user: User;

	constructor(private industryService: IndustryService, private userService: UserService) {}

	ngOnInit(){this.getIndustries();this.getUser();}

	getIndustries(): void{
		this.industryService.getIndustries().then(industries => this.industries = industries);
		console.log(this.industries);
	}

	getUser(): void{
		this.userService.getUser().then(user => this.user = user);
		console.log(this.user);
	}
}


text:
reportApp.directive('itemPage', ['utilService', function(util) {
  return {
    templateUrl: 'partials/itemPage.html',
    controller: 'itemPageController',
    scope: {
      data: '=data',
      controls: '=controls'
    },
    link: link
  }

  function link($scope) {
    $scope.$watch('data', function(){
      buildItem();
      console.log("[itemPageDirective][change]item=%s", angular.toJson($scope.item));
    }, true);

    function buildItem(){
      if(!$scope.data.selectedItem){
        return;
      }
      util.buildItemDisplayData($scope.data.selectedItem, function(data){
        $scope.item = data;
      });
    }
  }
}]);


text:
#include <linux/err.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/rtc.h>
#include <linux/spinlock.h>
#include <linux/types.h>
#include <linux/log2.h>

#include <asm/div64.h>
#include <asm/io.h>
#include <asm/uaccess.h>

MODULE_AUTHOR("Yoichi Yuasa <yuasa@linux-mips.org>");
MODULE_DESCRIPTION("NEC VR4100 series RTC driver");
MODULE_LICENSE("GPL v2");

/* RTC 1 registers */
#define ETIMELREG		0x00
#define ETIMEMREG		0x02
#define ETIMEHREG		0x04
/* RFU */
#define ECMPLREG		0x08
#define ECMPMREG		0x0a
#define ECMPHREG		0x0c
/* RFU */
#define RTCL1LREG		0x10
#define RTCL1HREG		0x12
#define RTCL1CNTLREG		0x14
#define RTCL1CNTHREG		0x16
#define RTCL2LREG		0x18
#define RTCL2HREG		0x1a
#define RTCL2CNTLREG		0x1c
#define RTCL2CNTHREG		0x1e

/* RTC 2 registers */
#define TCLKLREG		0x00
#define TCLKHREG		0x02
#define TCLKCNTLREG		0x04
#define TCLKCNTHREG		0x06
/* RFU */
#define RTCINTREG		0x1e
 #define TCLOCK_INT		0x08
 #define RTCLONG2_INT		0x04
 #define RTCLONG1_INT		0x02
 #define ELAPSEDTIME_INT	0x01

#define RTC_FREQUENCY		32768
#define MAX_PERIODIC_RATE	6553

static void __iomem *rtc1_base;
static void __iomem *rtc2_base;

#define rtc1_read(offset)		readw(rtc1_base + (offset))
#define rtc1_write(offset, value)	writew((value), rtc1_base + (offset))

#define rtc2_read(offset)		readw(rtc2_base + (offset))
#define rtc2_write(offset, value)	writew((value), rtc2_base + (offset))

static unsigned long epoch = 1970;	/* Jan 1 1970 00:00:00 */

static DEFINE_SPINLOCK(rtc_lock);
static char rtc_name[] = "RTC";
static unsigned long periodic_count;
static unsigned int alarm_enabled;
static int aie_irq;
static int pie_irq;

static inline unsigned long read_elapsed_second(void)
{

	unsigned long first_low, first_mid, first_high;

	unsigned long second_low, second_mid, second_high;

	do {
		first_low = rtc1_read(ETIMELREG);
		first_mid = rtc1_read(ETIMEMREG);
		first_high = rtc1_read(ETIMEHREG);
		second_low = rtc1_read(ETIMELREG);
		second_mid = rtc1_read(ETIMEMREG);
		second_high = rtc1_read(ETIMEHREG);
	} while (first_low != second_low || first_mid != second_mid ||
	         first_high != second_high);

	return (first_high << 17) | (first_mid << 1) | (first_low >> 15);
}

static inline void write_elapsed_second(unsigned long sec)
{
	spin_lock_irq(&rtc_lock);

	rtc1_write(ETIMELREG, (uint16_t)(sec << 15));
	rtc1_write(ETIMEMREG, (uint16_t)(sec >> 1));
	rtc1_write(ETIMEHREG, (uint16_t)(sec >> 17));

	spin_unlock_irq(&rtc_lock);
}

static void vr41xx_rtc_release(struct device *dev)
{

	spin_lock_irq(&rtc_lock);

	rtc1_write(ECMPLREG, 0);
	rtc1_write(ECMPMREG, 0);
	rtc1_write(ECMPHREG, 0);
	rtc1_write(RTCL1LREG, 0);
	rtc1_write(RTCL1HREG, 0);

	spin_unlock_irq(&rtc_lock);

	disable_irq(aie_irq);
	disable_irq(pie_irq);
}

static int vr41xx_rtc_read_time(struct device *dev, struct rtc_time *time)
{
	unsigned long epoch_sec, elapsed_sec;

	epoch_sec = mktime(epoch, 1, 1, 0, 0, 0);
	elapsed_sec = read_elapsed_second();

	rtc_time_to_tm(epoch_sec + elapsed_sec, time);

	return 0;
}

static int vr41xx_rtc_set_time(struct device *dev, struct rtc_time *time)
{
	unsigned long epoch_sec, current_sec;

	epoch_sec = mktime(epoch, 1, 1, 0, 0, 0);
	current_sec = mktime(time->tm_year + 1900, time->tm_mon + 1, time->tm_mday,
	                     time->tm_hour, time->tm_min, time->tm_sec);

	write_elapsed_second(current_sec - epoch_sec);

	return 0;
}

static int vr41xx_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *wkalrm)
{
	unsigned long low, mid, high;
	struct rtc_time *time = &wkalrm->time;

	spin_lock_irq(&rtc_lock);

	low = rtc1_read(ECMPLREG);
	mid = rtc1_read(ECMPMREG);
	high = rtc1_read(ECMPHREG);
	wkalrm->enabled = alarm_enabled;

	spin_unlock_irq(&rtc_lock);

	rtc_time_to_tm((high << 17) | (mid << 1) | (low >> 15), time);

	return 0;
}

static int vr41xx_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *wkalrm)
{
	unsigned long alarm_sec;
	struct rtc_time *time = &wkalrm->time;

	alarm_sec = mktime(time->tm_year + 1900, time->tm_mon + 1, time->tm_mday,
	                   time->tm_hour, time->tm_min, time->tm_sec);

	spin_lock_irq(&rtc_lock);

	if (alarm_enabled)
		disable_irq(aie_irq);

	rtc1_write(ECMPLREG, (uint16_t)(alarm_sec << 15));
	rtc1_write(ECMPMREG, (uint16_t)(alarm_sec >> 1));
	rtc1_write(ECMPHREG, (uint16_t)(alarm_sec >> 17));

	if (wkalrm->enabled)
		enable_irq(aie_irq);

	alarm_enabled = wkalrm->enabled;

	spin_unlock_irq(&rtc_lock);

	return 0;
}

static int vr41xx_rtc_ioctl(struct device *dev, unsigned int cmd, unsigned long arg)
{
	switch (cmd) {
	case RTC_EPOCH_READ:
		return put_user(epoch, (unsigned long __user *)arg);
	case RTC_EPOCH_SET:
		/* Doesn't support before 1900 */
		if (arg < 1900)
			return -EINVAL;
		epoch = arg;
		break;
	default:
		return -ENOIOCTLCMD;
	}

	return 0;
}

static int vr41xx_rtc_alarm_irq_enable(struct device *dev, unsigned int enabled)
{
	spin_lock_irq(&rtc_lock);
	if (enabled) {
		if (!alarm_enabled) {
			enable_irq(aie_irq);
			alarm_enabled = 1;
		}
	} else {
		if (alarm_enabled) {
			disable_irq(aie_irq);
			alarm_enabled = 0;
		}
	}
	spin_unlock_irq(&rtc_lock);
	return 0;
}

static irqreturn_t elapsedtime_interrupt(int irq, void *dev_id)
{
	struct platform_device *pdev = (struct platform_device *)dev_id;
	struct rtc_device *rtc = platform_get_drvdata(pdev);

	rtc2_write(RTCINTREG, ELAPSEDTIME_INT);

	rtc_update_irq(rtc, 1, RTC_AF);

	return IRQ_HANDLED;
}

static irqreturn_t rtclong1_interrupt(int irq, void *dev_id)
{
	struct platform_device *pdev = (struct platform_device *)dev_id;
	struct rtc_device *rtc = platform_get_drvdata(pdev);
	unsigned long count = periodic_count;

	rtc2_write(RTCINTREG, RTCLONG1_INT);

	rtc1_write(RTCL1LREG, count);
	rtc1_write(RTCL1HREG, count >> 16);

	rtc_update_irq(rtc, 1, RTC_PF);

	return IRQ_HANDLED;
}

static const struct rtc_class_ops vr41xx_rtc_ops = {
	.release	= vr41xx_rtc_release,
	.ioctl		= vr41xx_rtc_ioctl,
	.read_time	= vr41xx_rtc_read_time,
	.set_time	= vr41xx_rtc_set_time,
	.read_alarm	= vr41xx_rtc_read_alarm,
	.set_alarm	= vr41xx_rtc_set_alarm,
};

static int rtc_probe(struct platform_device *pdev)
{
	struct resource *res;
	struct rtc_device *rtc;
	int retval;

	if (pdev->num_resources != 4)
		return -EBUSY;

	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
	if (!res)
		return -EBUSY;

	rtc1_base = ioremap(res->start, resource_size(res));
	if (!rtc1_base)
		return -EBUSY;

	res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
	if (!res) {
		retval = -EBUSY;
		goto err_rtc1_iounmap;
	}

	rtc2_base = ioremap(res->start, resource_size(res));
	if (!rtc2_base) {
		retval = -EBUSY;
		goto err_rtc1_iounmap;
	}

	rtc = rtc_device_register(rtc_name, &pdev->dev, &vr41xx_rtc_ops, THIS_MODULE);
	if (IS_ERR(rtc)) {
		retval = PTR_ERR(rtc);
		goto err_iounmap_all;
	}

	rtc->max_user_freq = MAX_PERIODIC_RATE;

	spin_lock_irq(&rtc_lock);

	rtc1_write(ECMPLREG, 0);
	rtc1_write(ECMPMREG, 0);
	rtc1_write(ECMPHREG, 0);
	rtc1_write(RTCL1LREG, 0);
	rtc1_write(RTCL1HREG, 0);

	spin_unlock_irq(&rtc_lock);

	aie_irq = platform_get_irq(pdev, 0);
	if (aie_irq <= 0) {
		retval = -EBUSY;
		goto err_device_unregister;
	}

	retval = request_irq(aie_irq, elapsedtime_interrupt, 0,
	                     "elapsed_time", pdev);
	if (retval < 0)
		goto err_device_unregister;

	pie_irq = platform_get_irq(pdev, 1);
	if (pie_irq <= 0)
		goto err_free_irq;

	retval = request_irq(pie_irq, rtclong1_interrupt, 0,
		             "rtclong1", pdev);
	if (retval < 0)
		goto err_free_irq;

	platform_set_drvdata(pdev, rtc);

	disable_irq(aie_irq);
	disable_irq(pie_irq);

	dev_info(&pdev->dev, "Real Time Clock of NEC VR4100 series\n");

	return 0;

err_free_irq:
	free_irq(aie_irq, pdev);

err_device_unregister:
	rtc_device_unregister(rtc);

err_iounmap_all:
	iounmap(rtc2_base);
	rtc2_base = NULL;

err_rtc1_iounmap:
	iounmap(rtc1_base);
	rtc1_base = NULL;

	return retval;
}

static int rtc_remove(struct platform_device *pdev)
{
	struct rtc_device *rtc;

	rtc = platform_get_drvdata(pdev);
	if (rtc)
		rtc_device_unregister(rtc);

	platform_set_drvdata(pdev, NULL);

	free_irq(aie_irq, pdev);
	free_irq(pie_irq, pdev);
	if (rtc1_base)
		iounmap(rtc1_base);
	if (rtc2_base)
		iounmap(rtc2_base);

	return 0;
}

/* work with hotplug and coldplug */
MODULE_ALIAS("platform:RTC");

static struct platform_driver rtc_platform_driver = {
	.probe		= rtc_probe,
	.remove		= rtc_remove,
	.driver		= {
		.name	= rtc_name,
		.owner	= THIS_MODULE,
	},
};

module_platform_driver(rtc_platform_driver);


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `Texture3dDataSource` trait in crate `glium`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, Texture3dDataSource">

    <title>glium::texture::Texture3dDataSource - Rust</title>

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

glium::<wbr>texture

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Trait glium::<wbr>texture::<wbr>Texture3dDataSource

                [−]

        [src]

pub trait Texture3dDataSource<'a> {
    type Data: Send + Copy + Clone + 'a;
    fn into_raw(self) -> RawImage3d<'a, Self::Data>;
}

Trait that describes data for a two-dimensional texture.

Associated Types

type Data: Send + Copy + Clone + 'a

The type of each pixel.

Required Methods

fn into_raw(self) -> RawImage3d<'a, Self::Data>

Returns the raw representation of the data.

Implementors

impl<'a, P: PixelValue + Clone> Texture3dDataSource<'a> for Vec<Vec<Vec<P>>>

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).

                Search functions by type signature (e.g.
                vec -> usize)


text:
/* globals require, process, global, console */

/*************************************************************
 * Variables
 ************************************************************/
// Modules
var sh = require('../lib/shell');
var path = require('path');
var yaml = require('js-yaml');
yaml.merge = require('yaml-merge').mergeFiles;
var fs = require('fs');
var _ = {
  debounce: require('lodash/debounce'),
  filter: require('lodash/filter'),
  includes: require('lodash/includes'),
  isArray: require('lodash/isArray'),
  map: require('lodash/map'),
  reject: require('lodash/reject'),
  startsWith: require('lodash/startsWith'),
};
// Globals
var gulp = global.gulp;
var config = global.config;
// var paths = global.paths;

var tasks = global.tasks;
var browserSync = global.browserSync;
// Local
var plConfig = yaml.safeLoad(
  fs.readFileSync(config.patternLab.configFile, 'utf8')
);
var plRoot = path.join(config.patternLab.configFile, '../..');
var plSource = path.join(plRoot, plConfig.sourceDir);
// var plPublic = path.join(plRoot, plConfig.publicDir);
// var plMeta = path.join(plSource, '/_meta');
var consolePath = path.join(plRoot, 'core/console');

/*************************************************************
 * Operations
 ************************************************************/
function plBuild(cb) {
  sh('php ' + consolePath + ' ' + '--generate', true, function () {
    if (config.browserSync.enabled) {
      browserSync.reload();
      // console.log("==> BrowserSync Reloading... plBuild");
    }
    cb();
  });
}

gulp.task('pl', 'Compile Pattern Lab', plBuild);

gulp.task('pl:dev', _.debounce(function () {
}, config.browserSync.reloadDebounce));

var watchedExtensions = config.patternLab.watchedExtensions.join(',');
gulp.task('pl:watch', function () {
  var plGlob = path.normalize(plSource + '/**/*.{' + watchedExtensions + '}');
  gulp.watch(plGlob, function (event) {
    var relativePath = path.relative(process.cwd(), event.path);
    console.log('File ' + relativePath + ' was ' + event.type + ', loading...');
    sh('php ' + consolePath + ' ' + '--generate', false, function () {
      if (config.browserSync.enabled) {
        browserSync.reload();
      }
    });
  });
});

var plFullDependencies = [];

if (config.patternLab.scssToJson) {
  // turns scss files full of variables into json files that PL can iterate on
  gulp.task('pl:scss-to-json', function (done) {
    var scssToJson = config.patternLab.scssToJson;
    // console.log(scssToJson);

    scssToJson.forEach(function (pair) {
      var tempalteFile = fs.readFileSync(pair.src, 'utf8').split('\n');
      var scssVarList = _.filter(tempalteFile, function (item) {
        return _.startsWith(item, pair.lineStartsWith);
      });
      // console.log(scssVarList, item.src);
      var varsAndValues = _.map(scssVarList, function (item) {
        var x = item.split(':');
        return {
          name: x[0].trim(), // i.e. $color-gray
          value: x[1].replace(/;.*/, '').trim(), // i.e. hsl(0, 0%, 50%)
        };
      });

      // Process results that should be scrubbed out
      varsAndValues = _.reject(varsAndValues, function (item) {
        // Filter out variables if not to be included
        return (!pair.allowVarValues && _.startsWith(item.value, '$')) ||
          // Filter out specific vars if needed
          (_.isArray(pair.excludeVars) && _.includes(pair.excludeVars, item.name));
      });

      fs.writeFileSync(pair.dest, JSON.stringify({
        items: varsAndValues,
        meta: {
// eslint-disable-next-line max-len
          description: 'To add to these items, use Sass variables that start with ' + pair.lineStartsWith + ' in ' + pair.src + '',
        },
      }, null, '  '));
    });
    done();
  });
  plFullDependencies.push('pl:scss-to-json');

  gulp.task('pl:scss-to-json:watch', function () {
    var files = config.patternLab.scssToJson.map(function (file) {
      return file.src;
    });
    gulp.watch(files, ['pl:scss-to-json']);
  });
  tasks.watch.push('pl:scss-to-json:watch');
}

gulp.task('pl:config', '', function () {
  var plConfigFile = './pattern-lab/config/config.yml';
  var localConfigFile = './.pattern-lab.config.yml';
  var plConfig = yaml.merge([
    plConfigFile,
    localConfigFile,
  ]);

  console.log('PL Config: Loading', plConfigFile);
  console.log('PL Config: Overriding with', localConfigFile);

  try {
    var dumpOpts = {
      lineWidth: 1000,
      indent: 4,
    };
    var outputYml = yaml.safeDump(plConfig, dumpOpts);

    fs.writeFile(plConfigFile, outputYml, function (err) {
      if (err) {
        throw err;
      }
      console.log('It\'s saved!');
    });
  } catch (e) {
  }
});

/*************************************************************
 * Builders
 ************************************************************/
gulp.task('pl:full', false, plFullDependencies, plBuild);
tasks.compile.push('pl:full');

/*************************************************************
 * Watchers
 ************************************************************/
tasks.watch.push('pl:watch');


text:
package test

import (
	"bytes"
	"errors"
	"fmt"
	"math"
	"reflect"
	"runtime"
	"strings"
	"testing"
	"unicode"
)

// ErrPlain is the default error that is returned for functions in this package.
var ErrPlain = errors.New("error")

////////////////////////////////////////////////////////////////

func fileline(i int) string {
	_, file, line, ok := runtime.Caller(i)
	if !ok {
		return ""
	}
	parts := strings.Split(file, "/")
	file = parts[len(parts)-1]
	return fmt.Sprintf("%s:%d", file, line)
}

func trace() string {
	trace2 := fileline(2)
	trace3 := fileline(3)
	return "\r    " + strings.Repeat(" ", len(fmt.Sprintf("%s:", trace2))) + "\r    " + trace3
}

func message(msgs ...interface{}) string {
	if len(msgs) == 0 {
		return ""
	}
	s := fmt.Sprintln(msgs...)
	s = s[:len(s)-1] // remove newline
	return ": " + s
}

func printable(s string) string {
	s = strings.Replace(s, "\n", `\n`, -1)
	s = strings.Replace(s, "\r", `\r`, -1)
	s = strings.Replace(s, "\t", `\t`, -1)
	s = strings.Replace(s, "\x00", `\0`, -1)

	s2 := ""
	for _, r := range s {
		if !unicode.IsPrint(r) {
			s2 += fmt.Sprintf("\\x%X", r)
		} else {
			s2 += string(r)
		}
	}
	return s2
}

const (
	Red   = "31"
	Green = "32"
)

func color(color string, s interface{}) string {
	return fmt.Sprintf("\033[00;%sm%v\033[00m", color, s)
}

/////////////////////////////////////////////////////////////////

func Fail(t *testing.T, msgs ...interface{}) {
	t.Helper()
	t.Fatalf("%s%s", trace(), message(msgs...))
}

func Error(t *testing.T, err error, msgs ...interface{}) {
	t.Helper()
	if err != nil {
		t.Fatalf("%s%s: %s", trace(), message(msgs...), color(Red, err.Error()))
	}
}

func That(t *testing.T, condition bool, msgs ...interface{}) {
	t.Helper()
	if !condition {
		t.Fatalf("%s%s: false", trace(), message(msgs...))
	}
}

func T(t *testing.T, got, wanted interface{}, msgs ...interface{}) {
	t.Helper()
	gotType := reflect.TypeOf(got)
	wantedType := reflect.TypeOf(wanted)
	if gotType != wantedType {
		t.Fatalf("%s%s: type %v != %v", trace(), message(msgs...), color(Red, gotType), color(Green, wantedType))
		return
	}
	if reflect.DeepEqual(got, wanted) {
		return
	}

	if wantedType != nil {
		if equals, ok := wantedType.MethodByName("Equals"); ok && equals.Type.NumIn() == 2 && equals.Type.NumOut() == 1 && equals.Type.In(0) == wantedType && equals.Type.In(1) == gotType && equals.Type.Out(0).Kind() == reflect.Bool && equals.Func.Call([]reflect.Value{reflect.ValueOf(wanted), reflect.ValueOf(got)})[0].Bool() {
			return
		}
	}
	t.Fatalf("%s%s: %v != %v", trace(), message(msgs...), color(Red, got), color(Green, wanted))
}

func Bytes(t *testing.T, got, wanted []byte, msgs ...interface{}) {
	t.Helper()
	if !bytes.Equal(got, wanted) {
		gotString := printable(string(got))
		wantedString := printable(string(wanted))
		t.Fatalf("%s%s:\n%s\n%s", trace(), message(msgs...), color(Red, gotString), color(Green, wantedString))
	}
}

func String(t *testing.T, got, wanted string, msgs ...interface{}) {
	t.Helper()
	if got != wanted {
		gotString := printable(got)
		wantedString := printable(wanted)
		t.Fatalf("%s%s:\n%s\n%s", trace(), message(msgs...), color(Red, gotString), color(Green, wantedString))
	}
}

func Float(t *testing.T, got, wanted float64, msgs ...interface{}) {
	t.Helper()
	if math.IsNaN(wanted) != math.IsNaN(got) || !math.IsNaN(wanted) && math.Abs(got-wanted) > 1e-6 {
		t.Fatalf("%s%s: %v != %v", trace(), message(msgs...), color(Red, got), color(Green, wanted))
	}
}

func FloatDiff(t *testing.T, got, wanted, diff float64, msgs ...interface{}) {
	t.Helper()
	if math.IsNaN(wanted) != math.IsNaN(got) || !math.IsNaN(wanted) && math.Abs(got-wanted) > diff {
		t.Fatalf("%s%s: %v != %v", trace(), message(msgs...), color(Red, got), color(Green, fmt.Sprintf("%v ± %v", wanted, diff)))
	}
}

func Minify(t *testing.T, input string, err error, got, wanted string, msgs ...interface{}) {
	t.Helper()
	inputString := printable(input)
	if err != nil {
		t.Fatalf("%s%s:\n%s\n%s", trace(), message(msgs...), inputString, color(Red, err.Error()))
		return
	}

	if got != wanted {
		gotString := printable(got)
		wantedString := printable(wanted)
		t.Fatalf("%s%s:\n%s\n%s\n%s", trace(), message(msgs...), inputString, color(Red, gotString), color(Green, wantedString))
	}
}


text:
from __future__ import absolute_import, division, print_function, generators

__metaclass__ = type

import numpy as np
import re
import matplotlib.pyplot as plt
from astwro.phot import DiffPhot

class Plottable(object):
    plot_styles =    ['alpha', 'ls', 'linestyle', 'c', 'color', 'lw', 'linewidth',
                      'marker', 'mec', 'mew', 'mfc', 'ms', 'zorder', 'label']
    scatter_styles = ['alpha', 'c', 's', 'marker', 'edgecolors', 'label']
    (tool_plot, tool_errorbar, tool_scatter) = (1,2,3)
    def __init__(self, **kwargs):
        super(Plottable, self).__init__()
        _kwargs = kwargs
        # plot_styles =    {s: None for s in 'alpha', 'ls', 'c', 'lw', 'marker', 'mec', 'mew', 'mfc', 'ms', 'zorder'}
        # scatter_styles = {s: None for s in 'alpha', 'c', 's', 'marker', 'edgecolors'}

    def plot(self, ax=None, **kwargs):
        if ax is None:
            ax = self._setup_axes(**kwargs)
        self._plotonaxies(ax, **kwargs)
        return ax

    @staticmethod
    def _setup_axes(**kwargs):
        fig = plt.figure()
        return fig.add_subplot(111)

    def _plotonaxies(self, ax, **kwargs):
        pass

    @staticmethod
    def _style_kwargs(style, kwargs_list):
        res = None
        for kwargs in kwargs_list:
            try: res = kwargs[style]
            except KeyError: pass
        return res

    @staticmethod
    def _styles_kwargs(styles_list, kwargs_list):
        res = {}
        for s in styles_list:
            kw = Plottable._style_kwargs(s, kwargs_list)
            if kw is not None:
                res[s] = kw
        return res

    @staticmethod
    def _plot_styles_kwargs(kwargs_list):
        return Plottable._styles_kwargs(Plottable.plot_styles, kwargs_list)

    @staticmethod
    def _scatter_styles_kwargs(kwargs_list):
        return Plottable._styles_kwargs(Plottable.scatter_styles, kwargs_list)

class FigurePlotter(Plottable):
    def __init__(self, **kwargs):
        super(FigurePlotter, self).__init__(**kwargs)

    def _plotonaxies(self, ax, **kwargs):
        super(FigurePlotter, self)._plotonaxies(ax, **kwargs)
        r = kwargs.get('xlim')
        if r is not None:
            ax.set_xlim(r[0], r[1])
        r = kwargs.get('ylim')
        if r is not None:
            ax.set_ylim(r[0], r[1])

class Layer(Plottable):
    def __init__(self, **kwargs):
        super(Layer, self).__init__(**kwargs)
        self.default_styles = {}

    def plot_styles_kwargs(self, **kwargs):
        return self._plot_styles_kwargs([self.default_styles, kwargs])

    def scatter_styles_kwargs(self, **kwargs):
        return self._scatter_styles_kwargs([self.default_styles, kwargs])

    def _plotonaxies(self, ax, **kwargs):
        pass

class ShiftedLayer(Layer):
    def __init__(self, dx, dy, **kwargs):
        super(ShiftedLayer, self).__init__(**kwargs)
        self.dx = dx
        self.dy = dy

class IsochromeLayer(ShiftedLayer):
    def __init__(self, bands, age, Av, distance, feh=0.001, maxm=18.25, **kwargs):
        super(IsochromeLayer, self).__init__(**kwargs)
        from isochrones.mist import MIST_Isochrone
        MIST = MIST_Isochrone(bands)
        iso  = MIST.isochrone(age=np.log10(age), feh=feh, AV=Av, distance=distance, maxm=maxm)

    def _plotonaxies(self, ax, **kwargs):
        super(IsochromeLayer, self)._plotonaxies(ax, **kwargs)

class CollectionLayer(Layer):
    operators = {
        '-': lambda x, y: x - y,
        '+': lambda x, y: x + y,
    }
    oper_reg = re.compile('\s*(\w+)\s*([+-])\s*(\w+)\s*')

    def __init__(self, collections, masks=None, tool=Plottable.tool_plot, colors=None, sizes=None, subsets=None, **kwargs):
        super(CollectionLayer, self).__init__(**kwargs)
        self.collections = collections
        self.masks = masks
        self.default_styles['ls'] = 'None'
        self.default_styles['marker'] = '.'
        self.default_styles.update(self._plot_styles_kwargs([kwargs]))
        self.tool = tool
        self.colors = colors
        self.sizes = sizes
        self.subsets = subsets

    def __len__(self):
        return len(list(self.collections.values())[0])

    def get_values(self, color):
        try:
            m = self.oper_reg.match(color)
            if not m:
                return self.collections[color]
            else:
                a = m.groups()[0]
                op = m.groups()[1]
                b = m.groups()[2]
                return self.operators[op](self.collections[a], self.collections[b])
        except (TypeError, IndexError, KeyError):
            raise ValueError('"color" should be a band name or two color +/- operation, eg. "V", "B-V"')

    def get_masks(self, **kwargs):
        masks = kwargs.get('masks')
        n = len(self)
        if masks is None:
            masks = [np.ones(n, dtype=bool)]
        for i, mask in enumerate(masks):
            if (len(mask) != n):
                boolmask = np.zeros(n, dtype=bool)
                boolmask[mask] = True
                masks[i] = boolmask
        return masks

    def _plotonaxies(self, ax, **kwargs):
        super(CollectionLayer, self)._plotonaxies(ax, **kwargs)
        x = self.get_values(kwargs['xcolor'])
        y = self.get_values(kwargs['ycolor'])
        masks = self.get_masks(**kwargs)
        if self.tool == self.tool_plot:
            styles = self.plot_styles_kwargs(**kwargs)
            for mask in masks:
                ax.plot(x[mask], y[mask], **styles)
        elif self.tool == self.tool_scatter:
            styles = self.scatter_styles_kwargs(**kwargs)
            if self.colors:
                if self.colors == True: # just bool, cycle std cycler over subsets
                    assert len(self.subsets) == len(x), 'If `colors == True` for scatter, `subsets` of size of data should be specified'
                    palette = self.get_scatter_cycle_palette()
                    N = len(palette)
                    c = [palette[i%N] for i in self.subsets]
                else:
                    c = self.colors
                styles['c'] = c
            if self.sizes:
                styles['s'] = self.sizes
            for mask in masks:
                ax.scatter(x[mask], y[mask], **styles)

    def get_scatter_cycle_palette(self): return ['C'+l for l in ['0123456789']]

class CompoundPlot(FigurePlotter):
    def __init__(self, layers, **kwargs):
        super(CompoundPlot, self).__init__(**kwargs)
        self.layers = layers

    def _plotonaxies(self, ax, **kwargs):
        for l in self.layers:
            l._plotonaxies(ax, **kwargs)
        super(CompoundPlot, self)._plotonaxies(ax, **kwargs)

class FilterColorPlotter(CompoundPlot):
    def __init__(self, distance=10, age=0, Av=None, reddenings=None,
                 collections=None, limits=None, **kwargs):
        self.lstars = CollectionLayer(collections, **kwargs)
        super(FilterColorPlotter, self).__init__(layers=[self.lstars], **kwargs)
        self.age = age
        self.distance = distance
        self._Av = Av
        self.reddenings = reddenings
        self.limits = {} if limits is None else limits

    @property
    def modulus(self): return 5*np.log10(self.distance, 10) - 5

    @property
    def Av(self):
        if self._Av is not None:
            return self._Av
        return self._get_reddening('B-V') * 3.1  # 1984A&AS...58..447D

    def update_limits(self, colors, limits):
        """
        Set axis limits for plots.

        Dictionary of limits is also available via `FilterColorPlotter.limits` property.
        Note, that limits can be changed after drawing ion returned axis object also.

        Existing limits, not listed in `colors`, remains unchanged.

        Parameters
        ----------
        colors : iterable of str
            color(s) for which limit is set
        limits : list of tuples or tuple
            pairs representing limits
            if limits is a single tuple, same limits are set for all `colors`

        Example
        -------

            plotter = JohnsonCousinsPlotter(U=u, B=b, V=v)
            plotter.update_limits('UBV', (22, 10))
            plotter.update_limits(['U-B', 'B-V'], (-2, 2))
        """
        try:
            iter(colors)
        except TypeError:
            colors = [colors]
        try:
            st = {c: (l[0], l[1]) for c,l in zip (colors, limits)}
        except TypeError:
            st = {c: (limits[0], limits[1]) for c in colors}
        self.limits.update(st)

    def _get_reddening(self, color):
        try:
            return self.reddenings[color]
        except (KeyError, TypeError):
            return 0

    def _plotonaxies(self, ax, **kwargs):
        kwargs.setdefault('xlim', self.limits.get(kwargs['xcolor']))
        kwargs.setdefault('ylim', self.limits.get(kwargs['ycolor']))
        super(FilterColorPlotter, self)._plotonaxies(ax, **kwargs)

class JohnsonCousinsPlotter(FilterColorPlotter):
    default_limits = {
        'U': (20,5), 'V': (20,5), 'B': (20,5), 'R': (20,5), 'I': (20,5),
        'U-B': (0,2.5), 'B-V': (0,2.5), 'V-I': (0,3.5), 'V-R': (0,2.5), 'R-I': (0,2.5),
        'U_e': (0, 0.3), 'B_e': (0, 0.3), 'V_e': (0, 0.3), 'R_e': (0, 0.3), 'I_e': (0, 0.3),
    }
    def __init__(self, U=None, B=None, V=None, R=None, I=None,
                 U_e=None, B_e=None, V_e=None, R_e=None, I_e=None,
                 distance=None, age=None, Av=None, reddenings=None, **kwargs):
        collections = {c: v for c,v in zip('UVBRI', [U, V, B, R, I]) if v is not None}
        for c in  'UVBRI':  # DiffPhots as arguments? extract mag and error
            dp = collections.get(c)
            if isinstance(dp, DiffPhot):
                collections[c] = dp.mag
                if dp.mag_e is not None:
                    collections[c+'_e'] = dp.mag_e
        errors = {c+'_e': v for c, v in zip('UVBRI', [U_e, V_e, B_e, R_e, I_e]) if v is not None}
        collections.update(errors)
        super(JohnsonCousinsPlotter, self).__init__(
            distance, age, Av, reddenings, collections, limits=dict(self.default_limits), **kwargs)

class MultiJohnsonCousinsPlotter(JohnsonCousinsPlotter):
    def __init__(self, U=None, B=None, V=None, R=None, I=None,
                 U_e=None, B_e=None, V_e=None, R_e=None, I_e=None,
                 colors=True, sizes=False,
                 **kwargs):
        U, B, V, R, I, U_e, B_e, V_e, R_e, I_e = (np.concatenate(t) for t in [U,B,V,R,I,U_e,B_e,V_e,R_e,I_e])
        subsets = np.concatenate([ np.full_like(ss, n) for n, ss in enumerate(U)])
        super(MultiJohnsonCousinsPlotter, self).__init__(
            U, B, V, R, I, U_e, B_e, V_e, R_e, I_e, **kwargs)
        self.lstars.subsets = subsets
        self.lstars.colors = colors
        self.lstars.sizes = sizes

class _TestPlotter:
    def color_mag_plot(ax, x, y, xcolor='B-V', ycolor='V', isochrone=None, sptypes=True, legend=None,
                       masks=[None], labels=None, colors=None, edgecolors=None, alphas=None, sizes=None,
                       xlim=None, ylim=None):
        def p(par, i): return None if par is None or par[i] is None else par[i]

        for i, mask in enumerate(masks):
            s = p(sizes, i)
            if s is None:
                s = 2*(20-y[mask])
            ax.scatter(x[mask], y[mask],
               label = p(labels,i), s=s, c=p(colors,i), edgecolors=p(edgecolors,i), alpha=p(alphas,i))
        # if sptypes:
        #     ax2 = sp.plot_twiny_spectral_types(ax, xcolor)
        # if isochrone:
        #     ax.plot(iB - iV, iV, 'r', linewidth=1, label='${:g}\mathrm{{Myr}}$ isochrone'.format(isochrone/1e6))

        #ax.plot(iso_sm.B_mag - iso_sm.V_mag, iso_sm.V_mag, 'rx') # solar mass points
        # for a in np.arange(7,9, 0.3):
        #     iso3 = MIST.isochrone(age=a, feh=0.001, AV=Av, distance=distance, maxm=18.25)
        #     ax.plot(iso3.B_mag - iso3.V_mag, iso3.V_mag, label='{:.3f}My isochrone'.format(10**a/1e6), linewidth=1, alpha=0.94)
        # iso4 = MIST.isochrone(age=7, feh=0.001)#, maxm=18.25)
        # ax.plot(iso4.B_mag - iso4.V_mag + E_B_V, iso4.V_mag+ distance_modulus + Av, label='10My isochrone', linewidth=1, alpha=0.94)
        # for a in np.arange(0,4.5, 0.5):
        #     iso3 = MIST.evtrack(2.0**a, minage=7, maxage=np.log10(20e6))
        #     ax.plot(iso3.B_mag - iso3.V_mag + E_B_V, iso3.V_mag+ distance_modulus + Av, label='{:.3f}Ms track'.format(2.0**a), linewidth=1, alpha=0.94)

        # ax.plot(iso['Bmag'] - iso['Vmag'] + E_B_V, iso['Vmag'] + distance_modulus + Av, 'r', alpha=1, linewidth=1,
        #        label='10My isochrone')
        ax.set_xlabel('$B-V$')
        ax.set_ylabel('$V$')
        ax.set_xlim(0, 2.5)
#        ax2.set_xlim(0, 2.5)
        ax.set_ylim(20,5)
        if isinstance(legend, bool):
            if legend:
                ax.legend()
        else:
            ax.legend(loc=legend)

if __name__ == "__main__":
    from astroquery.vizier import Vizier
    massey = Vizier.query_region('NGC 6871', radius='0d6m0s', catalog='J/ApJ/454/151/ngc6871')[0]
    V = massey['Vmag']
    B = massey['B-V'] + V
    U = massey['U-B'] + B
    plotter = JohnsonCousinsPlotter(U, B, V, distnace=1649, age=10e6, Av=1.364)
    ax = plotter.plot(xcolor='B-V', ycolor='V')
    plt.show()


text:
require 'spec_helper'

describe Euler do

  before(:all) do
    Euler.config do |config|

    end
  end

  it "should be able to set config options with lambdas" do
    ds = lambda { |solution|

    }

    args = [1, 'euler-lang']

    ds.should_receive(:call).once.with(*args)

    Euler.config do |config|
      config.directory_strategy ds
    end

    Euler.directory_strategy *args
  end

  it "should have a few languages preregistered" do
    Euler.get_language('c').should be_truthy
    Euler.get_language('coffeescript').should be_truthy
    Euler.get_language('elixir').should be_truthy
    Euler.get_language('haskell').should be_truthy
    Euler.get_language('java').should be_truthy
    Euler.get_language('javascript').should be_truthy
    Euler.get_language('julia').should be_truthy
    Euler.get_language('perl').should be_truthy
    Euler.get_language('php').should be_truthy
    Euler.get_language('python').should be_truthy
    Euler.get_language('ruby').should be_truthy
    Euler.get_language('scala').should be_truthy
  end

  describe "Ruby language" do

    it "'s template should be a file" do
      ruby = Euler.get_language('ruby')
      tmpl = ruby.send(:template_path)
      File.exists?(tmpl).should be_truthy
    end

  end

end


text:
_[www.codever.land/bookmarks/t/rubygems](https://www.codever.land/bookmarks/t/rubygems)_
---
#### [Gemsmith](https://github.com/bkuhlmann/gemsmith)
_https://github.com/bkuhlmann/gemsmith_

A command line interface for smithing new Ruby gems.
* **tags**: [ruby](../tagged/ruby.md), [rubygems](../tagged/rubygems.md), [generator](../tagged/generator.md)
* :octocat: **[source code](https://github.com/bkuhlmann/gemsmith)**
---
#### [Hoe](http://www.zenspider.com/projects/hoe.html)
_http://www.zenspider.com/projects/hoe.html_

Hoe is a Rake/RubyGems helper for project Rakefiles.
* **tags**: [ruby](../tagged/ruby.md), [rubygems](../tagged/rubygems.md), [generator](../tagged/generator.md)
---


text:
namespace NPOI.HSSF.UserModel
{
    using System;
    using System.Text;

    using NPOI.HSSF.Record;
    using NPOI.HSSF.Model;
    using NPOI.SS.Formula.PTG;

    /// <summary>
    /// High Level Represantion of Named Range
    /// </summary>
    /// <remarks>@author Libin Roman (Vista Portal LDT. Developer)</remarks>
    public class HSSFName:NPOI.SS.UserModel.IName
    {
        private HSSFWorkbook book;
        private NameRecord _definedNameRec;
        private NameCommentRecord _commentRec;
        /* package */
        internal HSSFName(HSSFWorkbook book, NameRecord name):this(book, name, null)
        {

        }
        /// <summary>
        /// Creates new HSSFName   - called by HSSFWorkbook to Create a sheet from
        /// scratch.
        /// </summary>
        /// <param name="book">lowlevel Workbook object associated with the sheet.</param>
        /// <param name="name">the Name Record</param>
        /// <param name="comment"></param>
        internal HSSFName(HSSFWorkbook book, NameRecord name, NameCommentRecord comment)
        {
            this.book = book;
            this._definedNameRec = name;
            _commentRec = comment;
        }

        /// <summary>
        /// Gets or sets the sheets name which this named range is referenced to
        /// </summary>
        /// <value>sheet name, which this named range refered to</value>
        public String SheetName
        {
            get
            {
                String result;
                int indexToExternSheet = _definedNameRec.ExternSheetNumber;

                result = book.Workbook.FindSheetNameFromExternSheet(indexToExternSheet);

                return result;
            }
            //set
            //{
            //    int sheetNumber = book.GetSheetIndex(value);

            //    int externSheetNumber = book.GetExternalSheetIndex(sheetNumber);
            //    name.ExternSheetNumber = externSheetNumber;
            //}
        }

        /// <summary>
        /// Gets or sets the name of the named range
        /// </summary>
        /// <value>named range name</value>
        public String NameName
        {
            get
            {
                String result = _definedNameRec.NameText;

                return result;
            }
            set
            {
                ValidateName(value);
                _definedNameRec.NameText = value;
                InternalWorkbook wb = book.Workbook;
                int sheetNumber = _definedNameRec.SheetNumber;

                //Check to Ensure no other names have the same case-insensitive name
                for (int i = wb.NumNames- 1; i >= 0; i--)
                {
                    NameRecord rec = wb.GetNameRecord(i);
                    if (rec != _definedNameRec)
                    {
                        if (rec.NameText.Equals(NameName, StringComparison.OrdinalIgnoreCase) && sheetNumber == rec.SheetNumber)
                        {
                            String msg = "The " + (sheetNumber == 0 ? "workbook" : "sheet") + " already contains this name: " + value;
                            _definedNameRec.NameText = (value + "(2)");
                            throw new ArgumentException(msg);
                        }
                    }
                }
                // Update our comment, if there is one
                if (_commentRec != null)
                {
                    String oldName = _commentRec.NameText;
                    _commentRec.NameText=value;
                    book.Workbook.UpdateNameCommentRecordCache(_commentRec);
                }
            }
        }
        private void ValidateName(String name)
        {
            if (name.Length == 0) throw new ArgumentException("Name cannot be blank");

            char c = name[0];
            if (!(c == '_' || Char.IsLetter(c)) || name.IndexOf(' ') != -1)
            {
                throw new ArgumentException("Invalid name: '" + name + "'; Names must begin with a letter or underscore and not contain spaces");
            }
        }

        public String RefersToFormula
        {
            get
            {
                if (_definedNameRec.IsFunctionName)
                {
                    throw new InvalidOperationException("Only applicable to named ranges");
                }
                Ptg[] ptgs = _definedNameRec.NameDefinition;
                if (ptgs.Length < 1)
                {
                    // 'refersToFormula' has not been set yet
                    return null;
                }
                return HSSFFormulaParser.ToFormulaString(book, ptgs);
            }
            set
            {
                Ptg[] ptgs = HSSFFormulaParser.Parse(value, book, NPOI.SS.Formula.FormulaType.NamedRange, SheetIndex);
                _definedNameRec.NameDefinition = ptgs;
            }
        }
        /**
         * Returns the sheet index this name applies to.
         *
         * @return the sheet index this name applies to, -1 if this name applies to the entire workbook
         */
        public int SheetIndex
        {
            get
            {
                return _definedNameRec.SheetNumber - 1;
            }
            set
            {
                int lastSheetIx = book.NumberOfSheets - 1;
                if (value < -1 || value > lastSheetIx)
                {
                    throw new ArgumentException("Sheet index (" + value + ") is out of range" +
                            (lastSheetIx == -1 ? "" : (" (0.." + lastSheetIx + ")")));
                }

                _definedNameRec.SheetNumber = (value + 1);
            }
        }
        public string Comment
        {
            get
            {
                if (_commentRec != null)
                {
                    // Prefer the comment record if it has text in it
                    if (_commentRec.CommentText != null &&
                          _commentRec.CommentText.Length > 0)
                    {
                        return _commentRec.CommentText;
                    }
                }
                return _definedNameRec.DescriptionText;
            }
            set { _definedNameRec.DescriptionText = value; }
        }

        //
        /// <summary>
        /// Sets the NameParsedFormula structure that specifies the formula for the defined name.
        /// </summary>
        /// <param name="ptgs">the sequence of {@link Ptg}s for the formula.</param>
        public void SetNameDefinition(Ptg[] ptgs)
        {
            _definedNameRec.NameDefinition = (ptgs);
        }

        /// <summary>
        /// Tests if this name points to a cell that no longer exists
        /// </summary>
        /// <value>
        /// 	<c>true</c> if the name refers to a deleted cell; otherwise, <c>false</c>.
        /// </value>
        public bool IsDeleted
        {
            get
            {
                Ptg[] ptgs = _definedNameRec.NameDefinition;
                return Ptg.DoesFormulaReferToDeletedCell(ptgs);
            }
        }

        /// <summary>
        /// Gets a value indicating whether this instance is function name.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance is function name; otherwise, <c>false</c>.
        /// </value>
        public bool IsFunctionName
        {
            get
            {
                return _definedNameRec.IsFunctionName;
            }
        }
        /**
     * Indicates that the defined name refers to a user-defined function.
     * This attribute is used when there is an add-in or other code project associated with the file.
     *
     * @param value <c>true</c> indicates the name refers to a function.
     */
        public void SetFunction(bool value)
        {
            _definedNameRec.SetFunction(value);
        }
        /// <summary>
        /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </returns>
        public override String ToString()
        {
            StringBuilder sb = new StringBuilder(64);
            sb.Append(GetType().Name).Append(" [");
            sb.Append(_definedNameRec.NameText);
            sb.Append("]");
            return sb.ToString();
        }
    }
}


text:
package org.killbill.billing.tenant.api;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import javax.inject.Inject;
import javax.inject.Named;

import org.killbill.billing.callcontext.InternalTenantContext;
import org.killbill.billing.events.BusInternalEvent;
import org.killbill.billing.tenant.api.TenantInternalApi.CacheInvalidationCallback;
import org.killbill.billing.tenant.api.TenantKV.TenantKey;
import org.killbill.billing.tenant.api.user.DefaultTenantConfigChangeInternalEvent;
import org.killbill.billing.tenant.api.user.DefaultTenantConfigDeletionInternalEvent;
import org.killbill.billing.tenant.dao.TenantBroadcastDao;
import org.killbill.billing.tenant.dao.TenantBroadcastModelDao;
import org.killbill.billing.tenant.dao.TenantDao;
import org.killbill.billing.tenant.dao.TenantKVModelDao;
import org.killbill.billing.tenant.dao.TenantModelDao;
import org.killbill.billing.tenant.glue.DefaultTenantModule;
import org.killbill.billing.util.config.TenantConfig;
import org.killbill.bus.api.PersistentBus;
import org.killbill.bus.api.PersistentBus.EventBusException;
import org.killbill.commons.concurrent.Executors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;

/**
 * This class manages the callbacks that have been registered when per tenant objects have been inserted into the
 * tenant_kvs store; the flow is the following (for e.g catalog):
 * 1. CatalogUserApi is invoked to retrieve per tenant catalog
 * 2. If cache is empty, TenantCacheLoader is invoked and uses TenantInternalApi is load the data; at that time, the invalidation callback
 * is registered
 * <p/>
 * When this class initializes, it reads the current entry in the tenant_broadcasts table and from then on, keeps polling for new entries; when new
 * entries are found, it invokes the callback to invalidate the current caching and force the TenantCacheLoader to be invoked again.
 */
public class TenantCacheInvalidation {

    private final static int TERMINATION_TIMEOUT_SEC = 5;

    private static final Logger logger = LoggerFactory.getLogger(TenantCacheInvalidation.class);

    private final Map<TenantKey, CacheInvalidationCallback> cache;
    private final TenantBroadcastDao broadcastDao;
    private final TenantConfig tenantConfig;
    private final PersistentBus eventBus;
    private final TenantDao tenantDao;
    private AtomicLong latestRecordIdProcessed;
    private volatile boolean isStopped;

    private ScheduledExecutorService tenantExecutor;

    @Inject
    public TenantCacheInvalidation(@Named(DefaultTenantModule.NO_CACHING_TENANT) final TenantBroadcastDao broadcastDao,
                                   @Named(DefaultTenantModule.NO_CACHING_TENANT) final TenantDao tenantDao,
                                   final PersistentBus eventBus,
                                   final TenantConfig tenantConfig) {
        this.cache = new HashMap<TenantKey, CacheInvalidationCallback>();
        this.broadcastDao = broadcastDao;
        this.tenantConfig = tenantConfig;
        this.tenantDao = tenantDao;
        this.eventBus = eventBus;
        this.isStopped = false;
    }

    public void initialize() {
        final TenantBroadcastModelDao entry = broadcastDao.getLatestEntry();
        this.latestRecordIdProcessed = entry != null ? new AtomicLong(entry.getRecordId()) : new AtomicLong(0L);
        this.tenantExecutor = Executors.newSingleThreadScheduledExecutor("TenantExecutor");
        this.isStopped = false;
    }

    public void start() {
        final TimeUnit pendingRateUnit = tenantConfig.getTenantBroadcastServiceRunningRate().getUnit();
        final long pendingPeriod = tenantConfig.getTenantBroadcastServiceRunningRate().getPeriod();
        tenantExecutor.scheduleAtFixedRate(new TenantCacheInvalidationRunnable(this, broadcastDao, tenantDao), pendingPeriod, pendingPeriod, pendingRateUnit);

    }

    public void stop() {
        if (isStopped) {
            logger.warn("TenantExecutor is already in a stopped state");
            return;
        }
        try {
            tenantExecutor.shutdown();
            boolean success = tenantExecutor.awaitTermination(TERMINATION_TIMEOUT_SEC, TimeUnit.SECONDS);
            if (!success) {
                logger.warn("TenantExecutor failed to complete termination within " + TERMINATION_TIMEOUT_SEC + "sec");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.warn("TenantExecutor stop sequence got interrupted");
        } finally {
            isStopped = true;
        }
    }

    public void registerCallback(final TenantKey key, final CacheInvalidationCallback value) {
        if (!cache.containsKey(key)) {
            cache.put(key, value);
        }
    }

    public CacheInvalidationCallback getCacheInvalidation(final TenantKey key) {
        return cache.get(key);
    }

    public AtomicLong getLatestRecordIdProcessed() {
        return latestRecordIdProcessed;
    }

    public boolean isStopped() {
        return isStopped;
    }

    public void setLatestRecordIdProcessed(final Long newProcessedRecordId) {
        this.latestRecordIdProcessed.set(newProcessedRecordId);
    }

    public PersistentBus getEventBus() {
        return eventBus;
    }

    public static class TenantCacheInvalidationRunnable implements Runnable {

        private final TenantCacheInvalidation parent;
        private final TenantBroadcastDao broadcastDao;
        private final TenantDao tenantDao;

        public TenantCacheInvalidationRunnable(final TenantCacheInvalidation parent,
                                               final TenantBroadcastDao broadcastDao,
                                               final TenantDao tenantDao) {
            this.parent = parent;
            this.broadcastDao = broadcastDao;
            this.tenantDao = tenantDao;
        }

        @Override
        public void run() {
            if (parent.isStopped) {
                return;
            }

            final List<TenantBroadcastModelDao> entries = broadcastDao.getLatestEntriesFrom(parent.getLatestRecordIdProcessed().get());
            for (TenantBroadcastModelDao cur : entries) {
                if (parent.isStopped()) {
                    return;
                }

                try {
                    final TenantKeyAndCookie tenantKeyAndCookie = extractTenantKeyAndCookie(cur.getType());
                    if (tenantKeyAndCookie != null) {
                        final CacheInvalidationCallback callback = parent.getCacheInvalidation(tenantKeyAndCookie.getTenantKey());
                        if (callback != null) {
                            final InternalTenantContext tenantContext = new InternalTenantContext(cur.getTenantRecordId(), null);
                            callback.invalidateCache(tenantKeyAndCookie.getTenantKey(), tenantKeyAndCookie.getCookie(), tenantContext);

                            final Long tenantKvsTargetRecordId = cur.getTargetRecordId();
                            final BusInternalEvent event;
                            if (tenantKvsTargetRecordId != null) {
                                final TenantKVModelDao tenantModelDao = tenantDao.getKeyByRecordId(tenantKvsTargetRecordId, tenantContext);
                                if (tenantModelDao == null) {
                                    // Probably inactive entry
                                    continue;
                                }
                                event = new DefaultTenantConfigChangeInternalEvent(tenantModelDao.getId(), cur.getType(),
                                                                                null, tenantContext.getTenantRecordId(), cur.getUserToken());
                            } else {
                                event = new DefaultTenantConfigDeletionInternalEvent(cur.getType(),
                                                                                null, tenantContext.getTenantRecordId(), cur.getUserToken());
                            }
                            try {
                                parent.getEventBus().post(event);
                            } catch (final EventBusException e) {
                                logger.warn("Failed post bus event " + event, e);
                            }
                        }
                    } else {
                        logger.warn("Failed to find CacheInvalidationCallback for " + cur.getType());
                    }
                } finally {
                    parent.setLatestRecordIdProcessed(cur.getRecordId());
                }
            }
        }

        private TenantKeyAndCookie extractTenantKeyAndCookie(final String key) {
            final TenantKey tenantKey = Iterables.tryFind(ImmutableList.copyOf(TenantKey.values()), new Predicate<TenantKey>() {
                @Override
                public boolean apply(final TenantKey input) {
                    return key.startsWith(input.toString());
                }
            }).orNull();
            if (tenantKey == null) {
                return null;
            }

            final String cookie = !key.equals(tenantKey.toString()) ?
                                  key.substring(tenantKey.toString().length()) :
                                  null;
            return new TenantKeyAndCookie(tenantKey, cookie);
        }

    }

    private static final class TenantKeyAndCookie {

        private final TenantKey tenantKey;
        private final Object cookie;

        public TenantKeyAndCookie(final TenantKey tenantKey, final Object cookie) {
            this.tenantKey = tenantKey;
            this.cookie = cookie;
        }

        public TenantKey getTenantKey() {
            return tenantKey;
        }

        public Object getCookie() {
            return cookie;
        }
    }
}