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

import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.gen.JoinCompiler;
import com.facebook.presto.sql.planner.plan.PlanNodeId;
import com.google.common.collect.ImmutableList;
import com.google.common.primitives.Ints;

import java.util.Collection;
import java.util.List;
import java.util.Optional;

import static com.facebook.presto.spi.type.BooleanType.BOOLEAN;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;

public class MarkDistinctOperator
        implements Operator
{
    public static class MarkDistinctOperatorFactory
            implements OperatorFactory
    {
        private final int operatorId;
        private final PlanNodeId planNodeId;
        private final Optional<Integer> hashChannel;
        private final List<Integer> markDistinctChannels;
        private final List<Type> types;
        private final JoinCompiler joinCompiler;
        private boolean closed;

        public MarkDistinctOperatorFactory(
                int operatorId,
                PlanNodeId planNodeId,
                List<? extends Type> sourceTypes,
                Collection<Integer> markDistinctChannels,
                Optional<Integer> hashChannel,
                JoinCompiler joinCompiler)
        {
            this.operatorId = operatorId;
            this.planNodeId = requireNonNull(planNodeId, "planNodeId is null");
            this.markDistinctChannels = ImmutableList.copyOf(requireNonNull(markDistinctChannels, "markDistinctChannels is null"));
            checkArgument(!markDistinctChannels.isEmpty(), "markDistinctChannels is empty");
            this.hashChannel = requireNonNull(hashChannel, "hashChannel is null");
            this.joinCompiler = requireNonNull(joinCompiler, "joinCompiler is null");
            this.types = ImmutableList.<Type>builder()
                    .addAll(sourceTypes)
                    .add(BOOLEAN)
                    .build();
        }

        @Override
        public List<Type> getTypes()
        {
            return types;
        }

        @Override
        public Operator createOperator(DriverContext driverContext)
        {
            checkState(!closed, "Factory is already closed");
            OperatorContext operatorContext = driverContext.addOperatorContext(operatorId, planNodeId, MarkDistinctOperator.class.getSimpleName());
            return new MarkDistinctOperator(operatorContext, types, markDistinctChannels, hashChannel, joinCompiler);
        }

        @Override
        public void close()
        {
            closed = true;
        }

        @Override
        public OperatorFactory duplicate()
        {
            return new MarkDistinctOperatorFactory(operatorId, planNodeId, types.subList(0, types.size() - 1), markDistinctChannels, hashChannel, joinCompiler);
        }
    }

    private final OperatorContext operatorContext;
    private final List<Type> types;
    private final MarkDistinctHash markDistinctHash;

    private Page outputPage;
    private boolean finishing;

    public MarkDistinctOperator(OperatorContext operatorContext, List<Type> types, List<Integer> markDistinctChannels, Optional<Integer> hashChannel, JoinCompiler joinCompiler)
    {
        this.operatorContext = requireNonNull(operatorContext, "operatorContext is null");

        this.types = ImmutableList.copyOf(requireNonNull(types, "types is null"));
        requireNonNull(hashChannel, "hashChannel is null");
        requireNonNull(markDistinctChannels, "markDistinctChannels is null");

        ImmutableList.Builder<Type> distinctTypes = ImmutableList.builder();
        for (int channel : markDistinctChannels) {
            distinctTypes.add(types.get(channel));
        }
        this.markDistinctHash = new MarkDistinctHash(operatorContext.getSession(), distinctTypes.build(), Ints.toArray(markDistinctChannels), hashChannel, joinCompiler);
    }

    @Override
    public OperatorContext getOperatorContext()
    {
        return operatorContext;
    }

    @Override
    public List<Type> getTypes()
    {
        return types;
    }

    @Override
    public void finish()
    {
        finishing = true;
    }

    @Override
    public boolean isFinished()
    {
        return finishing && outputPage == null;
    }

    @Override
    public boolean needsInput()
    {
        operatorContext.setMemoryReservation(markDistinctHash.getEstimatedSize());
        if (finishing || outputPage != null) {
            return false;
        }
        return true;
    }

    @Override
    public void addInput(Page page)
    {
        requireNonNull(page, "page is null");
        checkState(!finishing, "Operator is finishing");
        checkState(outputPage == null, "Operator still has pending output");
        operatorContext.setMemoryReservation(markDistinctHash.getEstimatedSize());

        Block markerBlock = markDistinctHash.markDistinctRows(page);

        // add the new boolean column to the page
        Block[] sourceBlocks = page.getBlocks();
        Block[] outputBlocks = new Block[sourceBlocks.length + 1]; // +1 for the single boolean output channel

        System.arraycopy(sourceBlocks, 0, outputBlocks, 0, sourceBlocks.length);
        outputBlocks[sourceBlocks.length] = markerBlock;

        outputPage = new Page(outputBlocks);
    }

    @Override
    public Page getOutput()
    {
        Page result = outputPage;
        outputPage = null;
        return result;
    }
}


text:
layout: post
categories: day-by-day
date: 2017-03-05
title: Sonata en Madrid
image:
  thumbnail: /images/blog/thumbnails/2017-03-05-sonata-en-madrid.jpg
  path: /images/blog/2017-03-05-sonata-en-madrid.jpg
---

redpajama_set_name: RedPajamaGithub


text:
import pytest

import great_expectations.exceptions as ge_exceptions

def read_config_from_file(config_filename):
    with open(config_filename) as f_:
        config = f_.read()

    return config

def test_add_store_immediately_adds_to_config(empty_data_context):
    context = empty_data_context
    config_filename = context.root_directory + "/great_expectations.yml"

    assert "my_new_store" not in read_config_from_file(config_filename)
    context.add_store(
        "my_new_store",
        {
            "module_name": "great_expectations.data_context.store",
            "class_name": "ExpectationsStore",
        },
    )
    assert "my_new_store" in read_config_from_file(config_filename)

def test_add_datasource(empty_data_context):
    context = empty_data_context
    config_filename = context.root_directory + "/great_expectations.yml"

    # Config can't be instantiated
    with pytest.raises(TypeError):
        context.add_datasource(
            "my_new_datasource",
            **{
                "some": "broken",
                "config": "yikes",
            },
        )
    assert "my_new_datasource" not in context.datasources
    assert "my_new_datasource" not in read_config_from_file(config_filename)

    # Config doesn't instantiate an Datasource
    with pytest.raises(ge_exceptions.DatasourceInitializationError):
        context.add_datasource(
            "my_new_datasource",
            **{
                "module_name": "great_expectations.data_context.store",
                "class_name": "ExpectationsStore",
            },
        )
    assert "my_new_datasource" not in context.datasources
    assert "my_new_datasource" not in read_config_from_file(config_filename)

    # Config successfully instantiates an Datasource
    context.add_datasource(
        "my_new_datasource",
        **{
            "class_name": "Datasource",
            "execution_engine": {"class_name": "PandasExecutionEngine"},
            "data_connectors": {
                "test_runtime_data_connector": {
                    "class_name": "RuntimeDataConnector",
                    "batch_identifiers": ["run_id", "y", "m", "d"],
                }
            },
        },
    )
    assert "my_new_datasource" in context.datasources
    assert "my_new_datasource" in read_config_from_file(config_filename)


text:
package com.apptentive.android.sdk.model;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;

public class TimeExtendedData extends ExtendedData {

	private static final String KEY_TIMESTAMP = "timestamp";

	private static final int VERSION = 1;

	private double timestamp;

	@Override
	protected void init() {
		setType(Type.time);
		setVersion(VERSION);
	}

	public TimeExtendedData() {
		super();
		setTimestamp(System.currentTimeMillis());
	}

	public TimeExtendedData(String json) throws JSONException {
		super(json);
		JSONObject jsonObject = new JSONObject(json);
		setTimestamp(jsonObject.optDouble(KEY_TIMESTAMP));
	}

	public TimeExtendedData(Date date) {
		super();
		setTimestamp(date);
	}

	public TimeExtendedData(long millis) {
		super();
		setTimestamp(millis);
	}

	public TimeExtendedData(double seconds) {
		super();
		setTimestamp(seconds);
	}

	protected void setTimestamp(Date date) {
		if (date != null) {
			setTimestamp(date.getTime());
		} else {
			setTimestamp(System.currentTimeMillis());
		}
	}

	protected void setTimestamp(long millis) {
		setTimestamp(((double) millis) / 1000);
	}

	protected void setTimestamp(double dateInSeconds) {
		this.timestamp = dateInSeconds;
	}

	@Override
	public JSONObject toJsonObject() throws JSONException {
		JSONObject ret = super.toJsonObject();
		ret.put(KEY_TIMESTAMP, timestamp);
		return ret;
	}
}


text:
Ti.include("../globals.js");

var data = [];
var IMAGE_RESIZER = "http://nysenatemobile.appspot.com/servlet/ImageResizer?url=";

//
// SETUP WINDOW STYLES
//
var win = Ti.UI.currentWindow;

toolActInd = Titanium.UI.createActivityIndicator();
//toolActInd.style = Titanium.UI.iPhone.ActivityIndicatorStyle.PLAIN;
toolActInd.font = {fontFamily:'Helvetica Neue', fontSize:15,fontWeight:'bold'};
toolActInd.color = 'white';
toolActInd.message = 'Loading...';
win.setToolbar([toolActInd],{animated:true});
toolActInd.show();

var xhr = Ti.Network.createHTTPClient();

xhr.onreadystatechange = function () {
	Titanium.API.info("json request - ready start: " + xhr.readyState);

};

var homeItems;

function checkOnline (onlineState)
{

	if (!onlineState)
	{
		var alertOff = Titanium.UI.createAlertDialog({
			title:'No Network',
			message:'You must be online to access the NY Senate site',
			 buttonNames: ['OK']

		});

		alertOff.show();
	}
	else
	{
		//no worries!

	}
}

checkOnline(Ti.Network.online);

Ti.Network.addEventListener('change',function(e) {

	checkOnline (e.online);

});

xhr.onerror = function ()
{

	toolActInd.hide();
		win.setToolbar(null,{animated:true});

		var alertOff = Titanium.UI.createAlertDialog({
			title:'Network Error',
			message:'Unable to connect to NYSenate.gov.\nPlease try again later.',
			 buttonNames: ['OK']

		});

		alertOff.show();

};

xhr.onload = function() {

	loadFeatures(this.responseText);
};

function loadFeatures (featuresJSON)
{

		Titanium.API.info("got features data");

		var cTransform = Ti.UI.create2DMatrix().scale(0.75);

		homeItems = JSON.parse(featuresJSON).nodes;

		var BASEPATH = "http://nysenate.gov/";

		var sViews = [homeItems.length];

		for (var c=0;c<homeItems.length;c++)
		{
			var item = homeItems[c];

			var img;

			var imageUrl = BASEPATH + item.files_node_data_field_feature_image_filepath;
			imageUrl = imageUrl.replace("\/","/");
			imageUrl = imageUrl.replace(" ","%20");

			var cachedFile = getCachedFile(imageUrl);

			if (!cachedFile)
			{

				imageUrl = IMAGE_RESIZER + escape(imageUrl);
				Titanium.API.info("LOADING IMAGE " +imageUrl);
				cacheImage(imageUrl);

				img = Ti.UI.createImageView({
				url:imageUrl,
				left:0,
				width:160,
				canScale:true,
				enableZoomControls:false
				});

			}
			else
			{
				img = Ti.UI.createImageView({
				image:cachedFile,
				left:0,
				width:160,
				canScale:true,
				enableZoomControls:false
				});
			}

			var row = Ti.UI.createTableViewRow({height:120});

			//row.url = link;
			row.guid = item.nid;
			row.ntitle = item.node_title;

			var labelTitle = Ti.UI.createLabel({
				text:item.node_title,
				left:165,
				top:10,
				font:{fontSize:18}
			});

			row.add(labelTitle);

			row.add(img);

			data[c] = row;

		}

		tableview = Titanium.UI.createTableView({
			data:data
		});

		Titanium.UI.currentWindow.add(tableview);
		tableview.addEventListener('click',function(e)
		{

					showNYSenateContent(e.rowData.ntitle,"http://nysenate.gov/node/" + e.rowData.guid);

		});

		toolActInd.hide();
		win.setToolbar(null,{animated:true});

};

/*
*/

Titanium.API.info("loading json...");

xhr.open("GET","http://nysenate.gov/front_carousel/json");
xhr.send();

Titanium.API.info("json request: " + xhr.status);

var xhrVideo = Ti.Network.createHTTPClient();

xhrVideo.onreadystatechange = function () {
	Titanium.API.info("json request - ready start: " + xhr.readyState);

};

xhrVideo.onload = function() {

	try
	{
		Titanium.API.info("got featured video data");

		var videoItem = JSON.parse(this.responseText).nodes[0];

		var BASEPATH = "http://nysenate.gov/";

		var imageUrlVideo = "http://img.youtube.com/vi/" + videoItem.node_data_field_video_field_video + "/0.jpg";

		Titanium.API.info("LOADING IMAGE " +imageUrlVideo);

	//	imageUrlVideo = IMAGE_RESIZER + escape(imageUrlVideo);

		var imageViewVideo = Titanium.UI.createImageView({
			url:imageUrlVideo,
			visible:true,
			canScale:true,
			width:140,
			height:120,
			left:10,
			backgroundColor:"#000000",
			borderColor:"#ffffff",
			borderWidth:3,
			top:220,
			opacity:0
		});

		var videoTitle = videoItem.node_title;
		var videoTitleMax = 18;
		if (videoTitle.length > videoTitleMax)
		{
			videoTitle = videoTitle.substring(0,videoTitleMax) + "...";
		}

		videoTitle = '"' + videoTitle + '"';

		imageViewVideo.addEventListener('singletap', function(e)
		{
			playYouTube("Featured Video",videoItem.node_data_field_video_field_video);

		});

	}
	catch (E)
	{
		Titanium.API.debug("error: " + E);
		alert(E);
	}
};

/*
*/

Titanium.API.info("loading json...");

xhrVideo.open("GET","http://www.nysenate.gov/front_video/json");
xhrVideo.send();

var xhrBlog = Ti.Network.createHTTPClient();

xhrBlog.onreadystatechange = function () {
	Titanium.API.info("json request - ready start: " + xhr.readyState);

};

xhrBlog.onload = function() {

	try
	{
		Titanium.API.info("got blog data");

		var itemBlog = JSON.parse(this.responseText).nodes[0];

		var BASEPATH = "http://nysenate.gov/";

			var imageUrl = BASEPATH + itemBlog.files_node_data_field_feature_image_filepath;
			imageUrl = imageUrl.replace("\/","/");
			imageUrl = imageUrl.replace(" ","%20");

		//	imageUrl = IMAGE_RESIZER + escape(imageUrl);

		var imageViewBlog = Titanium.UI.createImageView({
			url:imageUrl,
			visible:true,
			canScale:true,
			width:140,
			height:120,
			right:10,
			backgroundColor:"#000000",
			borderColor:"#ffffff",
			borderWidth:3,
			top:220,
			opacity:0
		});

		var blogTitle = itemBlog.node_title;
		var blogTitleMax = 18;
		if (blogTitle.length > blogTitleMax)
		{
			blogTitle = blogTitle.substring(0,blogTitleMax) + "...";
		}

		blogTitle = '"' + blogTitle + '"';

		imageViewBlog.addEventListener('singletap', function(e)
		{

			showNYSenateContent(itemBlog.node_title,BASEPATH + "node/" + itemBlog.nid);
		});

	}
	catch (E)
	{
		Titanium.API.debug("error: " + E);
		alert(E);
	}
};

/*
*/

Titanium.API.info("loading json...");

xhrBlog.open("GET","http://www.nysenate.gov/front_content/blog/json");
xhrBlog.send();


text:
#ifndef __VOM_QOS_MARK_H__
#define __VOM_QOS_MARK_H__

#include <ostream>

#include "vom/interface.hpp"
#include "vom/qos_map.hpp"
#include "vom/qos_types.hpp"
#include "vom/singular_db.hpp"

namespace VOM {
namespace QoS {

/**
 * The marking of packets with QoS bits as they egress an interface
 */
class mark : public object_base
{
public:
  mark(const interface& i, const map& m, const source_t& source);
  mark(const mark& r);

  ~mark();

  typedef std::pair<interface::key_t, source_t> key_t;

  /**
   * Return the object's key
   */
  const key_t key() const;

  /**
   * comparison operator
   */
  bool operator==(const mark& bdae) const;

  /**
   * Return the matching 'singular instance'
   */
  std::shared_ptr<mark> singular() const;

  /**
   * Find the instnace of the bridge_domain domain in the OM
   */
  static std::shared_ptr<mark> find(const key_t& k);

  /**
   * Dump all bridge_domain-doamin into the stream provided
   */
  static void dump(std::ostream& os);

  /**
   * replay the object to create it in hardware
   */
  void replay(void);

  /**
   * Convert to string for debugging
   */
  std::string to_string() const;

private:
  /**
   * Class definition for listeners to OM events
   */
  class event_handler : public OM::listener, public inspect::command_handler
  {
  public:
    event_handler();
    virtual ~event_handler() = default;

    /**
     * Handle a populate event
     */
    void handle_populate(const client_db::key_t& key);

    /**
     * Handle a replay event
     */
    void handle_replay();

    /**
     * Show the object in the Singular DB
     */
    void show(std::ostream& os);

    /**
     * Get the sortable Id of the listener
     */
    dependency_t order() const;
  };

  /**
   * event_handler to register with OM
   */
  static event_handler m_evh;

  /**
   * Commit the acculmulated changes into VPP. i.e. to a 'HW" write.
   */
  void update(const mark& obj);

  /**
   * Find or add the instnace of the bridge_domain domain in the OM
   */
  static std::shared_ptr<mark> find_or_add(const mark& temp);

  /*
   * It's the VPPHW class that updates the objects in HW
   */
  friend class VOM::OM;

  /**
   * It's the singular_db class that calls replay()
   */
  friend class singular_db<key_t, mark>;

  /**
   * Sweep/reap the object if still stale
   */
  void sweep(void);

  /**
   * HW configuration for the config. The bool representing the
   * do/don't configured/unconfigured.
   */
  HW::item<bool> m_config;

  /**
   * The interface the mark applies to
   */
  std::shared_ptr<interface> m_itf;

  /**
   * The map the marking uses
   */
  std::shared_ptr<map> m_map;

  /**
   * QoS source to mark from
   */
  source_t m_src;

  /**
   * A map of all QoS Markers
   */
  static singular_db<key_t, mark> m_db;
};

}; // namesapce QoS

std::ostream& operator<<(std::ostream& os, const QoS::mark::key_t& key);

}; // namespace VOM

/*
 * fd.io coding-style-patch-verification: ON
 *
 * Local Variables:
 * eval: (c-set-style "mozilla")
 * End:
 */

#endif


text:
"""Support for the Tuya climate devices."""
from homeassistant.components.climate import ENTITY_ID_FORMAT, ClimateDevice
from homeassistant.components.climate.const import (
    STATE_AUTO, STATE_COOL, STATE_ECO, STATE_FAN_ONLY, STATE_HEAT,
    SUPPORT_FAN_MODE, SUPPORT_ON_OFF, SUPPORT_OPERATION_MODE,
    SUPPORT_TARGET_TEMPERATURE)
from homeassistant.components.fan import SPEED_HIGH, SPEED_LOW, SPEED_MEDIUM
from homeassistant.const import (
    ATTR_TEMPERATURE, PRECISION_WHOLE, TEMP_CELSIUS, TEMP_FAHRENHEIT)

from . import DATA_TUYA, TuyaDevice

DEVICE_TYPE = 'climate'

HA_STATE_TO_TUYA = {
    STATE_AUTO: 'auto',
    STATE_COOL: 'cold',
    STATE_ECO: 'eco',
    STATE_FAN_ONLY: 'wind',
    STATE_HEAT: 'hot',
}

TUYA_STATE_TO_HA = {value: key for key, value in HA_STATE_TO_TUYA.items()}

FAN_MODES = {SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH}

def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up Tuya Climate devices."""
    if discovery_info is None:
        return
    tuya = hass.data[DATA_TUYA]
    dev_ids = discovery_info.get('dev_ids')
    devices = []
    for dev_id in dev_ids:
        device = tuya.get_device_by_id(dev_id)
        if device is None:
            continue
        devices.append(TuyaClimateDevice(device))
    add_entities(devices)

class TuyaClimateDevice(TuyaDevice, ClimateDevice):
    """Tuya climate devices,include air conditioner,heater."""

    def __init__(self, tuya):
        """Init climate device."""
        super().__init__(tuya)
        self.entity_id = ENTITY_ID_FORMAT.format(tuya.object_id())
        self.operations = []

    async def async_added_to_hass(self):
        """Create operation list when add to hass."""
        await super().async_added_to_hass()
        modes = self.tuya.operation_list()
        if modes is None:
            return
        for mode in modes:
            if mode in TUYA_STATE_TO_HA:
                self.operations.append(TUYA_STATE_TO_HA[mode])

    @property
    def is_on(self):
        """Return true if climate is on."""
        return self.tuya.state()

    @property
    def precision(self):
        """Return the precision of the system."""
        return PRECISION_WHOLE

    @property
    def temperature_unit(self):
        """Return the unit of measurement used by the platform."""
        unit = self.tuya.temperature_unit()
        if unit == 'CELSIUS':
            return TEMP_CELSIUS
        if unit == 'FAHRENHEIT':
            return TEMP_FAHRENHEIT
        return TEMP_CELSIUS

    @property
    def current_operation(self):
        """Return current operation ie. heat, cool, idle."""
        mode = self.tuya.current_operation()
        if mode is None:
            return None
        return TUYA_STATE_TO_HA.get(mode)

    @property
    def operation_list(self):
        """Return the list of available operation modes."""
        return self.operations

    @property
    def current_temperature(self):
        """Return the current temperature."""
        return self.tuya.current_temperature()

    @property
    def target_temperature(self):
        """Return the temperature we try to reach."""
        return self.tuya.target_temperature()

    @property
    def target_temperature_step(self):
        """Return the supported step of target temperature."""
        return self.tuya.target_temperature_step()

    @property
    def current_fan_mode(self):
        """Return the fan setting."""
        return self.tuya.current_fan_mode()

    @property
    def fan_list(self):
        """Return the list of available fan modes."""
        return self.tuya.fan_list()

    def set_temperature(self, **kwargs):
        """Set new target temperature."""
        if ATTR_TEMPERATURE in kwargs:
            self.tuya.set_temperature(kwargs[ATTR_TEMPERATURE])

    def set_fan_mode(self, fan_mode):
        """Set new target fan mode."""
        self.tuya.set_fan_mode(fan_mode)

    def set_operation_mode(self, operation_mode):
        """Set new target operation mode."""
        self.tuya.set_operation_mode(HA_STATE_TO_TUYA.get(operation_mode))

    def turn_on(self):
        """Turn device on."""
        self.tuya.turn_on()

    def turn_off(self):
        """Turn device off."""
        self.tuya.turn_off()

    @property
    def supported_features(self):
        """Return the list of supported features."""
        supports = SUPPORT_ON_OFF
        if self.tuya.support_target_temperature():
            supports = supports | SUPPORT_TARGET_TEMPERATURE
        if self.tuya.support_mode():
            supports = supports | SUPPORT_OPERATION_MODE
        if self.tuya.support_wind_speed():
            supports = supports | SUPPORT_FAN_MODE
        return supports

    @property
    def min_temp(self):
        """Return the minimum temperature."""
        return self.tuya.min_temp()

    @property
    def max_temp(self):
        """Return the maximum temperature."""
        return self.tuya.max_temp()


text:
return function (loader)

  local Configuration = loader.load "cosy.configuration"
  local I18n          = loader.load "cosy.i18n"
  local Logger        = loader.load "cosy.logger"
  local Value         = loader.load "cosy.value"

  Configuration.load "cosy.parameters"

  local i18n   = I18n.load "cosy.parameters"
  i18n._locale = Configuration.locale

  local Parameters = setmetatable ({}, {
    __index = function (_, key)
      return Configuration.data [key]
    end,
  })

  function Parameters.check (store, request, parameters)
    parameters = parameters or {}
    if request.__DESCRIBE then
      local result = {
        required = {},
        optional = {},
      }
      local locale = Configuration.locale.default
      if request.locale then
        locale = request.locale or locale
      end
      for _, part in ipairs { "required", "optional" } do
        for k, v in pairs (parameters [part] or {}) do
          local name = {}
          for i = 2, #v.__keys do
            name [#name+1] = v.__keys [i]
          end
          name = table.concat (name, ":")
          local ok, err = pcall (function ()
            result [part] [k] = {
              type        = name,
              description = i18n [name] % {
                locale = locale,
              }
            }
          end)
          if not ok then
            Logger.warning {
              _      = i18n ["translation:failure"],
              reason = err,
            }
            result [part] [k] = {
              type        = name,
              description = "(missing description)",
            }
          end
        end
      end
      error (result)
    end
    local reasons = {}
    local checked = {}
    for _, field in ipairs { "required", "optional" } do
      for key, parameter in pairs (parameters [field] or {}) do
        local value = request [key]
        if field == "required" and value == nil then
          reasons [#reasons+1] = {
            _   = i18n ["check:not-found"],
            key = key,
          }
        elseif value ~= nil then
          for i = 1, parameter.checks and #parameter.checks or 0 do
            local ok, reason = parameter.checks [i] {
              parameter = parameter,
              request   = request,
              key       = key,
              store     = store,
            }
            checked [key] = true
            if not ok then
              reason.key           = key
              reasons [#reasons+1] = reason
              break
            end
          end
        end
      end
    end
    -- Special case: authentication can be added in any request
    -- without issuing an error...
    if request.authentication and not checked.authentication then
      request.authentication = nil
    end
    for key in pairs (request) do
      if not checked [key] then
        Logger.warning {
          _       = i18n ["check:no-check"],
          key     = key,
          request = Value.expression (request),
        }
        request [key] = nil
      end
    end
    if #reasons ~= 0 then
      error {
        _       = i18n ["check:error"],
        reasons = reasons,
      }
    end
  end

  return Parameters

end


text:
A [Software Bill of Materials (SBOM)](https://en.wikipedia.org/wiki/Software_bill_of_materials) is a list of software components that a software artifact depends on.
Having a list of dependencies can be helpful in determining whether any vulnerable components were used to build the software artifact.

**From v0.9+, `ko` generates and uploads an SBOM for every image it produces by default.**

ko will generate an SBOM in the [SPDX](https://spdx.dev/) format by default, but you can select the [CycloneDX](https://cyclonedx.org/) format instead with the `--sbom=cyclonedx` flag. To disable SBOM generation, pass `--sbom=none`.

These SBOMs can be downloaded using the [`cosign download sbom`](https://github.com/sigstore/cosign/blob/main/doc/cosign_download_sbom.md) command.


text:
Due  Mon. Oct. 20

---

Write a single-page browser game by adding a graphical interface to your Memory game engine from homework #6.  Your application should comprise three modules, each in an IIFE in separate files:

* The _game_ module (a.k.a. the "Model") is responsible for maintaining the state and rules of a game. It has an API (command-line interface) but otherwise has no commitment to any graphical representation nor any particular set of cards.
If you've written a Memory engine already, your game module is nearly finished.
If you're close to completing your own version, please do so.  But if not, for this exercise you may adopt the one in the Homework 6 solutions and modify it as directed below.

* The _GUI_ module (a.k.a. the "View") knows nothing about the logical structure or rules of the game, but it knows how to draw it in the browser and how to initiate action with clicks.
The _GUI_ includes both a _.js_ and a _.css_ file which work together and share the same assumptions about the interface.

* The _cards_ module specifies the game's content: the values and pairings of the memory cards.  Some card sets (e.g. images instead of text) will require a specialized GUI.

The body of your application will be a single HTML file which imports the modules and ties them together in a [main file](template/memory-main.js).

The following steps will help guide you through the development of the GUI, but you don't need to provide answers along the way.
You may develop your GUI by any process you like, as long as it has the public interface outlined in the [template file](template/memory-gui.js).

---
**a)**  In the GUI's IIFE, write a constructor _MemoryGUI_.  The first parameter of the constructor should be the size of the game (the number of cards on the initial board).  Assume the cards will be arranged in grid approximately square.

Generate a grid of cells, one per card.  You many use a `<table>` or a series of `<div>`s.  Each cell should have a unique id which maps onto a number, the position of the corresponding card in your game model.  Place the grid within the DOM element with id 'memorygame' (defined in the [html file](template/memory.html)).

---
**b)**  Make each cell clickable.  Pass a second argument to _MemoryGUI_: a callback of one parameter which defines an action to take when a square is clicked.  Eventually, this callback will trigger your model's _lift_ function, but for now it may be a test function.
Add an event listener to each cell which calls the callback, passing in the square's id, whenever you click it.

---
**c)**  Each card on the board can be in one of three states: face-down, face-up, and matched (possibly removed or hidden, depending on how you want your interface to look).
For each state, define a CSS class to display a card in that state.  The body of each card can be either the grid cell itself or another element within it.

---
**d)** Give your GUI three public methods, one for each state:

- `show(where,value)`: turn one card (at position _where_) face-up immediately.  The display value of that card (according to the game model) will be provided as parameter _value_.

- `hideSoon(whereArray)`: turn some cards (at positions listed in _whereArray_) face-down, but only after some time (or triggering event) decided by your GUI.
(Hint: you might want to use `window.setTimeout`).

- `removeSoon(whereArray)`: turn some cards (at positions listed in _whereArray_) into the _matched_ state, but only after a delay decided by your GUI.

---
**e)** Write another public method of GUI:
- `reset()`: set the state of all cards to face-down, restoring the initial display.

Add to _MemoryGUI_ another parameter _resetGameFn_, a callback which will reset the game module.  Then add a Reset button to your interface, implemented and styled any way you like.  When pushed, it should reset both game and GUI.

At this point, you should be able to debug your GUI by manually simulating the game from the console, driving the GUI through its four public methods.

---
**f)** Integrate your modules!  Modify your game module slightly:

-  Insert a parameter _GuiCtor_ to your game constructor (MemoryGame) in the first position.  If it's null, your game should run just as before with no interface.  Otherwise, it should be your new MemoryGui constructor, and your game instance should use it to make a corresponding GUI instance.
Save the GUI instance as a variable or property available to your game; you'll keep using it.  When you call the MemoryGui constructor, remember that you need to provide arguments: number of cards, a click callback, and a reset callback.

- Additionally, whenever a card is flipped, you game needs to tell the GUI (if there is one) to update itself.  Each _lift_ action will need to call one of GUI's public methods.

---
**g)** Design and implement a card set!  Be as creative as you like.  For the card values, you can use strings, numbers, or objects (which are matched according to some common property and converted to a simple value using a display callback).
You can use ordinary playing cards or Tarot cards or something else.  You can use their full name or an abbreviated name, or URLs for images.

Organize the code for generating your card set, its _match_ function, and any _display_ function into another IIFE in a third file (_memory-cards.js_).  This IIFE should define a constructor _MemoryCards_, and calling that constructor (possibly with some parameters) should produce an instance object with three properties:

 - an array _values_ containing the raw data (object or primitive) for each card;
 - a method _match(a,b)_ which compares two values;
 - a method _display(val)_ (possibly undefined) which converts a raw value to a display-able one.

Change the parameters of your MemoryGame constructor to accept only the MemoryGui constructor and a MemoryCards instance, and extract its three properties as needed.

You may extrapolate from [this example](template/memory-cards.js).

Have fun!


text:
<?php

namespace minipipo1\UserBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class minipipo1UserBundle extends Bundle
{
        public function getParent()
        {
                return 'FOSUserBundle';
        }
}


text:
function Invoke-Task {
    <#
        .SYNOPSIS
        Executes another task in the current build script.

        .DESCRIPTION
        This is a function that will allow you to invoke a Task from within another Task in the current build script.

        .PARAMETER taskName
        The name of the task to execute.

        .EXAMPLE
        Invoke-Task "Compile"

        This example calls the "Compile" task.

        .LINK
        Assert
        .LINK
        Exec
        .LINK
        FormatTaskName
        .LINK
        Framework
        .LINK
        Get-PSakeScriptTasks
        .LINK
        Include
        .LINK
        Invoke-psake
        .LINK
        Properties
        .LINK
        Task
        .LINK
        TaskSetup
        .LINK
        TaskTearDown
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$taskName
    )

    Assert $taskName ($msgs.error_invalid_task_name)

    $taskKey = $taskName.ToLower()

    if ($currentContext.aliases.Contains($taskKey)) {
        $taskName = $currentContext.aliases.$taskKey.Name
        $taskKey = $taskName.ToLower()
    }

    $currentContext = $psake.context.Peek()

    Assert ($currentContext.tasks.Contains($taskKey)) ($msgs.error_task_name_does_not_exist -f $taskName)

    if ($currentContext.executedTasks.Contains($taskKey))  { return }

    Assert (!$currentContext.callStack.Contains($taskKey)) ($msgs.error_circular_reference -f $taskName)

    $currentContext.callStack.Push($taskKey)

    $task = $currentContext.tasks.$taskKey

    $precondition_is_valid = & $task.Precondition

    if (!$precondition_is_valid) {
        WriteColoredOutput ($msgs.precondition_was_false -f $taskName) -foregroundcolor Cyan
    } else {
        if ($taskKey -ne 'default') {

            if ($task.PreAction -or $task.PostAction) {
                Assert ($null -ne $task.Action) ($msgs.error_missing_action_parameter -f $taskName)
            }

            if ($task.Action) {

                $stopwatch = [System.Diagnostics.Stopwatch]::StartNew()

                try {
                    foreach($childTask in $task.DependsOn) {
                        Invoke-Task $childTask
                    }

                    $currentContext.currentTaskName = $taskName

                    try {
                        & $currentContext.taskSetupScriptBlock
                        try {
                            if ($task.PreAction) {
                                & $task.PreAction
                            }

                            if ($currentContext.config.taskNameFormat -is [ScriptBlock]) {
                                $taskHeader = & $currentContext.config.taskNameFormat $taskName
                            } else {
                                $taskHeader = $currentContext.config.taskNameFormat -f $taskName
                            }
                            WriteColoredOutput $taskHeader -foregroundcolor Cyan

                            foreach ($variable in $task.requiredVariables) {
                                Assert ((Test-Path "variable:$variable") -and ($null -ne (Get-Variable $variable).Value)) ($msgs.required_variable_not_set -f $variable, $taskName)
                            }

                            & $task.Action
                        } finally {
                            if ($task.PostAction) {
                                & $task.PostAction
                            }
                        }
                    } finally {
                        & $currentContext.taskTearDownScriptBlock
                    }
                } catch {
                    if ($task.ContinueOnError) {
                        "-"*70
                        WriteColoredOutput ($msgs.continue_on_error -f $taskName,$_) -foregroundcolor Yellow
                        "-"*70
                    }  else {
                        throw $_
                    }
                } finally {
                    $task.Duration = $stopwatch.Elapsed
                }
            } else {
                # no action was specified but we still execute all the dependencies
                foreach($childTask in $task.DependsOn) {
                    Invoke-Task $childTask
                }
            }
        } else {
            foreach($childTask in $task.DependsOn) {
                Invoke-Task $childTask
            }
        }

        Assert (& $task.Postcondition) ($msgs.postcondition_failed -f $taskName)
    }

    $poppedTaskKey = $currentContext.callStack.Pop()
    Assert ($poppedTaskKey -eq $taskKey) ($msgs.error_corrupt_callstack -f $taskKey,$poppedTaskKey)

    $currentContext.executedTasks.Push($taskKey)
}


text:
<vector android:height="24dp" android:viewportHeight="80"
    android:viewportWidth="80" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
    <path
        android:pathData="M12,40H68" android:strokeColor="#eeeeee"
        android:strokeLineCap="round" android:strokeWidth="8"/>
    <path
        android:pathData="M12,24H68" android:strokeColor="#eeeeee"
        android:strokeLineCap="round" android:strokeWidth="8"/>
    <path
        android:pathData="M12,56H68" android:strokeColor="#eeeeee"
        android:strokeLineCap="round" android:strokeWidth="8"/>
</vector>


text:
package Win32::Exe::Manifest;

#############################################################################
# References
# http://msdn.microsoft.com/en-us/library/dd371711(VS.85).aspx
# http://msdn.microsoft.com/en-us/library/aa374191(VS.85).aspx
# http://msdn.microsoft.com/en-us/library/aa374219(v=VS.85).aspx
# http://msdn.microsoft.com/en-us/library/aa376607(v=VS.85).aspx
#----------------------------------------------------------------------------

use strict;
use warnings;
use Win32::Exe::Manifest::Parser;
use Exporter;
use base qw( Exporter );
use Carp;

our $VERSION = '0.15';

=head1 NAME

Win32::Exe::Manifest - MSWin Application and Assembly manifest handling

=head1 VERSION

This document describes version 0.15 of Win32::Exe::Manifest, released
November 30, 2010.

=head1 SYNOPSIS

    use Win32::Exe
    my $exe = Win32:::Exe->new('somefilepath');

    my $manifest = $exe->get_manifest if $exe->has_manifest;

    # Get themed controls
    $manifest->add_common_controls;

    # Change name
    $manifest->set_assembly_name('My.App.Name');

    # Require Admin permissions
    $manifest->set_execution_level('requireAdministrator');

    # write it out
    $exe->set_manifest($manifest);
    $exe->write;

    #roll your own
    use Win32::Exe::Manifest
    my $xml = $handmademanifest;
    ......
    my $manifest = Win32::Exe::Manifest->new($xml, 'application');
    $exe->set_manifest($manifest);
    $exe->write;

    #get formated $xml
    my $xml = $manifest->output;

    #try merge (experimental)

    my $mfest1 = $exe->get_manifest;
    my $mfest2 = Win32::Exe::Manifest->new($xml, 'application');

    $mfest1->merge_manifest($mfest2);

    $exe->set_manifest($mfest1);
    $exe->write;

    #add a dependency
    my $info =
    { type     => 'win32',
      name     => 'Dependency.Prog.Id',
      version  => 1.0.0.0,
      language => '*',
      processorArchitecture => '*',
      publicKeyToken => 'hjdajhahdsa7sadhaskl',
    };

    $manifest->add_dependency($info);
    $exe->set_manifest($manifest);
    $exe->write;

=head1 DESCRIPTION

This module parses and manipulates application and assembly
manifests used in MS Windows executables and DLLs. It is
part of the Win32::Exe distribution.

=head1 METHODS

=head2 Constructors

=head3 new

    Win32::Exe::Manifest->new($xml, $type);

Create a new manifest instance from the manifest xml in $xml. The
$type param is optional and may contain 'application' (the default),
or 'assembly'.

Manifest objects can also be created using Win32::Exe

    my $exe = Win32:::Exe->new('somefilepath');
    my $manifest = $exe->get_manifest if $exe->has_manifest;

=cut

sub new {
    my ($class, $xml, $type) = @_;
    my $self = bless {}, $class;
    $xml = $self->get_default_manifest() if !$xml;
    $type = 'application' if !$type;
    $type =~ /^(application|assembly)$/ or croak(qq(Invalid manifest type : $type : valid types are 'application', 'assembly'));
    $self->{_w32_exe_schema} = $self->get_default_schema;
    $self->{_w32_exe_datatype} = $type;
    $self->{_w32_exe_manifestid} = 1;
    my $handler = Win32::Exe::Manifest::Parser->new( $self->get_parser_config );
    while( $xml =~ s/""/"/g ) { carp qq(Manifest has badly formed value quotes); }
    $self->{_w32_exe_dataref} = $handler->xml_in( $xml );
    $self->_compress_schema();
    my $errors = $self->validate_errors;
    croak('Manifest XML had errors: ' . $errors) if $errors;
    return $self;
}

=head2 Output

=head3 output

    my $xml = $manifest->output;

Returns a formated $xml string containing all edits and changes made
using Win32::Exe::Manifest

=cut

sub output {
    my $self = shift;
    my $handler = Win32::Exe::Manifest::Parser->new( $self->get_parser_config );
    my $ref = $self->refhash;
    $self->_expand_schema();
    my $xml = $handler->xml_out( $ref );
    $self->_compress_schema();
    return $xml;
}

=head2 Application Identity

=head3 set_assembly_name

    $manifest->set_assembly_name('My.Application.Name');

Set the application or assembly name. The name should take the form of a progid
and should not include any spaces.

=head3 get_assembly_name

    my $appname = $manifest->get_assembly_name;

Return the assembly or application name from the manifest.

=cut

sub set_assembly_name {
    my($self, $name) = @_;
    $self->refhash()->{assembly}->[0]->{assemblyIdentity}->[0]->{name} = $name;
    my $errors = $self->validate_errors;
    croak('Manifest XML had errors following set name: ' . $errors) if $errors;
}

sub get_assembly_name {
    my($self) = @_;
    my $ref = $self->refhash();
    return (exists($ref->{assembly}->[0]->{assemblyIdentity}->[0]->{name})) ? $ref->{assembly}->[0]->{assemblyIdentity}->[0]->{name} : undef;
}

=head3 set_assembly_description

    $manifest->set_assembly_description('My Application Description');

Set the application description. The description is an informative string.

=head3 get_assembly_decription

    my $desc = $manifest->get_assembly_description;

Return the assembly description from the manifest.

=cut

sub set_assembly_description {
    my($self, $desc) = @_;
    my $valuename = $self->default_content;
    $self->refhash()->{assembly}->[0]->{description}->[0]->{$valuename} = $desc;
    my $errors = $self->validate_errors;
    croak('Manifest XML had errors following set description: ' . $errors) if $errors;
}

sub get_assembly_description {
    my($self) = @_;
    my $valuename = $self->default_content;
    my $ref = $self->refhash();
    return (exists($ref->{assembly}->[0]->{description}->[0]->{$valuename})) ? $ref->{assembly}->[0]->{description}->[0]->{$valuename} : undef;
}

=head3 set_assembly_version

    $manifest->set_assembly_version('1.7.8.34456');

Set the application or assembly version. The version should take the form of
'n.n.n.n' where each n is a number between 0-65535 inclusive.

=head3 get_assembly_version

    my $version = $manifest->get_assembly_version;

Return the assembly or application version from the manifest.

=cut

sub set_assembly_version {
    my($self, $version) = @_;
    $self->refhash()->{assembly}->[0]->{assemblyIdentity}->[0]->{version} = $version;
    my $errors = $self->validate_errors;
    croak('Manifest XML had errors following set version: ' . $errors) if $errors;
}

sub get_assembly_version {
    my($self) = @_;
    my $ref = $self->refhash();
    return (exists($ref->{assembly}->[0]->{assemblyIdentity}->[0]->{version})) ? $ref->{assembly}->[0]->{assemblyIdentity}->[0]->{version} : undef;
}

=head3 set_assembly_language

    $manifest->set_assembly_language($langid);

Set the application or assembly language. The language id is the
DHTML language code. If you want to set 'language neutral' then pass
'*' for the value.

see : L<http://msdn.microsoft.com/en-us/library/ms533052(VS.85).aspx>

=head3 get_assembly_language

    my $langid = $manifest->get_assembly_language;

Return the assembly or application language from the manifest. If there
is no language id in the manifest, the method will return '*'

=cut

sub set_assembly_language {
    my($self, $newval) = @_;
    $self->refhash()->{assembly}->[0]->{assemblyIdentity}->[0]->{language} = $newval;
    my $errors = $self->validate_errors;
    croak('Manifest XML had errors following set language: ' . $errors) if $errors;
}

sub get_assembly_language {
    my($self) = @_;
    my $ref = $self->refhash();
    return (exists($ref->{assembly}->[0]->{assemblyIdentity}->[0]->{language})) ? $ref->{assembly}->[0]->{assemblyIdentity}->[0]->{language} : '*';
}

=head3 set_assembly_architecture

    $manifest->set_assembly_architecture($arch);

Set the application or assembly architecture. Accepted values are :
x86 msil ia64 amd64 *. Note the lowercase format. If you want your manifest
to be architecture neutral, set architecture to '*'.

=head3 get_assembly_architecture

    my $arch = $manifest->get_assembly_architecture;

Return the assembly or application architecture from the manifest.

=cut

sub set_assembly_architecture {
    my($self, $newval) = @_;
    $self->refhash()->{assembly}->[0]->{assemblyIdentity}->[0]->{processorArchitecture} = $newval;
    my $errors = $self->validate_errors;
    croak('Manifest XML had errors following set processorArchitecture: ' . $errors) if $errors;
}

sub get_assembly_architecture {
    my($self) = @_;
    my $ref = $self->refhash();
    return (exists($ref->{assembly}->[0]->{assemblyIdentity}->[0]->{processorArchitecture})) ? $ref->{assembly}->[0]->{assemblyIdentity}->[0]->{processorArchitecture} : '*';
}

=head2 Trust and Security

=head3 set_execution_level

    $manifest->set_execution_level($level);

Set the application execution level. Accepted values are : asInvoker,
highestAvailable, requireAdministrator, none. If you pass the value
'none', any trustInfo section will be removed from the manifest.

See L<http://msdn.microsoft.com/en-us/library/bb756929.aspx>

=head3 get_execution_level

    my $level = $manifest->get_execution_level;

Return the application execution level.

=cut

sub set_execution_level {
    my($self, $level) = @_;
    $level =~ /^(asInvoker|requireAdministrator|highestAvailable|none)$/
        or croak(qq(Invalid exec level '$level'. Valid levels are 'asInvoker', 'requireAdministrator', 'highestAvailable', 'none'));

    my $ref = $self->refhash()->{assembly}->[0];
    my $schema = $self->get_current_schema;
    my $xmlns = $schema->{elementtypes}->{trustInfo}->{attributes}->{xmlns}->{default};

    if($level eq 'none') {
        # delete element and collapse tree if empty
        $self->_delete_collapse_tree($ref, [ qw(trustInfo security requestedPrivileges requestedExecutionLevel) ] );
    } else {
        # create value if it does not exist
        my $writeref = $self->_get_first_tree_node($ref, [ qw(trustInfo security requestedPrivileges requestedExecutionLevel)  ], undef );
        $writeref->{level} = $level;
        $writeref->{uiAccess} = 'false' if not exists($writeref->{uiAccess});
    }

    # in all cases, dump any namespace definitions - which cause crashes on some OS / namespace combos
    # and fix trustInfo namespace decl

    $self->_fixup_namespace( $ref, 'trustInfo', $xmlns );

    my $errors = $self->validate_errors;
    croak('Manifest XML had errors following set execution level: ' . $errors) if $errors;
}

sub get_execution_level {
    my $self = shift;
    my $ref = $self->refhash()->{assembly}->[0];
    return 'none' if not exists($ref->{trustInfo}->[0]->{security}->[0]->{requestedPrivileges}->[0]->{requestedExecutionLevel}->[0]->{level});
    return $ref->{trustInfo}->[0]->{security}->[0]->{requestedPrivileges}->[0]->{requestedExecutionLevel}->[0]->{level};
}

=head3 set_uiaccess

    $manifest->set_uiaccess($needed);

Set the application uiAccess requirement in the trustInfo manifest section.
Accepted values are 'true', 'false'. If no trustInfo section exists, one is
created with the execution level set to 'asInvoker'.

See L<http://msdn.microsoft.com/en-us/library/bb756929.aspx>

=head3 get_uiaccess

    my $accessneeded = $manifest->get_uiaccess;

Return the uiAccess setting from the trustInfo structure. If no trustInfo
structure exists, method returns undef.

=cut

sub set_uiaccess {
    my ($self, $access) = @_;
    $access =~ /^(true|false)$/
        or croak(qq(Invalid uiAccess setting '$access'. Valid settings are 'true', 'false'));

    my $ref = $self->refhash()->{assembly}->[0];
    if(exists($ref->{trustInfo}->[0]->{security}->[0]->{requestedPrivileges}->[0]->{requestedExecutionLevel}->[0]->{uiAccess})) {
        $ref->{trustInfo}->[0]->{security}->[0]->{requestedPrivileges}->[0]->{requestedExecutionLevel}->[0]->{uiAccess} = $access;
    } else {
        my $schema = $self->get_current_schema;
        my $xmlns = $schema->{elementtypes}->{trustInfo}->{attributes}->{xmlns}->{default};
        $ref->{trustInfo} = [ { xmlns => $xmlns, security => [ { requestedPrivileges => [ { requestedExecutionLevel => [ { level => 'asInvoker', uiAccess => $access  } ] } ] } ] } ];
    }
    my $errors = $self->validate_errors;
    croak('Manifest XML had errors following set uiAccess: ' . $errors) if $errors;
}

sub get_uiaccess {
    my $self = shift;
    my $ref = $self->refhash()->{assembly}->[0];
    return undef if not exists($ref->{trustInfo}->[0]->{security}->[0]->{requestedPrivileges}->[0]->{requestedExecutionLevel});
    return $ref->{trustInfo}->[0]->{security}->[0]->{requestedPrivileges}->[0]->{requestedExecutionLevel}->[0]->{uiAccess};
}

=head2 Application Dependencies

=head3 set_resource_id

    $manifest->set_resource_id($id);

Set the resource Id for the manifest. Valid id's are 1, 2 and 3. The default
is 1. Don't set this unless you are fully aware of the effects.

See L<http://msdn.microsoft.com/en-us/library/aa376607(VS.85).aspx>

=head3 get_resource_id

    my $id = $manifest->get_resource_id();

Return the resource Id for the manifest.

=cut

sub get_resource_id { $_[0]->{_w32_exe_manifestid} }

sub set_resource_id {
    my ($self, $id) = @_;
    $id =~ /^(1|2|3)$/ or croak(qq(invalid manifest resource id $id. Valid values are 1,2,3));
    $self->{_w32_exe_manifestid} = $id;
}

=head3 add_common_controls

    $manifest->add_common_controls();

Add a dependency on minimum version 6.0.0.0 of the Microsoft.Windows.Common-Controls shared
library. This is normally done with GUI applications to use themed controls on Windows XP
and above.

=cut

sub add_common_controls { $_[0]->add_template_dependency('Microsoft.Windows.Common-Controls'); }

sub add_template_dependency {
    my($self, $assemblyname) = @_;
    my $tmpl = $self->get_dependency_template($assemblyname);
    croak(qq(No template found for dependency $assemblyname)) if !$tmpl;
    $self->add_dependency($tmpl);
}

=head3 add_dependency

    $manifest->add_dependency($info);

Add a dependency on the assembly detailed in the $info hash reference. The contents of
$info should be of the form:

    my $info = { type     => 'win32',
                 name     => 'Dependency.Prog.Id',
                 version  => 1.0.0.0,
                 language => '*',
                 processorArchitecture => '*',
                 publicKeyToken => 'hjdajhahdsa7sadhaskl',
    };

Note that the version should be the least specific that your application requires. For
example, a version of '2.0.0.0' would mean the system loads the first matching
assembly it finds with a version of at least '2.0.0.0'.

See: L<http://msdn.microsoft.com/en-us/library/aa374219(v=VS.85).aspx>

=cut

sub add_dependency {
    my($self, $proto) = @_;
    my $name = $proto->{name};
    $proto->{type} = 'win32';
    $proto->{version} ||= '0.0.0.0';
    $proto->{language} ||= '*';
    $proto->{processorArchitecture} ||= '*';
    my %vals = %$proto;
    if( defined(my $depindex = $self->_get_dependendency_index($name)) ) {
        $self->refhash()->{assembly}->[0]->{dependency}->[$depindex]->{dependentAssembly}->[0]->{assemblyIdentity}->[0] =  \%vals;
    } else {
        $self->refhash()->{assembly}->[0]->{dependency} = [] if not exists $self->refhash()->{assembly}->[0]->{dependency};
        my $newdep = { dependentAssembly => [ { assemblyIdentity => [ \%vals ] } ] };
        push @{ $self->refhash()->{assembly}->[0]->{dependency} } , $newdep;
    }
    my $errors = $self->validate_errors;
    croak('Manifest XML had errors following dependency addition: ' . $errors) if $errors;
}

=head3 remove_dependency

    $manifest->remove_dependency($progid);

Remove a dependency with the $progid. For example, passing a $progid of
'Microsoft.Windows.Common-Controls' will remove the dependency added via
'add_common_controls' from the manifest.

=cut

sub remove_dependency {
    my($self, $depname) = @_;
    if( defined(my $depindex = $self->_get_dependendency_index($depname)) ) {
        my $ref = $self->refhash()->{assembly}->[0]->{dependency};
        my @depends = @$ref;
        splice(@depends, $depindex, 1);
        $self->refhash()->{assembly}->[0]->{dependency} = \@depends;
        return 1;
    } else {
        return 0;
    }
}

=head3 get_dependency

    my $info = $manifest->get_dependency($progid);

Return a dependency info hash for a dependency in the manifest with the 'name'
$progid. The info hash is a reference to a hash with the format:

    { type     => 'win32',
      name     => 'Dependency.Prog.Id',
      version  => 1.0.0.0,
      language => '*',
      processorArchitecture => '*',
      publicKeyToken => 'hjdajhahdsa7sadhaskl',
    };

If there is no dependency with the name $progid, returns undef.

=cut

sub get_dependency {
    my($self, $depname) = @_;
    if( defined(my $depindex = $self->_get_dependendency_index($depname)) ) {
        my $ref = $self->refhash()->{assembly}->[0]->{dependency}->[$depindex]->{dependentAssembly}->[0]->{assemblyIdentity}->[0];
        my %vals = %$ref;
        return \%vals;
    } else {
        return undef;
    }
}

=head3 get_dependencies

    my @deps = $manifest->get_dependencies($progid);

Return an array of hash references, one for each dependency in the manifest.
Each member is a reference to a hash with the format:

    { type     => 'win32',
      name     => 'Dependency.Prog.Id',
      version  => 1.0.0.0,
      language => '*',
      processorArchitecture => '*',
      publicKeyToken => 'hjdajhahdsa7sadhaskl',
    };

If there are no dependencies, returns an empty array.

=cut

sub get_dependencies {
    my $self = shift;
    my @depends = ();
    return (@depends) if not exists $self->refhash()->{assembly}->[0]->{dependency};
    for my $dependency ( @{ $self->refhash()->{assembly}->[0]->{dependency} } ) {
        my $dep = $dependency->{dependentAssembly}->[0]->{assemblyIdentity}->[0];
        my %vals = %$dep;
        push(@depends, \%vals);
    }
    return ( @depends );
}

=head2 Compatibility Settings

=head3 set_compatibility

    $manifest->set_compatibility( ('Windows Vista') );

Set the operating system feature compatibility flags. Parameter is a list of operating
systems that the application targets. In addition to the opertating system identifier
keys, this method also accepts the shorthand strings 'Windows Vista' and 'Windows 7'.

See : L<http://msdn.microsoft.com/en-us/library/dd371711(VS.85).aspx>

=head3 get_compatibility

    my @osids = $manifest->get_compatibility();

Returns a list of operating system identifier keys that the manifest notes as targetted
operating systems. You can convert these os ids to the shorthand strings 'Windows Vista'
and 'Windows 7' using the method

    my $shortstring = $manifest->get_osname_from_osid($osid);

There is a reverse method

    my $osid = $manifest->get_osid_from_osname($shortstring);

NOTE: Don't set this unless you fully understand the effects.

See : L<http://msdn.microsoft.com/en-us/library/dd371711(VS.85).aspx>

=cut

sub set_compatibility {
    my($self, @vals) = @_;
    return if ! scalar(@vals);
    my @osblock = ();
    for my $val ( @vals ) {
        my $compat = $val;
        $compat = '{e2011457-1546-43c5-a5fe-008deee3d3f0}' if(lc($compat) eq 'windows vista');
        $compat = '{35138b9a-5d96-4fbd-8e2d-a2440225f93a}' if(lc($compat) eq 'windows 7');
        croak(qq(Invalid OS key '$val' for compatibility)) if !Win32::Exe::Manifest::Parser->validate_osid($compat);
        push(@osblock, { Id => $compat });
    }
    my $ref = $self->refhash()->{assembly}->[0];
    my $schema = $self->get_current_schema;
    my $xmlns = $schema->{elementtypes}->{compatibility}->{attributes}->{xmlns}->{default};
    $ref->{compatibility} = [ { xmlns => $xmlns, application => [ { supportedOS => \@osblock, }, ], }, ];
    my $errors = $self->validate_errors;
    croak('Manifest XML had errors following set compatibility: ' . $errors) if $errors;
}

sub get_compatibility {
    my $self = shift;
    my @compats = ();
    my $ref = $self->refhash()->{assembly}->[0];
    if(exists($ref->{compatibility})) {
        my @oids = @{ $ref->{compatibility}->[0]->{application}->[0]->{supportedOS} };
        for my $oidref ( @oids ) {
            my $oskey = $oidref->{Id};
            push(@compats, $oskey);
        }
    }
    return (@compats);
}

=head3 set_dpiaware

    $manifest->set_dpdaware( 'true' );

Set section in the manifest if the application is dpi aware. Accepts values
true, false, and none. If the value 'none' is passed, the application\windowsSettings
section is removed from the manifest entirely.

See : L<http://msdn.microsoft.com/en-us/library/ee308410(VS.85).aspx>

=head3 get_dpiaware

    $manifest->set_dpdaware( 'true' );

Return the dpiAware setting from the manifest, if any. If there is no setting,
the method returns undef.

See : L<http://msdn.microsoft.com/en-us/library/ee308410(VS.85).aspx>

=cut

sub set_dpiaware {
    my ($self, $setval) = @_;

    $setval =~ /^(true|false|none)$/i or croak(qq(Invalid value for set_dpiaware '$setval'. Valid values are true:false:none));
    $setval = lc($setval);
    my $ref = $self->refhash()->{assembly}->[0];
    my $elementvaluename = $self->default_content;
    my $schema = $self->get_current_schema;
    my $namealias = $schema->{namespace}->{'urn:schemas-microsoft-com:asm.v3'};

    # handle remove value
    if($setval eq 'none') {
        # delete element and collapse tree if empty
        $self->_delete_collapse_tree($ref, [ qw(application windowSettings dpiAware) ] );
    } else {
        # create value if it does not exist
        my $writeref = $self->_get_first_tree_node($ref, [ qw(application windowsSettings)  ], $namealias );
        $writeref->{dpiAware} = [ { $elementvaluename => $setval } ];
        # add xmlns for windowsSettings
        my $xmlns = $schema->{elementtypes}->{windowsSettings}->{attributes}->{xmlns}->{default};
        $ref->{application}->[0]->{windowsSettings}->[0]->{xmlns} = $xmlns;
    }
    my $errors = $self->validate_errors;
    croak('Manifest XML had errors after dpiAware setting: ' . $errors) if $errors;
}

sub get_dpiaware {
    my $self = shift;
    my $ref = $self->refhash()->{assembly}->[0];
    my $elementvaluename = $self->default_content;
    return 'none' if(not exists($ref->{application}->[0]->{windowsSettings}->[0]->{dpiAware}->[0]->{$elementvaluename}));
    return $ref->{application}->[0]->{windowsSettings}->[0]->{dpiAware}->[0]->{$elementvaluename};
}

=head2 Manifest Information

=head3 get_manifest_type

    my $type = $manifest->get_manifest_type;

Returns the manifest type ( 'application' or 'assembly' );

=cut

sub get_manifest_type { $_[0]->{_w32_exe_datatype}; }

sub get_current_schema { $_[0]->{_w32_exe_schema}; }

sub set_current_schema {
    my($self, $schema) = @_;
    $self->{_w32_exe_schema} = $schema;
    my $errors = $self->validate_errors;
    croak('Manifest XML had errors following set schema: ' . $errors) if $errors;
}

sub default_xmldecl { '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' }

sub default_content { 'elementValue' }

sub get_parser_config {
    my $self = shift;
    my %config = (
        KeepRoot   => 1,
        ForceArray => 1,
        KeyAttr => {},
        XMLDecl => $self->default_xmldecl,
        ForceContent => 1,
        ContentKey => $self->default_content,
        # AttrIndent => 1,
    );
    return %config;
}

sub refhash { $_[0]->{_w32_exe_dataref}; }

sub merge_manifest {
    my($self, $xml) = @_;
    my $mergefest;
    my $class = ref($self);
    eval { $mergefest = $class->new($xml, $self->get_manifest_type); };
    croak(qq(Merging $@)) if $@;
    my $newref = $mergefest->refhash()->{assembly}->[0];
    my $oldref = $self->refhash()->{assembly}->[0];
    $self->_merge_element_merge('assembly', $oldref, $newref);
    my $errors = $self->validate_errors;
    croak('Manifest had errors after merging: ' . $errors) if $errors;
}

sub get_osname_from_osid {
    my($self, $osid) = @_;
    my $name = 'Unknown Windows Version';
    $name = 'Windows Vista' if $osid =~ /e2011457-1546-43c5-a5fe-008deee3d3f0/;
    $name = 'Windows 7' if $osid =~ /35138b9a-5d96-4fbd-8e2d-a2440225f93a/;
    return $name;
}

sub get_osid_from_osname {
    my($self, $name) = @_;
    my $osid = undef;
    $osid = '{e2011457-1546-43c5-a5fe-008deee3d3f0}' if(lc($name) eq 'windows vista');
    $osid = '{35138b9a-5d96-4fbd-8e2d-a2440225f93a}' if(lc($name) eq 'windows 7');
    return $osid;
}

sub _get_dependendency_index {
    my($self, $name) = @_;
    my $exref = $self->refhash()->{assembly}->[0];
    return undef if not exists $exref->{dependency};
    my $rval = undef;
    my @existing = @{ $exref->{dependency} };
    for(my $i = 0; $i < @existing; $i++) {
        my $depname = $existing[$i]->{dependentAssembly}->[0]->{assemblyIdentity}->[0]->{name};
        if($depname eq $name) {
            $rval = $i;
            last;
        }
    }
    return $rval;
}

sub _get_first_tree_node {
    my ($self, $ref, $paths, $namealias ) = @_;
    my $newref = $ref;
    while(my $path = shift(@$paths) ) {
        $newref->{$path} = [{}]  if(not exists($newref->{$path}));
        $newref = $newref->{$path}->[0];
        $newref->{elementnamespace} = $namealias if $namealias;
    }
    return $newref;
}

sub _delete_collapse_tree {
    my ($self, $ref, $paths ) = @_;
    my $rootkey = $paths->[0];
    my $deletekey = pop(@$paths);
    my $delref = $ref;
    my $dodelete = 1;
    while(my $checkpath = shift @$paths) {
        if(exists($delref->{$checkpath}->[0])) {
            $delref = $delref->{$checkpath}->[0];
        } else {
            $dodelete = 0;
            last;
        }
    }
    delete($delref->{$deletekey}) if($dodelete && exists($delref->{$deletekey}));
    delete($delref->{elementnamespace}) if($dodelete && exists($delref->{elementnamespace}));
    $self->_delete_if_empty($ref, $rootkey);
}

sub _merge_element_merge {
    my($self, $elementname, $exref, $mergeref) = @_;
    my $schema = $self->get_current_schema;
    my $elementvaluename = $self->default_content;
    my $elementdef = $schema->{elementtypes}->{$elementname};

    my @keynames = (sort keys(%$mergeref));
    my %elementnames = ();
    my %attributenames = ();
    my $valuepresent = 0;

    for my $kname(@keynames) {
        if( $kname eq $elementvaluename ) {
            $valuepresent = 1;
        } elsif(ref($mergeref->{$kname})) {
            $elementnames{$kname} = 1;
        } else {
            $attributenames{$kname} = 1;
        }
    }

    # merge value
    if($valuepresent) {
        $exref->{$elementvaluename} = $mergeref->{$elementvaluename};
    }

    # merge attributes
    for my $aname (sort keys( %attributenames )) {
        $exref->{$aname} = $mergeref->{$aname};
    }

    # merge elements
    for my $ename (sort keys( %elementnames )) {
        if(not exists($exref->{$ename})) {
            # simple addition
            $exref->{$ename} = $mergeref->{$ename};
            next;
        }
        if($ename eq 'dependency') {
            # handle dependency merge
            $self->_merge_dependencies( $exref, $mergeref );
            next;
        }
        my $maxallowed = $elementdef->{elements}->{$ename}->{max};
        if($maxallowed == 1) {
            $self->_merge_element_merge($ename, $exref->{$ename}->[0], $mergeref->{$ename}->[0]);
        } else {
            push(@{ $exref->{$ename} }, @{ $mergeref->{$ename} });
        }
    }
}

sub _merge_dependencies {
    my($self, $exref, $mergeref) = @_;
    my %existingdepends = ();
    my %mergingdepends = ();

    my @existing = @{ $exref->{dependency} };
    my @merging = @{ $mergeref->{dependency} };
    my @merged = ();

    for(my $i = 0; $i < @existing; $i++) {
        my $depname = $existing[$i]->{dependentAssembly}->[0]->{assemblyIdentity}->[0]->{name};
        $existingdepends{$depname} = $i;
    }

    for(my $i = 0; $i < @merging; $i++) {
        my $depname = $merging[$i]->{dependentAssembly}->[0]->{assemblyIdentity}->[0]->{name};
        $mergingdepends{$depname} = $i;
    }

    foreach my $classname (sort keys(%existingdepends)) {
        push(@merged, $existing[$existingdepends{$classname}]) if not exists $mergingdepends{$classname}
    }

    push(@merged, @merging);
    $exref->{dependency} = \@merged;
}

sub validate_errors {
    my $self = shift;
    eval { $self->validate_data; };
    return ($@) ? $@ : undef;
}

sub _fixup_namespace {
    my( $self, $ref, $keyname, $xmlns ) = @_;
    for my $element( @{ $ref->{$keyname} } ) {
        $element->{xmlns} = $xmlns if $xmlns;
        delete($element->{elementnamespace}) if(exists($element->{elementnamespace}));
        my @keynames = (sort keys(%$element));
        for my $subkeyname( @keynames ) {
            if(ref($element->{$subkeyname})) {
                # a sub-element
                $self->_fixup_namespace($element, $subkeyname, undef );
            }
        }
    }
}

sub _delete_if_empty {
    my($self, $ref, $refname) = @_;

    # this element array is empty if it only contains namespace attributes
    # and all it's elements are similarly empty;

    my $candelete = 1;
    for my $element ( @{ $ref->{$refname} }) {
        my @keynames = (sort keys(%$element));
        for my $keyname( @keynames ) {
            next if $keyname eq 'elementnamespace';
            next if $keyname =~ /^xmlns/;
            my $value = $element->{$keyname};
            if(ref($value)) {
                # this is an element array
                $candelete = 0 if !$self->_delete_if_empty($element, $keyname);
            } else {
                # we have a none-namespace attribute
                $candelete = 0;
            }
        }
    }

    delete($ref->{$refname}) if $candelete;
    return $candelete;
}

sub _compress_schema {
    my $self = shift;
    my $ref = $self->refhash;
    $self->_compress_element_reference($ref);
}

sub _compress_element_reference {
    my($self, $hashref) = @_;
    my $schema = $self->get_current_schema;

    my @attributes;
    my @elements;

    for my $keyname ( sort keys(%$hashref) ) {
        my $value = $hashref->{$keyname};
        if(ref($value)) {
            push(@elements, $keyname);
        } else {
            push(@attributes, $keyname);
        }
    }

    for my $keyname ( @attributes ) {
        #next if $keyname eq 'elementnamespace'; # - should never appear
        my $value = $hashref->{$keyname};
        if($keyname =~ /^xmlns:(.+)$/) {
            # this is a namespace declaration
            # record it in the current schema
            # and delete it from the record
            my $replacerequired = 0;
            my $namespacesname = $1;
            if(exists($schema->{namespace}->{$value})) {
                # namespace exists
                my $alias = $schema->{namespace}->{$value};
                if($namespacesname ne $alias) {
                    $schema->{nstranslation}->{$namespacesname} = $alias;
                    $namespacesname = $alias;
                    $replacerequired = 1;
                }
            } else {
                # make sure namespace name is unique before adding values
                while(exists($schema->{nstranslation}->{$namespacesname})) {
                    $namespacesname .= 'n';
                }
                $schema->{namespace}->{$value} = $namespacesname;
                $schema->{nstranslation}->{$namespacesname} = $namespacesname;
                $replacerequired = 1;
            }
            # delete the declaration
            delete($hashref->{$keyname});
        }
    }

    for my $keyname ( @elements ) {
        my $value = $hashref->{$keyname};
        if($keyname =~ /^(.+):(.+)$/) {
            # element has a namespace
            my $namespace = $1;
            my $shortname = $2;
            my $nsalias = $schema->{nstranslation}->{$namespace} || $namespace;
            $hashref->{$shortname} = $value;
            delete($hashref->{$keyname});

            $_->{elementnamespace} = $nsalias for( @$value );

        }
        $self->_compress_element_reference($_) for ( @$value );
    }
}

sub _expand_schema {
    my $self = shift;
    $self->{parser}->{namespaces} = {};
    my $ref = $self->refhash;
    $self->_expand_element_reference($ref);
    # add namespace keys to
    my $assembly = $ref->{assembly}->[0];
    if($assembly) {
        foreach my $key (sort keys(%{ $self->{parser}->{namespaces} })) {
            my $xmlns = $self->{parser}->{namespaces}->{$key};
            my $xmlnsname = qq(xmlns:$key);
            $assembly->{$xmlnsname} = $xmlns;
        }
    }
    $self->{parser}->{namespaces} = {};
}

sub _expand_element_reference {
    # prepend saved namespace prefixes to elements
    my($self, $hashref) = @_;
    my $schema = $self->get_current_schema;
    my @keynames = ( sort keys(%$hashref) );
    for my $keyname ( @keynames  ) {
        my $value = $hashref->{$keyname};
        if(ref($value)) { # an array
            # get namespace if any
            my $namespace = undef;
            for my $element(@$value) {
                if(exists($element->{elementnamespace})) {
                    $namespace = $element->{elementnamespace};
                    delete($element->{elementnamespace});
                }
            }
            if($namespace) {
                my $newname = qq($namespace:$keyname);
                $hashref->{$newname} = $value;
                delete($hashref->{$keyname});
                my $xmlns = $schema->{namespacelookup}->{$namespace};
                $self->{parser}->{namespaces}->{$namespace} = $xmlns;
            }
            $self->_expand_element_reference($_) for ( @$value );
        }
    }
}

sub validate_data {
    my($self) = @_;
    # top level element must be assembly
    # grab that and validate onwards

    my $schema = $self->get_current_schema;
    my $ref = $self->refhash;
    my @levels = sort keys(%$ref);
    croak('Too many top level elements : ' . join(', ', @levels)) if (scalar(@levels) != 1);
    croak(qq(Unexpected top level element $levels[0])) if $levels[0] ne 'assembly';

    my $elementname = 'assembly';
    my $elementdef = exists($schema->{elementtypes}->{$elementname}) ? $schema->{elementtypes}->{$elementname} : undef;
    croak(qq(no definition found for element type $elementname)) if !defined($elementdef);
    my $min = 1;
    my $max = 1;
    my $raw = $ref->{assembly};
    $self->validate_element_array('assembly', $min, $max, $raw);
}

sub validate_element_array {
    my($self, $elementname, $min, $max, $ref) = @_;

    my $schema = $self->get_current_schema;
    my $elementvaluename = $self->default_content;

    # get element definition
    my $elementdef = exists($schema->{elementtypes}->{$elementname}) ? $schema->{elementtypes}->{$elementname} : undef;
    croak(qq(no definition found for element type $elementname)) if !defined($elementdef);

    # check if this manifest type accepts element type
    my $currenttype = $self->get_manifest_type;
    my $exclusive = $elementdef->{exclusive};
    if(($exclusive ne 'none') && ($currenttype ne $exclusive)) {
        croak(qq(element type $elementname cannot appear in $currenttype manifests));
    }

    # check that numbers are OK
    my $numelements = scalar @$ref;
    croak (qq(not enough $elementname elements - count = $numelements - minimum = $min)) if(($min > 0) && ($numelements < $min));
    croak (qq(too many $elementname elements - count = $numelements - maximum = $max)) if(($max > 0) && ($numelements > $max));

    # validate each element item
    $self->validate_element($elementname, $elementdef, $_) for (@$ref);
}

sub validate_element {
    my($self, $ename, $elementdef, $ref) = @_;

    # ref contains elements, and attributes
    # any value is present as attribute 'elementvalue'
    # elements are arrayrefs
    # attributes are values

    my $schema = $self->get_current_schema;
    my $elementvaluename = $self->default_content;

    my @keynames = (sort keys(%$ref));
    my %elementnames = ();
    my %attributenames = ();
    my $valuepresent = 0;

    for my $kname(@keynames) {
        next if $kname eq 'elementnamespace';
        if( $kname eq $elementvaluename ) {
            $valuepresent = 1;
        } elsif(ref($ref->{$kname})) {
            if(not exists($elementdef->{elements}->{$kname})) {
                croak(qq(Unexpected element $kname in $ename));
            }
            $elementnames{$kname} = 1;
        } else {
            # allow no value namespace attributes to pass
            next if $kname =~ /^xmlns:.+$/;
            next if $kname eq 'xmlns';
            if(not exists($elementdef->{attributes}->{$kname})) {
                croak(qq(Unexpected attribute $kname in $ename));
            }
            $attributenames{$kname} = 1;
        }
    }

    # check we have all required elements
    foreach my $ekey (sort keys(%{ $elementdef->{elements} })) {
        if( $elementdef->{elements}->{$ekey}->{min} > 0 ) {
            croak qq(required element $ekey not found) if !exists($elementnames{$ekey});
        }
    }
    # check we have all required attributes
    foreach my $akey (sort keys(%{ $elementdef->{attributes} })) {
        next if $akey eq 'xmlns';
        if( $elementdef->{attributes}->{$akey}->{required} == 1 ) {
            croak qq(required attribute $akey not found) if !exists($attributenames{$akey});
        }
    }
    # check we have correct value / novalue
    my $valuerequired = $elementdef->{content}->{value};
    if($valuerequired != $valuepresent) {
        croak qq( unexpected value in $ename  - value required = $valuerequired : value present = $valuepresent);
    }

    # validate any value
    if($valuerequired) {
        my $validator = $elementdef->{value_validator};
        Win32::Exe::Manifest::Parser->$validator($ref->{$elementvaluename})
            or croak(qq(Invalid Value $ref->{$elementvaluename} for element $ename));
    }

    # validate attributes
    foreach my $aname (sort keys( %attributenames ) ) {
        next if $aname eq 'xmlns';
        my $avalue = $ref->{$aname};
        my $validator = $schema->{attributes}->{$aname};
        Win32::Exe::Manifest::Parser->$validator($avalue) or croak(qq(Invalid value $avalue for attribute $aname in $ename));
    }

    # validate elements
    foreach my $sub_ename (sort keys( %elementnames ) ) {
        my $elearryref = $ref->{$sub_ename};
        my $min = $elementdef->{elements}->{$sub_ename}->{min};
        my $max = $elementdef->{elements}->{$sub_ename}->{max};
        $self->validate_element_array($sub_ename, $min, $max, $elearryref);
    }
}

sub get_dependency_template {
    my ($self, $name) = @_;
    my $dependencytemplates = $self->get_dependency_template_hash;
    if(exists($dependencytemplates->{$name})) {
        return $dependencytemplates->{$name};
    } else {
        return undef;
    }
}

sub get_dependency_template_hash {
    my $self = shift;
    my $dependencytemplates = {
        'Microsoft.Windows.Common-Controls' => {
            name => 'Microsoft.Windows.Common-Controls',
            type => 'win32',
            version => '6.0.0.0',
            publicKeyToken => '6595b64144ccf1df',
            language => '*',
            processorArchitecture => '*',
        },
    };
    return $dependencytemplates;
}

sub get_default_manifest { Win32::Exe::Manifest::Parser->get_default_manifest(); }

sub get_default_schema { Win32::Exe::Manifest::Parser->get_default_schema(); }

1;

__END__

=head1 SEE ALSO

Modules that use Win32::Exe::Manifest

Win32::Exe

=head1 AUTHORS

Mark Dootson E<lt>mdootson@cpan.orgE<gt>

=head1 COPYRIGHT & LICENSE

Copyright 2010 by Mark Dootson E<lt>mdootson@cpan.orgE<gt>

This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.

See L<http://www.perl.com/perl/misc/Artistic.html>

=cut


text:
namespace  // anonymous
{

// ----------------------------------------------------------------------------
// Function leftOf()
// ----------------------------------------------------------------------------

// TODO(holtgrew): Move into the SeqAn library?

// Returns true if lhs is truly left of rhs.

bool leftOf(seqan::GenomicRegion const & lhs,
            seqan::GenomicRegion const & rhs)
{
    if (lhs.rID < rhs.rID)
        return true;
    if (lhs.rID > rhs.rID)
        return false;
    if (lhs.endPos <= rhs.beginPos)
        return true;
    return false;
}

// ----------------------------------------------------------------------------
// Function doOverlap()
// ----------------------------------------------------------------------------

// TODO(holtgrew): Move into the SeqAn library?

// Returns true if the two regions overlap.

bool doOverlap(seqan::GenomicRegion const & lhs,
               seqan::GenomicRegion const & rhs)
{
    if (lhs.rID != rhs.rID)
        return false;
    return (lhs.beginPos < rhs.endPos && rhs.beginPos < lhs.endPos);
}

}  // anonymous namespace

// ----------------------------------------------------------------------------
// Class ClusterMatchingImpl
// ----------------------------------------------------------------------------

// Implementation of the cluster matching.

class ClusterMatchingImpl
{
public:
    ClusterMatchingImpl()
    {}

    // Perform the clustering.
    void run(std::vector<std::pair<OeaClusterRecord, ClippingClusterRecord> > & result,
             std::vector<OeaClusterRecord> const & oeaClusters,
             std::vector<ClippingClusterRecord> const & clippingClusters);

    bool _doOverlap(OeaClusterRecord const & lhs, OeaClusterRecord const & rhs)
    {
        return (rhs.region.beginPos < lhs.region.endPos &&
                lhs.region.beginPos < rhs.region.endPos);
    }

    bool _isInCluster(OeaClusterRecord const & oea, ClippingClusterRecord const & clipping)
    {
        return (oea.region.rID == clipping.region.rID &&
                oea.region.beginPos <= clipping.region.beginPos &&
                oea.region.endPos >= clipping.region.endPos);
    }
};

void ClusterMatchingImpl::run(std::vector<std::pair<OeaClusterRecord, ClippingClusterRecord> > & result,
                              std::vector<OeaClusterRecord> const & oeaClusters,
                              std::vector<ClippingClusterRecord> const & clippingClusters)
{
    typedef lemon::SmartGraph TGraph;
    typedef TGraph::Node      TNode;
    typedef TGraph::Edge      TEdge;

    typedef lemon::SparseMap<TEdge, double> TEdgeWeights;
    typedef lemon::SparseMap<TNode, unsigned> TNodeIdMap;

    // Offsets of first OEA/clipping vertex.
    TNodeIdMap nodeIds;
    std::vector<TGraph::Node> oeaNodes;
    oeaNodes.reserve(oeaClusters.size());
    std::vector<TGraph::Node> clippingNodes;
    clippingNodes.reserve(clippingClusters.size());
    std::vector<TEdge> edges;

    TEdgeWeights edgeWeights;

    // -----------------------------------------------------------------------
    // Build Bipartite Graph
    // -----------------------------------------------------------------------

    // TODO(holtgrew): LEMON 1.2.3 does not support bipartite graphs and algorithms on them yet.
    TGraph g;
    g.reserveNode(oeaClusters.size() + clippingClusters.size());
    // Add vertices.
    for (std::vector<OeaClusterRecord>::const_iterator it = oeaClusters.begin(); it != oeaClusters.end(); ++it)
    {
        oeaNodes.push_back(g.addNode());
        nodeIds[oeaNodes.back()] = oeaNodes.size() - 1;
    }
    for (std::vector<ClippingClusterRecord>::const_iterator it = clippingClusters.begin(); it != clippingClusters.end(); ++it)
    {
        clippingNodes.push_back(g.addNode());
        nodeIds[clippingNodes.back()] = oeaNodes.size() + clippingNodes.size() - 1;
    }

    // Add edges in a sweep-line fashion.  We compute overlapping intervals the OEA clusters and then all clipping
    // clusters that fall into the interval.
    //
    // We need two ranges on both the OEA and the clipping records.
    typedef std::vector<OeaClusterRecord>::const_iterator TOeaIter;
    TOeaIter itOeaBegin = oeaClusters.begin();
    TOeaIter itOeaEnd = oeaClusters.begin();
    typedef std::vector<ClippingClusterRecord>::const_iterator TClippingIter;
    TClippingIter itClippingBegin = clippingClusters.begin();
    TClippingIter itClippingEnd = clippingClusters.begin();
    // Perform sweep-line algorithm.
    // TODO(holtgrew): Handling reference switch.
    while (itOeaBegin != oeaClusters.end() && itClippingBegin != clippingClusters.end())
    {
        // Go over intervals in OEA records.
        for (TOeaIter itOea = itOeaEnd++; itOeaEnd != oeaClusters.end(); ++itOeaEnd, ++itOea)
            if (!_doOverlap(*itOea, *itOeaEnd))
                break;
        // std::cerr << "OEA interval: (size = " << (itOeaEnd - itOeaBegin) << ") " << itOeaBegin->region.rID << "\t"
        //           << (itOeaBegin->region.beginPos + 1) << "\t" << (itOeaEnd - 1)->region.endPos << "\n";
        // for (TOeaIter it = itOeaBegin; it != itOeaEnd; ++it)
        //     std::cerr << "OEA\t" << *it << "\n";

        // Find first clipping record that is not before the OEA interval beginning.
        for (; itClippingBegin != clippingClusters.end() && leftOf(itClippingBegin->region, itOeaBegin->region); ++itClippingBegin)
            continue;  // skipping
        itClippingEnd = itClippingBegin;
        // Find last clipping record that is not behind the OEA interval beginning.
        for (; itClippingEnd != clippingClusters.end() && doOverlap(itClippingEnd->region, (itOeaEnd - 1)->region); ++itClippingEnd)
            continue;  // skipping
        // for (TClippingIter it = itClippingBegin; it != itClippingEnd; ++it)
        //     std::cerr << "CLIPPING\t" << *it << "\n";

        // Process the currently active window.
        for (TOeaIter itOea = itOeaBegin; itOea != itOeaEnd; ++itOea)
        {
            unsigned idOea = itOea - oeaClusters.begin();
            double weightOea = sqrt((1.0 + itOea->leftWeight) * (1.0 + itOea->rightWeight));
            for (TClippingIter itClipping = itClippingBegin; itClipping != itClippingEnd; ++itClipping)
            {
                if (!_isInCluster(*itOea, *itClipping))
                    continue;  // Clipping cluster not in OEA cluster.

                unsigned idClipping = itClipping - clippingClusters.begin();
                double weightClipping = sqrt((1.0 + itClipping->leftWeight) * (1.0 + itClipping->rightWeight));
                edges.push_back(g.addEdge(oeaNodes[idOea], clippingNodes[idClipping]));
                edgeWeights[edges.back()] = weightOea + weightClipping;
            }
        }

        // This overlapping region is done.
        itOeaBegin = itOeaEnd;
        itClippingBegin = itClippingEnd;
    }

    // -----------------------------------------------------------------------
    // Compute Matching
    // -----------------------------------------------------------------------

    lemon::MaxWeightedMatching<TGraph, TEdgeWeights> mwMatching(g, edgeWeights);
    mwMatching.run();

    // -----------------------------------------------------------------------
    // Write Out Result
    // -----------------------------------------------------------------------

    seqan::String<bool> oeaMatches;
    resize(oeaMatches, oeaClusters.size(), false);

    // TODO(holtgrew): We could also write out the candidates not supported by both OEA and clipping signals.
    for (unsigned i = 0; i < oeaClusters.size(); ++i)
    {
        if (mwMatching.mate(oeaNodes[i]) == lemon::INVALID)
            continue;
        unsigned idOea = nodeIds[oeaNodes[i]];
        unsigned idClipping = nodeIds[mwMatching.mate(oeaNodes[i])] - oeaNodes.size();
        result.push_back(std::make_pair(oeaClusters[idOea], clippingClusters[idClipping]));
        oeaMatches[idOea] = true;
    }

    ClippingClusterRecord invalidCCR;
    for (unsigned i = 0; i < length(oeaMatches); ++i)
    {
        if (oeaMatches[i])
            continue;  // Skip, is matched.
        result.push_back(std::make_pair(oeaClusters[i], invalidCCR));
    }

    // Sort resulting clusters.
    std::sort(result.begin(), result.end());
}

// ----------------------------------------------------------------------------
// Class ClusterMatching
// ----------------------------------------------------------------------------

void ClusterMatching::run(std::vector<std::pair<OeaClusterRecord, ClippingClusterRecord> > & matchedClusters,
                          std::vector<OeaClusterRecord> const & oeaClusters,
                          std::vector<ClippingClusterRecord> const & clippingClusters)
{
    impl->run(matchedClusters, oeaClusters, clippingClusters);
}

ClusterMatching::ClusterMatching() : impl(new ClusterMatchingImpl)
{}

ClusterMatching::~ClusterMatching()
{}


text:
// Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#pragma once
#include "MedusaPreDeclares.h"
#include "Resource/Model/Mesh/IMesh.h"
#include "Geometry/Point2.h"
#include "Geometry/Point3.h"
#include "Geometry/Color4.h"
#include "Graphics/GraphicsTypes.h"

MEDUSA_BEGIN;

/*
We choose separate buffer instead of interleaved, because we want to update only one component
*/
class TextureGeneralMesh :public IMesh
{
public:
	TextureGeneralMesh( bool isStatic = false);
	virtual ~TextureGeneralMesh(void);
public:
	virtual size_t VertexCount()const override { return mVertices.Count(); }
	virtual size_t IndexCount()const override { return mIndices.Count(); }

	const List<Point3F>& Vertices()  const { return mVertices; }
	const List<Point2F>& Texcoords() const { return mTexcoords; }
	const List<Color4F>& Colors() const { return mColors; }
	const List<uint>& Indices() const { return mIndices; }

	List<Point3F>& MutableVertices() { return mVertices; }
	List<Point2F>& MutableTexcoords() { return mTexcoords; }
	List<Color4F>& MutableColors() { return mColors; }
	List<uint>& MutableIndices() { return mIndices; }

	void AppendQuad(const QuadTextureVertex& quad);

	void AppendVertex(const Point3F& vertex, uint count = 1);

	void AppendVertices(const Point3F* vertices, size_t count);

	void AppendTexcoord(const Point2F& texcoord, uint count = 1);
	void AppendTexcoords(const Point2F* texcoords, size_t count);

	void AppendColor(const Color4F& color, uint count = 1);

	void AppendQuadIndex();

	void AppendIndex(uint index);
	void AppendIndices(uint* items, uint count);

	void AppendQuadRawData2D(const float* vertices, const float* texcoords, const Color4F& color, bool isInvertTexcoordY = false);

	void AppendRawData2D(const float* vertices, const float* texcoords, uint vertexCount, const uint* indices, uint indexCount, const Color4F& color, bool isInvertTexcoordY = false);

	virtual void Clear()override;

	virtual INode* CreateCloneInstance()const override;
public:
	virtual void AddToVertexBufferObject(VertexGraphicsBuffer& bufferObject, size_t vertexIndex, const Matrix4& matrix)const override;
	virtual void AddToTexCoordBufferObject(TexCoordGraphicsBuffer& bufferObject, size_t vertexIndex)const override;
	virtual void AddToColorBufferObject(ColorGraphicsBuffer& bufferObject, size_t vertexIndex, const Color4F& parentColor = Color4F::White)const override;
	virtual void AddToIndexBufferObject(IndexGraphicsBuffer& bufferObject, size_t vertexIndex, size_t indexIndex)const override;
public:
	bool CopyFrom(const TextureGeneralMesh& val);

protected:

	List<Point3F> mVertices;
	List<Point2F> mTexcoords;
	List<Color4F> mColors;
	List<uint> mIndices;

};

MEDUSA_END;


text:
'use strict';

/**
 * The response of list Redis operation.
 */
class RedisListResult extends Array {
  /**
   * Create a RedisListResult.
   * @property {string} [nextLink] Link for next page of results.
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of RedisListResult
   *
   * @returns {object} metadata of RedisListResult
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'RedisListResult',
      type: {
        name: 'Composite',
        className: 'RedisListResult',
        modelProperties: {
          value: {
            required: false,
            serializedName: '',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'RedisResourceElementType',
                  type: {
                    name: 'Composite',
                    className: 'RedisResource'
                  }
              }
            }
          },
          nextLink: {
            required: false,
            readOnly: true,
            serializedName: 'nextLink',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = RedisListResult;


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.team4639.frc2014.commands;

/**
 *
 * @author Prateek Mahajan
 */
public class ResetGyroCommand extends CommandBase {
  protected void initialize() {
    drive.resetGyro();
  }

  protected void execute() {
  }

  protected boolean isFinished() {
    return true;
  }

  protected void end() {
  }

  protected void interrupted() {
  }
}


text:
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using TryCSharp.Common;

namespace TryCSharp.Samples.IO
{
    /// <summary>
    ///     System.IO.Compression.ZipFileクラスのサンプルです。
    /// </summary>
    /// <remarks>
    ///     ZipFileクラスは、.NET Framework 4.5で追加されたクラスです。
    ///     このクラスを利用するには、「System.IO.Compression.FileSystem.dll」を
    ///     参照設定に追加する必要があります。
    ///     このクラスは、Metroアプリでは利用できません。
    ///     Metroアプリでは、代わりにZipArchiveクラスを利用します。
    /// </remarks>
    [Sample]
    public class ZipFileSamples02 : IExecutable
    {
        private string _zipFilePath;

        private string DesktopPath => Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

        public ZipFileSamples02()
        {
            _zipFilePath = string.Empty;
        }

        public void Execute()
        {
            //
            // ZipFileクラスの以下のメソッドを利用すると、既存のZIPファイルを開く事が出来る。
            //   ・OpenRead
            //   ・Open(string, ZipArchiveMode)
            //   ・Open(string, ZipArchiveMode, Encoding)
            // どのメソッドも、戻り値としてZipArchiveクラスのインスタンスを返す。
            // 実際にZIPファイル内のエントリ取得は、ZipArchiveから行う.
            // ZipArchiveクラスは、IDisposableを実装しているのでusingブロックで
            // 利用するのが好ましい。
            //
            // 尚、ZipArchiveクラスを利用する場合、参照設定に
            //   System.IO.Compression.dll
            // を追加する必要がある。
            //
            Prepare();

            //
            // OpenRead
            //
            using (var archive = ZipFile.OpenRead(_zipFilePath))
            {
                archive.Entries.ToList().ForEach(PrintEntry);
            }

            //
            // Open(string, ZipArchiveMode)
            //
            using (var archive = ZipFile.Open(_zipFilePath, ZipArchiveMode.Read))
            {
                //
                // ZipArchive.Entriesプロパティからは、ReadOnlyCollection<ZipArchiveEntry>が取得できる。
                // 1エントリの情報は、ZipArchiveEntryから取得できる。
                //
                // ZipArchiveEntryには、Nameというプロパティが存在し、このプロパティから実際のファイル名を取得できる。
                // また、Lengthプロパティより圧縮前のファイルサイズが取得できる。圧縮後のサイズは、CompressedLengthから取得できる。
                // エントリの内容を読み出すには、ZipArchiveEntry.Openメソッドを利用する。
                //
                archive.Entries.ToList().ForEach(PrintEntry);
            }

            //
            // Open(string, ZipArchiveMode, Encoding)
            //   テキストファイルのみ、中身を読み出して出力.
            //
            using (var archive = ZipFile.Open(_zipFilePath, ZipArchiveMode.Read, Encoding.GetEncoding("sjis")))
            {
                archive.Entries.Where(entry => entry.Name.EndsWith("txt")).ToList().ForEach(PrintEntryContents);
            }

            File.Delete(_zipFilePath);
            Directory.Delete(Path.Combine(DesktopPath, "ZipTest"), true);
        }

        private void Prepare()
        {
            //
            // サンプルZIPファイルを作成しておく.
            // (デスクトップ上にZipTest.zipという名称で出力される)
            //
            new ZipFileSamples01().Execute();
            _zipFilePath = Path.Combine(DesktopPath, "ZipTest.zip");
        }

        private void PrintEntry(ZipArchiveEntry entry)
        {
            Output.WriteLine("[{0}, {1}]", entry.Name, entry.Length);
        }

        private void PrintEntryContents(ZipArchiveEntry entry)
        {
            using (var reader = new StreamReader(entry.Open(), Encoding.GetEncoding("sjis")))
            {
                for (var line = reader.ReadLine(); line != null; line = reader.ReadLine())
                {
                    Output.WriteLine(line);
                }
            }
        }
    }
}


text:
<?php

namespace AntiMattr\Sears\Model;

use AntiMattr\Sears\Exception\IntegrationException;
use DateTime;

/**
 * @author Matthew Fitzgerald <matthewfitz@gmail.com>
 */
class Inventory implements RequestSerializerInterface
{
    /** @var string */
    protected $productId;

    /** @var int */
    protected $quantity;

    /** @var int */
    protected $threshold;

    /** @var DateTime */
    protected $updatedAt;

    /**
     * @return string $productId
     */
    public function getProductId()
    {
        return $this->productId;
    }

    /**
     * @param string $productId
     */
    public function setProductId($productId)
    {
        $this->productId = $productId;
    }

    /**
     * @return int $quantity
     */
    public function getQuantity()
    {
        return $this->quantity;
    }

    /**
     * @param int $quantity
     */
    public function setQuantity($quantity)
    {
        if (!is_numeric($quantity)) {
            return;
        }

        $this->quantity = (int) $quantity;
    }

    /**
     * @return int $threshold
     */
    public function getThreshold()
    {
        return $this->threshold;
    }

    /**
     * @param int $threshold
     */
    public function setThreshold($threshold)
    {
        if (!is_numeric($threshold)) {
            return;
        }

        $this->threshold = (int) $threshold;
    }

    /**
     * @return DateTime $updatedAt
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * @param DateTime $updatedAt
     */
    public function setUpdatedAt(DateTime $updatedAt)
    {
        $this->updatedAt = $updatedAt;
    }

    /**
     * @return array
     * @throws \AntiMattr\Sears\Exception\IntegrationException
     */
    public function toArray()
    {
        $required = array(
            'productId' => $this->getProductId(),
            'quantity'  => $this->getQuantity(),
        );

        $optional = array(
            'threshold' => $this->getThreshold(),
            'updatedAt' => $this->getUpdatedAt()->format('Y-m-d\TH:i:s')
        );

        $missing = array_filter($required, function($item){
            return (null === $item) ? true : false;
        });

        if (count($missing) > 0) {
            $message = sprintf(
                'Inventory requires: %s.',
                implode(", ", array_keys($missing))
            );
            throw new IntegrationException($message);
        }

        return array(
            '_attributes' => array(
                'item-id' => $required['productId']
            ),
            'quantity'                => $required['quantity'],
            'low-inventory-threshold' => $optional['threshold'],
            'inventory-timestamp'     => $optional['updatedAt'],
        );
    }
}