text:
#region COPYRIGHT© 2009-2014 Phillip Clark. All rights reserved.

// For licensing information see License.txt (MIT style licensing).

#endregion

using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Reflection.Emit;

namespace FlitBit.Emit
{
	/// <summary>
	///   Helper class for working with a modules in the IL stream.
	/// </summary>
	public class EmittedModule
	{
		private readonly Dictionary<string, EmittedClass> _classes = new Dictionary<string, EmittedClass>();

		/// <summary>
		///   Creates a new instance.
		/// </summary>
		/// <param name="assembly">the assembly, owner</param>
		/// <param name="name">the module's name</param>
		/// <param name="namespace">a namespace name for the classes in the module (base)</param>
		public EmittedModule(EmittedAssembly assembly, string name, string @namespace)
		{
			Contract.Requires<ArgumentNullException>(assembly != null);
			Contract.Requires<ArgumentNullException>(name != null);
			Contract.Requires<ArgumentNullException>(name.Length > 0);

			Assembly = assembly;
			Name = name;
			Namespace = @namespace ?? String.Empty;
#if DEBUG
			Builder = Assembly.Builder.DefineDynamicModule(name, name + ".dll", true);
#else
			this.Builder = this.Assembly.Builder.DefineDynamicModule(name, name + ".dll", false);
#endif
		}

		/// <summary>
		///   Gets the assembly within which the module resides.
		/// </summary>
		public EmittedAssembly Assembly { get; private set; }

		/// <summary>
		///   Gets the underlying ModuleBuilder for the module.
		/// </summary>
		public ModuleBuilder Builder { get; private set; }

		/// <summary>
		///   Indicates whether the module has been compiled.
		/// </summary>
		public bool IsCompiled { get; private set; }

		/// <summary>
		///   Gets the module's name.
		/// </summary>
		public string Name { get; private set; }

		/// <summary>
		///   Gets the default namespace for the module.
		/// </summary>
		public string Namespace { get; private set; }

		/// <summary>
		///   Compiles the module.
		/// </summary>
		/// <returns></returns>
		public Module Compile()
		{
			Contract.Requires<ArgumentNullException>(!IsCompiled, "module already compiled");

			foreach (EmittedClass c in _classes.Values)
			{
				// Classes may have been individually compiled.
				if (!c.IsCompiled)
				{
					c.Compile();
				}
			}
			IsCompiled = true;
			return Builder;
		}

		/// <summary>
		///   Defines a class.
		/// </summary>
		/// <param name="name">the class' name</param>
		/// <returns>the emitted class</returns>
		public EmittedClass DefineClass(string name)
		{
			Contract.Requires<ArgumentNullException>(name != null);
			Contract.Requires<ArgumentNullException>(name.Length > 0);
			Contract.Requires(!IsCompiled, "module already compiled");

			CheckClassName(name);

			var cls = new EmittedClass(Builder, name);
			_classes.Add(name, cls);
			return cls;
		}

		/// <summary>
		///   Defines a class
		/// </summary>
		/// <param name="name">the class' name</param>
		/// <param name="attributes">the class' attributes</param>
		/// <param name="supertype">the class' supertype</param>
		/// <param name="interfaces">list of interfaces the class will implement</param>
		/// <returns>the emitted class</returns>
		public EmittedClass DefineClass(string name, TypeAttributes attributes
			, Type supertype, Type[] interfaces)
		{
			Contract.Requires<ArgumentNullException>(name != null);
			Contract.Requires<ArgumentNullException>(name.Length > 0);

			CheckClassName(name);

			var cls = new EmittedClass(Builder, name, attributes, supertype, interfaces);
			_classes.Add(name, cls);
			return cls;
		}

		/// <summary>
		///   Saves the module.
		/// </summary>
		internal void Save()
		{
			Contract.Requires(Assembly != null);
			if (!Assembly.IsCompiled)
			{
				Assembly.Compile();
			}
			Assembly.Save(this);
		}

		private void CheckClassName(string name)
		{
			Contract.Requires<ArgumentNullException>(name != null);
			Contract.Requires<ArgumentNullException>(name.Length > 0);

			if (_classes.ContainsKey(name))
			{
				throw new InvalidOperationException(String.Concat(
					"Unable to generate duplicate class. The class name is already in use: module = ",
					Name, ", class = ", name)
					);
			}
		}
	}
}


text:
int debug = 0;
int verbose = 0;

redpajama_set_name: RedPajamaGithub


text:
import Ember from 'ember';
const { computed } = Ember;

export default Ember.Controller.extend({
  soManyProperties: computed(
    'model.homes.[]', function () {
      var propertiesSummary = '';
      var numberOfProperties = this.get('model.homes.length');
      if (numberOfProperties === 0) {
        propertiesSummary += 'no properties';
      } else if (numberOfProperties === 1) {
        propertiesSummary += numberOfProperties + ' property';
      } else {
        propertiesSummary += numberOfProperties + ' properties';
      }

      return propertiesSummary;
    })
});


text:
@interface BKEViewController : UIViewController

@end


text:
package org.shaolin.uimaster.page.widgets;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.shaolin.bmdp.datamodel.page.StringPropertyType;
import org.shaolin.bmdp.datamodel.page.ValidatorPropertyType;
import org.shaolin.bmdp.i18n.LocaleContext;
import org.shaolin.bmdp.i18n.ResourceUtil;
import org.shaolin.bmdp.json.JSONException;
import org.shaolin.bmdp.json.JSONObject;
import org.shaolin.uimaster.html.layout.IUISkin;
import org.shaolin.uimaster.page.AjaxContextHelper;
import org.shaolin.uimaster.page.HTMLUtil;
import org.shaolin.uimaster.page.UserRequestContext;
import org.shaolin.uimaster.page.WebConfig;
import org.shaolin.uimaster.page.ajax.Widget;
import org.shaolin.uimaster.page.cache.UIFormObject;
import org.shaolin.uimaster.page.exception.AttributeSetAlreadyException;
import org.shaolin.uimaster.page.javacc.VariableEvaluator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The top of all HTML widgets.
 *
 * Be aware of all these HTML* classes are the static/cached structure which shared for all user requests.
 * You can find the cache map is in {@link UIFormObject}.htmlWidgets. Every user requested data stores in
 * {@link UserRequestContext} while running only.
 *
 * @author wushaol
 *
 */
public abstract class HTMLWidgetType implements Serializable
{
    private static final transient Logger logger = LoggerFactory.getLogger(HTMLWidgetType.class);
    private static final long serialVersionUID = -6119707922874957783L;

    private String entityName;
    private final String id;
    // defined static maps.
    Map<String, Object> attributeMap;
    Map<String, Object> eventListenerMap;

    // defined static UISkin.
    private IUISkin uiskinObj;

	public HTMLWidgetType(final String id) {
    	this.id = id;
    }

    public void reset()
    {
        this.attributeMap = null;
        this.eventListenerMap = null;
    }

    public void setUIEntityName(String entityName) {
    	this.entityName = entityName;
    }

    public String getUIEntityName() {
    	return this.entityName;
    }

    public String getId()
    {
        return id;
    }

    public String getName()
    {
        return getName(true);
    }

    public String getName(boolean withSuffix)
    {
        String name = id;
        UserRequestContext context = UserRequestContext.UserContext.get();
        if (context != null)
        {
        	name = UserRequestContext.UserContext.get().getHTMLPrefix() + id;
        }
        return name;
    }

    public IUISkin getUISkin() {
		return uiskinObj;
	}

	public void setUISkin(IUISkin uiskinObj) {
		this.uiskinObj = uiskinObj;
	}

    /**
     * this is static attributes sharing for all users.
     *
     * @param attributeMap
     * @throws AttributeSetAlreadyException
     */
    public void setAttribute(Map<String, Object> attributeMap) throws AttributeSetAlreadyException
    {
        if (attributeMap == null){
            return;
        }
        if (this.attributeMap != null)
        {
        	throw new AttributeSetAlreadyException("");
        }
        attributeMap.remove("readOnly");//useless in here.
        this.attributeMap = Collections.unmodifiableMap(attributeMap);
    }

    /**
     * Add dynamic attribute for current user.
     *
     * @param name
     * @param value
     */
    public void addAttribute(String name, Object value)
    {
        int endIndex = name.indexOf("[");
        if (endIndex > -1)
        {
            name = name.substring(0, endIndex);
            Object valueList = UserRequestContext.UserContext.get().getAttribute(this.getName()).get(name);
			if (valueList != null) {
				if (valueList instanceof List) {
					((List) valueList).add(value);
				} else {
					logger.error(getName() + "'s " + name + " is not list attribute");
				}
			} else {
                valueList = new ArrayList();
                ((List) valueList).add(value);
                UserRequestContext.UserContext.get().addAttribute(this.getName(), name, valueList);
            }
        }
        else
        {
        	UserRequestContext.UserContext.get().addAttribute(this.getName(), name, value);
        }
    }

    public void setEventListener(Map<String, Object> eventMap) throws AttributeSetAlreadyException
	{
		if (eventMap == null) {
			return;
		}
		if (eventListenerMap != null) {
			throw new AttributeSetAlreadyException("");
		}
	    eventListenerMap = Collections.unmodifiableMap(eventMap);
	}

	public String getEventListener(String name)
	{
	    return eventListenerMap == null ? null : (String) eventListenerMap.get(name);
	}

	public boolean needAjaxSupport() {
    	Object v = this.getAttribute("needAjaxSupport");
    	return v == null ? false : "true".equalsIgnoreCase(v.toString());
    }

    public Object getAttribute(String name)
    {
    	Object v = null;
    	String uiid = this.getName();
		if (UserRequestContext.UserContext.get() != null
				&& UserRequestContext.UserContext.get().hasAttribute(uiid)) {
    		v = UserRequestContext.UserContext.get().getAttribute(uiid).get(name);
    	}
    	if (v != null) {
    		return v;
    	}
        return attributeMap == null ? null : attributeMap.get(name);
    }

    public Object removeAttribute(String name)
    {
    	String uiid = this.getName();
    	if (UserRequestContext.UserContext.get() != null
				&& UserRequestContext.UserContext.get().hasAttribute(uiid)) {
    		Object v = UserRequestContext.UserContext.get().getAttribute(uiid).remove(name);
    		if (v != null) {
    			return v;
    		}
    	}
    	// we must not remove the static attribute instead getting only.
    	return attributeMap == null ? null : attributeMap.get(name);
    }

    public boolean containsAttribute(String name)
    {
    	String uiid = this.getName();
		if (UserRequestContext.UserContext.get() != null
				&& UserRequestContext.UserContext.get().hasAttribute(uiid)) {
			return true;
		}
    	return attributeMap == null ? false : attributeMap.containsKey(name);
    }

    public void addStyle(String name, String value)
    {
    	UserRequestContext.UserContext.get().addStyle(getName(), name, value);
    }

    public String getStyle(String name)
    {
    	String v = null;
    	String uiid = this.getName();
		if (UserRequestContext.UserContext.get() != null
				&& UserRequestContext.UserContext.get().hasAttribute(uiid)) {
    		v = UserRequestContext.UserContext.get().getStyle(uiid, name);
    	}
		return v;
    }

    public void setAJAXAttributes(UserRequestContext context, Widget widget)
    {
        Map<String, Object> odMappingAttrs = context.getAttribute(getName());
        if (odMappingAttrs != null && !odMappingAttrs.isEmpty())
        {
            for (Iterator it = odMappingAttrs.entrySet().iterator(); it.hasNext();)
            {
                Map.Entry entry = (Map.Entry)it.next();
                String attributeName = (String)entry.getKey();;
                Object attributeValue = entry.getValue();
                setAJAXAttribute(attributeName, attributeValue, widget);
            }
        }

        if (attributeMap != null && !attributeMap.isEmpty())
        {
            if (odMappingAttrs == null || !odMappingAttrs.containsKey("viewPermission"))
            {
            	Object attributeValue = getAttribute("viewPermission");
                setAJAXAttribute("viewPermission", attributeValue, widget);
            }
            if (odMappingAttrs == null || !odMappingAttrs.containsKey("editPermission"))
            {
            	Object attributeValue = getAttribute("editPermission");
                setAJAXAttribute("editPermission", attributeValue, widget);
            }
            if (odMappingAttrs == null || !odMappingAttrs.containsKey("visible"))
            {
            	Object attributeValue = getAttribute("visible");
                setAJAXAttribute("visible", attributeValue, widget);
            }
            if (odMappingAttrs == null || !odMappingAttrs.containsKey("editable"))
            {
            	Object attributeValue = getAttribute("editable");
                setAJAXAttribute("editable", attributeValue, widget);
            }
        }
    }

    public void setAJAXAttribute(String attributeName, Object attributeValue, Widget widget)
    {
        if ("viewPermission".equals(attributeName))
        {
            String[] viewPermissions = convertToStringArray(attributeValue);
            if ((viewPermissions != null) && (viewPermissions.length > 0))
            {
                widget.setViewPermissions(viewPermissions);
            }
            return;
        }
        else if ("editPermission".equals(attributeName))
        {
            String[] editPermissions = convertToStringArray(attributeValue);
            if ((editPermissions != null) && (editPermissions.length > 0))
            {
                widget.setEditPermissions(editPermissions);
            }
            return;
        }
        else if ("visible".equals(attributeName))
        {
        	String attrValue = String.valueOf(attributeValue);
            if ("false".equals(attrValue))
            {
                widget.setVisible(false);
            }
            return;
        }
        else if ("editable".equals(attributeName))
        {
        	String attrValue = String.valueOf(attributeValue);
            if ("false".equals(attrValue))
            {
                widget.addAttribute("disabled", "true");
            }
            return;
        }
    }

    protected void setAJAXConstraints(Widget widget)
    {
        Object init = getAttribute("initValidation");
        if (init != null)
        {
            widget.addConstraint("initValidation", init, null);
        }
        Object value = getAttribute("validator");
        if (value != null)
        {
            ValidatorPropertyType validator = (ValidatorPropertyType)value;
            String message = validator.getErrMsg();
            if (message == null)
            {
                if (validator.getI18NMsg() != null)
                {
                    message = ResourceUtil.getResource(LocaleContext.getUserLocale(),
                            validator.getI18NMsg().getBundle(),
                            validator.getI18NMsg().getKey());
                }
            }
            List<StringPropertyType> params = validator.getParams();
            String[] parameters = new String[params.size()];
            for (int i = 0; i < params.size(); i++)
            {
                parameters[i] = params.get(i).getValue();
            }
            widget.addCustomValidator(validator.getFuncCode(), parameters, message);
        }

        if (containsAttribute("allowBlank")) {
	        widget.addConstraint("allowBlank",
	        		getAttribute("allowBlank"),
	        		(String)getAttribute("allowBlankText"));
        }
		if (this instanceof HTMLTextWidgetType) {
			widget.addConstraint("minLength",
					getAttribute("minLength"),
					(String)getAttribute("lengthText"));
			widget.addConstraint("regex",
					getAttribute("regex"),
					(String)getAttribute("regexText"));
			if (this instanceof HTMLTextAreaType) {
				widget.addConstraint("maxLength",
						getAttribute("maxLength"),
						(String)getAttribute("lengthText"));
			}
		} else if (this instanceof HTMLChoiceType) {
			if (this instanceof HTMLSingleChoiceType) {
				widget.addConstraint("selectedValueConstraint",
						getAttribute("selectedValueConstraint"),
						(String)getAttribute("selectedValueConstraintText"));
			} else if (this instanceof HTMLMultiChoiceType) {
				widget.addConstraint("selectedValuesConstraint",
						(Object[])getAttribute("selectedValuesConstraint"),
						(String)getAttribute("selectedValuesConstraintText"));
			}
		} else if (this instanceof HTMLSelectComponentType) {
			if (this instanceof HTMLCheckBoxType) {
				widget.addConstraint("mustCheck",
						getAttribute("mustCheck"),
						(String)getAttribute("mustCheckText"));
			}
		}
    }

    public String getReconfigurateFunction(String handler)
    {
        return getReconfigurateFunction(handler, true);
    }

    public String getReconfigurateFunction(final String handler, boolean needParameter)
    {
    	UserRequestContext context = UserRequestContext.UserContext.get();
    	String aHandler = handler;
        String functionPrefix = context.getHTMLPrefix();
        String reconfiguration = context.getReconfigFunction(functionPrefix, aHandler);
        while (reconfiguration != null)
        {
            if (functionPrefix.endsWith("."))
            {
                functionPrefix = functionPrefix.substring(0, functionPrefix.length() - 1);
            }
            int endIndex = functionPrefix.lastIndexOf(".");
            if (endIndex == -1)
            {
                functionPrefix = "";
            }
            else
            {
                functionPrefix = functionPrefix.substring(0 ,endIndex + 1);
            }
            aHandler = reconfiguration;
            reconfiguration = context.getReconfigFunction(functionPrefix, aHandler);
        }

        String functionName = "defaultname." + functionPrefix + aHandler;
        if (needParameter && aHandler.indexOf('(') == -1) {
	        String parameter = "defaultname." + getName() + ",event";
	        return "javascript:" + functionName + "(" + parameter + ")";
        } else {
        	return "javascript:" + functionName;
        }
    }

    public HTMLLayoutType getHTMLLayout()
    {
        return (HTMLLayoutType)UserRequestContext.UserContext.get().getAttribute(this.getName(), "layout");
    }

    public void setHTMLLayout(final HTMLLayoutType htmlLayout)
    {
    	UserRequestContext.UserContext.get().addAttribute(this.getName(), "layout", htmlLayout);
    }

    public abstract void generateBeginHTML(UserRequestContext context, UIFormObject ownerEntity, int depth);

    public abstract void generateEndHTML(UserRequestContext context, UIFormObject ownerEntity, int depth);

    public void generateAttributes(UserRequestContext context) throws IOException
    {
    	if (attributeMap != null && !attributeMap.isEmpty())
        {
	    	String type = (String)attributeMap.get("type");
	        if (type != null)
	        {
	            String defaultCssClass = "uimaster_" + type.substring(0, 1).toLowerCase() + type.substring(1, type.length()-4);
	            if (isReadOnly() != null && isReadOnly().booleanValue())
	            {
	                defaultCssClass += "_readonly";
	            }
	            String UIStyle = (String)getAttribute("UIStyle");
	            if (UIStyle != null && !UIStyle.trim().equals("null"))
	            {
	            	if (defaultCssClass.contains(UIStyle)) {
	            		UIStyle = defaultCssClass;
	            	} else {
	            		UIStyle = defaultCssClass + " " + UIStyle;
	            	}
	                addAttribute("UIStyle", UIStyle);
	            }
	            else
	            {
	            	addAttribute("UIStyle", defaultCssClass);
	            }
	        }
	    }

        Map<String, Object> odMappingAttrs = context.getAttribute(getName());
        if (odMappingAttrs != null && !odMappingAttrs.isEmpty())
        {
            for (Iterator it = odMappingAttrs.keySet().iterator(); it.hasNext(); )
            {
                String attributeName = (String) it.next();
                Object attributeValue = odMappingAttrs.get(attributeName);
                generateAttribute(context, attributeName, attributeValue);
            }
        }

        if (attributeMap != null && !attributeMap.isEmpty())
        {
            for (Iterator it = attributeMap.keySet().iterator(); it.hasNext(); )
            {
                String attributeName = (String) it.next();
                if ("type".equals(attributeName)) {
                	continue;
                }
                if (odMappingAttrs == null || !odMappingAttrs.containsKey(attributeName))
                {
                    Object attributeValue = getAttribute(attributeName);
                    generateAttribute(context, attributeName, attributeValue);
                }
            }
        }

        if (context.hasStyle(this.getName()))
        {
            context.generateHTML(" style=\"");
            Iterator it = context.getStyle(this.getName()).entrySet().iterator();
            while (it.hasNext())
            {
                Map.Entry entry = (Map.Entry)it.next();
                String name = (String) entry.getKey();
                String value = (String) entry.getValue();
                context.generateHTML(name);
                context.generateHTML(":");
                context.generateHTML(value);
                context.generateHTML(";");
            }
            context.generateHTML("\"");
            context.getStyle(this.getName()).clear();//only used once.
        }
    }

    private String[] convertToStringArray(Object attributeValue)
    {
        if (attributeValue instanceof String)
        {
            return new String[]{(String)attributeValue};
        }
        else if (attributeValue instanceof List)
        {
            List<String> temp = (List<String>)attributeValue;
            String[] tempArray = new String[temp.size()];
            return temp.toArray(tempArray);
        }
        else
        {
            return null;
        }
    }

    /**
     * This method will replace \\ to \ to avoid html escape issue
     * @param origin
     */
    private String handleEscape(String origin)
    {
        StringBuffer sb = new StringBuffer(origin.length());
        int index1 = 0;
        int index2 = 0;
        while(true)
        {
            index1 = origin.indexOf("\\\\",index2);
            if(index1 < 0)//to the end
            {
                sb.append(origin.substring(index2));
                break;
            }
            else
            {
                sb.append(origin.substring(index2,index1));
                sb.append("\\");
                index2 = index1+2;
            }
        }
        return sb.toString();
    }

    public void generateEventListeners(UserRequestContext context) throws IOException
    {
		if (eventListenerMap != null) {
            for (Iterator<String> it = eventListenerMap.keySet().iterator();it.hasNext();) {
                String event = it.next();
                context.generateHTML(" ");
                context.generateHTML(event);
                context.generateHTML("=\"");
                context.generateHTML(getReconfigurateFunction(getEventListener(event)));
                context.generateHTML("\"");
            }
        }
    }

    private static final List<String> SKIP_ATTRS = new ArrayList<String>();
    static{
	    SKIP_ATTRS.add("referenceEntity");
	    SKIP_ATTRS.add("layout");
	    SKIP_ATTRS.add("initValidation");
	    SKIP_ATTRS.add("validator");
	    SKIP_ATTRS.add("viewPermission");
	    SKIP_ATTRS.add("editPermission");
    }
    public void generateAttribute(UserRequestContext context, String attributeName, Object attributeValue) throws IOException
    {
        if(SKIP_ATTRS.contains(attributeName))
        {
            return;
        }

        String attrValue = attributeValue == null ? "": attributeValue.toString();
        if ("visible".equals(attributeName))
        {
            if ("false".equals(attrValue))
            {
                addStyle("display", "none");
            }
        }
        else if ("editable".equals(attributeName))
        {
            if ("false".equals(attrValue))
            {
                context.generateHTML(" disabled=\"true\"");
            }
        }
        else if ("UIStyle".equals(attributeName))
        {
            if (!"null".equals(attrValue))
            {
                context.generateHTML(" class=\"");
                context.generateHTML(attrValue);
                context.generateHTML("\"");
            }
        }
        else if("reconfiguration".equals(attributeName))
        {
            context.generateHTML(" reconfiguration='");
            context.generateHTML(attrValue);
            context.generateHTML("'");
        }
        else if("regex".equals(attributeName))
        {
            context.generateHTML(" regex=\"");
            context.generateHTML(HTMLUtil.formatHtmlValue(this.handleEscape(attrValue)));
            context.generateHTML("\"");
        }
        else if (attributeName.endsWith("-msg--"))
        {
            return;
        }
        else if ("value".equals(attributeName))
        {
            if(context.isValueMask())
            {
                context.generateHTML(" ");
                context.generateHTML(attributeName);
                context.generateHTML("=\"");
                context.generateHTML(HTMLUtil.formatHtmlValue(WebConfig.getHiddenValueMask()));
                context.generateHTML("\"");
            }
        }
        else if ("readOnly".equals(attributeName) && "false".equals(attrValue))
        {
        	return;
        }
        else
        {
            context.generateHTML(" ");
            context.generateHTML(attributeName);
            context.generateHTML("=\"");
            context.generateHTML(HTMLUtil.formatHtmlValue(attrValue));
            context.generateHTML("\"");
        }
    }

    public void addHints(UserRequestContext context) {
    	if (this.getAttribute("hints") != null || this.getAttribute("hintsDesc") != null) {
    		String desc = (String)this.getAttribute("hintsDesc");
    		if (desc == null) {
    			desc = "";
    		}
        	context.generateHTML("<i class=\"ui-icon ui-icon-lightbulb uimaster-hints-icon\" alt=\""+desc+"\" onclick=\"javascript:UIMaster.getHints(this, '"+this.getAttribute("hints")+"');\"></i>");
        }
    }

    public void generateWidget(UserRequestContext context)
    {
        Object visibleValue = getAttribute("visible");
        boolean unVisible = false;
        if ( visibleValue != null )
        {
            unVisible = visibleValue.toString().equals("false");
        }
        if ( unVisible )
        {
            context.generateHTML("<span style=\"display:none;\">");
        }
        String widgetLabel = (String)removeAttribute("widgetLabel");
        if ( widgetLabel !=  null && !widgetLabel.equals("") )
        {
            String widgetLabelColor = (String)removeAttribute("widgetLabelColor");
            String widgetLabelFont = (String)removeAttribute("widgetLabelFont");

            context.generateHTML("<label");
            context.generateHTML(" id=\"" + getName() + "_widgetLabel\"");
            context.generateHTML(" style=\"");
            if ( widgetLabelColor != null )
            {
                context.generateHTML("color:");
                if (widgetLabelColor.startsWith("#"))
                {
                    context.generateHTML(widgetLabelColor);
                }
                else
                {
                    context.generateHTML("rgb(" + widgetLabelColor + ")");
                }
                context.generateHTML(";");
            }
            if ( widgetLabelFont != null )
            {
                String[] fontInfo  = widgetLabelFont.split(",");
                if (fontInfo.length != 3)
                {
                    logger.warn("widgetLabelFont error:" + widgetLabelFont);
                }
                else
                {
                    String fontStyle = "Plain".equals(fontInfo[2]) ? "normal" : fontInfo[2];
                    fontStyle += " " + fontInfo[1] + "pt";
                    fontStyle += " " + fontInfo[0];
                    context.generateHTML("font:");
                    context.generateHTML(fontStyle);
                    context.generateHTML(";");
                }
            }
            context.generateHTML("\" class=\"uimaster_widgetLabel\">");
            if ( widgetLabel.equals(" ") )
            {
                context.generateHTML(" ");
            }
            else
            {
                context.generateHTML(widgetLabel);
            }
            context.generateHTML("</label>");
        }

        if ( unVisible )
        {
            context.generateHTML("</span>");
        }
    }

    public void generateEndWidget(UserRequestContext context)
    {
    	addHints(context);
    	String dlinkInfo = (String)getAttribute("dtargetInfo");
        if (dlinkInfo != null)
        {
        	int index = dlinkInfo.lastIndexOf(";");
        	String link = dlinkInfo.substring(0, index);
        	String uipanel = dlinkInfo.substring(index + 1);
        	String comment = (String)getAttribute("dlinkInfo");
        	context.generateHTML("<span><a href=\"javascript:dPageLink('");
        	context.generateHTML(link);
        	context.generateHTML("','");
        	context.generateHTML(uipanel);
        	context.generateHTML("');\" title=\"");
        	context.generateHTML(comment);
        	context.generateHTML("\");\">");
        	context.generateHTML(comment);
        	context.generateHTML("</a></span>");
        }
    }

    public Boolean isReadOnly()
    {
    	Object v = getAttribute("readOnly");
        return v == null ? Boolean.FALSE : "true".equalsIgnoreCase(v.toString());
    }

    public void setReadOnly(boolean v)
    {
    	UserRequestContext.UserContext.get().addAttribute(this.getName(), "readOnly", v);
    }

    public boolean isVisible()
    {
        Object visible = getAttribute("visible");
        return visible == null ? true : "true".equalsIgnoreCase(visible.toString());
    }

    public void setVisible(boolean visible)
    {
        addAttribute("visible", String.valueOf(visible));
    }

    public void disableValidation()
    {
        addAttribute("validationFlag", "disabled");
    }

    public boolean isEditable()
    {
        Object editable = getAttribute("editable");
        return (editable == null || editable.toString().trim().isEmpty()) ? true : "true".equalsIgnoreCase(editable.toString());
    }

    public void setEditable(boolean editable)
    {
        addAttribute("editable", String.valueOf(editable));
    }

    public String getUIID()
    {
        return this.id;
    }

    /**
     * Whether this component can have editPermission.
     */
    public boolean isEditPermissionEnabled()
    {
        return true;
    }

    /**
     * this method uses for UI to Data operation.
     * @return
     */
	protected String getValueFromRequest(UserRequestContext context)
	{
		return context.getRequest().getParameter(this.getUIID());
	}

	/**
     * this method uses for UI to Data operation.
     * @return
     */
	protected String[] getValuesFromRequest(UserRequestContext context)
	{
		return context.getRequest().getParameterValues(this.getUIID());
	}

	public JSONObject createJsonModel(VariableEvaluator ee) throws JSONException {
		JSONObject json = new JSONObject();
	    	json.put("type", Widget.mappingAjaxWidgetName(this.getClass()));
	    	json.put("entity", this.getUIEntityName());
	    	json.put("uiid", this.getName());
	    	if (AjaxContextHelper.getAjaxContext() != null){
	    		json.put("_framePrefix", AjaxContextHelper.getAjaxContext().getFrameId());
	    	} else if (UserRequestContext.UserContext.get() != null) {
	    		json.put("_framePrefix", UserRequestContext.UserContext.get().getFrameInfo());
	    	}
	    	if (!json.has("_framePrefix")) {
	    		json.put("_framePrefix", "");
	    	}
	    	Boolean readOnly = isReadOnly();
	    	if (readOnly != null && readOnly.booleanValue()) {
	    		json.put("readOnly", true);
	    	}
	    	if (!isVisible()) {
	    		json.put("visible", false);
	    	}

	    	JSONObject attrJson = null;
	    	if (this.attributeMap != null) {
	    		attrJson = new JSONObject();
	    		// only get value for json model;
	    		if (this.attributeMap.containsKey("value")) {
	    			attrJson.put("value", this.attributeMap.get("value"));
	    		}
	    		if (this.attributeMap.containsKey("values")) {
	    			attrJson.put("values", this.attributeMap.get("values"));
	    		}
	    	}
	    	if (UserRequestContext.UserContext.get() != null
	    			&& UserRequestContext.UserContext.get().hasAttribute(this.getName())) {
	    		if (attrJson == null) {
	    			attrJson = new JSONObject();
	    		}
	    		Map<String, Object> dyanmicValues = UserRequestContext.UserContext.get().getAttribute(this.getName());
	    		Set<Map.Entry<String, Object>> entries = dyanmicValues.entrySet();
	    		for (Map.Entry<String, Object> entry : entries) {
	    			if (entry.getValue() != null) {
	    				attrJson.put(entry.getKey(), entry.getValue());
	    			}
	    		}
	    		if (attrJson.has("layout")) {
	    			attrJson.remove("layout");
	    		}
	    		if (attrJson.has("UIStyle")) {
	    			attrJson.remove("UIStyle");
	    		}
	    		if (attrJson.has("readOnly")) {
	    			attrJson.remove("readOnly");
	    		}
	    		if (attrJson.has("createdRefEntities")) {
	    			//remove HTML pre-next panel.
	    			attrJson.remove("createdRefEntities");
	    		}
	    		json.put("attrMap", attrJson);
	    	}
	    	if (UserRequestContext.UserContext.get() != null
	    			&& UserRequestContext.UserContext.get().hasStyle(this.getName())) {
	    		json.put("styleMap", new JSONObject(new HashMap(UserRequestContext.UserContext.get().getStyle(this.getName()))));
	    	}
	    	return json;
	}

	public String toString() {
		return this.getName() + "[" + this.getClass().getSimpleName() + "]" + this.hashCode();
	}
}


text:
// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
// Original code is licensed as follows:

#include "xfa/src/fxbarcode/barcode.h"
#include "BC_QRCoderECB.h"
CBC_QRCoderECB::CBC_QRCoderECB(int32_t count, int32_t dataCodeWords) {
  m_dataCodeWords = dataCodeWords;
  m_count = count;
}
CBC_QRCoderECB::~CBC_QRCoderECB() {}
int32_t CBC_QRCoderECB::GetCount() {
  return m_count;
}
int32_t CBC_QRCoderECB::GetDataCodeWords() {
  return m_dataCodeWords;
}


text:
import { Policies } from '../../index';
const { EmberSetHeader } = Policies;

export default new EmberSetHeader();


text:
import { Component, OnInit } from '@angular/core';
import { NavController} from 'ionic-angular';

@Component({
    templateUrl: 'build/pages/lists/inset.html',
})
export class ListInsetPage implements OnInit {

    constructor(private nav: NavController) {
    }

    ngOnInit() {

    }

}


text:
{% extends 'categories/management/content.html' %}

{% from 'forms/_form.html' import form_rows, form_header, form_footer, form_fieldset %}

{% block title %}
    {% trans %}Category protection{% endtrans %}
{% endblock %}

{% block content %}
    {{ form_header(form) }}
    {{ form_rows(form, skip=form._event_creation_fields,
                 widget_attrs={'own_no_access_contact': {'placeholder': category.no_access_contact}}) }}
    {% call form_fieldset(_('Event creation settings')) %}
        {{ form_rows(form, fields=form._event_creation_fields) }}
    {% endcall %}
    {% call form_footer(form) %}
        <input class="i-button big highlight"
               type="submit"
               value="{% trans %}Save{% endtrans %}"
               data-disabled-until-change
               data-save-reminder>
    {% endcall %}

    <script>
        (function() {
            'use strict';

            var eventCreationRestrictedField = $('#{{ form.event_creation_restricted.id }}');
            eventCreationRestrictedField.on('change', function() {
                toggleAclField($('#{{ form.event_creators.id }}'), !this.checked);
            });

            _.defer(function() {
                eventCreationRestrictedField.trigger('change');
            });
        })();
    </script>
{% endblock %}


text:
    #include "hwc2/hwc2_glfw.h"
#elif ENABLE_ANGLE
    #include "hwc2/hwc2_angle.h"
#endif

namespace android {
namespace hardware {
namespace graphics {
namespace composer {
namespace V2_1 {

::android::sp<IComposer>  defaultComposer()
{
#if ENABLE_GLFW
    return new ComposerGLFW();
#elif ENABLE_ANGLE
    return new ComposerAngle();
#else
    return new ComposerDefault();
#endif
}

}  // namespace V2_1
}  // namespace composer
}  // namespace graphics
}  // namespace hardware
}  // namespace android


text:
@charset "UTF-8";

.fileinput-button {
  position: relative;
  overflow: hidden;
  float: left;
  margin-right: 4px;
}
.fileinput-button input {
  position: absolute;
  top: 0;
  right: 0;
  margin: 0;
  opacity: 0;
  filter: alpha(opacity=0);
  transform: translate(-300px, 0) scale(4);
  font-size: 23px;
  direction: ltr;
  cursor: pointer;
}
.fileupload-buttonbar .btn,
.fileupload-buttonbar .toggle {
  margin-bottom: 5px;
}
.files .progress {
  width: 200px;
}
.progress-animated .bar {
  background: url(../img/progressbar.gif) !important;
  filter: none;
}
.fileupload-loading {
  position: absolute;
  left: 50%;
  width: 128px;
  height: 128px;
  background: url(../img/loading.gif) center no-repeat;
  display: none;
}
.fileupload-processing .fileupload-loading {
  display: block;
}

/* Fix for IE 6: */
* html .fileinput-button {
  line-height: 24px;
  margin: 1px -3px 0 0;
}

/* Fix for IE 7: */
* + html .fileinput-button {
  padding: 2px 15px;
  margin: 1px 0 0 0;
}

@media (max-width: 767px) {
  .fileupload-buttonbar .toggle,
  .files .toggle,
  .files .btn span {
    display: none;
  }
  .files .preview * {
    width: 40px;
  }
  .files .name * {
    width: 80px;
    display: inline-block;
    word-wrap: break-word;
  }
  .files .progress {
    width: 20px;
  }
}

/*sh*/
.progress {
    background-color: #F7F7F7;
    background-image: linear-gradient(to bottom, #F5F5F5, #F9F9F9);
    background-repeat: repeat-x;
    border-radius: 4px 4px 4px 4px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1) inset;
    height: 20px;
    margin-bottom: 20px;
    overflow: hidden;
}

.progress-success.progress-striped .bar, .progress-striped .bar-success {
    background-color: #62C462;
    background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
}
.progress.active .bar {
    animation: 2s linear 0s normal none infinite progress-bar-stripes;
}
.progress-success .bar, .progress .bar-success {
    background-color: #5EB95E;
    background-image: linear-gradient(to bottom, #62C462, #57A957);
    background-repeat: repeat-x;
}


text:
package raven

// http://sentry.readthedocs.org/en/latest/developer/interfaces/index.html#sentry.interfaces.Message
type Message struct {
	// Required
	Message string `json:"message"`

	// Optional
	Params []interface{} `json:"params,omitempty"`
}

func (m *Message) Class() string { return "logentry" }

// http://sentry.readthedocs.org/en/latest/developer/interfaces/index.html#sentry.interfaces.Template
type Template struct {
	// Required
	Filename    string `json:"filename"`
	Lineno      int    `json:"lineno"`
	ContextLine string `json:"context_line"`

	// Optional
	PreContext   []string `json:"pre_context,omitempty"`
	PostContext  []string `json:"post_context,omitempty"`
	AbsolutePath string   `json:"abs_path,omitempty"`
}

func (t *Template) Class() string { return "template" }

// http://sentry.readthedocs.org/en/latest/developer/interfaces/index.html#sentry.interfaces.User
type User struct {
	// All fields are optional
	ID       string `json:"id,omitempty"`
	Username string `json:"username,omitempty"`
	Email    string `json:"email,omitempty"`
	IP       string `json:"ip_address,omitempty"`
}

func (h *User) Class() string { return "user" }

// http://sentry.readthedocs.org/en/latest/developer/interfaces/index.html#sentry.interfaces.Query
type Query struct {
	// Required
	Query string `json:"query"`

	// Optional
	Engine string `json:"engine,omitempty"`
}

func (q *Query) Class() string { return "query" }


text:
export {default as isBodyField} from "./util/isField"
export {default as isBodyFile} from "./util/isFile"

export * from "./BodyField"
export * from "./BodyFile"
export * from "./Body"
export * from "./parse"


text:
``eps_sdev``
--------------------

- Available in: Naïve-Bayes
- Hyperparameter: yes

Description
~~~~~~~~~~~

This option specifies the threshold value for standard deviation. If this threshold is not met, then the ``min_sdev`` value is used.

This option is not set by default. When specified, this value must be greater than 0.

Related Parameters
~~~~~~~~~~~~~~~~~~

- `min_sdev <min_sdev.html>`__

Example
~~~~~~~

.. tabs::
   .. code-tab:: r R

        library(h2o)
        h2o.init()

        # import the cars dataset
        cars <- h2o.importFile("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv")

        # Specify model-building exercise (1:binomial, 2:multinomial)
        problem <- sample(1:2, 1)

        # Specify response column based on predictor value and problem type
        predictors <- c("displacement","power","weight","acceleration","year")
        if ( problem == 1 ) { response_col <- "economy_20mpg" } else { response_col <- "cylinders" }

        # Convert the response column to a factor
        cars[, response_col] <- as.factor(cars[, response_col])

        # Specify model parameters
        laplace <- c(1)
        min_sdev <- c(0.1)
        eps_sdev <- c(0.5)

        # Build the model
        cars_naivebayes <- h2o.naiveBayes(x = predictors, y = response_col, training_frame = cars,
                                          eps_sdev = eps_sdev, min_sdev = min_sdev, laplace = laplace)
        print(cars_naivebayes)

        # Specify grid search parameters
        grid_space <- list()
        grid_space$laplace <- c(1, 2)
        grid_space$min_sdev <- c(0.1, 0.2)
        grid_space$eps_sdev <- c(0.5, 0.6)

        # Specify response column based on predictor value and problem type
        predictors <- c("displacement","power","weight","acceleration","year")
        if ( problem == 1 ) { response_col <- "economy_20mpg"} else { response_col <- "cylinders" }

        # Convert the response column to a factor
        cars[, response_col] <- as.factor(cars[, response_col])

        # Construct the grid of naive bayes models
        cars_naivebayes_grid <- h2o.grid("naivebayes", grid_id = "naiveBayes_grid_cars_test",
                                         x = predictors, y = response_col, training_frame = cars,
                                         hyper_params = grid_space)
        print(cars_naivebayes_grid)

   .. code-tab:: python

        import h2o
        h2o.init()
        import random
        from h2o.estimators.naive_bayes import H2ONaiveBayesEstimator
        from h2o.grid.grid_search import H2OGridSearch

        # import the cars dataset:
        cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv")

        # Specify model-building exercise (1:binomial, 2:multinomial)
        problem = random.sample(["binomial","multinomial"],1)

        # Specify response column based on predictor value and problem type
        predictors = ["displacement","power","weight","acceleration","year"]
        if problem == "binomial":
            response_col = "economy_20mpg"
        else:
            response_col = "cylinders"

        # Convert the response column to a factor
        cars[response_col] = cars[response_col].asfactor()

        # Train the model
        cars_nb = H2ONaiveBayesEstimator(min_sdev=0.1, eps_sdev=0.5, seed=1234)
        cars_nb.train(x=predictors, y=response_col, training_frame=cars)
        cars_nb.show()

        # Predict on training data
        cars_pred = cars_nb.predict(cars)
        cars_pred.head()

        # Specify grid search parameters
        hyper_params = {'laplace':[1,2], 'min_sdev':[0.1,0.2], 'eps_sdev':[0.5,0.6]}

        # Construct the grid of naive bayes models
        cars_nb = H2ONaiveBayesEstimator(seed = 1234)
        cars_grid = H2OGridSearch(model=cars_nb, hyper_params=hyper_params)

        # Train using the grid
        cars_grid.train(x=predictors, y=response_col, training_frame=cars)
        cars_grid.show()


text:
<!doctype html>

  <title>core-layout-grid example</title>

  <link rel="import" href="core-layout-grid.html">

  <grid-test></grid-test>

  <polymer-element name="grid-test" on-tap="{{rotate}}">
  <template>

    <core-layout-grid nodes="{{nodes}}" layout="{{layout}}"></core-layout-grid>

    <panel id="toolbar">toolbar (click to rotate)</panel>
    <panel id="sidebar">sidebar</panel>
    <panel id="workspace">workspace</panel>
    <panel id="outputToolbar">otherbar</panel>
    <panel id="output">
      output

Documentation

Verbiage

In backbone record integer LED amplified internet protocol a extension reflective.
      Array kilohertz LED. Wavelength extension patch supporting wave an by prompt.

    </panel>

  </template>

  </polymer-element>


text:
package org.elasticsearch.action.search;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.type.ParsedScrollId;
import org.elasticsearch.action.search.type.TransportSearchScrollQueryAndFetchAction;
import org.elasticsearch.action.search.type.TransportSearchScrollQueryThenFetchAction;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.HandledTransportAction;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;

import static org.elasticsearch.action.search.type.ParsedScrollId.QUERY_AND_FETCH_TYPE;
import static org.elasticsearch.action.search.type.ParsedScrollId.QUERY_THEN_FETCH_TYPE;
import static org.elasticsearch.action.search.type.TransportSearchHelper.parseScrollId;

/**
 *
 */
public class TransportSearchScrollAction extends HandledTransportAction<SearchScrollRequest, SearchResponse> {

    private final TransportSearchScrollQueryThenFetchAction queryThenFetchAction;
    private final TransportSearchScrollQueryAndFetchAction queryAndFetchAction;

    @Inject
    public TransportSearchScrollAction(Settings settings, ThreadPool threadPool, TransportService transportService,
                                       TransportSearchScrollQueryThenFetchAction queryThenFetchAction,
                                       TransportSearchScrollQueryAndFetchAction queryAndFetchAction,
                                       ActionFilters actionFilters,
                                       IndexNameExpressionResolver indexNameExpressionResolver) {
        super(settings, SearchScrollAction.NAME, threadPool, transportService, actionFilters, indexNameExpressionResolver, SearchScrollRequest::new);
        this.queryThenFetchAction = queryThenFetchAction;
        this.queryAndFetchAction = queryAndFetchAction;
    }

    @Override
    protected void doExecute(SearchScrollRequest request, ActionListener<SearchResponse> listener) {
        try {
            ParsedScrollId scrollId = parseScrollId(request.scrollId());
            if (scrollId.getType().equals(QUERY_THEN_FETCH_TYPE)) {
                queryThenFetchAction.execute(request, scrollId, listener);
            } else if (scrollId.getType().equals(QUERY_AND_FETCH_TYPE)) {
                queryAndFetchAction.execute(request, scrollId, listener);
            } else {
                throw new IllegalArgumentException("Scroll id type [" + scrollId.getType() + "] unrecognized");
            }
        } catch (Throwable e) {
            listener.onFailure(e);
        }
    }
}


text:
package org.kie.workbench.common.stunner.bpmn.client.shape.view.handler;

import org.kie.workbench.common.stunner.bpmn.definition.BaseCatchingIntermediateEvent;
import org.kie.workbench.common.stunner.bpmn.definition.IntermediateConditionalEvent;
import org.kie.workbench.common.stunner.bpmn.definition.IntermediateEscalationEvent;
import org.kie.workbench.common.stunner.bpmn.definition.IntermediateMessageEventCatching;
import org.kie.workbench.common.stunner.bpmn.definition.IntermediateSignalEventCatching;
import org.kie.workbench.common.stunner.bpmn.definition.IntermediateTimerEvent;
import org.kie.workbench.common.stunner.core.client.shape.view.ShapeViewHandler;
import org.kie.workbench.common.stunner.svg.client.shape.view.SVGShapeView;
import org.kie.workbench.common.stunner.svg.client.shape.view.SVGViewUtils;

public class EventCancelActivityViewHandler
        implements ShapeViewHandler<BaseCatchingIntermediateEvent, SVGShapeView<?>> {

    // The id for the circle to change in the SVG file.
    static final String ID_INTERMEDIATE = "intermediate";

    @Override
    public void handle(final BaseCatchingIntermediateEvent bean,
                       final SVGShapeView<?> view) {
        Boolean isCancelActivity = null;
        if (bean instanceof IntermediateSignalEventCatching) {
            isCancelActivity = ((IntermediateSignalEventCatching) bean).getExecutionSet().getCancelActivity().getValue();
        } else if (bean instanceof IntermediateTimerEvent) {
            isCancelActivity = ((IntermediateTimerEvent) bean).getExecutionSet().getCancelActivity().getValue();
        } else if (bean instanceof IntermediateMessageEventCatching) {
            isCancelActivity = ((IntermediateMessageEventCatching) bean).getExecutionSet().getCancelActivity().getValue();
        } else if (bean instanceof IntermediateConditionalEvent) {
            isCancelActivity = ((IntermediateConditionalEvent) bean).getExecutionSet().getCancelActivity().getValue();
        } else if (bean instanceof IntermediateEscalationEvent) {
            isCancelActivity = ((IntermediateEscalationEvent) bean).getExecutionSet().getCancelActivity().getValue();
        }
        if (null != isCancelActivity) {
            // Cancel -> Normal
            // NO Cancel -> dash
            final double fillAlpha = isCancelActivity ? 1 : 0;
            final double strokeAlpha = isCancelActivity ? 0 : 1;
            SVGViewUtils.getPrimitive(view,
                                      ID_INTERMEDIATE)
                    .ifPresent(p -> p.get().setFillAlpha(fillAlpha).setStrokeAlpha(strokeAlpha));
        }
    }
}


text:
[![Stories in Ready](https://badge.waffle.io/kinkstruction/kinkstruction.png?label=ready&title=Ready)](https://waffle.io/kinkstruction/kinkstruction)
# Kinkstruction

## Important Note

Before we go any further, you should know that this code is for an adult website. There is--and will be--no obscene or pornagraphic content within the repository itself. However, if you're under 18 years of age or are offended by viewing the code behind a site that allows graphic descriptions of sexual acts and BDSM activities, then you should probably leave now.

## So, what is this, anyway?

The idea behind Kinkstruction is to fill a specific niche within BDSM: task tracking and some social networking around the tracking of said tasks (presumably, the tasks would be given from a dominant to a submissive, but that need not be the case). Doing this can serve several purposes, including:

* "Spicing up" long distance BDSM relationships.

* Sharing tasks with friends or with everyone on Kinkstruction, allowing for commentary, cheerleading, or even humiliation. (Note that no information about users or tasks will *ever* be viewable by web crawlers or anyone who does not have an account.)

* By assigning points to tasks, kinkstruction provides a pathway to [gamification](http://en.wikipedia.org/wiki/Gamification) of BDSM-oriented tasks.

What is now the main idea behind Kinkstruction started as a much simpler web application for keeping track of orgasms and tease & denial sessions.

## Also, did I mention that it's free?

Not only free to join and use, but the software is open source (you're looking at the code repository *right now*)!

## Interesting...will it be able to do anything else?

There are several ideas in the queue (some more half-baked than others), including:

* Tasks that are dependent upon how users vote on a poll attached to the task (eg voting on a type of punishment, adding one day of chastity for every upvote, etc).

* Various games of chance that submissives can use for gambling their points.

* Repeated writing tasks--e.g. writing "I will be a good boy for Mistress" ten times. Without the use of backspace or repositioning the cursor. Point penalties apply for each mistake.

* Tasks attached to timers.

* Tasks that are built upon events attached to timers. This would allow Kinkstruction to compete with milovana.com (NSFW link).

* And several more. Take a look at [the issues](https://github.com/kinkstruction/kinkstruction/issues) for other ideas.

## Neat! Can I contribute?

Oh dear gods, *yes*! Pull requests are more than welcome. Besides creating an issue, I'm also available via email (`admin [at] kinkstruction [dot] com`).

## When can I sign up and start using the site?

I'm still working on an MVP (minimum viable product) right now. However, I have a day job, so I can't hack away at Kinkstruction as much as I'd like. I'm roughly aiming to have the MVP up and running by ~~September 15~~ the end of September (that's a rough ETA, however).


text:
<?php

declare(strict_types=1);

namespace Zephir\Operators\Other;

use ReflectionClass;
use ReflectionException;
use Zephir\Classes\Entry;
use Zephir\CompilationContext;
use Zephir\CompiledExpression;
use Zephir\Exception;
use Zephir\Exception\CompilerException;
use Zephir\Expression;
use Zephir\MethodCall;
use Zephir\Operators\AbstractOperator;

use function Zephir\escape_class;

/**
 * Creates a new instance of a class
 */
class NewInstanceOperator extends AbstractOperator
{
    protected bool $literalOnly = false;

    /**
     * Creates a new instance.
     *
     * @param array              $expression
     * @param CompilationContext $compilationContext
     *
     * @return CompiledExpression
     *
     * @throws ReflectionException
     * @throws Exception
     */
    public function compile(array $expression, CompilationContext $compilationContext): CompiledExpression
    {
        $codePrinter = $compilationContext->codePrinter;

        /**
         * Resolves the symbol that expects the value
         */
        $this->literalOnly = false;
        $symbolVariable = $this->getExpectedNonLiteral($compilationContext, $expression);
        if (!$symbolVariable->isVariable()) {
            throw new CompilerException('Objects can only be instantiated into dynamic variables', $expression);
        }

        if ($symbolVariable->isLocalOnly()) {
            throw new CompilerException('Cannot use non-heap variable to store new instance', $expression);
        }

        if ('return_value' !== $symbolVariable->getName()) {
            if ($symbolVariable->hasDifferentDynamicType(['unknown', 'undefined', 'object', 'null'])) {
                $compilationContext->logger->warning(
                    'Possible attempt to use non-object in "new" operator',
                    ['non-valid-new', $expression]
                );
            }
        }

        /**
         * Mark variables as dynamic objects
         */
        $symbolVariable->setDynamicTypes('object');

        $dynamic = false;
        if ('self' == $expression['class'] || 'static' == $expression['class']) {
            $className = $compilationContext->classDefinition->getCompleteName();
        } else {
            $className = $expression['class'];
            $dynamic = $expression['dynamic'];
            if (!$dynamic) {
                $className = $compilationContext->getFullName($expression['class']);
            }
        }

        if (!$className) {
            throw new CompilerException('A class name is required to instantiate the object', $expression);
        }

        /**
         * stdclass doesn't have constructors.
         */
        $lowerClassName = strtolower($className);
        $isStdClass = 'stdclass' === $lowerClassName || '\stdclass' === $lowerClassName;

        if ($isStdClass) {
            if (isset($expression['parameters']) && \count($expression['parameters']) > 0) {
                throw new CompilerException('stdclass does not receive parameters in its constructor', $expression);
            }

            $compilationContext->backend->initObject($symbolVariable, null, $compilationContext);
            $symbolVariable->setClassTypes('stdclass');
        } else {
            $classDefinition = false;
            if ($compilationContext->compiler->isClass($className)) {
                $classDefinition = $compilationContext->compiler->getClassDefinition($className);
            }

            /**
             * Classes inside the same extension
             */
            if ($classDefinition) {
                $compilationContext->backend->initObject($symbolVariable, $classDefinition->getClassEntry($compilationContext), $compilationContext);
                $symbolVariable->setClassTypes($className);
                $symbolVariable->setAssociatedClass($classDefinition);
            } else {
                /**
                 * Classes outside the extension
                 */
                if ($dynamic) {
                    $classNameVariable = $compilationContext->symbolTable->getVariableForRead($className, $compilationContext, $expression);
                    if ($classNameVariable->isNotVariableAndString()) {
                        throw new CompilerException('Only dynamic/string variables can be used in new operator. '.$classNameVariable->getName(), $expression);
                    }

                    /**
                     * Use a safe string version of the variable to avoid segfaults
                     */
                    $compilationContext->headersManager->add('kernel/object');
                    $safeSymbolVariable = $compilationContext->symbolTable->getTempVariable('variable', $compilationContext);
                    $safeSymbolVariable->setMustInitNull(true);
                    $safeSymbolVariable->setIsInitialized(true, $compilationContext);
                    $safeSymbolVariable->increaseUses();
                    $safeSymbol = $compilationContext->backend->getVariableCode($safeSymbolVariable);
                    $classNameSymbol = $compilationContext->backend->getVariableCode($classNameVariable);

                    $compilationContext->codePrinter->output('zephir_fetch_safe_class('.$safeSymbol.', '.$classNameSymbol.');');
                    $classNameToFetch = 'Z_STRVAL_P('.$safeSymbol.'), Z_STRLEN_P('.$safeSymbol.')';
                    $zendClassEntry = $compilationContext->cacheManager->getClassEntryCache()->get($classNameToFetch, true, $compilationContext);
                    $classEntry = $zendClassEntry->getName();

                    $compilationContext->codePrinter->output('if(!'.$classEntry.') {');
                    $compilationContext->codePrinter->increaseLevel();
                    $compilationContext->codePrinter->output('RETURN_MM_NULL();');
                    $compilationContext->codePrinter->decreaseLevel();
                    $compilationContext->codePrinter->output('}');
                } else {
                    if (!class_exists($className, false)) {
                        $compilationContext->logger->warning(
                            'Class "'.$className.'" does not exist at compile time',
                            ['nonexistent-class', $expression]
                        );
                        $classNameToFetch = 'SL("'.escape_class($className).'")';

                        $zendClassEntry = $compilationContext->cacheManager->getClassEntryCache()->get($classNameToFetch, false, $compilationContext);
                        $classEntry = $zendClassEntry->getName();
                    } else {
                        $reflectionClass = new ReflectionClass($className);
                        if ($reflectionClass->isInterface()) {
                            throw new CompilerException('Interfaces cannot be instantiated', $expression);
                        }

                        if (method_exists($reflectionClass, 'isTrait') && $reflectionClass->isTrait()) {
                            throw new CompilerException('Traits cannot be instantiated', $expression);
                        }

                        $classEntry = (new Entry($expression['class'], $compilationContext))->get();
                        $symbolVariable->setAssociatedClass($reflectionClass);
                    }

                    $symbolVariable->setClassTypes($className);
                }

                $compilationContext->backend->initObject($symbolVariable, $classEntry, $compilationContext);
            }
        }

        /**
         * Mark variable initialized
         */
        $symbolVariable->setIsInitialized(true, $compilationContext);

        /**
         * Don't check the constructor for stdclass instances
         */
        if ($isStdClass) {
            return new CompiledExpression('variable', $symbolVariable->getRealName(), $expression);
        }

        /**
         * Call the constructor
         * For classes in the same extension we check if the class does implement a constructor
         * For external classes we always assume the class does implement a constructor.
         */
        $callConstructor = false;
        if ($compilationContext->compiler->isClass($className)) {
            $classDefinition = $compilationContext->compiler->getClassDefinition($className);

            if ('class' != $classDefinition->getType()) {
                throw new CompilerException('Only classes can be instantiated', $expression);
            }

            $callConstructor = $classDefinition->hasMethod('__construct');
        } else {
            if ($compilationContext->compiler->isBundledClass($className)) {
                $classDefinition = $compilationContext->compiler->getInternalClassDefinition($className);
                $callConstructor = $classDefinition->hasMethod('__construct');
            }
        }

        /* TODO: use the MethodBuilder here */
        if (isset($expression['parameters'])) {
            $callExpr = new Expression([
                'variable' => ['type' => 'variable', 'value' => $symbolVariable->getRealName()],
                'name' => '__construct',
                'parameters' => $expression['parameters'],
                'call-type' => MethodCall::CALL_NORMAL,
                'file' => $expression['file'],
                'line' => $expression['line'],
                'char' => $expression['char'],
                'check' => $callConstructor,
            ]);
        } else {
            $callExpr = new Expression([
                'variable' => ['type' => 'variable', 'value' => $symbolVariable->getRealName()],
                'name' => '__construct',
                'call-type' => MethodCall::CALL_NORMAL,
                'file' => $expression['file'],
                'line' => $expression['line'],
                'char' => $expression['char'],
                'check' => $callConstructor,
            ]);
        }

        /**
         * If we are certain that there is a constructor we call it, otherwise we checked it at runtime.
         */
        if ($callConstructor) {
            $methodCall = new MethodCall();
            $callExpr->setExpectReturn(false);
            $methodCall->compile($callExpr, $compilationContext);
        } else {
            $compilationContext->headersManager->add('kernel/fcall');

            /* TODO:, generate the code using builders */
            $compilationContext->backend->checkConstructor($symbolVariable, $compilationContext);
            $codePrinter->increaseLevel();

            $methodCall = new MethodCall();
            $callExpr->setExpectReturn(false);
            $methodCall->compile($callExpr, $compilationContext);

            $codePrinter->decreaseLevel();
            $codePrinter->output('}');
            $codePrinter->outputBlankLine();
        }

        return new CompiledExpression('variable', $symbolVariable->getRealName(), $expression);
    }
}


text:
Ext.define('app.view.main.MainModel', {
    extend: 'Ext.app.ViewModel'
});


text:
using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using MQTTnet.Formatter;
using MQTTnet.Packets;

namespace MQTTnet.Adapter
{
    public interface IMqttChannelAdapter : IDisposable
    {
        string Endpoint { get; }

        bool IsSecureConnection { get; }

        X509Certificate2 ClientCertificate { get; }

        MqttPacketFormatterAdapter PacketFormatterAdapter { get; }

        long BytesSent { get; }

        long BytesReceived { get; }

        bool IsReadingPacket { get; }

        Task ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken);

        Task DisconnectAsync(TimeSpan timeout, CancellationToken cancellationToken);

        Task SendPacketAsync(MqttBasePacket packet, CancellationToken cancellationToken);

        Task<MqttBasePacket> ReceivePacketAsync(CancellationToken cancellationToken);

        void ResetStatistics();
    }
}


text:
<?php namespace Mana\OAuth2\Repository;

use Mana\OAuth2\Model\Session;
use Mana\OAuth2\Model\SessionRedirect;
use Mana\OAuth2\Model\SessionAuthcode;
use Mana\OAuth2\Model\SessionTokenScope;
use Mana\OAuth2\Model\SessionAccessToken;
use Mana\OAuth2\Model\SessionRefreshToken;
use Mana\OAuth2\Model\SessionAuthcodeScope;
use League\OAuth2\Server\Storage\SessionInterface;

class SessionRepository implements SessionInterface
{
    /**
     * Create a new session
     *
     * @param  string $clientId  The client ID
     * @param  string $ownerType The type of the session owner (e.g. "user")
     * @param  string $ownerId   The ID of the session owner (e.g. "123")
     * @return int               The session ID
     */
    public function createSession($clientId, $ownerType, $ownerId)
    {
        $session = Session::create([
            'client_id'  => $clientId,
            'owner_type' => $ownerType,
            'owner_id'   => $ownerId,
        ]);

        return $session->id;
    }

    /**
     * Delete a session
     *
     * @param  string $clientId  The client ID
     * @param  string $ownerType The type of the session owner (e.g. "user")
     * @param  string $ownerId   The ID of the session owner (e.g. "123")
     * @return void
     */
    public function deleteSession($clientId, $ownerType, $ownerId)
    {
        Session::where('client_id', $clientId)
            ->where('owner_type', $ownerType)
            ->where('owner_id', $ownerId)
            ->delete();
    }

    /**
     * Associate a redirect URI with a session
     *
     * @param  int    $sessionId   The session ID
     * @param  string $redirectUri The redirect URI
     * @return void
     */
    public function associateRedirectUri($sessionId, $redirectUri)
    {
        SessionRedirect::create([
            'session_id'   => $sessionId,
            'redirect_uri' => $redirectUri,
        ]);
    }

    /**
     * Associate an access token with a session
     *
     * @param  int    $sessionId   The session ID
     * @param  string $accessToken The access token
     * @param  int    $expireTime  Unix timestamp of the access token expiry time
     * @return void
     */
    public function associateAccessToken($sessionId, $accessToken, $expireTime)
    {
        SessionAccessToken::create([
            'session_id'           => $sessionId,
            'access_token'         => $accessToken,
            'access_token_expires' => $expireTime,
        ]);
    }

    /**
     * Associate a refresh token with a session
     *
     * @param  int    $accessTokenId The access token ID
     * @param  string $refreshToken  The refresh token
     * @param  int    $expireTime    Unix timestamp of the refresh token expiry time
     * @param  string $clientId      The client ID
     * @return void
     */
    public function associateRefreshToken($accessTokenId, $refreshToken, $expireTime, $clientId)
    {
        SessionRefreshToken::create([
            'session_access_token_id' => $accessTokenId,
            'refresh_token'           => $refreshToken,
            'refresh_token_expires'   => $expireTime,
            'client_id'               => $clientId,
        ]);
    }

    /**
     * Assocate an authorization code with a session
     *
     * @param  int    $sessionId  The session ID
     * @param  string $authCode   The authorization code
     * @param  int    $expireTime Unix timestamp of the access token expiry time
     * @return int                The auth code ID
     */
    public function associateAuthCode($sessionId, $authCode, $expireTime)
    {
        $code = SessionAuthcode::create([
            'session_id'        => $sessionId,
            'auth_code'         => $authCode,
            'auth_code_expires' => $expireTime,
        ]);

        return $code->id;
    }

    /**
     * Remove an associated authorization token from a session
     *
     * @param  int    $sessionId   The session ID
     * @return void
     */
    public function removeAuthCode($sessionId)
    {
        SessionAuthcode::where('session_id', $sessionId)->delete();
    }

    /**
     * Validate an authorization code
     *
     * @param  string     $clientId    The client ID
     * @param  string     $redirectUri The redirect URI
     * @param  string     $authCode    The authorization code
     * @return array|bool              False if invalid or array as above
     */
    public function validateAuthCode($clientId, $redirectUri, $authCode)
    {
        $code = SessionAuthcode::join('oauth_session_authcodes', 'oauth_session_authcodes.session_id', '=', 'oauth_sessions.id')
            ->join('oauth_session_redirects', 'oauth_session_redirects.session_id', '=', 'oauth_sessions.id ')
            ->select('oauth_sessions.id AS session_id', 'oauth_session_authcodes.id AS authcode_id')
            ->where('oauth_sessions.client_id', $clientId)
            ->where('oauth_session_authcodes.auth_code', $authCode)
            ->where('oauth_session_redirects.redirect_uri', $redirectUri)
            ->first();

        return is_null($code) ? false : $code->toArray();
    }

    /**
     * Validate an access token
     *
     * @param  string     $accessToken The access token
     * @return array|bool              False if invalid or an array as above
     */
    public function validateAccessToken($accessToken)
    {
        /** @var SessionAccessToken|null $token */
        $token = SessionAccessToken::join('oauth_sessions', 'oauth_sessions.id', '=', 'oauth_session_access_tokens.session_id')
            ->select('oauth_session_access_tokens.session_id', 'oauth_sessions.client_id', 'oauth_sessions.owner_id', 'oauth_sessions.owner_type')
            ->where('oauth_session_access_tokens.access_token', $accessToken)
            ->where('oauth_session_access_tokens.access_token_expires', '>=', time())
            ->first();

        return $token ? $token->toArray() : false;
    }

    /**
     * Removes a refresh token
     *
     * @param  string $refreshToken The refresh token to be removed
     * @return void
     */
    public function removeRefreshToken($refreshToken)
    {
        SessionRefreshToken::where('refresh_token', $refreshToken)->delete();
    }

    /**
     * Validate a refresh token
     *
     * @param  string   $refreshToken The access token
     * @param  string   $clientId     The client ID
     * @return int|bool               The ID of the access token the refresh token is linked to (or false if invalid)
     */
    public function validateRefreshToken($refreshToken, $clientId)
    {
        /** @var SessionRefreshToken|null $token */
        $token = SessionRefreshToken::select('session_access_token_id')
            ->where('refresh_token', $refreshToken)
            ->where('client_id', $clientId)
            ->where('refresh_token_expires', time())
            ->first();

        return $token ? $token->session_access_token_id : false;
    }

    /**
     * Get an access token by ID
     *
     * @param  int    $accessTokenId The access token ID
     * @return array
     */
    public function getAccessToken($accessTokenId)
    {
        /** @var SessionAccessToken $token */
        $token = SessionAccessToken::where('id', $accessTokenId)->first();

        return $token ? $token->toArray() : false;
    }

    /**
     * Associate scopes with an auth code (bound to the session)
     *
     * @param  int $authCodeId The auth code ID
     * @param  int $scopeId    The scope ID
     * @return void
     */
    public function associateAuthCodeScope($authCodeId, $scopeId)
    {
        SessionAuthcodeScope::create([
            'session_authcode_id' => $authCodeId,
            'scope_id'            => $scopeId,
        ]);
    }

    /**
     * Get the scopes associated with an auth code
     *
     * @param  int   $oauthSessionAuthCodeId The session ID
     * @return array
     */
    public function getAuthCodeScopes($oauthSessionAuthCodeId)
    {
        /** @var \Illuminate\Database\Eloquent\Collection $scopes */
        $scopes = SessionAuthcodeScope::select('scope_id')
            ->where('session_authcode_id', $oauthSessionAuthCodeId)
            ->get();

        return $scopes->all();
    }

    /**
     * Associate a scope with an access token
     *
     * @param  int    $accessTokenId The ID of the access token
     * @param  int    $scopeId       The ID of the scope
     * @return void
     */
    public function associateScope($accessTokenId, $scopeId)
    {
        SessionTokenScope::create([
            'session_access_token_id' => $accessTokenId,
            'scope_id'                => $scopeId,
        ]);
    }

    /**
     * Get all associated access tokens for an access token
     *
     * @param  string $accessToken The access token
     * @return array
     */
    public function getScopes($accessToken)
    {
        /** @var \Illuminate\Database\Eloquent\Collection $scopes */
        $scopes = SessionTokenScope::join('oauth_session_access_tokens', 'oauth_session_access_tokens.id', '=', 'oauth_session_token_scopes.session_access_token_id')
            ->join('oauth_scopes', 'oauth_scopes.id', '=', 'oauth_session_token_scopes.scope_id')
            ->select('oauth_scopes.*')
            ->where('oauth_session_token_scopes.access_token', $accessToken)
            ->get();

        return $scopes->all();
    }
}


text:
Open in Paw is still under development, doesn't have yet its complete features, and [Paw HTTP Client](http://luckymarmot.com/paw) is not yet adapted to handle the URL links that this extension opens.

When development will be finished, the "master" branch will only keep stable releases, for now "master" is used as a simple development branche.

Also, the Safari Extension will be built so you won't need to build it yourself :)

#Open in Paw

This is a Safari Extension made to open URLs from Safari into [Paw HTTP Client](http://luckymarmot.com/paw).

##Context Menu

The main feature is being able to Right + Click or Control + Click on any link in Safari to open it in Paw. Also adding the ability to open the current page URL.

#Building

You can find complete information on the Apple Documentation: [Safari Extensions Development Guide](http://developer.apple.com/library/safari/#documentation/Tools/Conceptual/SafariExtensionGuide/Introduction/Introduction.html).

#License

This Safari Extension is released under the [MIT License](http://opensource.org/licenses/MIT). Therefore, feel free to reuse part (or the whole!) code.

Please note that [Paw HTTP Client](http://luckymarmot.com/paw) is not Open Source nor released under an Open Source License. Safari is the property of [Apple, Inc](http://www.apple.com).

By [Micha Mazaheri](http://micha.mazaheri.me)


text:
module Appdrones
  class AppdronesRailtie < ::Rails::Railtie

    rake_tasks do
        load "tasks/appdrones_tasks.rake"
    end
  end
end