text:
package org.sakaiproject.sitemanage.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.email.api.EmailService;
import org.sakaiproject.emailtemplateservice.model.RenderedTemplate;
import org.sakaiproject.emailtemplateservice.service.EmailTemplateService;
import org.sakaiproject.entitybroker.DeveloperHelperService;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.sitemanage.api.UserNotificationProvider;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserDirectoryService;
import org.sakaiproject.util.ResourceLoader;

public class ETSUserNotificationProviderImpl implements UserNotificationProvider {

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

	private static final String NOTIFY_ADDED_PARTICIPANT ="sitemange.notifyAddedParticipant";

	private static final String NOTIFY_NEW_USER ="sitemanage.notifyNewUserEmail";

	private static final String NOTIFY_TEMPLATE_USE = "sitemanage.notifyTemplateUse";

	// to send an email to course authorizer based on course site request
	private static final String NOTITY_COURSE_REQUEST_AUTHORIZER = "sitemanage.notifyCourseRequestAuthorizer";

	// to send an email to course site requestor
	private static final String NOTIFY_COURSE_REQUEST_REQUESTER = "sitemanage.notifyCourseRequestRequester";

	// to send an email to support team about course request
	private static final String NOTIFY_COURSE_REQUEST_SUPPORT = "sitemanage.notifyCourseRequestSupport";

	private static final String NOTIFY_SITE_CREATION = "sitemanage.notifySiteCreation";

	private static final String NOTIFY_SITE_CREATION_CONFIRMATION = "sitemanage.notifySiteCreation.confirmation";

	private static final String SITE_IMPORT_EMAIL_TEMPLATE_FILE_NAME 		= "notifySiteImportConfirmation.xml";
	private static final String SITE_IMPORT_EMAIL_TEMPLATE_KEY 				= "sitemanage.siteImport.Confirmation";
	private static final String SITE_IMPORT_EMAIL_TEMPLATE_VAR_WORKSITE 	= "worksiteName";
	private static final String SITE_IMPORT_EMAIL_TEMPLATE_VAR_LINK 		= "linkToWorksite";
	private static final String SITE_IMPORT_EMAIL_TEMPLATE_VAR_INSTITUTION 	= "institution";
	private static final String SAK_PROP_UI_INSTITUTION						= "ui.institution";

	private EmailService emailService;
	public void setEmailService(EmailService es) {
		emailService = es;
	}

	private ServerConfigurationService serverConfigurationService;
	public void setServerConfigurationService(ServerConfigurationService scs) {
		serverConfigurationService = scs;
	}

	private UserDirectoryService userDirectoryService;
	public void setUserDirectoryService(UserDirectoryService uds) {
		userDirectoryService = uds;
	}

	private EmailTemplateService emailTemplateService;
	public void setEmailTemplateService(EmailTemplateService ets) {
		emailTemplateService = ets;
	}

	private DeveloperHelperService developerHelperService;
	public void setDeveloperHelperService(DeveloperHelperService dhs) {
		this.developerHelperService = dhs;
	}

	public void init() {
		LOG.info("init()");

		ClassLoader loader = ETSUserNotificationProviderImpl.class.getClassLoader();
		emailTemplateService.importTemplateFromXmlFile(loader.getResourceAsStream("notifyAddedParticipants.xml"), NOTIFY_ADDED_PARTICIPANT);
		emailTemplateService.importTemplateFromXmlFile(loader.getResourceAsStream("notifyNewuser.xml"), NOTIFY_NEW_USER);
		emailTemplateService.importTemplateFromXmlFile(loader.getResourceAsStream("notifyTemplateUse.xml"), NOTIFY_TEMPLATE_USE);
		emailTemplateService.importTemplateFromXmlFile(loader.getResourceAsStream("notifyCourseRequestAuthorizer.xml"), NOTITY_COURSE_REQUEST_AUTHORIZER);
		emailTemplateService.importTemplateFromXmlFile(loader.getResourceAsStream("notifyCourseRequestRequester.xml"), NOTIFY_COURSE_REQUEST_REQUESTER);
		emailTemplateService.importTemplateFromXmlFile(loader.getResourceAsStream("notifyCourseRequestSupport.xml"), NOTIFY_COURSE_REQUEST_SUPPORT);
		emailTemplateService.importTemplateFromXmlFile(loader.getResourceAsStream("notifySiteCreation.xml"), NOTIFY_SITE_CREATION);
		emailTemplateService.importTemplateFromXmlFile(loader.getResourceAsStream("notifySiteCreationConfirmation.xml"), NOTIFY_SITE_CREATION_CONFIRMATION);
		emailTemplateService.importTemplateFromXmlFile(loader.getResourceAsStream(SITE_IMPORT_EMAIL_TEMPLATE_FILE_NAME), SITE_IMPORT_EMAIL_TEMPLATE_KEY);
	}

	public void notifyAddedParticipant(boolean newNonOfficialAccount,
			User user, Site site) {

		String from = serverConfigurationService.getBoolean(NOTIFY_FROM_CURRENT_USER, false)?
				getCurrentUserEmailAddress():getSetupRequestEmailAddress();
		//we need to get the template

		if (from != null) {
			String productionSiteName = serverConfigurationService.getString(
					"ui.service", "");
			String emailId = user.getEmail();
			String to = emailId;
			String headerTo = emailId;
			String replyTo = from;
			Map<String, String> rv = new HashMap<>();
			rv.put("productionSiteName", productionSiteName);

			Map<String, String> replacementValues = new HashMap<>();
			replacementValues.put("userName", user.getDisplayName());
			replacementValues.put("userEid", user.getEid());
			replacementValues.put("localSakaiName", productionSiteName);
			replacementValues.put("currentUserName",userDirectoryService.getCurrentUser().getDisplayName());
			replacementValues.put("localSakaiUrl", serverConfigurationService.getPortalUrl());
			String nonOfficialAccountUrl = serverConfigurationService.getString("nonOfficialAccount.url", null);
			replacementValues.put("hasNonOfficialAccountUrl", nonOfficialAccountUrl!=null?Boolean.TRUE.toString().toLowerCase():Boolean.FALSE.toString().toLowerCase());
			replacementValues.put("nonOfficialAccountUrl",nonOfficialAccountUrl);
			replacementValues.put("siteName", site.getTitle());
			replacementValues.put("productionSiteName", productionSiteName);
			replacementValues.put("newNonOfficialAccount", Boolean.toString(newNonOfficialAccount).toLowerCase());
			replacementValues.put("xloginText", serverConfigurationService.getString("xlogin.text", "Login"));
			replacementValues.put("loginText", serverConfigurationService.getString("login.text", "Login"));
			replacementValues.put("siteUrl", site.getUrl());

			// send email
			emailTemplateServiceSend(NOTIFY_ADDED_PARTICIPANT, null, user, from, to, headerTo, replyTo, replacementValues);
		} // if
	}

	public void notifyNewUserEmail(User user, String newUserPassword,
			Site site) {

		String from = getSetupRequestEmailAddress();
		String productionSiteName = serverConfigurationService.getString(
				"ui.service", "");
		String newUserEmail = user.getEmail();
		String to = newUserEmail;
		String headerTo = newUserEmail;
		String replyTo = from;

		if (from != null && newUserEmail != null) {
			/*
			 * $userName
			 * $localSakaiName
			 * $currentUserName
			 * $localSakaiUrl
			 */
			Map<String, String> replacementValues = new HashMap<>();
			replacementValues.put("userName", user.getDisplayName());
			replacementValues.put("localSakaiName",serverConfigurationService.getString("ui.service", ""));
			replacementValues.put("currentUserName",userDirectoryService.getCurrentUser().getDisplayName());
			replacementValues.put("userEid", user.getEid());
			replacementValues.put("localSakaiUrl", serverConfigurationService.getPortalUrl());
			replacementValues.put("newPassword",newUserPassword);
			replacementValues.put("siteName", site.getTitle());
			replacementValues.put("productionSiteName", productionSiteName);

			// send email
			emailTemplateServiceSend(NOTIFY_NEW_USER, null, user, from, to, headerTo, replyTo, replacementValues);
		}
	}

	public void notifyTemplateUse(Site templateSite, User currentUser, Site site) {
		// send an email to track who are using the template
		String from = getSetupRequestEmailAddress();
		// send it to the email archive of the template site
		// TODO: need a better way to get the email archive address
		//String domain = from.substring(from.indexOf('@'));
		String templateEmailArchive = templateSite.getId() + "@" + serverConfigurationService.getServerName();
		String to = templateEmailArchive;
		String headerTo = templateEmailArchive;
		String replyTo = templateEmailArchive;

		if (from != null && templateEmailArchive != null) {
			Map<String, String> replacementValues = new HashMap<>();
			replacementValues.put("templateSiteTitle", templateSite.getTitle());
			replacementValues.put("templateSiteId", templateSite.getId());
			replacementValues.put("currentUserDisplayName", currentUser.getDisplayName());
			replacementValues.put("currentUserDisplayId", currentUser.getDisplayId());
			SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance());
			dform.applyPattern("yyyy-MM-dd HH:mm:ss");
			String dateDisplay = dform.format(new Date());
			replacementValues.put("currentDate", dateDisplay);
			replacementValues.put("newSiteId", site.getId());
			replacementValues.put("newSiteTitle", site.getTitle());

			emailTemplateServiceSend(NOTIFY_TEMPLATE_USE, (new ResourceLoader()).getLocale(), currentUser, from, to, headerTo, replyTo, replacementValues);
		}
	}

	public boolean notifyCourseRequestAuthorizer(String instructorId, String requestEmail, String replyToEmail, String termTitle, String requestSectionInfo, String siteTitle, String siteId, String additionalInfo, String serverName)
	{
		try {
			User instructor = userDirectoryService.getUserByEid(instructorId);
			String to = instructor.getEmail();
			String from = requestEmail;
			String headerTo = to;
			String replyTo = replyToEmail;
			User currentUser = userDirectoryService.getCurrentUser();
			String currentUserDisplayName = currentUser!=null?currentUser.getDisplayName():"";
			String currentUserDisplayId = currentUser!=null?currentUser.getDisplayId():"";

			Map<String, String> replacementValues = new HashMap<>();
			replacementValues.put("currentUserDisplayName", currentUserDisplayName);
			replacementValues.put("currentUserDisplayId", currentUserDisplayId);
			replacementValues.put("termTitle", termTitle);
			replacementValues.put("requestSectionInfo", requestSectionInfo);
			replacementValues.put("siteTitle", siteTitle);
			replacementValues.put("siteId", siteId);
			replacementValues.put("specialInstruction", additionalInfo);
			replacementValues.put("serverName", serverName);

			return emailTemplateServiceSend(NOTITY_COURSE_REQUEST_AUTHORIZER, null, instructor, from, to, headerTo, replyTo, replacementValues) != null;

		}
		catch (Exception e)
		{
			LOG.warn(this + " cannot find user " + instructorId, e);
			return false;
		}
	}

	public String notifyCourseRequestSupport(String requestEmail, String serverName, String request, String termTitle, int requestListSize, String requestSectionInfo,
			String officialAccountName, String siteTitle, String siteId, String additionalInfo, boolean requireAuthorizer, String authorizerNotified, String authorizerNotNotified)
	{
		User currentUser = userDirectoryService.getCurrentUser();
		String currentUserDisplayName = currentUser!=null?currentUser.getDisplayName():"";
		String currentUserDisplayId = currentUser!=null?currentUser.getDisplayId():"";
		String currentUserEmail = currentUser!=null?currentUser.getEmail():"";

		// To Support
		String from = currentUserEmail;
		String to = requestEmail;
		String headerTo = requestEmail;
		String replyTo = currentUserEmail;

		Map<String, String> replacementValues = new HashMap<>();
		replacementValues.put("currentUserDisplayName", currentUserDisplayName);
		replacementValues.put("currentUserDisplayId", currentUserDisplayId);
		replacementValues.put("termTitle", termTitle);
		replacementValues.put("requestSectionInfo", requestSectionInfo);
		replacementValues.put("requestListSize", String.valueOf(requestListSize));
		replacementValues.put("siteTitle", siteTitle);
		replacementValues.put("siteId", siteId);
		replacementValues.put("specialInstruction", additionalInfo);
		replacementValues.put("serverName", serverName);

		SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance());
		dform.applyPattern("yyyy-MM-dd HH:mm:ss");
		String dateDisplay = dform.format(new Date());
		replacementValues.put("dateDisplay", dateDisplay);

		replacementValues.put("requireAuthorizer", String.valueOf(requireAuthorizer));
		replacementValues.put("authorizerNotified", authorizerNotified);
		replacementValues.put("authorizerNotNotified", authorizerNotNotified);

		try
		{
			return emailTemplateServiceSend(NOTIFY_COURSE_REQUEST_SUPPORT, (new ResourceLoader()).getLocale(), currentUser, from, to, headerTo, replyTo, replacementValues);
		}
		catch (Exception e)
		{
			LOG.warn(this + " problem in send site request email to support for " + currentUserDisplayName, e );
			return "";
		}
	}

	public void notifyCourseRequestRequester(String requestEmail, String supportEmailContent, String termTitle)
	{
		User currentUser = userDirectoryService.getCurrentUser();
		String currentUserDisplayName = currentUser!=null?currentUser.getDisplayName():"";
		String currentUserDisplayId = currentUser!=null?currentUser.getDisplayId():"";
		String currentUserEmail = currentUser!=null?currentUser.getEmail():"";

		String from = requestEmail;
		String to = currentUserEmail;
		String headerTo = to;
		String replyTo = to;
		Map<String, String> replacementValues = new HashMap<>();
		replacementValues.put("currentUserDisplayName", currentUserDisplayName);
		replacementValues.put("currentUserDisplayId", currentUserDisplayId);
		replacementValues.put("currentUserEmail", currentUserEmail);
		replacementValues.put("termTitle", termTitle);
		replacementValues.put("supportEmailContent", supportEmailContent);
		replacementValues.put("requestEmail", requestEmail);

		emailTemplateServiceSend(NOTIFY_COURSE_REQUEST_REQUESTER, (new ResourceLoader()).getLocale(), currentUser, from, to, headerTo, replyTo, replacementValues);
	}

	public void notifySiteCreation(Site site, List notifySites, boolean courseSite, String termTitle, String requestEmail) {
		User currentUser = userDirectoryService.getCurrentUser();
		String currentUserDisplayName = currentUser!=null?currentUser.getDisplayName():"";
		String currentUserDisplayId = currentUser!=null?currentUser.getDisplayId():"";
		String currentUserEmail = currentUser!=null?currentUser.getEmail():"";

		SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance());
		dform.applyPattern("yyyy-MM-dd HH:mm:ss");
		String dateDisplay = dform.format(new Date());

		String from = currentUserEmail;
		String to = requestEmail;
		String headerTo = requestEmail;
		String replyTo = currentUserEmail;
		Map<String, String> replacementValues = new HashMap<>();
		replacementValues.put("currentUserDisplayName", currentUserDisplayName);
		replacementValues.put("currentUserDisplayId", currentUserDisplayId);
		replacementValues.put("currentUserEmail", currentUserEmail);
		replacementValues.put("dateDisplay", dateDisplay);
		replacementValues.put("termTitle", termTitle);
		replacementValues.put("serviceName", serverConfigurationService.getString( "ui.service", serverConfigurationService.getServerName() ) );
		replacementValues.put("siteTitle", site!=null?site.getTitle():"");
		replacementValues.put("siteId", site!=null?site.getId():"");
		replacementValues.put("courseSite", String.valueOf(courseSite));

		StringBuilder buf = new StringBuilder();
		if (notifySites!= null)
		{
			int nbr_sections = notifySites.size();
			replacementValues.put("numSections", String.valueOf(nbr_sections));
			for (int i = 0; i < nbr_sections; i++) {
				String course = (String) notifySites.get(i);
				buf.append( course ).append("\n");
			}
		}
		else
		{
			replacementValues.put("numSections", "0");
		}
		replacementValues.put("sections", buf.toString());

		emailTemplateServiceSend(NOTIFY_SITE_CREATION, (new ResourceLoader()).getLocale(), currentUser, from, to, headerTo, replyTo, replacementValues);

		// send a confirmation email to site creator
		from = requestEmail;
		to = currentUserEmail;
		headerTo = currentUserEmail;
		replyTo = serverConfigurationService.getString("setup.request","no-reply@" + serverConfigurationService.getServerName());
		emailTemplateServiceSend(NOTIFY_SITE_CREATION_CONFIRMATION, (new ResourceLoader()).getLocale(), currentUser, from, to, headerTo, replyTo, replacementValues);

	}

	/*
	 *  Private methods
	 */

	private String getSetupRequestEmailAddress() {
		String from = serverConfigurationService.getString("setup.request",
				null);
		if (from == null) {
			LOG.warn(this + " - no 'setup.request' in configuration");
			from = "postmaster@".concat(serverConfigurationService
					.getServerName());
		}
		return from;
	}

	private String getCurrentUserEmailAddress() {
		User currentUser = userDirectoryService.getCurrentUser();
		String email = currentUser != null ? currentUser.getEmail():null;
		if (email == null || email.length() == 0) {
			email = getSetupRequestEmailAddress();
		}
		return email;
	}

	/**
	 * use EmailTemplateService to send email
	 * @param templateName
	 * @param user
	 * @param from
	 * @param to
	 * @param headerTo
	 * @param replyTo
	 * @param replacementValues
	 * @return the email content
	 */
	private String emailTemplateServiceSend(String templateName, Locale locale, User user, String from, String to, String headerTo, String replyTo, Map<String, String> replacementValues) {
		LOG.debug("getting template: " + templateName);
		RenderedTemplate template;
		try {
			if (locale == null)
			{
				// use user's locale
				template = emailTemplateService.getRenderedTemplateForUser(templateName, user!=null?user.getReference():"", replacementValues);
			}
			else
			{
				// use local
				template = emailTemplateService.getRenderedTemplate(templateName, locale, replacementValues);
			}
			if (template != null)
			{
				List<String> headers = new ArrayList<>();
				headers.add("Precedence: bulk");

				String content = template.getRenderedMessage();
				emailService.send(from, to, template.getRenderedSubject(), content, headerTo, replyTo, headers);
				return content;
			}
		}
		catch (Exception e) {
			LOG.warn(this + e.getMessage());
			return null;
		}
		return null;
	}

	public void notifySiteImportCompleted(String toEmail, String siteId, String siteTitle){
		if(toEmail != null && !"".equals(toEmail)){

			// Create the map of replacement values
			Map<String, String> replacementValues = new HashMap<>();
			replacementValues.put(SITE_IMPORT_EMAIL_TEMPLATE_VAR_WORKSITE, siteTitle);
			replacementValues.put(SITE_IMPORT_EMAIL_TEMPLATE_VAR_LINK, developerHelperService.getLocationReferenceURL(SITE_REF_PREFIX + siteId));
			replacementValues.put(SITE_IMPORT_EMAIL_TEMPLATE_VAR_INSTITUTION, serverConfigurationService.getString(SAK_PROP_UI_INSTITUTION));

			// Use the email template service to send the email
			String headerTo = toEmail;
			String replyTo = toEmail;
			emailTemplateServiceSend(SITE_IMPORT_EMAIL_TEMPLATE_KEY, Locale.ENGLISH, userDirectoryService.getCurrentUser(), getSetupRequestEmailAddress(),
					toEmail, headerTo, replyTo, replacementValues);
		}
	}
}


text:
@interface GPUImageSourceOverBlendFilter : GPUImageTwoInputFilter

@end

redpajama_set_name: RedPajamaGithub


text:
package com.viesis.viescraft.client.gui.airship.frames;

import java.awt.Color;
import java.io.IOException;

import org.lwjgl.input.Keyboard;

import com.viesis.viescraft.api.GuiVC;
import com.viesis.viescraft.api.Reference;
import com.viesis.viescraft.api.util.Keybinds;
import com.viesis.viescraft.common.entity.airshipcolors.EntityAirshipBaseVC;
import com.viesis.viescraft.common.entity.airshipcolors.containers.all.ContainerAirshipAppearance;
import com.viesis.viescraft.network.NetworkHandler;
import com.viesis.viescraft.network.server.airship.MessageGuiDefault;
import com.viesis.viescraft.network.server.airship.MessageGuiModuleInventoryLarge;
import com.viesis.viescraft.network.server.airship.MessageGuiModuleInventorySmall;
import com.viesis.viescraft.network.server.airship.MessageGuiModuleJukebox;
import com.viesis.viescraft.network.server.appearance.MessageGuiAppearanceHelperPage5;
import com.viesis.viescraft.network.server.appearance.MessageGuiAppearancePage4;

import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.inventory.IInventory;
import net.minecraft.util.ResourceLocation;

public class GuiAirshipAppearancePg5 extends GuiContainer {

	private IInventory playerInv;
	private EntityAirshipBaseVC airship;
	public static int metaInfo;
	public static boolean metaActiveInfo;

	public GuiAirshipAppearancePg5(IInventory playerInv, EntityAirshipBaseVC airship)
	{
		super(new ContainerAirshipAppearance(playerInv, airship));

		this.playerInv = playerInv;
		this.airship = airship;
		this.xSize = 176;
		this.ySize = 166;
	}

	/**
     * Adds the buttons (and other controls) to the screen in question.
     */
    @Override
    public void initGui()
    {
    	super.initGui();

    	buttonList.clear();
    	Keyboard.enableRepeatEvents(true);

    	GuiVC.buttonDone = new GuiButton( 30, this.guiLeft + 40, this.guiTop + 156, 96, 20, "Done");
    	GuiVC.buttonPrev = new GuiButton( 32, this.guiLeft + 4, this.guiTop + 4, 57, 20, "Prev");

    	GuiVC.button26 = new GuiButton( 26, this.guiLeft + 15, this.guiTop + 62, 57, 20, "Mythic");
    	GuiVC.button39 = new GuiButton( 39, this.guiLeft + 15, this.guiTop + 97, 57, 20, "Water");
    	GuiVC.button40 = new GuiButton( 40, this.guiLeft + 105, this.guiTop + 62, 57, 20, "Lava");
    	GuiVC.button41 = new GuiButton( 41, this.guiLeft + 105, this.guiTop + 97, 57, 20, "Ender");

		this.buttonList.add(GuiVC.buttonDone);
		this.buttonList.add(GuiVC.buttonPrev);

		this.buttonList.add(GuiVC.button26);
		this.buttonList.add(GuiVC.button39);
		this.buttonList.add(GuiVC.button40);
		this.buttonList.add(GuiVC.button41);

		if(this.airship.metaFrameCore == 26)
    	{
    		GuiVC.button39.visible = false;
    		GuiVC.button40.visible = false;
    		GuiVC.button41.visible = false;
    	}
		if(this.airship.metaFrameCore == 27)
    	{
			GuiVC.button40.visible = false;
    		GuiVC.button41.visible = false;
    	}
		if(this.airship.metaFrameCore == 28)
    	{
			GuiVC.button41.visible = false;
    	}
    }

    /**
     * Called by the controls from the buttonList when activated. (Mouse pressed for buttons)
     */
	@Override
    protected void actionPerformed(GuiButton parButton)
    {
		if (parButton.id == 30)
	    {
			//If airship has small inv module installed
        	if(this.airship.getModuleInventorySmall())
        	{
        		NetworkHandler.sendToServer(new MessageGuiModuleInventorySmall());
        	}
        	//If airship has large inv module installed
        	else if(this.airship.getModuleInventoryLarge())
        	{
        		NetworkHandler.sendToServer(new MessageGuiModuleInventoryLarge());
        	}
        	//If airship has jukebox module installed
        	else if(this.airship.getModuleJukebox())
        	{
        		NetworkHandler.sendToServer(new MessageGuiModuleJukebox());
        	}
        	//Default for airship gui
        	else
        	{
        		NetworkHandler.sendToServer(new MessageGuiDefault());
        	}
	    }
		if (parButton.id == 32)
	    {
			NetworkHandler.sendToServer(new MessageGuiAppearancePage4());
	    }
		if (parButton.id == 26)
	    {
			this.metaInfo = 26;
			metaActiveInfo = true;
			NetworkHandler.sendToServer(new MessageGuiAppearanceHelperPage5());
	    }
		if (parButton.id == 39)
	    {
			this.metaInfo = 27;
			metaActiveInfo = true;
			NetworkHandler.sendToServer(new MessageGuiAppearanceHelperPage5());
	    }
		if (parButton.id == 40)
	    {
			this.metaInfo = 28;
			metaActiveInfo = true;
			NetworkHandler.sendToServer(new MessageGuiAppearanceHelperPage5());
	    }
		if (parButton.id == 41)
	    {
			this.metaInfo = 29;
			metaActiveInfo = true;
			NetworkHandler.sendToServer(new MessageGuiAppearanceHelperPage5());
	    }

        this.buttonList.clear();
        this.initGui();
        this.updateScreen();
    }

	@Override
	protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY)
	{
		GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f);
		this.mc.getTextureManager().bindTexture(new ResourceLocation(Reference.MOD_ID + ":" + "textures/gui/container_airship_appearance.png"));
		this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize);
		this.drawRect(this.guiLeft + 32, this.guiTop - 16, this.guiLeft + 142, this.guiTop, Color.LIGHT_GRAY.getRGB());
		this.drawRect(this.guiLeft + 34, this.guiTop - 14, this.guiLeft + 140, this.guiTop, Color.BLACK.getRGB());
    }

	@Override
	protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY)
	{
		this.fontRendererObj.drawString("Tier IV", 71, 10, 11111111);
		this.fontRendererObj.drawString("Frame Appearance", 40, -10, 65521);
	}

	@Override
	protected void keyTyped(char typedChar, int keyCode) throws IOException
    {
		if (keyCode == 1
        ||	keyCode == Keybinds.vcInventory.getKeyCode()
        || this.mc.gameSettings.keyBindInventory.isActiveAndMatches(keyCode))
        {
            this.mc.player.closeScreen();
        }
    }

	@Override
	public void updateScreen()
    {
        super.updateScreen();

        if (!this.mc.player.isEntityAlive() || this.mc.player.isDead
        || !this.mc.player.isRiding())
        {
            this.mc.player.closeScreen();
        }
    }
}


text:
package org.omg.CORBA;

//
// IDL:omg.org/CORBA/SetOverrideType:1.0
//
final public class SetOverrideTypeHolder implements org.omg.CORBA.portable.Streamable
{
    public SetOverrideType value;

    public
    SetOverrideTypeHolder()
    {
    }

    public
    SetOverrideTypeHolder(SetOverrideType initial)
    {
        value = initial;
    }

    public void
    _read(org.omg.CORBA.portable.InputStream in)
    {
        value = SetOverrideTypeHelper.read(in);
    }

    public void
    _write(org.omg.CORBA.portable.OutputStream out)
    {
        SetOverrideTypeHelper.write(out, value);
    }

    public org.omg.CORBA.TypeCode
    _type()
    {
        return SetOverrideTypeHelper.type();
    }
}


text:
package io.fabric8.kubernetes.api.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Version;
import io.sundr.builder.annotations.Buildable;
import io.sundr.transform.annotations.TemplateTransformation;
import io.sundr.transform.annotations.TemplateTransformations;
import lombok.EqualsAndHashCode;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "apiVersion",
    "kind",
    "metadata",
    "items"
})
@ToString
@EqualsAndHashCode
@Setter
@Accessors(prefix = {
    "_",
    ""
})
@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = true, lazyCollectionInitEnabled = false, builderPackage = "io.fabric8.kubernetes.api.builder")
@TemplateTransformations({
    @TemplateTransformation(value = "/manifest.vm", outputPath = "META-INF/services/io.fabric8.kubernetes.api.model.KubernetesResource", gather = true)
})
@Version("v1")
@Group("")
public class PersistentVolumeClaimList implements KubernetesResource, KubernetesResourceList<io.fabric8.kubernetes.api.model.PersistentVolumeClaim>
{

    /**
     *
     * (Required)
     *
     */
    @JsonProperty("apiVersion")
    private String apiVersion = "v1";
    @JsonProperty("items")
    private List<io.fabric8.kubernetes.api.model.PersistentVolumeClaim> items = new ArrayList<io.fabric8.kubernetes.api.model.PersistentVolumeClaim>();
    /**
     *
     * (Required)
     *
     */
    @JsonProperty("kind")
    private String kind = "PersistentVolumeClaimList";
    @JsonProperty("metadata")
    private ListMeta metadata;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    /**
     * No args constructor for use in serialization
     *
     */
    public PersistentVolumeClaimList() {
    }

    /**
     *
     * @param metadata
     * @param apiVersion
     * @param kind
     * @param items
     */
    public PersistentVolumeClaimList(String apiVersion, List<io.fabric8.kubernetes.api.model.PersistentVolumeClaim> items, String kind, ListMeta metadata) {
        super();
        this.apiVersion = apiVersion;
        this.items = items;
        this.kind = kind;
        this.metadata = metadata;
    }

    /**
     *
     * (Required)
     *
     */
    @JsonProperty("apiVersion")
    public String getApiVersion() {
        return apiVersion;
    }

    /**
     *
     * (Required)
     *
     */
    @JsonProperty("apiVersion")
    public void setApiVersion(String apiVersion) {
        this.apiVersion = apiVersion;
    }

    @JsonProperty("items")
    public List<io.fabric8.kubernetes.api.model.PersistentVolumeClaim> getItems() {
        return items;
    }

    @JsonProperty("items")
    public void setItems(List<io.fabric8.kubernetes.api.model.PersistentVolumeClaim> items) {
        this.items = items;
    }

    /**
     *
     * (Required)
     *
     */
    @JsonProperty("kind")
    public String getKind() {
        return kind;
    }

    /**
     *
     * (Required)
     *
     */
    @JsonProperty("kind")
    public void setKind(String kind) {
        this.kind = kind;
    }

    @JsonProperty("metadata")
    public ListMeta getMetadata() {
        return metadata;
    }

    @JsonProperty("metadata")
    public void setMetadata(ListMeta metadata) {
        this.metadata = metadata;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: hp
 * Date: 22/12/2014
 * Time: 09:17
 */

namespace Sise\Bundle\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;

class MainController extends Controller
{
    public function updateAction($id)
    {
    }

    public function registerAction(Request $request)
    {

    }
}


text:
package com.predic8.beautifier;

import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;

import junit.framework.Assert;
import junit.framework.TestCase;

public class HtmlBeautifierTest extends TestCase {

	XMLBeautifier beautifier;

	InputStream inputStream;

	Writer writer;
	@Override
	protected void setUp() throws Exception {
		File base = new File("target/test");
		base.mkdirs();
		writer = new FileWriter(new File(base, "html_drain.html"));

		inputStream = this.getClass().getResourceAsStream("/BLZService.xml");
		writer.write("<link rel='stylesheet' href='style.css' />
");
		XMLBeautifierFormatter formatter = new HtmlBeautifierFormatter(writer, 0);
		beautifier = new XMLBeautifier(formatter);
		super.setUp();
	}

	@Override
	protected void tearDown() throws Exception {
		inputStream.close();
		super.tearDown();
	}

	public void testFile() throws Exception {
		beautifier.parse(new InputStreamReader(inputStream));
		writer.write("
");
		writer.close();
		Assert.assertEquals(new File("src/test/resources/html_drain.html").length(), new File("target/test/html_drain.html").length());
	}
}


text:
Maven TypeScript Compiler Plugin
================================

This plugin adds [TypeScript](http://typescriptlang.org/) compilation to your Maven project without adding any
prerequisites (e.g. installing Node.js) other than JDK 8. It unpacks the TypeScript compiler from a Maven artifact,
makes the [Avatar.js](https://avatar-js.java.net/) native library available with the expected filename, then executes
tsc on the Avatar.js server, which uses Nashorn to execute JavaScript.

Why?
----

There are a variety of reasons that a development team can't require Node.js and NPM for their build process, including
company policy, regulatory and audit compliance, and inertia. While individual developers may be able to work around
these roadblocks, a requirement to install new software on the build server is more likely to remain a problem.

Also, a well-integrated, all-JVM build is a neat idea.

Why not?
--------

It's slow. Startup time for tsc is somewhere around 12 seconds.

What about watching the directory and recompiling when a file changes?
----------------------------------------------------------------------

That's your IDE's job. If you want to do it anyway, run the tsc:watch goal.

Alternatives
------------

Where no such restrictions apply, consider other plugins such as
[frontend-maven-plugin](https://github.com/eirslett/frontend-maven-plugin) or
[grunt-maven-plugin](https://github.com/allegro/grunt-maven-plugin).

How to use
----------

As the Maven artifacts provided by this project are unlikely to be available to your Maven instance, first
install/deploy the [TypeScript redistribution](typescript/) and [tsc-maven-plugin](tsc-maven-plugin/) artifacts,
either to your local Maven repository ($HOME/.m2/repository) or your local Maven repository manager (e.g. Artifactory
or Nexus). Next, take a look at the included [demo project](tsc-maven-demo-project/) for usage information.

Reasonable defaults have been provided for every user-serviceable configuration option. Refer to
[AbstractTypeScriptMojo](tsc-maven-plugin/src/main/java/ca/eqv/maven/plugins/tsc/mojo/AbstractTypeScriptMojo.java)
(or your IDE's tooltips while editing your POM) to see what can be changed on the fly.

Project status
--------------

This project is currently on hold pending two matters:

* Completion of the [Angular 2](http://angular.io/) switchover from Traceur/AtScript to TypeScript. The [information
available at this time](https://github.com/Microsoft/TypeScript/issues/1557) suggests that the upcoming TypeScript 1.5
release may support the required language changes for this to take place. Until then, a suitable demo project for
exploring the second matter cannot be completed.

* A team decision on whether to adopt Angular 2 for front-end development, and whether we are willing to tie together
two build processes (Maven triggering a Grunt build that uses [grunt-ts](https://github.com/TypeStrong/grunt-ts) for
TypeScript compilation) or would prefer to use only Maven.

License
-------

Except where otherwise noted, everything contained in this repository is

    Copyright 2015 William Ono

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


text:
package com.synopsys.arc.jenkins.plugins.ownership.jobs;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.synopsys.arc.jenkins.plugins.ownership.OwnershipDescription;
import hudson.cli.CLICommandInvoker;
import hudson.cli.UpdateJobCommand;
import hudson.model.FreeStyleProject;
import hudson.model.Item;
import hudson.model.Job;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import jenkins.model.Jenkins;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRule.WebClient;
import org.jvnet.hudson.test.MockAuthorizationStrategy;

import static hudson.cli.CLICommandInvoker.Matcher.failedWith;
import static hudson.cli.CLICommandInvoker.Matcher.succeededSilently;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

public class JobOwnerJobPropertyTest {

    @Rule
    public JenkinsRule r = new JenkinsRule();

    @Before
    public void setupSecurity() {
        r.jenkins.setSecurityRealm(r.createDummySecurityRealm());
        MockAuthorizationStrategy mas = new MockAuthorizationStrategy();
        mas.grant(Jenkins.ADMINISTER) // Implies MANAGE_ITEMS_OWNERSHIP.
                .everywhere()
                .to("admin");
        mas.grant(Item.CONFIGURE, Item.READ, Jenkins.READ)
                .everywhere()
                .to("non-admin");
        r.jenkins.setAuthorizationStrategy(mas);
    }

    @Test
    @Issue("SECURITY-498")
    public void changeOwnerViaPost() throws Exception {
        FreeStyleProject p = r.createFreeStyleProject();
        p.getProperty(JobOwnerJobProperty.class).setOwnershipDescription(new OwnershipDescription(true, "admin", null));

        WebClient wc = r.createWebClient();
        wc.login("non-admin", "non-admin");
        WebRequest req = new WebRequest(wc.createCrumbedUrl(String.format("%sconfig.xml", p.getUrl())), HttpMethod.POST);
        req.setAdditionalHeader("Content-Type", "application/xml");
        req.setRequestBody(getJobXml("admin"));
        wc.getPage(req);
        assertThat("Users should be able to configure jobs when ownership is unchanged",
                getPrimaryOwner(p), is(equalTo("admin")));

        try {
            wc.login("non-admin", "non-admin");
            req.setRequestBody(getJobXml("non-admin"));
            wc.getPage(req);
            fail("Users should not be able to configure job ownership without Manger Ownership/Jobs permissions");
        } catch (FailingHttpStatusCodeException e) {
            assertThat(getPrimaryOwner(p), is(equalTo("admin")));
        }

        wc.login("admin", "admin");
        req.setRequestBody(getJobXml("non-admin"));
        wc.getPage(req);
        assertThat("Users with Manage Ownership/Jobs permissions should be able to change ownership",
                getPrimaryOwner(p), is(equalTo("non-admin")));
    }

    @Test
    @Issue("SECURITY-498")
    public void changeOwnerViaCLI() throws Exception {
        FreeStyleProject p = r.createFreeStyleProject();
        p.getProperty(JobOwnerJobProperty.class).setOwnershipDescription(new OwnershipDescription(true, "admin", null));

        CLICommandInvoker command = new CLICommandInvoker(r, new UpdateJobCommand())
                .asUser("non-admin")
                .withArgs(p.getFullName())
                .withStdin(getJobXmlAsStream("admin"));
        assertThat("Users without Overall/Administer permissions should not be able to configure jobs via CLI",
                command.invoke(), failedWith(1));
        assertThat(getPrimaryOwner(p), is(equalTo("admin")));

        command.asUser("admin")
                .withArgs(p.getFullName())
                .withStdin(getJobXmlAsStream("non-admin"));
        assertThat("Users with Overall/Administer permissions should be able to configure jobs via CLI",
                command.invoke(), succeededSilently());
        assertThat(getPrimaryOwner(p), is(equalTo("non-admin")));
    }

    private String getPrimaryOwner(Job<?,?> job) {
        return job.getProperty(JobOwnerJobProperty.class).getOwnership().getPrimaryOwnerId();
    }

    private String getJobXml(String ownerSid) {
        return String.format(JOB_XML_TEMPLATE, ownerSid);
    }

    private InputStream getJobXmlAsStream(String ownerSid) {
        return new ByteArrayInputStream(getJobXml(ownerSid).getBytes(StandardCharsets.UTF_8));
    }

    private static final String JOB_XML_TEMPLATE =
            "<?xml version='1.0' encoding='UTF-8'?>" +
            "<project>" +
            "<properties>" +
            "    <com.synopsys.arc.jenkins.plugins.ownership.jobs.JobOwnerJobProperty plugin=\"ownership@0.10.1-SNAPSHOT\">" +
            "        <ownership>" +
            "           <ownershipEnabled>true</ownershipEnabled>" +
            "           <primaryOwnerId>%s</primaryOwnerId>" +
            "           <coownersIds class=\"sorted-set\"/>" +
            "       </ownership>" +
            "   </com.synopsys.arc.jenkins.plugins.ownership.jobs.JobOwnerJobProperty>" +
            "</properties>" +
            "</project>";
}


text:
import discord
from discord.ext import commands

AVOID = ['342891382584770560', '300564141096304650', '360722519860445184', '312038519294001152', '321832332279676928']

class Modtools:
  def __init__(self, bot):
    self.bot = bot

  @commands.command(pass_context=True)
  async def propagateMute(self, ctx):
    if self.bot.Henry(ctx):
      for role in ctx.message.server.roles:
        if role.id == '338575090847580160':
          MUTED_ROLE = role

      overwrite = discord.PermissionOverwrite()
      setattr(overwrite, 'send_messages', False)
      setattr(overwrite, 'manage_messages', False)
      setattr(overwrite, 'manage_channels', False)
      setattr(overwrite, 'manage_server', False)
      setattr(overwrite, 'manage_nicknames', False)
      setattr(overwrite, 'manage_roles', False)
      for channel in ctx.message.server.channels:
        if channel.id not in AVOID:
          await self.bot.edit_channel_permissions(channel, MUTED_ROLE, overwrite)

#  @commands.command(pass_context=True)
#  async def lock(self, ctx):
#    """Locks the current channel."""
#    for role in ctx.message.server.roles:
#      if role.id == '338575090847580160':
#        MUTED_ROLE = role
#      if role.id == '296466915235332106':
#        BOTS_ROLE = role
#    if self.minion(ctx):
#      everyone = []
#      for user in ctx.message.server.members:
#        if ctx.message.channel.permissions_for(user).send_messages and BOTS_ROLE not in user.roles: #don't mute bots
#          everyone.append(user)
#      for user in everyone:
#        await self.bot.add_roles(user, MUTED_ROLE)
#      await self.bot.say("Locking Channel")
#    else:
#      await self.bot.say("You ain't no mod, shoo!")

  @commands.command(pass_context=True)
  async def unlock(self, ctx):
    """Unlocks the current channel."""
    if self.minion(ctx):
      for role in ctx.message.server.roles:
        if role.id == '338575090847580160':
          MUTED_ROLE = role
      everyone = []
      for user in ctx.message.server.members:
        if ctx.message.channel.permissions_for(user).send_messages:
          everyone.append(user)
      for user in everyone:
        if MUTED_ROLE in user.roles:
          await self.bot.remove_roles(user, MUTED_ROLE)
      await self.bot.say("Unlocking Channel")
    else:
      await self.bot.say("You ain't no mod, shoo!")

  async def ch_perms(self, channel, user, value):
    """Helper function"""
    overwrite = discord.PermissionOverwrite()
    overwrite.send_messages = value
    await self.bot.edit_channel_permissions(channel, user, overwrite)

  @commands.command(pass_context=True)
  async def unrestrict(self, ctx, *msg):
    """Undo any restrictions on a user for all channels.
    Usage: !unrestrict [users..]
    """
    if self.minion(ctx):
      channels = ctx.message.server.channels
      for user in ctx.message.mentions:
        await self.bot.say("Unrestricting user "+user.name)
        for ch in channels:
          await self.ch_perms(ch, user, None) #None sets to default(inherited) value.
    else:
      await self.bot.say("You ain't no mod, shoo!")

  @commands.command(pass_context=True)
  async def restrict(self, ctx):
    if self.minion(ctx):
      for role in ctx.message.server.roles:
        if role.id == '338575090847580160':
          MUTED_ROLE = role
      await self.bot.add_roles(ctx.message.mentions[0], MUTED_ROLE)
      await self.bot.say("{} has been muted.".format(ctx.message.mentions[0].mention))
    else:
      await self.bot.say("You ain't no mod, shoo!")

  def minion(self, ctx):
    for role in ctx.message.author.roles:
      if "314296819272122368" == role.id:
        return True
    return False

  @commands.command(pass_context=True)
  async def modsay(self, ctx, *msg):
    """Give a stern message.
       Heavily inspired by brenfan's .em code <3
    """
    author = ctx.message.author
    if author.permissions_in(ctx.message.channel).manage_channels or author.server_permissions.manage_channels:

      try:
        color = red
      except Exception:
        color = discord.Colour(0xff0000)
      string = "\n\n["+" ".join(msg)+"]()"
      embed = discord.Embed(description = string, color = color, title="An Echo From the Heavens Says...", footer="Moderator Warning")
      embed.set_author(name=author.display_name, icon_url = author.avatar_url)
      embed.set_footer(text="Moderator Warning")
      await self.bot.say(embed=embed)
    try:
      await self.bot.delete_message(ctx.message)
    except Exception:
      print("Not allowed to delete message")

  @commands.command(pass_context=True)
  async def clear(self, ctx, amount):
    """Clear set amount of messages
    """
    if len(ctx.message.mentions) > 0:
      send_msg = await self.bot.say("Feature coming. Bug Henry.")
      # await self.bot.purge_from(ctx.message.channel, limit = 50, check=is_me)
    else:
      await self.bot.purge_from(ctx.message.channel, limit = amount, check=True)
      send_msg = await self.bot.say("{} message(s) has been deleted.".format(amount))

    await asyncio.sleep(3)
    await self.bot.delete_message(send_msg)

def setup(bot):
  bot.add_cog(Modtools(bot))


text:
package com.kind.samples.utils;

import java.text.SimpleDateFormat;

public class DateUtils {

    /**
     * 时间戳转换为日期
     *
     * @param time
     * @return
     */
    public static String time2Date(Long time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        if (time != null) {
            String date = format.format(time);
            return date;
        }
        return null;

    }

    public static void main(String[] args) throws Exception {
        System.out.println(DateUtils.time2Date(1447948800000L));
    }
}


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2008,2009 IITP RAS
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Author: Kirill Andreev <andreev@iitp.ru>
 */

#ifndef WIFI_TIMING_ELEMENT_H
#define WIFI_TIMING_ELEMENT_H

#include <vector>
#include "ns3/nstime.h"
#include "ns3/mesh-information-element-vector.h"

namespace ns3 {
namespace dot11s {
/**
 * \ingroup dot11s
 * \brief Describes one unit of beacon timing element
 */
class IeBeaconTimingUnit : public SimpleRefCount<IeBeaconTimingUnit>
{
public:
  IeBeaconTimingUnit ();
  void SetAid (uint8_t aid);
  void SetLastBeacon (uint16_t lastBeacon);
  void SetBeaconInterval (uint16_t beaconInterval);

  uint8_t GetAid () const;
  uint16_t GetLastBeacon () const;
  uint16_t GetBeaconInterval () const;

private:
  /// Least significant octet of AID:
  uint8_t m_aid;
  /// Last time we received a beacon in accordance with a local TSF measured in 256 microseconds unit
  uint16_t m_lastBeacon;
  /// Beacon interval of remote mesh point
  uint16_t m_beaconInterval;
  friend bool operator== (const IeBeaconTimingUnit & a, const IeBeaconTimingUnit & b);
};

/**
 * \ingroup dot11s
 * \brief See 7.3.2.89 of 802.11s draft 2.07
 */
class IeBeaconTiming : public WifiInformationElement
{
public:
  /**
   * \ingroup dot11s
   * This type is a list of timing elements obtained from neighbours with their beacons:
   */
  typedef std::vector< Ptr<IeBeaconTimingUnit> > NeighboursTimingUnitsList;

  IeBeaconTiming ();
  /**
   * This methods are needed for beacon collision
   * avoidance module:
   */
  NeighboursTimingUnitsList GetNeighboursTimingElementsList ();
  void AddNeighboursTimingElementUnit (
    uint16_t aid,
    Time last_beacon,
    Time beacon_interval
    );
  void   DelNeighboursTimingElementUnit (
    uint16_t aid,
    Time  last_beacon,
    Time  beacon_interval
    );
  void   ClearTimingElement ();
  /**
   * \name Inherited from WifiInformationElement
   * \{
   */
  virtual WifiInformationElementId ElementId () const;
  virtual uint8_t GetInformationFieldSize () const;
  virtual void SerializeInformationField (Buffer::Iterator i) const;
  virtual uint8_t DeserializeInformationField (Buffer::Iterator i, uint8_t length);
  virtual void Print (std::ostream& os) const;
  ///\}
  bool operator== (WifiInformationElement const & a) const;
private:
  /**
   * Converters:
   */
  static uint16_t TimestampToU16 (Time x);
  static uint16_t BeaconIntervalToU16 (Time x);
  static uint8_t AidToU8 (uint16_t x);

  NeighboursTimingUnitsList  m_neighbours;
  /**
   * Timing element parameters:
   */
  uint16_t  m_numOfUnits;
};
bool operator== (const IeBeaconTimingUnit & a, const IeBeaconTimingUnit & b);
std::ostream &operator << (std::ostream &os, const IeBeaconTiming &beaconTiming);
} // namespace dot11s
} // namespace ns3
#endif


text:
package com.hadithbd.banglahadith.ui;

import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.View;

import com.hadithbd.banglahadith.R;
import com.hadithbd.banglahadith.database.DbManager;
import com.hadithbd.banglahadith.util.Constants;

public class BookQnActivity extends BaseActivity implements View.OnClickListener {

    private ActionBar actionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_qn);
        DbManager.init(this);

        int contentId = 0;
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            contentId = extras.getInt(Constants.BOOK_CONTENT_ID);
        }

        setHomeBackground();

        actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public void onClick(View v) {

    }
}


text:
#include "config.h"
#include "HTMLAllCollection.h"

#include "Element.h"

namespace WebCore {

PassRef<HTMLAllCollection> HTMLAllCollection::create(Document& document, CollectionType type)
{
    return adoptRef(*new HTMLAllCollection(document, type));
}

HTMLAllCollection::HTMLAllCollection(Document& document, CollectionType type)
    : HTMLCollection(document, type)
{
}

HTMLAllCollection::~HTMLAllCollection()
{
}

Node* HTMLAllCollection::namedItemWithIndex(const AtomicString& name, unsigned index) const
{
    updateNamedElementCache();
    const CollectionNamedElementCache& cache = namedItemCaches();

    if (const Vector<Element*>* elements = cache.findElementsWithId(name)) {
        if (index < elements->size())
            return elements->at(index);
        index -= elements->size();
    }

    if (const Vector<Element*>* elements = cache.findElementsWithName(name)) {
        if (index < elements->size())
            return elements->at(index);
    }

    return 0;
}

} // namespace WebCore


text:
namespace SlimMessageBus.Host.Test;

using SlimMessageBus.Host.Config;
using SlimMessageBus.Host.Interceptor;

public class PublishInterceptorPipelineTests
{
    private readonly MessageBusMock _busMock;

    public PublishInterceptorPipelineTests()
    {
        _busMock = new MessageBusMock();
    }

    [Theory]
    [InlineData(false, false)]
    [InlineData(true, false)]
    [InlineData(true, true)]
    public async Task When_Next_Then_InterceptorIsCalledAndTargetIsCalled(bool producerInterceptorRegisterd, bool publishInterceptorRegisterd)
    {
        // arrange
        var message = new SomeMessage();
        var topic = "topic1";

        var producerInterceptorMock = new Mock<IProducerInterceptor<SomeMessage>>();
        producerInterceptorMock
            .Setup(x => x.OnHandle(message, It.IsAny<Func<Task<object>>>(), It.IsAny<IProducerContext>()))
            .Returns((SomeMessage message, Func<Task<object>> next, IProducerContext context) => next());

        var producerInterceptors = producerInterceptorRegisterd ? new[] { producerInterceptorMock.Object } : null;

        var publishInterceptorMock = new Mock<IPublishInterceptor<SomeMessage>>();
        publishInterceptorMock
            .Setup(x => x.OnHandle(message, It.IsAny<Func<Task>>(), It.IsAny<IProducerContext>()))
            .Returns((SomeMessage message, Func<Task> next, IProducerContext context) => next());

        var publishInterceptors = publishInterceptorRegisterd ? new[] { publishInterceptorMock.Object } : null;

        var producerSettings = new ProducerBuilder<SomeMessage>(new ProducerSettings())
            .DefaultTopic(topic)
            .Settings;

        var context = new PublishContext
        {
            Path = topic,
            Headers = new Dictionary<string, object>(),
        };

        _busMock.BusMock
            .Setup(x => x.PublishInternal(message, context.Path, context.Headers, context.CancellationToken, producerSettings))
            .Returns(() => Task.FromResult<object>(null));

        var subject = new PublishInterceptorPipeline(_busMock.Bus, message, producerSettings, context, producerInterceptors: producerInterceptors, publishInterceptors: publishInterceptors);

        // act
        var result = await subject.Next();

        // assert
        result.Should().BeNull();

        if (producerInterceptorRegisterd)
        {
            producerInterceptorMock.Verify(x => x.OnHandle(message, It.IsAny<Func<Task<object>>>(), It.IsAny<IProducerContext>()), Times.Once);
        }
        producerInterceptorMock.VerifyNoOtherCalls();

        if (publishInterceptorRegisterd)
        {
            publishInterceptorMock.Verify(x => x.OnHandle(message, It.IsAny<Func<Task>>(), It.IsAny<IProducerContext>()), Times.Once);
        }
        publishInterceptorMock.VerifyNoOtherCalls();

        _busMock.BusMock.Verify(x => x.PublishInternal(message, context.Path, context.Headers, context.CancellationToken, producerSettings), Times.Once);
        _busMock.BusMock.VerifyNoOtherCalls();
    }
}


text:
Packets

Check your Packetes

{{ shellscript }}

Shell Packetes

Pakete: {{packets.shell.length}}

Makiert: {{checked.shell.length}}

            <input type="text" placeholder="filter" class="form-control" ng-model="shellfilter">

                        {{value}}

Node Packetes

Pakete: {{packets.node.length}}

Makiert: {{checked.node.length}}

            <input type="text" placeholder="filter" class="form-control" ng-model="nodefilter">

                        {{value}}

DPKG Packetes

Pakete: {{packets.dpkg.length}}

Makiert: {{checked.dpkg.length}}

            <input type="text" placeholder="filter" class="form-control" ng-model="dpkgfilter">

                        {{value.name}}

Other Tools

Pakete: {{packets.other.length}}

Makiert: {{checked.other.length}}

            <input type="text" placeholder="filter" class="form-control" ng-model="otherfilter">

                        {{value.name}}

<button class="btn btn-primary" ng-click="checkout();">Checkout</button>


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;

namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
    [Collection(nameof(SharedIntegrationHostFixture))]
    public class CSharpF1Help : AbstractEditorTest
    {
        protected override string LanguageName => LanguageNames.CSharp;

        public CSharpF1Help(VisualStudioInstanceFactory instanceFactory)
            : base(instanceFactory, nameof(CSharpF1Help))
        {
        }

        [Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
        void F1Help()
        {
            var text = @"
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;

namespace F1TestNamespace
{
    #region TaoRegion
    abstract class ShapesClass { }

    class Program$$
    {
        public static void Main()
        {
        }

        public IEnumerable<int> Linq1()
        {
            int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
            int i = numbers.First();
            int j = Array.IndexOf(numbers, 1);

            var lowNums1 =
                from n in numbers
                orderby n ascending
                where n < 5
                select n;

            var numberGroups =
              from n in numbers
              let m = 1
              join p in numbers on i equals p
              group n by n % 5 into g
              select new { Remainder = g.Key, Numbers = g };

            foreach (int element in numbers) yield return i;
        }

    }
    #endregion TaoRegion
}";

            SetUpEditor(text);
            Verify("abstract", "abstract_CSharpKeyword");
            Verify("ascending", "ascending_CSharpKeyword");
            Verify("from", "from_CSharpKeyword");
            Verify("First();", "System.Linq.Enumerable.First``1");
        }

        private void Verify(string word, string expectedKeyword)
        {
            VisualStudio.Editor.PlaceCaret(word, charsOffset: -1);
            Assert.Contains(expectedKeyword, VisualStudio.Editor.GetF1Keyword());
        }
    }
}


text:
#pragma once
#include <aws/devops-guru/DevOpsGuru_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace DevOpsGuru
{
namespace Model
{

  /**
   *
 Contains the names of AWS CloudFormation stacks used to update a collection
   * of stacks.

See Also:
   AWS
   * API Reference

   */
  class AWS_DEVOPSGURU_API UpdateCloudFormationCollectionFilter
  {
  public:
    UpdateCloudFormationCollectionFilter();
    UpdateCloudFormationCollectionFilter(Aws::Utils::Json::JsonView jsonValue);
    UpdateCloudFormationCollectionFilter& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
 An array of the name of stacks to update.

     */
    inline const Aws::Vector<Aws::String>& GetStackNames() const{ return m_stackNames; }

    /**
     *
 An array of the name of stacks to update.

     */
    inline bool StackNamesHasBeenSet() const { return m_stackNamesHasBeenSet; }

    /**
     *
 An array of the name of stacks to update.

     */
    inline void SetStackNames(const Aws::Vector<Aws::String>& value) { m_stackNamesHasBeenSet = true; m_stackNames = value; }

    /**
     *
 An array of the name of stacks to update.

     */
    inline void SetStackNames(Aws::Vector<Aws::String>&& value) { m_stackNamesHasBeenSet = true; m_stackNames = std::move(value); }

    /**
     *
 An array of the name of stacks to update.

     */
    inline UpdateCloudFormationCollectionFilter& WithStackNames(const Aws::Vector<Aws::String>& value) { SetStackNames(value); return *this;}

    /**
     *
 An array of the name of stacks to update.

     */
    inline UpdateCloudFormationCollectionFilter& WithStackNames(Aws::Vector<Aws::String>&& value) { SetStackNames(std::move(value)); return *this;}

    /**
     *
 An array of the name of stacks to update.

     */
    inline UpdateCloudFormationCollectionFilter& AddStackNames(const Aws::String& value) { m_stackNamesHasBeenSet = true; m_stackNames.push_back(value); return *this; }

    /**
     *
 An array of the name of stacks to update.

     */
    inline UpdateCloudFormationCollectionFilter& AddStackNames(Aws::String&& value) { m_stackNamesHasBeenSet = true; m_stackNames.push_back(std::move(value)); return *this; }

    /**
     *
 An array of the name of stacks to update.

     */
    inline UpdateCloudFormationCollectionFilter& AddStackNames(const char* value) { m_stackNamesHasBeenSet = true; m_stackNames.push_back(value); return *this; }

  private:

    Aws::Vector<Aws::String> m_stackNames;
    bool m_stackNamesHasBeenSet;
  };

} // namespace Model
} // namespace DevOpsGuru
} // namespace Aws


text:
class AlbumSerializer < ActiveModel::Serializer
  attributes :id, :name
  has_many :photos
end


text:
namespace py = pybind11;

void regclass_pyngraph_op_util_IndexReduction(py::module m);


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms").   Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
 * @path ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-25.js
 * @description Object.isExtensible returns true if O is extensible and has a prototype that is not extensible
 */

function testcase() {

        var proto = {};
        Object.preventExtensions(proto);

        var ConstructFun = function () { };
        ConstructFun.prototype = proto;

        var obj = new ConstructFun();

        return Object.isExtensible(obj);

    }
runTestCase(testcase);


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Profile</title>
  <link rel="stylesheet" href="stylesheets/bootstrap.min.css">
  <link rel="stylesheet" href="stylesheets/MyCss.css">

Fit Buddy

Monitor and Control your Activity and Food

My Profile

Log In

Sign up

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

      </button>

About Us

Fit Blog

Contact Us

Sign Up

 Already a Fit Buddy?<form style="display: inline" action="login.html" method="get"><button type="submit" class="btn btn-default">Log In</button></form>

    <form class="form-horizontal signup-form" id="signUpForm" name="signUpForm" onsubmit="return validateSignUpFormOnSubmit();">

      Username:

        <input class="form-control" placeholder="Enter Username" id="username" name="username">

      Email:

        <input class="form-control"  placeholder="Enter Email" id="emailId" name="emailId">

      Password:

        <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd">

      Confirm Password:

        <input type="password" class="form-control" placeholder="Confirm password" id="confirmpwd" name="confirmpwd">

      First Name:

        <input class="form-control" placeholder="Enter First Name" id="firstname" name="firstname" >

      Last Name:

        <input class="form-control" placeholder="Enter Last Name" id="lastname" name="lastname">

     Date of birth:

      Day:
      <select class="form-control" id="sel1">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
        <option>6</option>
        <option>7</option>
        <option>8</option>
        <option>9</option>
        <option>10</option>
        <option>11</option>
        <option>12</option>
        <option>13</option>
        <option>14</option>
        <option>15</option>
        <option>16</option>
        <option>17</option>
        <option>18</option>
        <option>19</option>
        <option>20</option>
        <option>21</option>
        <option>22</option>
        <option>23</option>
        <option>24</option>
        <option>25</option>
        <option>26</option>
        <option>27</option>
        <option>28</option>
        <option>29</option>
        <option>30</option>
        <option>31</option>
      </select>

      Month:
      <select class="form-control" id="sel2">
        <option>January</option>
        <option>February</option>
        <option>March</option>
        <option>April</option>
        <option>May</option>
        <option>June</option>
        <option>July</option>
        <option>August</option>
        <option>September</option>
        <option>October</option>
        <option>November</option>
        <option>December</option>
      </select>

      Year:
      <select class="form-control" id="sel3">
        <option>2015</option>
        <option>2014</option>
        <option>2013</option>
        <option>2011</option>
        <option>2010</option>
        <option>2009</option>
        <option>2008</option>
        <option>2007</option>
        <option>2006</option>
        <option>2005</option>
        <option>2004</option>
        <option>2003</option>
        <option>2002</option>
        <option>2001</option>
        <option>1999</option>
        <option>1998</option>
        <option>1997</option>
        <option>1996</option>
        <option>1995</option>
        <option>1994</option>
        <option>1993</option>
        <option>1992</option>
        <option>1991</option>
        <option>1990</option>
        <option>1989</option>
        <option>1988</option>
        <option>1987</option>
        <option>1986</option>
        <option>1985</option>
        <option>1984</option>
        <option>1983</option>
        <option>1982</option>
        <option>1981</option>
        <option>1980</option>
        <option>1979</option>
        <option>1978</option>
        <option>1977</option>
        <option>1976</option>
        <option>1975</option>
        <option>1974</option>
        <option>1973</option>
        <option>1972</option>
        <option>1971</option>
        <option>1970</option>
        <option>1969</option>
        <option>1968</option>
        <option>1967</option>

      </select>

      Height:

        <input class="form-control" placeholder="Height" id="height">

      Weight:

        <input class="form-control" placeholder="Weight" id="weight">

        <button type="submit" class="btn btn-default">Register</button>

  </form>

All Rights Reserved for Setareh :D #DoNotCopy


text:
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/rtc.h>

#include <asm/lv1call.h>
#include <asm/ps3.h>

static u64 read_rtc(void)
{
	int result;
	u64 rtc_val;
	u64 tb_val;

	result = lv1_get_rtc(&rtc_val, &tb_val);
	BUG_ON(result);

	return rtc_val;
}

static int ps3_get_time(struct device *dev, struct rtc_time *tm)
{
	rtc_time_to_tm(read_rtc() + ps3_os_area_get_rtc_diff(), tm);
	return rtc_valid_tm(tm);
}

static int ps3_set_time(struct device *dev, struct rtc_time *tm)
{
	unsigned long now;

	rtc_tm_to_time(tm, &now);
	ps3_os_area_set_rtc_diff(now - read_rtc());
	return 0;
}

static const struct rtc_class_ops ps3_rtc_ops = {
	.read_time = ps3_get_time,
	.set_time = ps3_set_time,
};

static int __init ps3_rtc_probe(struct platform_device *dev)
{
	struct rtc_device *rtc;

	rtc = devm_rtc_device_register(&dev->dev, "rtc-ps3", &ps3_rtc_ops,
				  THIS_MODULE);
	if (IS_ERR(rtc))
		return PTR_ERR(rtc);

	platform_set_drvdata(dev, rtc);
	return 0;
}

static int __exit ps3_rtc_remove(struct platform_device *dev)
{
	return 0;
}

static struct platform_driver ps3_rtc_driver = {
	.driver = {
		.name = "rtc-ps3",
	},
	.remove = __exit_p(ps3_rtc_remove),
};

module_platform_driver_probe(ps3_rtc_driver, ps3_rtc_probe);

MODULE_AUTHOR("Sony Corporation");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("ps3 RTC driver");
MODULE_ALIAS("platform:rtc-ps3");


text:
<?php
require_once 'PHPUnit/Framework.php';

require_once 'recess/lang/RecessLangAllTests.php';
require_once 'recess/framework/RecessFrameworkAllTests.php';
require_once 'recess/database/RecessDatabaseAllTests.php';
require_once 'recess/http/RecessHttpAllTests.php';

class RecessAllTests {

	public static function suite() {
		$suite = new PHPUnit_Framework_TestSuite('recess');

		$suite->addTestSuite(RecessLangAllTests::suite());
		$suite->addTestSuite(RecessFrameworkAllTests::suite());
		$suite->addTestSuite(RecessDatabaseAllTests::suite());

		return $suite;
	}

}
?>


text:
from __future__ import absolute_import

from django.test import TestCase

from .base import DJTTestCase

class BasicsTests(TestCase):

    def test_imports(self):
        """
        Ensure all taxii_services modules can be imported.
        """
        import taxii_services
        import taxii_services.admin
        import taxii_services.exceptions
        import taxii_services.handlers
        import taxii_services.management
        import taxii_services.middleware
        import taxii_services.models
        import taxii_services.urls
        import taxii_services.views

        """
        Test import of default message handlers.
        """
        import taxii_services.message_handlers.base_handlers
        import taxii_services.message_handlers.discovery_request_handlers
        import taxii_services.message_handlers.collection_information_request_handlers
        import taxii_services.message_handlers.inbox_message_handlers
        import taxii_services.message_handlers.poll_fulifllment_request_handlers
        import taxii_services.message_handlers.poll_request_handlers
        import taxii_services.message_handlers.subscription_request_handlers


text:
jsonrpc.{ch} implements the parsing and validation of the jsonrpc/2.0 request before handing it over to
user-defined methods.

jsonrpc_server.c is an example of usage using ZeroMQ as a transport.
It has been tested against ZeroMQ 3.2.2 and jansson 2.3.1

Since significant functionality is provided by [jansson library](https://github.com/akheron/jansson), the same licence is chosen to be used by this code.


text:
require 'test_helper'

class TestBitmaskAttribute < Test::Unit::TestCase

  context "Campaign" do

    teardown do
      Company.destroy_all
      Campaign.destroy_all
    end

    should "can assign single value to bitmask" do
      assert_stored Campaign.new(:medium => :web), :web
    end

    should "can assign multiple values to bitmask" do
      assert_stored Campaign.new(:medium => [:web, :print]), :web, :print
    end

    should "can add single value to bitmask" do
      campaign = Campaign.new(:medium => [:web, :print])
      assert_stored campaign, :web, :print
      campaign.medium << :phone
      assert_stored campaign, :web, :print, :phone
    end

    should "ignores duplicate values added to bitmask" do
      campaign = Campaign.new(:medium => [:web, :print])
      assert_stored campaign, :web, :print
      campaign.medium << :phone
      assert_stored campaign, :web, :print, :phone
      campaign.medium << :phone
      assert_stored campaign, :web, :print, :phone
      assert_equal 1, campaign.medium.select { |value| value == :phone }.size
    end

    should "can assign new values at once to bitmask" do
      campaign = Campaign.new(:medium => [:web, :print])
      assert_stored campaign, :web, :print
      campaign.medium = [:phone, :email]
      assert_stored campaign, :phone, :email
    end

    should "can save bitmask to db and retrieve values transparently" do
      campaign = Campaign.new(:medium => [:web, :print])
      assert_stored campaign, :web, :print
      assert campaign.save
      assert_stored Campaign.find(campaign.id), :web, :print
    end

    should "can add custom behavor to value proxies during bitmask definition" do
      campaign = Campaign.new(:medium => [:web, :print])
      assert_raises NoMethodError do
        campaign.medium.worked?
      end
      assert_nothing_raised do
        campaign.misc.worked?
      end
      assert campaign.misc.worked?
    end

    should "not use unsupported values" do

      assert_unsupported { Campaign.new(:medium => [:web, :print, :this_will_fail]) }

      campaign = Campaign.new(:medium => [:web, :print])
      assert campaign.medium.include?(:web)
      assert campaign.medium.include?(:print)

      assert_unsupported { campaign.medium << :this_will_also_fail << :email }
      assert !campaign.medium.include?(:this_will_also_fail)
      assert campaign.medium.include?(:web)
      assert campaign.medium.include?(:print)
      assert !campaign.medium.include?(:email)

      assert_unsupported { campaign.medium << :email << :this_will_fail_also }
      assert campaign.medium.include?(:web)
      assert campaign.medium.include?(:print)
      assert campaign.medium.include?(:email)

      assert_nothing_raised { campaign.medium = [:phone] }
      assert_unsupported { campaign.medium = [:so_will_this, :print, :and_this, :email] }
      assert !campaign.medium.include?(:so_will_this)
      assert !campaign.medium.include?(:and_this)
      assert !campaign.medium.include?(:print)
      assert !campaign.medium.include?(:email)
      assert campaign.medium.include?(:phone)

      campaign = Campaign.new(:medium => [:web, :print])
      assert_nothing_raised { campaign.medium.push(:phone, :email)}
      assert_equal(4, campaign.medium.count)
      assert_unsupported { campaign.medium.push(:fail1, :fail2) }
      assert_nothing_raised { campaign.medium.push(:phone, :email) }
      assert_nothing_raised { campaign.medium << :web << :print }
      assert_equal(4, campaign.medium.count)

    end

    should "can determine bitmasks using convenience method" do
      assert Campaign.bitmask_for_medium(:web, :print)
      assert_equal(
        Campaign.bitmasks[:medium][:web] | Campaign.bitmasks[:medium][:print],
        Campaign.bitmask_for_medium(:web, :print)
      )
    end

    should "assert use of unknown value in convenience method will result in exception" do
      assert_unsupported { Campaign.bitmask_for_medium(:web, :and_this_isnt_valid)  }
    end

    should "hash of values is with indifferent access" do
      string_bit = nil
      assert_nothing_raised do
        assert (string_bit = Campaign.bitmask_for_medium('web', 'print'))
      end
      assert_equal Campaign.bitmask_for_medium(:web, :print), string_bit
    end

    should "save bitmask with non-standard attribute names" do
      campaign = Campaign.new(:Legacy => [:upper, :case])
      assert campaign.save
      assert_equal [:upper, :case], Campaign.find(campaign.id).Legacy
    end

    should "ignore blanks fed as values" do
      campaign = Campaign.new(:medium => [:web, :print, ''])
      assert_stored campaign, :web, :print
    end

    context "checking" do

      setup { @campaign = Campaign.new(:medium => [:web, :print]) }

      context "for a single value" do

        should "be supported by an attribute_for_value convenience method" do
          assert @campaign.medium_for_web?
          assert @campaign.medium_for_print?
          assert !@campaign.medium_for_email?
        end

        should "be supported by the simple predicate method" do
          assert @campaign.medium?(:web)
          assert @campaign.medium?(:print)
          assert !@campaign.medium?(:email)
        end

      end

      context "for multiple values" do

        should "be supported by the simple predicate method" do
          assert @campaign.medium?(:web, :print)
          assert !@campaign.medium?(:web, :email)
        end

      end

    end

    context "scopes" do

      setup do
        @company = Company.create(:name => "Test Co, Intl.")
        @campaign1 = @company.campaigns.create :medium => [:web, :print]
        @campaign2 = @company.campaigns.create
        @campaign3 = @company.campaigns.create :medium => [:web, :email]
      end

      should "support retrieval by any value" do
        assert_equal [@campaign1, @campaign3], @company.campaigns.with_medium
      end

      should "support retrieval by one matching value" do
        assert_equal [@campaign1], @company.campaigns.with_medium(:print)
      end

      should "support retrieval by all matching values" do
        assert_equal [@campaign1], @company.campaigns.with_medium(:web, :print)
        assert_equal [@campaign3], @company.campaigns.with_medium(:web, :email)
      end

      should "support retrieval for a value that is not set" do
        assert_equal [@campaign2], @company.campaigns.without_medium(:web)
        assert_equal [@campaign2, @campaign3], @company.campaigns.without_medium(:print)
        assert_equal [@campaign1, @campaign2], @company.campaigns.without_medium(:email)
      end

      should "support retrieval for no values" do
        assert_equal [@campaign2], @company.campaigns.no_medium
      end

    end

    should "can check if at least one value is set" do
      campaign = Campaign.new(:medium => [:web, :print])

      assert campaign.medium?

      campaign = Campaign.new

      assert !campaign.medium?
    end

    should "find by bitmask values" do

      campaign1 = Campaign.new(:medium => [:web, :print])
      assert campaign1.save

      campaign2 = Campaign.new(:medium => [:web])
      assert campaign2.save

      campaign3 = Campaign.new(:medium => [:print])
      assert campaign3.save

      assert_equal(
        Campaign.find(:all, :conditions => ['medium & ? <> 0', Campaign.bitmask_for_medium(:print)]),
        Campaign.medium_for_print
      )

      assert_equal(
        Campaign.find(:all, :conditions => ['medium & ? <> 0', Campaign.bitmask_for_medium(:web)]),
        Campaign.medium_for_web
      )

      assert_equal(2, Campaign.medium_for_print.size)
      assert_equal(2, Campaign.medium_for_web.size)
      assert_equal(1, Campaign.medium_for_web.medium_for_print.size)
      assert_equal(1, Campaign.medium_for_print.medium_for_web.size)

      assert_equal [], Campaign.medium_for_email
      assert_equal [], Campaign.medium_for_web.medium_for_email

    end

    should "find no values" do
      campaign = Campaign.create(:medium => [:web, :print])
      assert campaign.save

      assert_equal [], Campaign.no_medium

      campaign.medium = []
      assert campaign.save

      assert_equal [campaign], Campaign.no_medium
    end

    #######
    private
    #######

    def assert_unsupported(&block)
      assert_raises(ArgumentError, &block)
    end

    def assert_stored(record, *values)
      values.each do |value|
        assert record.medium.any? { |v| v.to_s == value.to_s }, "Values #{record.medium.inspect} does not include #{value.inspect}"
      end
      full_mask = values.inject(0) do |mask, value|
        mask | Campaign.bitmasks[:medium][value]
      end
      assert_equal full_mask, record.medium.to_i
    end

  end

end