text:
from falcon.status_codes import HTTP_204
from falcon.status_codes import HTTP_400
from falcon.status_codes import HTTP_404
from falcon.status_codes import HTTP_405

def path_not_found(req, resp, **kwargs):
    """Simply sets responseto "404 Not Found", no body."""
    resp.status = HTTP_404

def bad_request(req, resp, **kwargs):
    """Sets response to "400 Bad Request", no body."""
    resp.status = HTTP_400

def create_method_not_allowed(allowed_methods):
    """Creates a responder for "405 Method Not Allowed"

    Args:
        allowed_methods: A list of HTTP methods (uppercase) that should be
            returned in the Allow header.

    """
    allowed = ', '.join(allowed_methods)

    def method_not_allowed(req, resp, **kwargs):
        resp.status = HTTP_405
        resp.set_header('Allow', allowed)

    return method_not_allowed

def create_default_options(allowed_methods):
    """Creates a default responder for the OPTIONS method

    Args:
        allowed_methods: A list of HTTP methods (uppercase) that should be
            returned in the Allow header.

    """
    allowed = ', '.join(allowed_methods)

    def on_options(req, resp, **kwargs):
        resp.status = HTTP_204
        resp.set_header('Allow', allowed)

    return on_options


text:
<?php

namespace app\components;

use Yii;
use yii\web\UrlRuleInterface;

class UrlRule implements UrlRuleInterface {

	/**
	 * Parses the given request and returns the corresponding route and parameters.
	 * @param \yii\web\UrlManager $manager the URL manager
	 * @param \yii\web\Request $request the request component
	 * @return array|boolean the parsing result. The route and the parameters are returned as an array.
	 * If false, it means this rule cannot be used to parse this path info.
	 */
	public function parseRequest($manager, $request) {

		$pathInfo = $request->getPathInfo();

		$pathInfo = trim($pathInfo, '/ ');

		switch ($pathInfo) {
			case 'admin/knowledgebases':
			case 'admin/knowledgebases/index':
				$route = 'admin-knowledgebases/index';
				break;
			case 'admin/knowledgebases/update':
				$route = 'admin-knowledgebases/update';
				break;
			case 'admin/knowledgebases/delete':
				$route = 'admin-knowledgebases/delete';
				break;
			case 'admin/knowledgebases/entries':
				$route = 'admin-knowledgebases/entries';
				break;
			case 'admin/knowledgebases/categories/update':
				$route = 'admin-knowledgebases/categories-update';
				break;
			case 'admin/knowledgebases/categories/delete':
				$route = 'admin-knowledgebases/categories-delete';
				break;
			case 'admin/knowledgebases/categories/tree':
				$route = 'admin-knowledgebases/categories-tree';
				break;
			case 'admin/knowledgebases/articles/update':
				$route = 'admin-knowledgebases/articles-update';
				break;
			case 'admin/knowledgebases/articles/delete':
				$route = 'admin-knowledgebases/articles-delete';
				break;
			case 'admin/knowledgebases/entries/files/upload':
				$route = 'admin-knowledgebases/entries-files-upload';
				break;
			case 'admin/knowledgebases/entries/files/download':
				$route = 'admin-knowledgebases/entries-files-download';
				break;
			default:
				$route = $pathInfo;
		}

		$params = array();

		return [$route, $params];

	}

	/**
	 * Creates a URL according to the given route and parameters.
	 * @param \yii\web\UrlManager $manager the URL manager
	 * @param string $route the route. It should not have slashes at the beginning or the end.
	 * @param array $params the parameters
	 * @return string|boolean the created URL, or false if this rule cannot be used for creating this URL.
	 */
	public function createUrl($manager, $route, $params) {

		switch ($route) {
			case 'admin-knowledgebases/index':
				$url = 'admin/knowledgebases/index';
				break;
			case 'admin-knowledgebases/update':
				$url = 'admin/knowledgebases/update';
				break;
			case 'admin-knowledgebases/delete':
				$url = 'admin/knowledgebases/delete';
				break;
			case 'admin-knowledgebases/entries':
				$url = 'admin/knowledgebases/entries';
				break;
			case 'admin-knowledgebases/categories-update':
				$url = 'admin/knowledgebases/categories/update';
				break;
			case 'admin-knowledgebases/categories-delete':
				$url = 'admin/knowledgebases/categories/delete';
				break;
			case 'admin-knowledgebases/categories-tree':
				$url = 'admin/knowledgebases/categories/tree';
				break;
			case 'admin-knowledgebases/articles-update':
				$url = 'admin/knowledgebases/articles/update';
				break;
			case 'admin-knowledgebases/articles-delete':
				$url = 'admin/knowledgebases/articles/delete';
				break;
			case 'admin-knowledgebases/entries-files-upload':
				$url = 'admin/knowledgebases/entries/files/upload';
				break;
			case 'admin-knowledgebases/entries-files-download':
				$url = 'admin/knowledgebases/entries/files/download';
				break;
			default:
				return false;
		}

		$query = (count($params)) ? '?' . http_build_query($params) : '';

		return $url . $query;

	}

}

redpajama_set_name: RedPajamaGithub


text:
class CreateLandingPageEngPictureLinkTexts < ActiveRecord::Migration
  def change
    create_table :landing_page_eng_picture_link_texts do |t|
      t.text :categories
      t.text :tags
      t.string :image
      t.string :title
      t.text :body
      t.string :link
      t.integer :landing_page_id
      t.integer :product_id

      t.timestamps
    end
  end
end


text:
package com.evolveum.midpoint.web.component.wizard.resource.component.schemahandling;

import com.evolveum.midpoint.gui.api.component.BasePanel;
import com.evolveum.midpoint.gui.api.model.NonEmptyModel;
import com.evolveum.midpoint.gui.api.util.WebComponentUtil;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.util.ItemPathUtil;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition;
import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition;
import com.evolveum.midpoint.schema.processor.ResourceSchema;
import com.evolveum.midpoint.schema.processor.ResourceSchemaImpl;
import com.evolveum.midpoint.schema.util.ResourceTypeUtil;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.component.form.multivalue.MultiValueTextEditPanel;
import com.evolveum.midpoint.web.component.form.multivalue.MultiValueTextPanel;
import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour;
import com.evolveum.midpoint.web.component.wizard.WizardUtil;
import com.evolveum.midpoint.web.component.wizard.resource.SchemaHandlingStep;
import com.evolveum.midpoint.web.component.wizard.resource.component.schemahandling.modal.LimitationsEditorDialog;
import com.evolveum.midpoint.web.component.wizard.resource.component.schemahandling.modal.MappingEditorDialog;
import com.evolveum.midpoint.web.component.wizard.resource.dto.MappingTypeDto;
import com.evolveum.midpoint.web.page.admin.configuration.component.EmptyOnChangeAjaxFormUpdatingBehavior;
import com.evolveum.midpoint.web.page.admin.resources.PageResourceWizard;
import com.evolveum.midpoint.web.page.admin.resources.PageResources;
import com.evolveum.midpoint.web.util.InfoTooltipBehavior;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import com.evolveum.prism.xml.ns._public.types_3.ItemPathType;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.*;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.model.*;
import org.jetbrains.annotations.NotNull;
import org.w3c.dom.Element;

import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 *  @author shood
 * */
public class ResourceAttributeEditor extends BasePanel<ResourceAttributeDefinitionType> {

    private static final Trace LOGGER = TraceManager.getTrace(ResourceAttributeEditor.class);

    private static final String ID_LABEL = "label";
    private static final String ID_SCHEMA_REF_PANEL = "schemaRefPanel";
    private static final String ID_NON_SCHEMA_REF_PANEL = "nonSchemaReferencePanel";	// temporarily not used
    private static final String ID_REFERENCE_SELECT = "referenceSelect";
    private static final String ID_REFERENCE_ALLOW = "allowRef";						// temporarily not used
    private static final String ID_DISPLAY_NAME = "displayName";
    private static final String ID_DESCRIPTION = "description";
    private static final String ID_EXCLUSIVE_STRONG = "exclusiveStrong";
    private static final String ID_TOLERANT = "tolerant";
    private static final String ID_TOLERANT_VP = "tolerantValuePattern";
    private static final String ID_INTOLERANT_VP = "intolerantValuePattern";
    private static final String ID_FETCH_STRATEGY = "fetchStrategy";
    private static final String ID_MATCHING_RULE = "matchingRule";
    private static final String ID_UNKNOWN_MATCHING_RULE = "unknownMatchingRule";
    private static final String ID_INBOUND = "inbound";
    private static final String ID_OUTBOUND_LABEL = "outboundLabel";
    private static final String ID_BUTTON_OUTBOUND = "buttonOutbound";
    private static final String ID_BUTTON_LIMITATIONS = "buttonLimitations";
    private static final String ID_MODAL_LIMITATIONS = "limitationsEditor";
    private static final String ID_MODAL_INBOUND = "inboundEditor";
    private static final String ID_MODAL_OUTBOUND = "outboundEditor";
    private static final String ID_T_REF = "referenceTooltip";
    private static final String ID_T_ALLOW = "allowTooltip";
    private static final String ID_T_LIMITATIONS = "limitationsTooltip";
    private static final String ID_T_EXCLUSIVE_STRONG = "exclusiveStrongTooltip";
    private static final String ID_T_TOLERANT = "tolerantTooltip";
    private static final String ID_T_TOLERANT_VP = "tolerantVPTooltip";
    private static final String ID_T_INTOLERANT_VP = "intolerantVPTooltip";
    private static final String ID_T_FETCH = "fetchStrategyTooltip";
    private static final String ID_T_MATCHING_RULE = "matchingRuleTooltip";
    private static final String ID_T_OUTBOUND = "outboundTooltip";
    private static final String ID_T_INBOUND = "inboundTooltip";
    private static final String ID_DELETE_OUTBOUND = "deleteOutbound";

    private PrismObject<ResourceType> resource;
    private ResourceObjectTypeDefinitionType objectType;
    private boolean nonSchemaRefValueAllowed = false;
	@NotNull final private SchemaHandlingStep parentStep;

    public ResourceAttributeEditor(String id, IModel<ResourceAttributeDefinitionType> model, ResourceObjectTypeDefinitionType objectType,
			PrismObject<ResourceType> resource, SchemaHandlingStep parentStep, NonEmptyModel<Boolean> readOnlyModel) {
        super(id, model);

        this.resource = resource;
        this.objectType = objectType;
		this.parentStep = parentStep;
		initLayout(readOnlyModel);
    }

    protected void initLayout(final NonEmptyModel<Boolean> readOnlyModel) {

        Label label = new Label(ID_LABEL, new ResourceModel("ResourceAttributeEditor.label.edit"));
		label.add(WebComponentUtil.enabledIfFalse(readOnlyModel));
        add(label);

/*
		TEMPORARILY DISABLED

        QNameEditorPanel nonSchemaRefPanel = new QNameEditorPanel(ID_NON_SCHEMA_REF_PANEL, new PropertyModel<ItemPathType>(getModel(), "ref"),
                "SchemaHandlingStep.attribute.label.attributeName", "SchemaHandlingStep.attribute.tooltip.attributeLocalPart",
                "SchemaHandlingStep.attribute.label.attributeNamespace", "SchemaHandlingStep.attribute.tooltip.attributeNamespace", true, true) {
			@Override
			protected void onUpdate(AjaxRequestTarget target) {
				target.add(parentStep.getAttributeList());
			}
		};

        nonSchemaRefPanel.setOutputMarkupId(true);
        nonSchemaRefPanel.setOutputMarkupPlaceholderTag(true);
        nonSchemaRefPanel.add(new VisibleEnableBehaviour(){

            @Override
            public boolean isVisible() {
                return nonSchemaRefValueAllowed;
            }
        });
        add(nonSchemaRefPanel);
*/

        WebMarkupContainer schemaRefPanel = new WebMarkupContainer(ID_SCHEMA_REF_PANEL);
        schemaRefPanel.setOutputMarkupId(true);
        schemaRefPanel.setOutputMarkupPlaceholderTag(true);
        schemaRefPanel.add(new VisibleEnableBehaviour(){
            @Override
            public boolean isVisible() {
                return !nonSchemaRefValueAllowed;
            }
			@Override
			public boolean isEnabled() {
				return !readOnlyModel.getObject();
			}
		});
        add(schemaRefPanel);

        Label refTooltip = new Label(ID_T_REF);
        refTooltip.add(new InfoTooltipBehavior());
        refTooltip.setOutputMarkupId(true);
        refTooltip.setOutputMarkupId(true);
        schemaRefPanel.add(refTooltip);

        DropDownChoice refSelect = new DropDownChoice<ItemPathType>(ID_REFERENCE_SELECT, new PropertyModel<ItemPathType>(getModel(), "ref"),
                new AbstractReadOnlyModel<List<ItemPathType>>() {

                    @Override
                    public List<ItemPathType> getObject() {
                        return loadObjectReferences();
                    }
                }, new IChoiceRenderer<ItemPathType>() {
                	@Override
                			public ItemPathType getObject(String id, IModel<? extends List<? extends ItemPathType>> choices) {
                		return StringUtils.isNotBlank(id) ? choices.getObject().get(Integer.parseInt(id)) : null;
                			}

            @Override
            public Object getDisplayValue(ItemPathType object) {
                return prepareReferenceDisplayValue(object);
            }

            @Override
            public String getIdValue(ItemPathType object, int index) {
                return Integer.toString(index);
            }
        }){

            @Override
            protected boolean isSelected(ItemPathType object, int index, String selected) {
                if(getModelObject() == null || getModelObject().equals(new ItemPathType())){
                    return false;
                }

                QName referenceQName = ItemPathUtil.getOnlySegmentQNameRobust(getModelObject());
                QName optionQName = ItemPathUtil.getOnlySegmentQNameRobust(object);

                return ObjectUtils.equals(referenceQName, optionQName);
            }
        };
        refSelect.setNullValid(false);
        refSelect.setOutputMarkupId(true);
        refSelect.setOutputMarkupPlaceholderTag(true);
		refSelect.add(new EmptyOnChangeAjaxFormUpdatingBehavior() {
			@Override
			protected void onUpdate(AjaxRequestTarget target) {
				target.add(parentStep.getAttributeList());
				((PageResourceWizard) getPageBase()).refreshIssues(target);
			}
		});
		refSelect.add(WebComponentUtil.enabledIfFalse(readOnlyModel));
        schemaRefPanel.add(refSelect);

/*
		TEMPORARILY DISABLED

        CheckBox allowNonSchema = new CheckBox(ID_REFERENCE_ALLOW, new PropertyModel<Boolean>(this, "nonSchemaRefValueAllowed"));
        allowNonSchema.add(new AjaxFormComponentUpdatingBehavior("change") {

            @Override
            protected void onUpdate(AjaxRequestTarget target) {
                target.add(get(ID_NON_SCHEMA_REF_PANEL), get(ID_SCHEMA_REF_PANEL));
            }
        });
        add(allowNonSchema);
*/

        TextField displayName = new TextField<>(ID_DISPLAY_NAME, new PropertyModel<String>(getModel(), "displayName"));
		displayName.add(new EmptyOnChangeAjaxFormUpdatingBehavior() {
			@Override
			protected void onUpdate(AjaxRequestTarget target) {
				target.add(parentStep.getAttributeList());
			}
		});
		displayName.add(WebComponentUtil.enabledIfFalse(readOnlyModel));
        add(displayName);

        TextArea description = new TextArea<>(ID_DESCRIPTION, new PropertyModel<String>(getModel(), "description"));
		description.add(WebComponentUtil.enabledIfFalse(readOnlyModel));
        add(description);

        AjaxLink limitations = new AjaxLink(ID_BUTTON_LIMITATIONS) {

            @Override
            public void onClick(AjaxRequestTarget target) {
                limitationsEditPerformed(target);
            }
        };
        add(limitations);

        CheckBox exclusiveStrong = new CheckBox(ID_EXCLUSIVE_STRONG, new PropertyModel<Boolean>(getModel(), "exclusiveStrong"));
		exclusiveStrong.add(WebComponentUtil.enabledIfFalse(readOnlyModel));
        add(exclusiveStrong);

        CheckBox tolerant = new CheckBox(ID_TOLERANT, new PropertyModel<Boolean>(getModel(), "tolerant"));
		tolerant.add(WebComponentUtil.enabledIfFalse(readOnlyModel));
        add(tolerant);

        MultiValueTextPanel tolerantVP = new MultiValueTextPanel<>(ID_TOLERANT_VP,
                new PropertyModel<List<String>>(getModel(), "tolerantValuePattern"), readOnlyModel, true);
		tolerantVP.add(WebComponentUtil.enabledIfFalse(readOnlyModel));
		add(tolerantVP);

        MultiValueTextPanel intolerantVP = new MultiValueTextPanel<>(ID_INTOLERANT_VP,
                new PropertyModel<List<String>>(getModel(), "intolerantValuePattern"), readOnlyModel, true);
		intolerantVP.add(WebComponentUtil.enabledIfFalse(readOnlyModel));
        add(intolerantVP);

        DropDownChoice fetchStrategy = new DropDownChoice<>(ID_FETCH_STRATEGY,
                new PropertyModel<AttributeFetchStrategyType>(getModel(), "fetchStrategy"),
                WebComponentUtil.createReadonlyModelFromEnum(AttributeFetchStrategyType.class),
                new EnumChoiceRenderer<AttributeFetchStrategyType>(this));
        fetchStrategy.setNullValid(true);
		fetchStrategy.add(WebComponentUtil.enabledIfFalse(readOnlyModel));
        add(fetchStrategy);

		AttributeEditorUtils.addMatchingRuleFields(this, readOnlyModel);

        TextField outboundLabel = new TextField<>(ID_OUTBOUND_LABEL,
                new AbstractReadOnlyModel<String>() {

                    @Override
                    public String getObject() {
                        ResourceAttributeDefinitionType attributeDefinition = getModel().getObject();

                        if(attributeDefinition == null){
                            return null;
                        }

                        return MappingTypeDto.createMappingLabel(attributeDefinition.getOutbound(), LOGGER, getPageBase().getPrismContext(),
                                getString("MappingType.label.placeholder"), getString("MultiValueField.nameNotSpecified"));
                    }
                });
        outboundLabel.setEnabled(false);
        outboundLabel.setOutputMarkupId(true);
		VisibleEnableBehaviour showIfEditingOrOutboundExists = AttributeEditorUtils.createShowIfEditingOrOutboundExists(getModel(), readOnlyModel);
		outboundLabel.add(showIfEditingOrOutboundExists);
        add(outboundLabel);

        AjaxSubmitLink outbound = new AjaxSubmitLink(ID_BUTTON_OUTBOUND) {

            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                outboundEditPerformed(target);
            }

			@Override
			protected void onError(AjaxRequestTarget target, Form<?> form) {
				target.add(parentStep.getPageBase().getFeedbackPanel());
			}
        };
        outbound.setOutputMarkupId(true);
		outbound.add(showIfEditingOrOutboundExists);
        add(outbound);

        AjaxSubmitLink deleteOutbound = new AjaxSubmitLink(ID_DELETE_OUTBOUND) {

            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                deleteOutboundPerformed(target);
            }

			@Override
			protected void onError(AjaxRequestTarget target, Form<?> form) {
				target.add(parentStep.getPageBase().getFeedbackPanel());
			}
		};
        deleteOutbound.setOutputMarkupId(true);
		deleteOutbound.add(WebComponentUtil.visibleIfFalse(readOnlyModel));
        add(deleteOutbound);

        MultiValueTextEditPanel inbound = new MultiValueTextEditPanel<MappingType>(ID_INBOUND,
                new PropertyModel<List<MappingType>>(getModel(), "inbound"), null, false, true, readOnlyModel) {

            @Override
            protected IModel<String> createTextModel(final IModel<MappingType> model) {
                return new Model<String>() {

                    @Override
                    public String getObject() {
                        return MappingTypeDto.createMappingLabel(model.getObject(), LOGGER, getPageBase().getPrismContext(),
                                getString("MappingType.label.placeholder"), getString("MultiValueField.nameNotSpecified"));
                    }
                };
            }

            @Override
            protected MappingType createNewEmptyItem(){
                return WizardUtil.createEmptyMapping();
            }

			@Override
			protected void performAddValueHook(AjaxRequestTarget target, MappingType added) {
				target.add(parentStep.getAttributeList());
				target.add(parentStep.getAssociationList());
				((PageResourceWizard) getPageBase()).refreshIssues(target);
			}

			@Override
			protected void performRemoveValueHook(AjaxRequestTarget target, ListItem<MappingType> item) {
				target.add(parentStep.getAttributeList());
				target.add(parentStep.getAssociationList());
				((PageResourceWizard) getPageBase()).refreshIssues(target);
			}

			@Override
            protected void editPerformed(AjaxRequestTarget target, MappingType object){
                inboundEditPerformed(target, object);
            }
        };
        inbound.setOutputMarkupId(true);
        add(inbound);

        Label allowTooltip = new Label(ID_T_ALLOW);
        allowTooltip.add(new InfoTooltipBehavior());
        add(allowTooltip);

        Label limitationsTooltip = new Label(ID_T_LIMITATIONS);
        limitationsTooltip.add(new InfoTooltipBehavior());
        add(limitationsTooltip);

        Label exclusiveStrongTooltip = new Label(ID_T_EXCLUSIVE_STRONG);
        exclusiveStrongTooltip.add(new InfoTooltipBehavior());
        add(exclusiveStrongTooltip);

        Label tolerantTooltip = new Label(ID_T_TOLERANT);
        tolerantTooltip.add(new InfoTooltipBehavior());
        add(tolerantTooltip);

        Label tolerantVPTooltip = new Label(ID_T_TOLERANT_VP);
        tolerantVPTooltip.add(new InfoTooltipBehavior());
        add(tolerantVPTooltip);

        Label intolerantVPTooltip = new Label(ID_T_INTOLERANT_VP);
        intolerantVPTooltip.add(new InfoTooltipBehavior());
        add(intolerantVPTooltip);

        Label fetchTooltip = new Label(ID_T_FETCH);
        fetchTooltip.add(new InfoTooltipBehavior());
        add(fetchTooltip);

        Label matchingRuleTooltip = new Label(ID_T_MATCHING_RULE);
        matchingRuleTooltip.add(new InfoTooltipBehavior());
        add(matchingRuleTooltip);

        Label outboundTooltip = new Label(ID_T_OUTBOUND);
        outboundTooltip.add(new InfoTooltipBehavior());
        add(outboundTooltip);

        Label inboundTooltip = new Label(ID_T_INBOUND);
        inboundTooltip.add(new InfoTooltipBehavior());
        add(inboundTooltip);

        initModals(readOnlyModel);
    }

	private void initModals(NonEmptyModel<Boolean> readOnlyModel) {
        ModalWindow limitationsEditor = new LimitationsEditorDialog(ID_MODAL_LIMITATIONS,
                new PropertyModel<List<PropertyLimitationsType>>(getModel(), "limitations"), readOnlyModel);
        add(limitationsEditor);

        ModalWindow inboundEditor = new MappingEditorDialog(ID_MODAL_INBOUND, null, readOnlyModel) {

            @Override
            public void updateComponents(AjaxRequestTarget target) {
				target.add(ResourceAttributeEditor.this.get(ID_INBOUND), parentStep.getAttributeList());
            }
        };
        add(inboundEditor);

        ModalWindow outboundEditor = new MappingEditorDialog(ID_MODAL_OUTBOUND, null, readOnlyModel) {

            @Override
            public void updateComponents(AjaxRequestTarget target) {
                target.add(ResourceAttributeEditor.this.get(ID_OUTBOUND_LABEL), ResourceAttributeEditor.this.get(ID_BUTTON_OUTBOUND), parentStep.getAttributeList());
            }
        };
        add(outboundEditor);
    }

    private List<ItemPathType> loadObjectReferences(){
        List<ItemPathType> references = new ArrayList<>();

        ResourceSchema schema = loadResourceSchema();
        if (schema == null || objectType == null) {
            return references;
        }

        for (ObjectClassComplexTypeDefinition def: schema.getObjectClassDefinitions()) {
            if (objectType.getObjectClass().equals(def.getTypeName()) ||
                    objectType.getAuxiliaryObjectClass().contains(def.getTypeName())) {
                for (ResourceAttributeDefinition attributeDefinition : def.getAttributeDefinitions()) {
                    ItemPath itemPath = new ItemPath(attributeDefinition.getName());
                    ItemPathType itemPathType = new ItemPathType(itemPath);
                    if (!references.contains(itemPathType)) {
                        references.add(itemPathType);
                    }
                }
            }
        }

        Collections.sort(references, new Comparator<ItemPathType>() {

            @Override
            public int compare(ItemPathType o1, ItemPathType o2) {
                String s1 = prepareReferenceDisplayValue(o1);
                String s2 = prepareReferenceDisplayValue(o2);

                return String.CASE_INSENSITIVE_ORDER.compare(s1, s2);
            }
        });

        return references;
    }

    private ResourceSchema loadResourceSchema() {
        if(resource != null){
            Element xsdSchema = ResourceTypeUtil.getResourceXsdSchema(resource);
            if (xsdSchema == null) {
                return null;
            }

            try {
                return ResourceSchemaImpl.parse(xsdSchema, resource.toString(), getPageBase().getPrismContext());
            } catch (SchemaException|RuntimeException e) {
                LoggingUtils.logUnexpectedException(LOGGER, "Couldn't parse resource schema.", e);
                getSession().error(getString("ResourceAttributeEditor.message.cantParseSchema") + " " + e.getMessage());

                throw new RestartResponseException(PageResources.class);
            }
        }

        return null;
    }

    private String prepareReferenceDisplayValue(ItemPathType object){
        if (object == null || object.getItemPath() == null) {
            return "";
        }

        ItemPath path = object.getItemPath();
        if (path.getSegments().size() != 1) {
            return path.toString();
        }

        QName name = ItemPathUtil.getOnlySegmentQName(path);

        StringBuilder sb = new StringBuilder();
        String prefix = SchemaConstants.NS_ICF_SCHEMA.equals(name.getNamespaceURI()) ? "icfs" : "ri";
        sb.append(prefix);
        sb.append(": ");
        sb.append(name.getLocalPart());

        return sb.toString();
    }

    private void limitationsEditPerformed(AjaxRequestTarget target){
        LimitationsEditorDialog window = (LimitationsEditorDialog)get(ID_MODAL_LIMITATIONS);
        window.show(target);
    }

    private void deleteOutboundPerformed(AjaxRequestTarget target) {
        ResourceAttributeDefinitionType def = getModelObject();
        def.setOutbound(null);
        target.add(this, parentStep.getAttributeList());
    }

    private void outboundEditPerformed(AjaxRequestTarget target){
        MappingEditorDialog window = (MappingEditorDialog) get(ID_MODAL_OUTBOUND);
        window.updateModel(target, new PropertyModel<MappingType>(getModel(), "outbound"), false);
        window.show(target);
    }

    private void inboundEditPerformed(AjaxRequestTarget target, MappingType mapping){
        MappingEditorDialog window = (MappingEditorDialog) get(ID_MODAL_INBOUND);
        window.updateModel(target, mapping, true);
        window.show(target);
    }
}


text:
#ifndef FREERTOS_CONFIG_H
#define FREERTOS_CONFIG_H

/*-----------------------------------------------------------
 * Application specific definitions.
 *
 * These definitions should be adjusted for your particular hardware and
 * application requirements.
 *
 * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE
 * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE.
 *
 * See http://www.freertos.org/a00110.html.
 *----------------------------------------------------------*/

// Include MCU header
#include "bsp/board_mcu.h"

#if CFG_TUSB_MCU == OPT_MCU_ESP32S2 || CFG_TUSB_MCU == OPT_MCU_ESP32S3
  #error "ESP32-Sx should use IDF's FreeRTOSConfig.h"
#endif

// TODO fix later
#if CFG_TUSB_MCU == OPT_MCU_MM32F327X
  extern u32 SystemCoreClock;
#else
  // FIXME cause redundant-decls warnings
  extern uint32_t SystemCoreClock;
#endif

/* Cortex M23/M33 port configuration. */
#define configENABLE_MPU								        0
#define configENABLE_FPU								        1
#define configENABLE_TRUSTZONE					        0
#define configMINIMAL_SECURE_STACK_SIZE					( 1024 )

#define configUSE_PREEMPTION                    1
#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0
#define configCPU_CLOCK_HZ                      SystemCoreClock
#define configTICK_RATE_HZ                      ( 1000 )
#define configMAX_PRIORITIES                    ( 5 )
#define configMINIMAL_STACK_SIZE                ( 128 )
#define configTOTAL_HEAP_SIZE                   ( 0*1024 ) // dynamic is not used
#define configMAX_TASK_NAME_LEN                 16
#define configUSE_16_BIT_TICKS                  0
#define configIDLE_SHOULD_YIELD                 1
#define configUSE_MUTEXES                       1
#define configUSE_RECURSIVE_MUTEXES             1
#define configUSE_COUNTING_SEMAPHORES           1
#define configQUEUE_REGISTRY_SIZE               2
#define configUSE_QUEUE_SETS                    0
#define configUSE_TIME_SLICING                  0
#define configUSE_NEWLIB_REENTRANT              0
#define configENABLE_BACKWARD_COMPATIBILITY     1
#define configSTACK_ALLOCATION_FROM_SEPARATE_HEAP   0

#define configSUPPORT_STATIC_ALLOCATION         1
#define configSUPPORT_DYNAMIC_ALLOCATION        0

/* Hook function related definitions. */
#define configUSE_IDLE_HOOK                    0
#define configUSE_TICK_HOOK                    0
#define configUSE_MALLOC_FAILED_HOOK           0 // cause nested extern warning
#define configCHECK_FOR_STACK_OVERFLOW         2

/* Run time and task stats gathering related definitions. */
#define configGENERATE_RUN_TIME_STATS          0
#define configUSE_TRACE_FACILITY               1 // legacy trace
#define configUSE_STATS_FORMATTING_FUNCTIONS   0

/* Co-routine definitions. */
#define configUSE_CO_ROUTINES                  0
#define configMAX_CO_ROUTINE_PRIORITIES        2

/* Software timer related definitions. */
#define configUSE_TIMERS                       1
#define configTIMER_TASK_PRIORITY              (configMAX_PRIORITIES-2)
#define configTIMER_QUEUE_LENGTH               32
#define configTIMER_TASK_STACK_DEPTH           configMINIMAL_STACK_SIZE

/* Optional functions - most linkers will remove unused functions anyway. */
#define INCLUDE_vTaskPrioritySet               0
#define INCLUDE_uxTaskPriorityGet              0
#define INCLUDE_vTaskDelete                    0
#define INCLUDE_vTaskSuspend                   1 // required for queue, semaphore, mutex to be blocked indefinitely with portMAX_DELAY
#define INCLUDE_xResumeFromISR                 0
#define INCLUDE_vTaskDelayUntil                1
#define INCLUDE_vTaskDelay                     1
#define INCLUDE_xTaskGetSchedulerState         0
#define INCLUDE_xTaskGetCurrentTaskHandle      0
#define INCLUDE_uxTaskGetStackHighWaterMark    0
#define INCLUDE_xTaskGetIdleTaskHandle         0
#define INCLUDE_xTimerGetTimerDaemonTaskHandle 0
#define INCLUDE_pcTaskGetTaskName              0
#define INCLUDE_eTaskGetState                  0
#define INCLUDE_xEventGroupSetBitFromISR       0
#define INCLUDE_xTimerPendFunctionCall         0

/* Define to trap errors during development. */
// Halt CPU (breakpoint) when hitting error, only apply for Cortex M3, M4, M7
#if defined(__ARM_ARCH_7M__) || defined (__ARM_ARCH_7EM__)
  #define configASSERT(_exp) \
    do {\
      if ( !(_exp) ) { \
        volatile uint32_t* ARM_CM_DHCSR =  ((volatile uint32_t*) 0xE000EDF0UL); /* Cortex M CoreDebug->DHCSR */ \
        if ( (*ARM_CM_DHCSR) & 1UL ) {  /* Only halt mcu if debugger is attached */ \
          taskDISABLE_INTERRUPTS(); \
           __asm("BKPT #0\n"); \
        }\
      }\
    } while(0)
#else
  #define configASSERT( x )
#endif

#ifdef __RX__
/* Renesas RX series */
#define vSoftwareInterruptISR					INT_Excep_ICU_SWINT
#define vTickISR								INT_Excep_CMT0_CMI0
#define configPERIPHERAL_CLOCK_HZ				(configCPU_CLOCK_HZ/2)
#define configKERNEL_INTERRUPT_PRIORITY			1
#define configMAX_SYSCALL_INTERRUPT_PRIORITY	4

#else

/* FreeRTOS hooks to NVIC vectors */
#define xPortPendSVHandler    PendSV_Handler
#define xPortSysTickHandler   SysTick_Handler
#define vPortSVCHandler       SVC_Handler

//--------------------------------------------------------------------+
// Interrupt nesting behavior configuration.
//--------------------------------------------------------------------+
#if defined(__NVIC_PRIO_BITS)
  // For Cortex-M specific: __NVIC_PRIO_BITS is defined in core_cmx.h
	#define configPRIO_BITS       __NVIC_PRIO_BITS
#elif defined(__ECLIC_INTCTLBITS)
  // RISC-V Bumblebee core from nuclei
  #define configPRIO_BITS       __ECLIC_INTCTLBITS
#else
  #error "FreeRTOS configPRIO_BITS to be defined"
#endif

/* The lowest interrupt priority that can be used in a call to a "set priority" function. */
#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY			  ((1<<configPRIO_BITS) - 1)

/* The highest interrupt priority that can be used by any interrupt service
routine that makes calls to interrupt safe FreeRTOS API functions.  DO NOT CALL
INTERRUPT SAFE FREERTOS API FUNCTIONS FROM ANY INTERRUPT THAT HAS A HIGHER
PRIORITY THAN THIS! (higher priorities are lower numeric values. */
#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY	2

/* Interrupt priorities used by the kernel port layer itself.  These are generic
to all Cortex-M ports, and do not rely on any particular library functions. */
#define configKERNEL_INTERRUPT_PRIORITY 		          ( configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )

/* !!!! configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to zero !!!!
See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html. */
#define configMAX_SYSCALL_INTERRUPT_PRIORITY 	        ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )

#endif

#endif /* __FREERTOS_CONFIG__H */


text:
class ConcreteTool
		: public ToolBase
{
	Q_OBJECT

public:
	ConcreteTool(int& argc, char *argv[])
		: ToolBase(argc, argv)
	{
	}

	virtual void setup()
	{
		setDescription("Sort a BEDPE file according to chromosomal position.");
		addInfile("in", "Input BEDPE file.", false);
		addOutfile("out", "Output BEDPE file.", false);

		changeLog(2022,  2, 17, "Initial version");
	}

	virtual void main()
	{
		BedpeFile file;
		file.load(getInfile("in"));
		file.sort();
		file.toTSV(getOutfile("out"));
	}
};

#include "main.moc"

int main(int argc, char *argv[])
{
	ConcreteTool tool(argc, argv);
	return tool.execute();
}


text:
package gov.samhsa.consent2share.service.reference;

import gov.samhsa.consent2share.domain.reference.MaritalStatusCode;
import gov.samhsa.consent2share.domain.reference.MaritalStatusCodeRepository;
import gov.samhsa.consent2share.service.dto.LookupDto;

import java.util.ArrayList;
import java.util.List;

import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * The Class MaritalStatusCodeServiceImpl.
 */
@Service
@Transactional
public class MaritalStatusCodeServiceImpl implements MaritalStatusCodeService {

	/** The marital status code repository. */
	@Autowired
	MaritalStatusCodeRepository maritalStatusCodeRepository;

	/** The model mapper. */
	@Autowired
	ModelMapper modelMapper;

	/* (non-Javadoc)
	 * @see gov.samhsa.consent2share.service.reference.MaritalStatusCodeService#findAllMaritalStatusCodes()
	 */
	@Override
	public List<LookupDto> findAllMaritalStatusCodes() {
		List<LookupDto> lookups = new ArrayList<LookupDto>();

		List<MaritalStatusCode> maritalStatusCodeList = maritalStatusCodeRepository.findAll();

		for (MaritalStatusCode entity : maritalStatusCodeList) {
			lookups.add(modelMapper.map(entity, LookupDto.class));
		}
		return lookups;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include
        layout="@layout/view_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="@string/banner_ad_unit_id" />

    <android.support.v7.widget.CardView
        android:id="@+id/cardview_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:clickable="true"
        android:foreground="?android:attr/selectableItemBackground"
        app:cardCornerRadius="4dp"
        app:cardElevation="2dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="10dp">

            <android.support.v7.widget.SwitchCompat
                android:id="@+id/sw_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="20dp"
                android:text="Toggle Switch Default" />

            <android.support.v7.widget.SwitchCompat
                android:id="@+id/sw_button2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="20dp"
                android:text="Toggle Switch Custom"
                android:textColor="@color/cardview_light_background"
                android:theme="@style/TWOHSwitch" />

        </LinearLayout>
    </android.support.v7.widget.CardView>

    <include layout="@layout/view_readtutorialbutton" />
</LinearLayout>


text:
"""GitHubRepo module for pybossa-github-builder."""

import re
import json
import os
import jsonschema
from . import github

class InvalidPybossaProjectError(Exception):
    """Raied if a repo is not for a vaild PyBossa project."""

    def __init__(self, msg=None):
        if msg is None:
            msg = 'that is not a valid PyBossa project'
        super(Exception, self).__init__(msg)

class GitHubURLError(Exception):
    """Raised if a GitHub URL is invalid."""

    def __init__(self):
        super(Exception, self).__init__('that is not a valid GitHub URL')

class GitHubRepo(object):
    """A class for interacting with a GitHub repo for a PyBossa project."""

    root_endpoint = 'https://api.github.com'

    def __init__(self, url):
        self.user, self.repo = self.get_user_and_repo(url)

    def load_contents(self):
        """Load the contents of a GitHub repo."""
        base_url = '{0}/repos/{1}/{2}/contents'.format(self.root_endpoint,
                                                       self.user, self.repo)
        self.contents = {}

        def get_dir_contents(path=''):
            url = '{0}/{1}'.format(base_url, path)
            resp = github.get(url)
            for item in resp:
                if item['type'] == 'dir':
                    get_dir_contents(item['path'])
                elif item['type'] == 'file':
                    self.contents[item['path']] = item
        get_dir_contents()

    def validate(self):
        """Validate a GitHub repo as a PyBossa project."""
        if 'project.json' not in self.contents:  # pragma: no cover
            raise InvalidPybossaProjectError('no project.json file found')
        try:
            project_json = self.get_project_json()
        except ValueError as e:
            raise InvalidPybossaProjectError(str(e))
        path = os.path.join(os.path.dirname(__file__), 'project_schema.json')
        project_schema = json.load(open(path))
        try:
            jsonschema.validate(project_json, project_schema)
        except jsonschema.exceptions.ValidationError as e:  # pragma: no cover
            err_msg = 'project.json does not validate against the schema'
            raise InvalidPybossaProjectError(err_msg)

    def get_user_and_repo(self, url):
        """Return the GitHub user and repo."""
        patn = r'github\.[^\/:]+[\/|:]([^\/]+)\/([^\/|\s|\)]+)[.git|\/]?'
        match = re.search(patn, url)
        if not match:
            raise GitHubURLError()
        parts = re.split('/|:', match.group(0))
        user = parts[1]
        repo = parts[2].split('.git')[0]
        return user, repo

    def get_project_json(self):
        """Download and return project.json."""
        url = self.contents['project.json']['download_url']
        resp = github.get(url)
        return json.loads(resp.content)


text: export{useLocaleContext}from"../../modules/useLocale";


text:
module Main where

import ALife.Creatur.Daemon       (CreaturDaemon (..), Job (..), launch,
                                   simpleDaemon)
import ALife.Creatur.Task         (doNothing, runInteractingAgents, simpleJob)
import ALife.Creatur.Universe     (mkSimpleUniverse)
import System.Directory           (canonicalizePath)
import Tutorial.Chapter10.Martian (run)

main :: IO ()
main = do
  dir <- canonicalizePath "chapter10" -- Required for daemon
  let u = mkSimpleUniverse "Chapter10" dir
  let j = simpleJob
        { task=runInteractingAgents run doNothing doNothing,
          sleepTime=0 }
  launch $ CreaturDaemon (simpleDaemon j u) j


text:
<!DOCTYPE HTML>

	<meta charset="UTF-8">
	<title>JS Stacktrace test</title>

JS Stacktrace test file

The errors are logged in the console. This needs to be changed to post to a server using standard a JS XHR request (no helper libraries, which we assume may fail).


text:
namespace __sanitizer {
int interceptWhenPossible(uptr dll_function, const char *real_function);
}

// ----------------- Function interception helper macros -------------------- //
// Weak functions, could be redefined in the main executable, but that is not
// necessary, so we shouldn't die if we can not find a reference.
#define INTERCEPT_WEAK(Name) interceptWhenPossible((uptr) Name, #Name);

#define INTERCEPT_SANITIZER_WEAK_FUNCTION(Name)                                \
  static int intercept_##Name() {                                              \
    return __sanitizer::interceptWhenPossible((__sanitizer::uptr) Name, #Name);\
  }                                                                            \
  __pragma(section(".WEAK$M", long, read))                                     \
  __declspec(allocate(".WEAK$M")) int (*__weak_intercept_##Name)() =           \
      intercept_##Name;

#endif // SANITIZER_WIN_WEAK_INTERCEPTION_H


text:
This sample shows CustomXMLParts handling techniques from my [DB-Addin](https://github.com/rkapl123/DBAddin) as well as XML schema validation.

Here, I use CustomXMLParts as an advanced storage for Database modifier definitions (for writing Excel Data to a Database table (DBMapper), doing DML Statements such as insert/update/delete (DBAction) and executing sequences of DBMappers and DBActions (DB Sequence)).

The Sample only contains creating and viewing/editing DBMapper Definitions in a stripped down class (all in one) without any other meaningful action code to concentrate on the usage of CustomXMLParts. Besides that, I demonstrate the usage of validating the XML against an existing schema.

## CustomXMLParts Usage

All CustomXMLParts Objects are found in the namespace `Microsoft.Office.Core`, referenced by the Office.dll within Exceldna.Interop.

Fetching an existing CustomXMLParts XML document is done by selecting the required namespace:

```VB
        Dim CustomXmlParts As Object = ExcelDnaUtil.Application.ActiveWorkbook.CustomXMLParts.SelectByNamespace("DBModifDef")
```

Adding the XML document if the namespace doesn't yet exist (in a new workbook) is done by adding the root element:
```VB
        If CustomXmlParts.Count = 0 Then
            ' in case no CustomXmlPart in Namespace DBModifDef exists in the workbook, add one
            ExcelDnaUtil.Application.ActiveWorkbook.CustomXMLParts.Add("<root xmlns=""DBModifDef""></root>")
            CustomXmlParts = ExcelDnaUtil.Application.ActiveWorkbook.CustomXMLParts.SelectByNamespace("DBModifDef")
        End If
```

### Adding sub elements

Sub elements are added with the Methond `AppendChildNode` of the selected node:

```VB
        ' NamespaceURI:="DBModifDef" is required to avoid adding a xmlns attribute to each element.
        CustomXmlParts(1).SelectSingleNode("/ns0:root").AppendChildNode(createdDBModifType, NamespaceURI:="DBModifDef")
```

The appended child element is placed last, to append further child elements, you need to call `LastChild`
```VB
        Dim dbModifNode As CustomXMLNode = CustomXmlParts(1).SelectSingleNode("/ns0:root").LastChild
        ' append the detailed settings to the definition element
        dbModifNode.AppendChildNode("Name", NodeType:=MsoCustomXMLNodeType.msoCustomXMLNodeAttribute, NodeValue:=createdDBModifType + Guid.NewGuid().ToString())
        dbModifNode.AppendChildNode("execOnSave", NamespaceURI:="DBModifDef", NodeValue:="True")
        dbModifNode.AppendChildNode("askBeforeExecute", NamespaceURI:="DBModifDef", NodeValue:="True")
```

### Retrieving elements

When retrieving element values, it's a good idea to check for the count of nodes contained to avoid exceptions:
```VB
        Dim nodeCount As Integer = definitionXML.SelectNodes("ns0:" + nodeName).Count
        If nodeCount = 0 Then
            getParamFromXML = "" ' optional nodes become empty strings
        Else
            getParamFromXML = definitionXML.SelectSingleNode("ns0:" + nodeName).Text
        End If
```

### Iterating through nodes

When iterating through nodes you take the `ChildNodes` method of the (root) node object and us `BaseName` of the iterator variable (node object) to get it's element name.
Here the name is usually in the (one and only) attribute "name" of the element, so if that exists, it is taken as the nodes name.

```VB
	For Each customXMLNodeDef As CustomXMLNode In CustomXmlParts(1).SelectSingleNode("/ns0:root").ChildNodes
		Dim DBModiftype As String = Left(customXMLNodeDef.BaseName, 8)
		If DBModiftype = "DBSeqnce" Or DBModiftype = "DBMapper" Or DBModiftype = "DBAction" Then
			Dim nodeName As String
			If customXMLNodeDef.Attributes.Count > 0 Then
				nodeName = customXMLNodeDef.Attributes(1).Text
			Else
				nodeName = customXMLNodeDef.BaseName + "unknown"
			End If

			' finally create the DBModif Object and fill parameters into CustomXMLPart:
			Dim newDBModif As DBModif = New DBModif(customXMLNodeDef, DBModiftype)
...
```

## SchemaFile Usage

To utilize validated XML files, you need to create a [XML schema definition, short XSD](https://www.w3.org/TR/xmlschema11-1/) document, that you add to a [XML resource component](https://docs.microsoft.com/en-us/dotnet/framework/resources/creating-resource-files-for-desktop-apps).
Of course you can add as many xsd schema definitions as you want to the XML resource component.

After adding the XSD file to the XML resource component, you can fetch the schema in your code with
`Dim schemaString As String = My.Resources.<XML resource Name>.<XSD Name>`.

Validation of an existing XML string is then done with
```VB
...
	Dim schemaString As String = My.Resources.<XML resource Name>.<XSD Name>
	Dim schemadoc As XmlReader = XmlReader.Create(New StringReader(schemaString))
	doc.Schemas.Add("<Schema Name>", schemadoc)
	Dim eventHandler As Schema.ValidationEventHandler = New Schema.ValidationEventHandler(AddressOf myValidationEventHandler)
	doc.LoadXml(<your XML String, e.g. taken from Me.EditBox.Text>)
	doc.Validate(eventHandler)
...
	Sub myValidationEventHandler(sender As Object, e As Schema.ValidationEventArgs)
		' simply pass back Errors and Warnings as an exception
		If e.Severity = Schema.XmlSeverityType.Error Or e.Severity = Schema.XmlSeverityType.Warning Then Throw New Exception(e.Message)
	End Sub
```

## Testing Sample

After building the sample, simply activate the Addin by opening CustomXMLParts-AddIn64.xll or CustomXMLParts-AddIn.xll (32 bit) in bin/Debug or bin/Release and select the new CustomXMLParts Ribbon.


text:
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Threading;
using Nest;
using Serilog;

namespace ElasticOps.TestData
{
    public class Program
    {
        private static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .WriteTo.ColoredConsole()
                .CreateLogger();

            var section = ConfigurationManager.GetSection("Nodes") as NameValueCollection;
            foreach (var key in section.AllKeys)
            {
                var uri = section[key];
                Log.Logger.Information("Start creating data for: {clusterUri}", uri);
                var client = GetClient(uri);
                CreateIndex("products", client);
            }

            Log.Logger.Information("DONE!");
            Console.ReadLine();
        }

        private static ElasticClient GetClient(string uri)
        {
            var node = new Uri(uri);

            var settings = new ConnectionSettings(node);

            return new ElasticClient(settings);
        }

        private static void CreateIndex(string name, ElasticClient client)
        {
            if (client.IndexExists(x => x.Index(name)).Exists)
            {
                Log.Logger.Information("Delete index {indexName}", name);

                client.DeleteIndex(x => x.Index(name));
            }

            Log.Logger.Information("Create index {indexName}", name);
            client.CreateIndex(name, c => c
                .NumberOfReplicas(0)
                .NumberOfShards(1)
                .AddMapping<Book>(m => m.MapFromAttributes())
                .AddMapping<CD>(m => m.MapFromAttributes()));
            Log.Logger.Information("Index {indexName} created", name);

            Log.Logger.Information("Closing index {indexName}", name);

            Thread.Sleep(30000);
            var closeRes = client.CloseIndex(x => x.Index(name));

            if (!closeRes.Acknowledged)
                Log.Logger.Error("Could not close index: {message}",closeRes.ServerError.Error);

            Log.Logger.Information("Add analyzer to index {indexName}", name);
            var res = client.Raw.IndicesPutSettings(name, File.ReadAllText("Analyzer.json"));

            if (!res.Success)
                Log.Logger.Error("Could not create analyzer: {error}", res.OriginalException.ToString());

            Log.Logger.Information("Open index {indexName}", name);
            client.OpenIndex(x => x.Index(name));

            RandomBooks(1000, name, client);
            RandomCDs(1000, name, client);
        }

        private static void RandomBooks(int n, string indexName, ElasticClient client)
        {
            Log.Logger.Information("Creating {numberOfDocs} book documents in index {indexName}", n, indexName);

            for (var i = 0; i < n; i++)
            {
                var book = new Book
                {
                    Id = i,
                    Description = LoremNET.Lorem.Paragraph(20, 10),
                    Title = LoremNET.Lorem.Words(1, 5),
                    Year = (int) LoremNET.Lorem.Number(1965, 2015)
                };

                client.Index(book, ind => ind.Index(indexName));

                if (i%1000 == 0)
                    Log.Logger.Information("Created {numberOfDocs} book documents in index {indexName}", i, indexName);
            }
        }

        private static void RandomCDs(int n, string indexName, ElasticClient client)
        {
            Log.Logger.Information("Creating {numberOfDocs} CD documents in index {indexName}", n, indexName);

            for (var i = 0; i < n; i++)
            {
                var book = new CD
                {
                    Id = i,
                    Title = LoremNET.Lorem.Words(1, 5),
                    Genere = LoremNET.Lorem.Words(1, 2),
                    ReleaseDate = LoremNET.Lorem.DateTime(1990)
                };

                client.Index(book, ind => ind.Index(indexName));

                if (i%1000 == 0)
                    Log.Logger.Information("Created {numberOfDocs} CD documents in index {indexName}", i, indexName);
            }
        }
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>DocOnce Description</title>

    <link rel="stylesheet" href="_static/basic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="_static/bootstrap-3.3.4/css/bootstrap.min.css" type="text/css" />
    <link rel="stylesheet" href="_static/bootstrap-3.3.4/css/bootstrap-theme.min.css" type="text/css" />
    <link rel="stylesheet" href="_static/bootstrap-sphinx.css" type="text/css" />

    <link rel="top" title="DocOnce Description" href="#" />
    <link rel="next" title="DocOnce Description" href="manual.html" />

<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

          DocOnce Description
        1.0

  Site

DocOnce Description

What Is DocOnce?

Demos and Documentation

Markup Based on Special Lines

Heading with title and author(s)

Copyright

Table of contents

Section headings

Abstract

Appendix

Figures

Basic syntax

Figure Placement

Figure References

Inline Figures

Handling Variable Figure Paths

Figures with Subfigures

Sidecaption in LaTeX and HTML

Plot Files in LaTeX

Interactive Bokeh Plots for HTML

Converting Matplotlib Plots to Bokeh

Movies

The Basic Command

MP4, WebM, and Ogg Movies in HTML

Movie Handling in Various Formats

YouTube and Vimeo Movies

Animation Based on Filename Generators

Copying Computer Code from Source Files

Inserting the Output from Operating System Commands

Comments

Tables

Basic Syntax

Quick way of creating tables

Tables from DocOnce to CSV Data Files

Lists

Inline Tagging

Emphasized Words

Inline Verbatim Text

Links to Web Addresses

Links to Mail Addresses

Links to Local Files

Quotes

Non-Breaking Space

Horizontal rule

Em-dash

En-dash

Ampersand

Footnotes

Inline Comments

Inline Comments for Editing

Forced Line Breaks

Inline Mathematics

Cross-Referencing

Generalized Cross-Referencing

Generalized References

Generalized References to Chapters

Generalized References to LaTeX Documents

Tool for Generating Generalized References

A Worked Example

Index

Emojis

Exercises, Problems, Projects, and Examples

Examples on Exercise Syntax

Elements in an Exercise

Solutions

Example

Exercise versus Problem and Project

Modified Heading

Data Structure for all Exercises

Typesetting of Exercises

Remark on Typesettng of Examples

List of Exercises, Problems, and Projects

Numbering of Extra Equations in Solutions

Book

Use the tag command

Typesetting of solutions to exercises

Extracting Selected Exercises in a Separate Document

Extracting Exercises as Stand-Alone Documents

Example on an Exercise

Exercise 1: Compute integrals

Remarks

Other Environments

Blocks of Verbatim Computer Code

Typesetting Styles

Executable and Non-Executable Code

Hiding code blocks in HTML

Customizing Code Environments Types for Sphinx

Examples

Copying Code from Source Files

The fromto and from-to directives

Removing indentation in copied code

LaTeX Blocks of Mathematical Text

Support of LaTeX Math in Various Output Formats

ePub and Mobi

Apple iBook Format

Dealing with Mathematics in Formats without LaTeX Math Support

Mathematics for PowerPoint/OpenOffice

Macros (Newcommands)

Writing Guidelines (Especially for LaTeX Users!)

Typesetting of Algorithms

Admonitions

Examples on Admonition Types

Layout of Admonitions in HTML

Layout of Admonitions in LaTeX

LaTeX code Environments Inside Admonitions

The Box Environment

User-Defined Environments

Example 1: Addition

Bibliography (References)

Importing your data to the Publish database

Requirements to input data

Adding new references to the database

Exporting the database

Referring to publications

Specifying the Publish database

LaTeX Bibliography Style

Preprocessing and Postprocessing

The Preprocess and Mako Preprocessors

Splitting Documents into Smaller Pieces

Writing Slides

Overview

Slide Types

Syntax

Slide Elements

Title page

Parts Page

Standard bullet list page

Equations, movies, figures

HTML5 Slides

Potential Problems

LaTeX Beamer Slides

Themes

Pop of list items and blocks

Compilation

Support for non-English

Misc

Missing Features

Git .gitignore File

Emacs DocOnce Formatter

Atom Syntax Highlighting for DocOnce

Mako Programming

The Basics of Mako

Debugging Python code in Mako

Example: Nomenclature functionality

Example: Executing Python and using SymPy Objects in LaTeX

Example: Extending Tables to Handle Figures

Solution for LaTeX and HTML

Generating the Entire Table

Generating the Entire Table in a Native Format via Mako

Generating the Entire Table in a Native Format as a Post Process

Example: Defining a Theorem Environment

Tools for Writing DocOnce Documents

Debugging

From DocOnce to Other Formats

Writing a Makefile

Generating a Makefile

Spell checking

Preprocessing

Variable Substition with Preprocessors

Removal of Inline Comments

Notes

Demo of Different Formats

Tweaking the DocOnce Output

Useful Options for doconce format

HTML

Basic HTML Output

Typesetting of Code

Handling of Movies

HTML Styles

HTML templates

Splitting HTML documents

The HTML File Collection

Filenames

URL to files hosted on GitHub

Other HTML options

Blog Posts

Pandoc and Markdown

Markdown to HTML conversion

Strict Markdown

GitHub-flavored Markdown

MultiMarkdown

Strapdown rendering of Markdown text

Using Pandoc to go from LaTeX to MS Word or HTML

LaTeX

Overview

The old ptex2tex step

LaTeX-PDF: Generate LaTeX (Step 1)

The translation command

Newcommands

Output for paper vs screen

Command-line options

Syntax highlighting

Drafts

Potential problems with ampersand

Part 2 of Step 1 (outdated)

LaTeX-PDF: Edit the LaTeX File (Step 2, Optional)

LaTeX-PDF: Generate PDF (Step 3)

XeLaTeX

From PDF to e-book formats

Microsoft Word or LibreOffice

Jupyter (IPython) Notebooks

Hidden code blocks

Displaying code as plain text instead of executable cells

Figures

Movies

Admonitions

References to an External Textbook

Conversion from Notebook Back to DocOnce

Matlab Notebooks

Plain ASCII Text

reStructuredText

Sphinx

The Basic Steps

Links

Themes

Using a Your Own Configuration File

Compiling Multiple Themes

Example

RunestoneInteractive books

The manual Sphinx procedure

Wiki Formats

Google Docs

Options for the doconce commands

doconce format command-line options

Installation of DocOnce and its Dependencies

DocOnce

Dependencies

Python v2.7

Preprocessors

Bibliography

Image file handling

Spellcheck

Ptex2tex for LaTeX Output

Pygments and the Minted Code Style

LaTeX packages

Sphinx or reStructuredText Output

Markdown and Pandoc Output

Epydoc Output

Analyzing file differences

Basic Parsing Ideas

Typesetting of Function Arguments, Return Values, and Variables

References

  Page

DocOnce Description

Index

    DocOnce Descr... »

<form class="navbar-form navbar-right" action="search.html" method="get">

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

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

DocOnce Description¶

Contents:

DocOnce Description

What Is DocOnce?

Markup Based on Special Lines

Inline Tagging

Exercises, Problems, Projects, and Examples

Other Environments

Bibliography (References)

Preprocessing and Postprocessing

Writing Slides

Support for non-English

Misc

Mako Programming

From DocOnce to Other Formats

HTML

Pandoc and Markdown

LaTeX

Jupyter (IPython) Notebooks

Matlab Notebooks

Plain ASCII Text

reStructuredText

Sphinx

Wiki Formats

Google Docs

Options for the doconce commands

Installation of DocOnce and its Dependencies

Basic Parsing Ideas

References

Index¶

Index

      Back to top

  Source

        © Copyright 2016, Hans Petter Langtangen.

      Created using DocOnce and Sphinx 1.4.4.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.apache.ddlutils.platform (DdlUtils 1.0 API Documentation)
</TITLE>

<META NAME="keywords" CONTENT="org.apache.ddlutils.platform package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

org.apache.ddlutils.platform

Classes

CreationParameters

DatabaseMetaDataWrapper

DefaultTableDefinitionChangesPredicate

DefaultValueHelper

JdbcModelReader

MetaDataColumnDescriptor

ModelBasedResultSetIterator

PlatformImplBase

SqlBuilder


text:
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System;
using UniLua;

//环境光属性
namespace Hstj
{
    public class LuaExport :LuaObject
    {
        protected string m_szResult = "";

        void Start()
        {
            Init();
        }
        public virtual void Init()
        {
        }
        //==================public property function==============================
        public ILuaState _fileLua
        {
            get
            {
                return Game.LuaApi;
            }
        }
        public string ResultString
        {
            set
            {
                m_szResult = value;
//                 _fileLua.L_DoString("return" + value);
//                 ImportProperty();
//                 _fileLua.Pop(1);
            }
            get
            {
                return m_szResult;
            }
        }
        public virtual string[] PropertyString
        {
            get
            {
                return new string[] { "ambientLight", "ambientIntensity", "fog", "fogColor", "fogDensity", "fogEndDistance", "fogMode", "fogStartDistance"};
            }
        }
        //==================public function=======================================
        protected override void ExtraRefLua()
        {
            Game.Lua.SetTableFunction(-1, "ImportProperty", new CSharpFunctionDelegate(Lua_ImportProperty));
        }
        protected override bool WidgetReadOper(ILuaState lua, string key)
        {
            switch (key)
            {
                case "name":
                    lua.PushString(gameObject.name);
                    break;
                case "fDir":
                    lua.PushNumber(transform.localEulerAngles.y);
                    break;
                case "position":
                    Vector3ToStack(lua, transform.position);
                    break;
                case "localPosition":
                    Vector3ToStack(lua, transform.localPosition);
                    break;
                case "localRotate":
                    Vector3ToStack(lua, transform.localEulerAngles);
                    break;
                case "localScale":
                    Vector3ToStack(lua, transform.localScale);
                    break;
                case "ambientLight":
                    ColorToStack(lua, RenderSettings.ambientLight);
                    break;
                case "ambientIntensity":
#if UNITY_4_6
                    lua.PushNumber(1.0);
#else
                    lua.PushNumber(RenderSettings.ambientIntensity);
#endif
                    break;
                case "fog":
                    lua.PushBoolean(RenderSettings.fog);
                    break;
                case "fogColor":
                    ColorToStack(lua, RenderSettings.fogColor);
                    break;
                case "fogDensity":
                    lua.PushNumber(RenderSettings.fogDensity);
                    break;
                case "fogEndDistance":
                    lua.PushNumber(RenderSettings.fogEndDistance);
                    break;
                case "fogMode":
                    lua.PushInteger((int)RenderSettings.fogMode);
                    break;
                case "fogStartDistance":
                    lua.PushNumber(RenderSettings.fogStartDistance);
                    break;
                default:
                    return false;
            }
            return true;
        }
        protected override bool WidgetWriteOper(ILuaState lua, string key)
        {
            //Debug.Log("LuaExport:StramImportOper:"+key);
            int dwStackIndex = lua.GetTop();
            switch (key)
            {
                case "name":
                    gameObject.name = lua.L_CheckString(3);
                    break;
                case "fDir":
                    transform.localEulerAngles = new Vector3(0, (float)lua.L_CheckNumber(3), 0);
                    break;
                case "position":
                    transform.position = GetVector3(lua, 3);
                    break;
                case "localPosition":
                    transform.localPosition = GetVector3(lua, 3);
                    break;
                case "localRotate":
                    transform.localEulerAngles = GetVector3(lua, 3);
                    break;
                case "localScale":
                    transform.localScale = GetVector3(lua, 3);
                    break;
                case "ambientLight":
                    RenderSettings.ambientLight = GetColor(lua, 3);
                    break;
                case "ambientIntensity":
#if UNITY_4_6

#else
                    RenderSettings.ambientIntensity = (float)lua.ToNumber(3);
#endif
                    break;
                case "fog":
                    RenderSettings.fog = lua.ToBoolean(3);
                    break;
                case "fogColor":
                    RenderSettings.fogColor = GetColor(lua, 3);
                    break;
                case "fogDensity":
                    RenderSettings.fogDensity = (float)lua.ToNumber(3);
                    break;
                case "fogEndDistance":
                    RenderSettings.fogEndDistance = (float)lua.ToNumber(3);
                    break;
                case "fogMode":
                    RenderSettings.fogMode = (FogMode)lua.ToInteger(3);;
                    break;
                case "fogStartDistance":
                    RenderSettings.fogStartDistance = (float)lua.ToNumber(3);
                    break;
                default:
                    return false;
            }
            if (dwStackIndex != lua.GetTop())
                Debug.LogWarning("LuaExport:WidgetWriteOper stack Exception:start=" + key + ":" + dwStackIndex + " end=" + lua.GetTop());
            return true;
        }
        /// <summary>
        /// 将Table序列化成为字符串写入文件
        /// </summary>
        public string SerializeTable(int index)
        {
            //获取LibCore中_SerializeTable函数,然后串行化table, 以后要重写,从而不依赖LibCore(因为有在非运行状态下获取内容)
            if (_fileLua.Type(index) != LuaType.LUA_TTABLE)
            {
                Debug.LogWarning("LuaExport:SerializeTable param must a table.. please check");
                return "";
            }
            int dwStackIndex = _fileLua.GetTop();
            _fileLua.PushValue(index);
            _fileLua.GetGlobal("_SerializeTable");
            _fileLua.Insert(-2);
            _fileLua.PushBoolean(false);
            if (_fileLua.PCall(2, 1, 0) != 0)
            {
                Debug.LogWarning(_fileLua.ToString(-1) + " in SerializeTable");
                _fileLua.Pop(-1);
                return "";
            }
            m_szResult = _fileLua.ToString(-1);
            //Debug.Log(m_szResult);
            _fileLua.Pop(1);
            if (dwStackIndex != _fileLua.GetTop())
                Debug.LogWarning("LuaExport:SerializeTable stack Exception:start=" + dwStackIndex + " end=" + _fileLua.GetTop());
            return m_szResult;
        }
        /// <summary>
        /// 获取文件大小
        /// </summary>
        public long GetFileSize(string path)
        {
            FileStream fstream = File.OpenRead(path);
            long len = fstream.Seek(0, SeekOrigin.End);
            fstream.Close();
            return len;
        }
        /// <summary>
        ///
        /// </summary>
        public static Vector3 GetVector2(ILuaState lua, int dwIndex)
        {
            Vector2 v = Vector2.zero;
            lua.PushValue(dwIndex);
            lua.PushString("x");
            lua.GetTable(-2);
            v.x = (float)lua.ToNumber(-1);
            lua.Pop(1);

            lua.PushString("y");
            lua.GetTable(-2);
            v.y = (float)lua.ToNumber(-1);
            lua.Pop(1);

            lua.Pop(1);

            return v;
        }
        public static Vector3 GetVector3(ILuaState lua, int dwIndex)
        {
            return LuaItween.GetVector3(lua, dwIndex);
        }
        public static Vector3[] GetPath(ILuaState lua, int dwIndex)
        {
            return LuaItween.GetPath(lua, dwIndex);
        }
        public static Quaternion GetQuaternion(ILuaState lua, int dwIndex)
        {
            Quaternion v = new Quaternion();
            lua.PushValue(dwIndex);
            lua.PushString("x");
            lua.GetTable(-2);
            v.x = (float)lua.ToNumber(-1);
            lua.Pop(1);

            lua.PushString("y");
            lua.GetTable(-2);
            v.y = (float)lua.ToNumber(-1);
            lua.Pop(1);

            lua.PushString("z");
            lua.GetTable(-2);
            v.z = (float)lua.ToNumber(-1);
            lua.Pop(1);

            lua.PushString("w");
            lua.GetTable(-2);
            v.w = (float)lua.ToNumber(-1);
            lua.Pop(1);

            lua.Pop(1);
            return v;
        }
        public static Color GetColor(ILuaState lua, int dwIndex)
        {
            Color v = Color.black;
            lua.PushValue(dwIndex);
            lua.PushString("r");
            lua.GetTable(-2);
            v.r = (float)lua.ToNumber(-1);
            lua.Pop(1);

            lua.PushString("g");
            lua.GetTable(-2);
            v.g = (float)lua.ToNumber(-1);
            lua.Pop(1);

            lua.PushString("b");
            lua.GetTable(-2);
            v.b = (float)lua.ToNumber(-1);
            lua.Pop(1);

            lua.PushString("a");
            lua.GetTable(-2);
            v.a = (float)lua.ToNumber(-1);
            lua.Pop(1);

            lua.Pop(1);
            return v;

        }
        public static normalInfo GetNormalInfo(ILuaState lua, int dwIndex)
        {
            normalInfo nInfo = new normalInfo();
            lua.PushValue(dwIndex);
            lua.PushString("LRAngle");
            lua.GetTable(-2);
            nInfo.rotationLR = (float)lua.ToNumber(-1);
            lua.Pop(1);

            lua.PushString("UDAngle");
            lua.GetTable(-2);
            nInfo.rotationUD = (float)lua.ToNumber(-1);
            lua.Pop(1);

            lua.PushString("distance");
            lua.GetTable(-2);
            nInfo.distance = (float)lua.ToNumber(-1);
            lua.Pop(1);

            lua.PushString("offset");
            lua.GetTable(-2);
            nInfo.offSet = GetVector3(lua, -1);
            lua.Pop(1);

            lua.Pop(1);
            return nInfo;

        }
        public static Keyframe GetKeyframe(ILuaState lua, int index)
        {
            Keyframe key = new Keyframe();
            lua.PushValue(index);
            lua.PushString("time");
            lua.GetTable(-2);
            key.time = (float)lua.ToNumber(-1);
            lua.Pop(1);

            lua.PushString("value");
            lua.GetTable(-2);
            key.value = (float)lua.ToNumber(-1);
            lua.Pop(1);

            lua.PushString("inTangent");
            lua.GetTable(-2);
            key.inTangent = (float)lua.ToNumber(-1);
            lua.Pop(1);

            lua.PushString("outTangent");
            lua.GetTable(-2);
            key.outTangent = (float)lua.ToNumber(-1);
            lua.Pop(1);

            lua.Pop(1);
            return key;

        }
        public static AnimationCurve GetAnimationCurve(ILuaState lua, int dwIndex)
        {
            AnimationCurve animCurve = new AnimationCurve();
            lua.PushValue(dwIndex);
            int count = lua.L_Len(-1);

            for (int i = 1; i <= count; i++)
            {
                lua.PushInteger(i);
                lua.GetTable(-2);
                Keyframe key = GetKeyframe(lua, -1);
                animCurve.AddKey(key);
                lua.Pop(1);
            }
            lua.Pop(1);
            return animCurve;
        }
        public static void Vector2ToStack(ILuaState lua, Vector2 v3)
        {
            lua.NewTable();
            lua.PushNumber(v3.x);
            lua.SetField(-2, "x");
            lua.PushNumber(v3.y);
            lua.SetField(-2, "y");
        }
        public static void Vector3ToStack(ILuaState lua, Vector3 v3)
        {
            lua.NewTable();
            lua.PushNumber(v3.x);
            lua.SetField(-2, "x");
            lua.PushNumber(v3.y);
            lua.SetField(-2, "y");
            lua.PushNumber(v3.z);
            lua.SetField(-2, "z");
        }
        public static void QuaternionToStack(ILuaState lua, Quaternion qat)
        {
            lua.NewTable();
            lua.PushNumber(qat.x);
            lua.SetField(-2, "x");
            lua.PushNumber(qat.y);
            lua.SetField(-2, "y");
            lua.PushNumber(qat.z);
            lua.SetField(-2, "z");
            lua.PushNumber(qat.w);
            lua.SetField(-2, "w");
        }
        public static void ColorToStack(ILuaState lua, Color cr)
        {
            lua.NewTable();
            lua.PushNumber(cr.r);
            lua.SetField(-2, "r");
            lua.PushNumber(cr.g);
            lua.SetField(-2, "g");
            lua.PushNumber(cr.b);
            lua.SetField(-2, "b");
            lua.PushNumber(cr.a);
            lua.SetField(-2, "a");
        }
        public static void NormalInfoToStack(ILuaState lua, normalInfo nor)
        {
            lua.NewTable();
            lua.PushNumber(nor.distance);
            lua.SetField(-2, "distance");
            lua.PushNumber(nor.rotationLR);
            lua.SetField(-2, "LRAngle");
            lua.PushNumber(nor.rotationUD);
            lua.SetField(-2, "UDAngle");
            Vector3ToStack(lua, nor.offSet);
            lua.SetField(-2, "offset");
        }
        public static void KeyframeToStack(ILuaState lua, Keyframe keys)
        {
            lua.NewTable();
            lua.PushNumber(keys.time);
            lua.SetField(-2, "time");
            lua.PushNumber(keys.value);
            lua.SetField(-2, "value");
            lua.PushNumber(keys.inTangent);
            lua.SetField(-2, "inTangent");
            lua.PushNumber(keys.outTangent);
            lua.SetField(-2, "outTangent");
        }
        public static void AnimationCurveToStack(ILuaState lua, AnimationCurve aniCurve)
        {
            lua.NewTable();
            for (int i = 0; i < aniCurve.keys.Length;i++ )
            {
                lua.PushNumber(i+1);
                Keyframe key = aniCurve.keys[i];
                KeyframeToStack(lua, key);
                lua.SetTable(-3);
            }
        }
        //===================virtual function====================================

        /// <summary>
        /// 导出组件属性到文件   //, FileStream可以导出transform基本属性,如position, localPosition, localRotate, localScale
        /// </summary>
        public virtual string ExportProperty(string[] strProperty)
        {
            string[] listProperty = null;
            if (strProperty !=null)
                listProperty = strProperty;
            else
                listProperty = strProperty;
            _fileLua.NewTable();
            bool bSet = false;
            foreach (string key in listProperty)
            {
                bSet = WidgetReadOper(_fileLua, key);
                if (bSet == true)
                {
                    _fileLua.SetField(-2, key);
                }
            }
            string strResult = SerializeTable(-1);
            //_fileLua.Pop(1);
            return strResult;
        }
        /// <summary>
        /// 导入: 从文件或者表中读取属性,生成新的组件或改变现有组件属性
        /// </summary>
        public virtual void ImportProperty(int dwIndex)
        {
            bool bFlag = false;
            _fileLua.PushValue(dwIndex);
            _fileLua.PushNil();
            while (_fileLua.Next(-2))
            {
                string key = _fileLua.L_CheckString(-2);
                _fileLua.Insert(3);
                bFlag = WidgetWriteOper(_fileLua, key);
                _fileLua.Remove(3);
                if (bFlag == false)
                {
                   Debug.Log("LuaExport ImportProperty can't find Property key[:"+key+":] check....");
                }

            }
            _fileLua.Pop(1);
        }
        /////////////////////////////////////////////////////////////
        int Lua_ImportProperty(ILuaState lua)
        {
            if (lua.Type(2) != LuaType.LUA_TTABLE)
            {
                Debug.LogWarning("LuaExport:ImportProperty param1 is not table...");
                return 0;
            }
            Debug.Log("Lua_ImportProperty:"+lua.GetTop()+":"+lua.Type(-1));
            ImportProperty(2);
            Debug.Log("Lua_ImportProperty:"+lua.GetTop()+":"+lua.Type(-1));
            return 0;
        }
    }
}


text:
PATH=../src:/usr/local/lib/sh:$PATH

. tap.shl
plan 5

if [ "$OS" = "darwin" ]; then
    errno_opts='-f /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/errno.h'
fi

is "$(errno $errno_opts 4)" \
    '  4: EINTR       Interrupted system call' \
    "find error by number"

is "$(errno $errno_opts EINTR)" \
    '  4: EINTR       Interrupted system call' \
    "find error by code"

is "$(errno $errno_opts 'system call')" \
    '  4: EINTR       Interrupted system call' \
    "find error by (approximate) description"

expected="\
  4: EINTR       Interrupted system call
 23: ENFILE      Too many open files in system
 30: EROFS       Read-only file system"

is "$(errno $errno_opts 'system')" "$expected" \
    "find by description can return multiple results"

expected="\
  4: EINTR       Interrupted system call
 34: ERANGE      Result too large"

is "$(errno $errno_opts 4 34)" "$expected" \
    "can find by multiple arguments"


text:
Building
--------

1. Perform the standard cmake operations in the to create a build directory

2. run the make command to complie

3. If you are on a GPU capable device with cuda installed you will see two executables

	- GpuCpuTest: this will be the comparision test, the main exectuable to run

	- CpuRun: just a way to test the opencv implmenetion on a device without a GPU

4. Execute the GpuCpuTest in order to see the comparison


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycotaxon 9(1): 240 (1979)

#### Original name
Chrysoconia McCabe & G.A. Escobar

### Remarks
null


text:
import Logger from "utils/Logger";

export const { logDebug, logError } = new Logger( "ChatService" );


text:
var Client = require('ssh2').Client,
	connection_options = require('../config/cluster-config').connection_options;

exports.run = function(cluster, callback) {
	var conn = new Client();
	var shardStatusCmd = 'mongo --port ' + cluster.manager.port + ' --eval "sh.status()"';

	conn.on('ready', function() {
  	conn.exec(shardStatusCmd, function(err, stream) {
	    if (err) {
	    	throw err;
	    }
	    var clusterStatus = '',
	    		errMsg = '';

	    stream.setEncoding("utf8");
	    stream.on('close', function(code, signal) {
	      conn.end();
	      var res = {
	      	code: code,
	      	signal: signal,
	      	msg: errMsg? errMsg : clusterStatus
	      }
	      callback(null, res);
	    })
	    .on('data', function(data) {
	      clusterStatus += data;
	    })
	    .stderr.on('data', function(data) {
	      errMsg += data;
	    });
  	});
	}).connect({
  	host: cluster.manager.host,
  	port: 22,
  	username: connection_options.username,
  	privateKey: connection_options.privateKey
	});
}

exports.name = "Monitor Mongo Shard";


text:
Configure Magento Onepage Checkout Steps!!

## Features
### Disabling steps
#### Login
Pure guest checkout. (Login removed and straight to guest billing.)

Mixed checkout. (Register radio button on billing and login popup.)

Login required. (When login is required, you cannot remove the login step.)

#### Billing
Unable to remove billing.

#### Shipping
When removed, you can choose to add this step to the billing.

#### Shipping Method
When removed, you need to pick a default shipping method which will be used.

#### Payment Method
When removed, you need to pick a default payment method which will be used.

#### Review
When removed, will be merged with payment method.

### Other
#### Persistent checkout
Remember data for a not logged-in user after return to cart / refresh.

#### Show products and total sidebar.
Above the regular progress bar.

#This project is under construction!
Currently working:

##Login
Pure guest checkout. (Login removed and straight to guest billing.)

Mixed checkout. (Register radio button on billing and login popup.)

## Other
Persistent checkout

#### This extension is being developed in Magento 1.9.1 later versions will be tested after, backwards compatibility is the final stage


text:
/*
 * This file is to be included at the top of the header files defining the
 * interface to individual codecs and contains various workarounds common
 * to all codec implementations.
 */
#ifdef __cplusplus
extern "C" {
#endif


text:
/*
 * This file is part of the Mingw32 package.
 *
 * This file.h maps to the root fcntl.h
 * TODO?
 */
#include <fcntl.h>


text:
//
//  ViewController.m
//  TestPresent
//
//  Created by gaokunpeng on 15/8/5.
//  Copyright (c) 2015年 qianfeng. All rights reserved.
//

#import "ViewController.h"
#import "SecondViewController.h"
#import "ThirdViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

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

//storyboard传参
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    //从哪一个视图控制器跳转
    //id sCtrl = segue.sourceViewController;
    //跳转后的视图控制器对象
    id destCtrl = segue.destinationViewController;

    if ([destCtrl isKindOfClass:[SecondViewController class]]) {
        //传递参数
        SecondViewController *secondCtrl = (SecondViewController *)destCtrl;
        secondCtrl.param = @"参数二";

    }
}
//第二种方式
- (IBAction)click2ndBtn:(id)sender {
    /*
     第一个参数:segue对象的标示符
     第二个参数:触发跳转的对象(nil)
     */
    [self performSegueWithIdentifier:@"secondSegue" sender:nil];

}

//第三种方式
- (IBAction)click3rdBtn:(id)sender {

    //创建视图控制器对象
    /*
     第一个参数:storyboard文件的名字
     第二个参数:nil(mainBundle)
     */
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    //参数:视图控制器在storyboard里面的标示符
    ThirdViewController *thirdCtrl = [sb instantiateViewControllerWithIdentifier:@"third"];
    thirdCtrl.param = @"第三个参数";

    [self presentViewController:thirdCtrl animated:YES completion:nil];
}
@end


text:
import StringUtil from './StringUtil.js'

const MONTH_NAME = ['January','February','March','April','May','June','July','August','September','October','November','December'];
const MONTH_ABBR = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

const DateUtil = {

	monthName: function(date) {
		return MONTH_NAME[date.getMonth()];
	},

	monthAbbr: function(date) {
		return MONTH_ABBR[date.getMonth()];
	},

	toString: function(date) {
		// TODO: add format option
		var day = StringUtil.leftPad(date.getDate(), '0', 2);
		let month = StringUtil.leftPad(date.getMonth() + 1, '0', 2);
		let year = date.getFullYear();

		// return month + '/' + day + '/' + year;
		return year + '-' + month + '-' + day;
	},

	toDate: function(value) {
		if(value instanceof Date) {
			return value;
		}

		if(typeof value === 'string') {
			return new Date(value);
		}

		throw new Error('Invalid date: ' + value);
	},

	daysInMonth: function(date) {
		date = DateUtil.toDate(date);

		date = new Date(date.getFullYear(), date.getMonth()+1, 0);

		return date.getDate();
	},

	firstDayOfMonth: function(date) {
		date = DateUtil.toDate(date);

		date = new Date(date.getFullYear(), date.getMonth(), 1);

		return date.getDay();
	},

	weekOfMonth: function(date) {
		let firstDay = DateUtil.firstDayOfMonth(date);

		return Math.floor((date.getDate() + firstDay) / 7);
	},

	weeksInMonth: function(date) {
		let daysInMonth = DateUtil.daysInMonth(date);

		date = new Date(date.getFullYear(), date.getMonth(), daysInMonth - 1);

		return DateUtil.weekOfMonth(date) + 1;
	}
};

export default DateUtil;


text:
<?php

namespace app\controllers;

use Yii;
use yii\web\AccessControl;
use yii\web\Controller;
use yii\web\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;

class SiteController extends Controller
{
	public function behaviors()
	{
		return [
			'access' => [
				'class' => AccessControl::className(),
				'only' => ['login', 'logout'],
				'rules' => [
					[
						'actions' => ['login'],
						'allow' => true,
						'roles' => ['?'],
					],
					[
						'actions' => ['logout'],
						'allow' => true,
						'roles' => ['@'],
					],
				],
			],
			'verbs' => [
				'class' => VerbFilter::className(),
				'actions' => [
					'delete' => ['post'],
				],
			],
		];
	}

	public function actions()
	{
		return [
			'error' => [
				'class' => 'yii\web\ErrorAction',
			],
			'captcha' => [
				'class' => 'yii\captcha\CaptchaAction',
				'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
			],
		];
	}

	public function actionIndex()
	{
		return $this->render('index');
	}

	public function actionLogin()
	{
		$model = new LoginForm();
		if ($model->load($_POST) && $model->login()) {
			return $this->goBack();
		} else {
			return $this->render('login', [
				'model' => $model,
			]);
		}
	}

	public function actionLogout()
	{
		Yii::$app->user->logout();
		return $this->goHome();
	}

	public function actionContact()
	{
		$model = new ContactForm;
		if ($model->load($_POST) && $model->contact(Yii::$app->params['adminEmail'])) {
			Yii::$app->session->setFlash('contactFormSubmitted');
			return $this->refresh();
		} else {
			return $this->render('contact', [
				'model' => $model,
			]);
		}
	}

	public function actionAbout()
	{
		return $this->render('about');
	}
}


text:
package node

import (
	"encoding/json"
	"net/http"
	"syscall"

	"strconv"

	"fmt"

	"github.com/gorilla/mux"
	client "github.com/zero-os/0-core/client/go-client"
	"github.com/zero-os/0-orchestrator/api/tools"
)

// SendSignalProcess is the handler for POST /nodes/{nodeid}/containers/{containername}/processes/{processid}
// Send signal to the process
func (api *NodeAPI) SendSignalProcess(w http.ResponseWriter, r *http.Request) {
	var reqBody ProcessSignal

	// decode request
	if err := json.NewDecoder(r.Body).Decode(&reqBody); err != nil {
		tools.WriteError(w, http.StatusBadRequest, err, "Error decoding request body")
		return
	}

	// validate request
	if err := reqBody.Validate(); err != nil {
		tools.WriteError(w, http.StatusBadRequest, err, "")
		return
	}

	vars := mux.Vars(r)
	pId, err := strconv.ParseUint(vars["processid"], 10, 64)

	if err != nil {
		tools.WriteError(w, http.StatusInternalServerError, err, "Error casting process id into an intiger")
		return
	}

	processId := client.ProcessId(pId)

	// Get container connection
	cl, err := tools.GetContainerConnection(r, api)
	if err != nil {
		tools.WriteError(w, http.StatusInternalServerError, err, "Failed to establish connection to container")
		return
	}

	// Send signal to the container process
	core := client.Core(cl)
	if err := core.KillProcess(processId, syscall.Signal(reqBody.Signal)); err != nil {
		errmsg := fmt.Sprintf("Error sending signal %s to process %s", reqBody.Signal, processId)
		tools.WriteError(w, http.StatusInternalServerError, err, errmsg)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}


text:
<?php
// Call Zend_View_Helper_Placeholder_RegistryTest::main() if this source file is executed directly.
if (!defined("PHPUnit_MAIN_METHOD")) {
    define("PHPUnit_MAIN_METHOD", "Zend_View_Helper_Placeholder_RegistryTest::main");
}

require_once dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/TestHelper.php';
require_once "PHPUnit/Framework/TestCase.php";
require_once "PHPUnit/Framework/TestSuite.php";

/** Zend_View_Helper_Placeholder_Registry */
require_once 'Zend/View/Helper/Placeholder/Registry.php';

/**
 * Test class for Zend_View_Helper_Placeholder_Registry.
 *
 * @category   Zend
 * @package    Zend_View
 * @subpackage UnitTests
 */
class Zend_View_Helper_Placeholder_RegistryTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var Zend_View_Helper_Placeholder_Registry
     */
    public $registry;

    /**
     * Runs the test methods of this class.
     *
     * @return void
     */
    public static function main()
    {
        require_once "PHPUnit/TextUI/TestRunner.php";

        $suite  = new PHPUnit_Framework_TestSuite("Zend_View_Helper_Placeholder_RegistryTest");
        $result = PHPUnit_TextUI_TestRunner::run($suite);
    }

    /**
     * Sets up the fixture, for example, open a network connection.
     * This method is called before a test is executed.
     *
     * @return void
     */
    public function setUp()
    {
        $registry = Zend_Registry::getInstance();
        if (isset($registry[Zend_View_Helper_Placeholder_Registry::REGISTRY_KEY])) {
            unset($registry[Zend_View_Helper_Placeholder_Registry::REGISTRY_KEY]);
        }
        $this->registry = new Zend_View_Helper_Placeholder_Registry();
    }

    /**
     * Tears down the fixture, for example, close a network connection.
     * This method is called after a test is executed.
     *
     * @return void
     */
    public function tearDown()
    {
        unset($this->registry);
    }

    /**
     * @return void
     */
    public function testCreateContainer()
    {
        $this->assertFalse($this->registry->containerExists('foo'));
        $this->registry->createContainer('foo');
        $this->assertTrue($this->registry->containerExists('foo'));
    }

    /**
     * @return void
     */
    public function testCreateContainerCreatesDefaultContainerClass()
    {
        $this->assertFalse($this->registry->containerExists('foo'));
        $container = $this->registry->createContainer('foo');
        $this->assertTrue($container instanceof Zend_View_Helper_Placeholder_Container);
    }

    /**
     * @return void
     */
    public function testGetContainerCreatesContainerIfNonExistent()
    {
        $this->assertFalse($this->registry->containerExists('foo'));
        $container = $this->registry->getContainer('foo');
        $this->assertTrue($container instanceof Zend_View_Helper_Placeholder_Container_Abstract);
        $this->assertTrue($this->registry->containerExists('foo'));
    }

    /**
     * @return void
     */
    public function testSetContainerCreatesRegistryEntry()
    {
        $foo = new Zend_View_Helper_Placeholder_Container(array('foo', 'bar'));
        $this->assertFalse($this->registry->containerExists('foo'));
        $this->registry->setContainer('foo', $foo);
        $this->assertTrue($this->registry->containerExists('foo'));
    }

    /**
     * @return void
     */
    public function testSetContainerCreatesRegistersContainerInstance()
    {
        $foo = new Zend_View_Helper_Placeholder_Container(array('foo', 'bar'));
        $this->assertFalse($this->registry->containerExists('foo'));
        $this->registry->setContainer('foo', $foo);
        $container = $this->registry->getContainer('foo');
        $this->assertSame($foo, $container);
    }

    /**
     * @return void
     */
    public function testContainerClassAccessorsSetState()
    {
        $this->assertEquals('Zend_View_Helper_Placeholder_Container', $this->registry->getContainerClass());
        $this->registry->setContainerClass('Zend_View_Helper_Placeholder_RegistryTest_Container');
        $this->assertEquals('Zend_View_Helper_Placeholder_RegistryTest_Container', $this->registry->getContainerClass());
    }

    /**
     * @return void
     */
    public function testSetContainerClassThrowsExceptionWithInvalidContainerClass()
    {
        try {
            $this->registry->setContainerClass('Zend_View_Helper_Placeholder_RegistryTest_BogusContainer');
            $this->fail('Invalid container classes should not be accepted');
        } catch (Exception $e) {
        }
    }

    public function testDeletingContainerRemovesFromRegistry()
    {
        $this->registry->createContainer('foo');
        $this->assertTrue($this->registry->containerExists('foo'));
        $result = $this->registry->deleteContainer('foo');
        $this->assertFalse($this->registry->containerExists('foo'));
        $this->assertTrue($result);
    }

    public function testDeleteContainerReturnsFalseIfContainerDoesNotExist()
    {
        $result = $this->registry->deleteContainer('foo');
        $this->assertFalse($result);
    }

    /**
     * @return void
     */
    public function testUsingCustomContainerClassCreatesContainersOfCustomClass()
    {
        $this->registry->setContainerClass('Zend_View_Helper_Placeholder_RegistryTest_Container');
        $container = $this->registry->createContainer('foo');
        $this->assertTrue($container instanceof Zend_View_Helper_Placeholder_RegistryTest_Container);
    }

    public function testGetRegistryReturnsRegistryInstance()
    {
        $registry = Zend_View_Helper_Placeholder_Registry::getRegistry();
        $this->assertTrue($registry instanceof Zend_View_Helper_Placeholder_Registry);
    }

    public function testGetRegistrySubsequentTimesReturnsSameInstance()
    {
        $registry1 = Zend_View_Helper_Placeholder_Registry::getRegistry();
        $registry2 = Zend_View_Helper_Placeholder_Registry::getRegistry();
        $this->assertSame($registry1, $registry2);
    }

    public function testGetRegistryRegistersWithGlobalRegistry()
    {
        $this->assertFalse(Zend_Registry::isRegistered(Zend_View_Helper_Placeholder_Registry::REGISTRY_KEY));
        $registry = Zend_View_Helper_Placeholder_Registry::getRegistry();
        $this->assertTrue(Zend_Registry::isRegistered(Zend_View_Helper_Placeholder_Registry::REGISTRY_KEY));

        $registered = Zend_Registry::get(Zend_View_Helper_Placeholder_Registry::REGISTRY_KEY);
        $this->assertSame($registry, $registered);
    }
}

class Zend_View_Helper_Placeholder_RegistryTest_Container extends Zend_View_Helper_Placeholder_Container_Abstract
{
}

class Zend_View_Helper_Placeholder_RegistryTest_BogusContainer
{
}

// Call Zend_View_Helper_Placeholder_RegistryTest::main() if this source file is executed directly.
if (PHPUnit_MAIN_METHOD == "Zend_View_Helper_Placeholder_RegistryTest::main") {
    Zend_View_Helper_Placeholder_RegistryTest::main();
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>co.vandenham.telegram.botapi (TelegramBots4Java)</title>
<meta name="date" content="2015-09-01">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

co.vandenham.telegram.botapi

Interfaces

AbstractChatContextFactory

RegistrableTelegramBot.MessageListener

Classes

ChatContext

ChatContextTelegramBot

HandlerNotifier

RegistrableTelegramBot

TelegramBot

Annotation Types

CommandHandler

DefaultHandler

MessageHandler