text:
package com.vaadin.server;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.jsoup.nodes.DataNode;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.DocumentType;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.parser.Tag;

import com.google.gwt.thirdparty.guava.common.net.UrlEscapers;
import com.vaadin.annotations.JavaScript;
import com.vaadin.annotations.StyleSheet;
import com.vaadin.annotations.Viewport;
import com.vaadin.annotations.ViewportGeneratorClass;
import com.vaadin.server.communication.AtmospherePushConnection;
import com.vaadin.shared.ApplicationConstants;
import com.vaadin.shared.VaadinUriResolver;
import com.vaadin.shared.Version;
import com.vaadin.shared.communication.PushMode;
import com.vaadin.ui.UI;

import elemental.json.Json;
import elemental.json.JsonException;
import elemental.json.JsonObject;
import elemental.json.impl.JsonUtil;

/**
 *
 * @author Vaadin Ltd
 * @since 7.0.0
 *
 * @deprecated As of 7.0. Will likely change or be removed in a future version
 */
@Deprecated
public abstract class BootstrapHandler extends SynchronizedRequestHandler {

    /**
     * Parameter that is added to the UI init request if the session has already
     * been restarted when generating the bootstrap HTML and ?restartApplication
     * should thus be ignored when handling the UI init request.
     */
    public static final String IGNORE_RESTART_PARAM = "ignoreRestart";

    protected class BootstrapContext implements Serializable {

        private final VaadinResponse response;
        private final BootstrapFragmentResponse bootstrapResponse;

        private String widgetsetName;
        private String themeName;
        private String appId;
        private PushMode pushMode;
        private JsonObject applicationParameters;
        private VaadinUriResolver uriResolver;

        public BootstrapContext(VaadinResponse response,
                BootstrapFragmentResponse bootstrapResponse) {
            this.response = response;
            this.bootstrapResponse = bootstrapResponse;
        }

        public VaadinResponse getResponse() {
            return response;
        }

        public VaadinRequest getRequest() {
            return bootstrapResponse.getRequest();
        }

        public VaadinSession getSession() {
            return bootstrapResponse.getSession();
        }

        public Class<? extends UI> getUIClass() {
            return bootstrapResponse.getUiClass();
        }

        public String getWidgetsetName() {
            if (widgetsetName == null) {
                widgetsetName = getWidgetsetForUI(this);
            }
            return widgetsetName;
        }

        public String getThemeName() {
            if (themeName == null) {
                themeName = findAndEscapeThemeName(this);
            }
            return themeName;
        }

        public PushMode getPushMode() {
            if (pushMode == null) {
                UICreateEvent event = new UICreateEvent(getRequest(),
                        getUIClass());

                pushMode = getBootstrapResponse().getUIProvider().getPushMode(
                        event);
                if (pushMode == null) {
                    pushMode = getRequest().getService()
                            .getDeploymentConfiguration().getPushMode();
                }

                if (pushMode.isEnabled()
                        && !getRequest().getService().ensurePushAvailable()) {
                    /*
                     * Fall back if not supported (ensurePushAvailable will log
                     * information to the developer the first time this happens)
                     */
                    pushMode = PushMode.DISABLED;
                }
            }
            return pushMode;
        }

        public String getAppId() {
            if (appId == null) {
                appId = getRequest().getService().getMainDivId(getSession(),
                        getRequest(), getUIClass());
            }
            return appId;
        }

        public BootstrapFragmentResponse getBootstrapResponse() {
            return bootstrapResponse;
        }

        public JsonObject getApplicationParameters() {
            if (applicationParameters == null) {
                applicationParameters = BootstrapHandler.this
                        .getApplicationParameters(this);
            }

            return applicationParameters;
        }

        public VaadinUriResolver getUriResolver() {
            if (uriResolver == null) {
                uriResolver = new BootstrapUriResolver(this);
            }

            return uriResolver;
        }
    }

    private class BootstrapUriResolver extends VaadinUriResolver {
        private final BootstrapContext context;

        public BootstrapUriResolver(BootstrapContext bootstrapContext) {
            context = bootstrapContext;
        }

        @Override
        protected String getVaadinDirUrl() {
            return context.getApplicationParameters().getString(
                    ApplicationConstants.VAADIN_DIR_URL);
        }

        @Override
        protected String getThemeUri() {
            return getVaadinDirUrl() + "themes/" + context.getThemeName();
        }

        @Override
        protected String getServiceUrlParameterName() {
            return getConfigOrNull(ApplicationConstants.SERVICE_URL_PARAMETER_NAME);
        }

        @Override
        protected String getServiceUrl() {
            String serviceUrl = getConfigOrNull(ApplicationConstants.SERVICE_URL);
            if (serviceUrl == null) {
                return "./";
            } else if (!serviceUrl.endsWith("/")) {
                serviceUrl += "/";
            }
            return serviceUrl;
        }

        private String getConfigOrNull(String name) {
            JsonObject parameters = context.getApplicationParameters();
            if (parameters.hasKey(name)) {
                return parameters.getString(name);
            } else {
                return null;
            }
        }

        @Override
        protected String encodeQueryStringParameterValue(String queryString) {
            return UrlEscapers.urlFormParameterEscaper().escape(queryString);
        }
    }

    @Override
    protected boolean canHandleRequest(VaadinRequest request) {
        // We do not want to handle /APP requests here, instead let it fall
        // through and produce a 404
        return !ServletPortletHelper.isAppRequest(request);
    }

    @Override
    public boolean synchronizedHandleRequest(VaadinSession session,
            VaadinRequest request, VaadinResponse response) throws IOException {
        try {
            List<UIProvider> uiProviders = session.getUIProviders();

            UIClassSelectionEvent classSelectionEvent = new UIClassSelectionEvent(
                    request);

            // Find UI provider and UI class
            Class<? extends UI> uiClass = null;
            UIProvider provider = null;
            for (UIProvider p : uiProviders) {
                uiClass = p.getUIClass(classSelectionEvent);
                // If we found something
                if (uiClass != null) {
                    provider = p;
                    break;
                }
            }

            if (provider == null) {
                // Can't generate bootstrap if no UI provider matches
                return false;
            }

            BootstrapContext context = new BootstrapContext(response,
                    new BootstrapFragmentResponse(this, request, session,
                            uiClass, new ArrayList<Node>(), provider));

            setupMainDiv(context);

            BootstrapFragmentResponse fragmentResponse = context
                    .getBootstrapResponse();
            session.modifyBootstrapResponse(fragmentResponse);

            String html = getBootstrapHtml(context);

            writeBootstrapPage(response, html);
        } catch (JsonException e) {
            writeError(response, e);
        }

        return true;
    }

    private String getBootstrapHtml(BootstrapContext context) {
        VaadinRequest request = context.getRequest();
        VaadinResponse response = context.getResponse();
        VaadinService vaadinService = request.getService();

        BootstrapFragmentResponse fragmentResponse = context
                .getBootstrapResponse();

        if (vaadinService.isStandalone(request)) {
            Map<String, Object> headers = new LinkedHashMap<String, Object>();
            Document document = Document.createShell("");
            BootstrapPageResponse pageResponse = new BootstrapPageResponse(
                    this, request, context.getSession(), context.getUIClass(),
                    document, headers, fragmentResponse.getUIProvider());
            List<Node> fragmentNodes = fragmentResponse.getFragmentNodes();
            Element body = document.body();
            for (Node node : fragmentNodes) {
                body.appendChild(node);
            }

            setupStandaloneDocument(context, pageResponse);
            context.getSession().modifyBootstrapResponse(pageResponse);

            sendBootstrapHeaders(response, headers);

            return document.outerHtml();
        } else {
            StringBuilder sb = new StringBuilder();
            for (Node node : fragmentResponse.getFragmentNodes()) {
                if (sb.length() != 0) {
                    sb.append('\n');
                }
                sb.append(node.outerHtml());
            }

            return sb.toString();
        }
    }

    private void sendBootstrapHeaders(VaadinResponse response,
            Map<String, Object> headers) {
        Set<Entry<String, Object>> entrySet = headers.entrySet();
        for (Entry<String, Object> header : entrySet) {
            Object value = header.getValue();
            if (value instanceof String) {
                response.setHeader(header.getKey(), (String) value);
            } else if (value instanceof Long) {
                response.setDateHeader(header.getKey(),
                        ((Long) value).longValue());
            } else {
                throw new RuntimeException("Unsupported header value: " + value);
            }
        }
    }

    private void writeBootstrapPage(VaadinResponse response, String html)
            throws IOException {
        response.setContentType("text/html");
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                response.getOutputStream(), "UTF-8"));
        writer.append(html);
        writer.close();
    }

    private void setupStandaloneDocument(BootstrapContext context,
            BootstrapPageResponse response) {
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        Document document = response.getDocument();

        DocumentType doctype = new DocumentType("html", "", "",
                document.baseUri());
        document.child(0).before(doctype);

        Element head = document.head();
        head.appendElement("meta").attr("http-equiv", "Content-Type")
                .attr("content", "text/html; charset=utf-8");

        /*
         * Enable Chrome Frame in all versions of IE if installed.
         */
        head.appendElement("meta").attr("http-equiv", "X-UA-Compatible")
                .attr("content", "IE=11;chrome=1");

        Class<? extends UI> uiClass = context.getUIClass();

        String viewportContent = null;
        Viewport viewportAnnotation = uiClass.getAnnotation(Viewport.class);
        ViewportGeneratorClass viewportGeneratorClassAnnotation = uiClass
                .getAnnotation(ViewportGeneratorClass.class);
        if (viewportAnnotation != null
                && viewportGeneratorClassAnnotation != null) {
            throw new IllegalStateException(uiClass.getCanonicalName()
                    + " cannot be annotated with both @"
                    + Viewport.class.getSimpleName() + " and @"
                    + ViewportGeneratorClass.class.getSimpleName());
        }

        if (viewportAnnotation != null) {
            viewportContent = viewportAnnotation.value();
        } else if (viewportGeneratorClassAnnotation != null) {
            Class<? extends ViewportGenerator> viewportGeneratorClass = viewportGeneratorClassAnnotation
                    .value();
            try {
                viewportContent = viewportGeneratorClass.newInstance()
                        .getViewport(context.getRequest());
            } catch (Exception e) {
                throw new RuntimeException(
                        "Error processing viewport generator "
                                + viewportGeneratorClass.getCanonicalName(), e);
            }
        }

        if (viewportContent != null) {
            head.appendElement("meta").attr("name", "viewport")
                    .attr("content", viewportContent);
        }

        String title = response.getUIProvider().getPageTitle(
                new UICreateEvent(context.getRequest(), context.getUIClass()));
        if (title != null) {
            head.appendElement("title").appendText(title);
        }

        head.appendElement("style").attr("type", "text/css")
                .appendText("html, body {height:100%;margin:0;}");

        // Add favicon links
        String themeName = context.getThemeName();
        if (themeName != null) {
            String themeUri = getThemeUri(context, themeName);
            head.appendElement("link").attr("rel", "shortcut icon")
                    .attr("type", "image/vnd.microsoft.icon")
                    .attr("href", themeUri + "/favicon.ico");
            head.appendElement("link").attr("rel", "icon")
                    .attr("type", "image/vnd.microsoft.icon")
                    .attr("href", themeUri + "/favicon.ico");
        }

        JavaScript javaScript = uiClass.getAnnotation(JavaScript.class);
        if (javaScript != null) {
            String[] resources = javaScript.value();
            for (String resource : resources) {
                String url = registerDependency(context, uiClass, resource);
                head.appendElement("script").attr("type", "text/javascript")
                        .attr("src", url);
            }
        }

        StyleSheet styleSheet = uiClass.getAnnotation(StyleSheet.class);
        if (styleSheet != null) {
            String[] resources = styleSheet.value();
            for (String resource : resources) {
                String url = registerDependency(context, uiClass, resource);
                head.appendElement("link").attr("rel", "stylesheet")
                        .attr("type", "text/css").attr("href", url);
            }
        }

        Element body = document.body();
        body.attr("scroll", "auto");
        body.addClass(ApplicationConstants.GENERATED_BODY_CLASSNAME);
    }

    private String registerDependency(BootstrapContext context,
            Class<? extends UI> uiClass, String resource) {
        String url = context.getSession().getCommunicationManager()
                .registerDependency(resource, uiClass);

        url = context.getUriResolver().resolveVaadinUri(url);

        return url;
    }

    protected String getMainDivStyle(BootstrapContext context) {
        return null;
    }

    public String getWidgetsetForUI(BootstrapContext context) {
        VaadinRequest request = context.getRequest();

        UICreateEvent event = new UICreateEvent(context.getRequest(),
                context.getUIClass());
        String widgetset = context.getBootstrapResponse().getUIProvider()
                .getWidgetset(event);
        if (widgetset == null) {
            widgetset = request.getService().getConfiguredWidgetset(request);
        }

        widgetset = VaadinServlet.stripSpecialChars(widgetset);
        return widgetset;
    }

    /**
     * Method to write the div element into which that actual Vaadin application
     * is rendered.
     * <p>
     * Override this method if you want to add some custom html around around
     * the div element into which the actual Vaadin application will be
     * rendered.
     *
     * @param context
     *
     * @throws IOException
     */
    private void setupMainDiv(BootstrapContext context) throws IOException {
        String style = getMainDivStyle(context);

        /*- Add classnames;
         *      .v-app
         *      .v-app-loading
         *- Additionally added from javascript:
         *      <themeName, remove non-alphanum>
         */

        List<Node> fragmentNodes = context.getBootstrapResponse()
                .getFragmentNodes();

        Element mainDiv = new Element(Tag.valueOf("div"), "");
        mainDiv.attr("id", context.getAppId());
        mainDiv.addClass("v-app");
        mainDiv.addClass(context.getThemeName());
        mainDiv.addClass(context.getUIClass().getSimpleName()
                .toLowerCase(Locale.ENGLISH));
        if (style != null && style.length() != 0) {
            mainDiv.attr("style", style);
        }
        mainDiv.appendElement("div").addClass("v-app-loading");
        mainDiv.appendElement("noscript")
                .append("You have to enable javascript in your browser to use an application built with Vaadin.");
        fragmentNodes.add(mainDiv);

        VaadinRequest request = context.getRequest();

        VaadinService vaadinService = request.getService();
        String vaadinLocation = vaadinService.getStaticFileLocation(request)
                + "/VAADIN/";

        // Parameter appended to JS to bypass caches after version upgrade.
        String versionQueryParam = "?v=" + Version.getFullVersion();

        if (context.getPushMode().isEnabled()) {
            // Load client-side dependencies for push support
            String pushJS = vaadinLocation;
            if (context.getRequest().getService().getDeploymentConfiguration()
                    .isProductionMode()) {
                pushJS += ApplicationConstants.VAADIN_PUSH_JS;
            } else {
                pushJS += ApplicationConstants.VAADIN_PUSH_DEBUG_JS;
            }

            pushJS += versionQueryParam;

            fragmentNodes.add(new Element(Tag.valueOf("script"), "").attr(
                    "type", "text/javascript").attr("src", pushJS));
        }

        String bootstrapLocation = vaadinLocation
                + ApplicationConstants.VAADIN_BOOTSTRAP_JS + versionQueryParam;
        fragmentNodes.add(new Element(Tag.valueOf("script"), "").attr("type",
                "text/javascript").attr("src", bootstrapLocation));
        Element mainScriptTag = new Element(Tag.valueOf("script"), "").attr(
                "type", "text/javascript");

        StringBuilder builder = new StringBuilder();
        builder.append("//<![CDATA[\n");
        builder.append("if (!window.vaadin) alert("
                + JsonUtil.quote("Failed to load the bootstrap javascript: "
                        + bootstrapLocation) + ");\n");

        appendMainScriptTagContents(context, builder);

        builder.append("//]]>");
        mainScriptTag.appendChild(new DataNode(builder.toString(),
                mainScriptTag.baseUri()));
        fragmentNodes.add(mainScriptTag);

    }

    protected void appendMainScriptTagContents(BootstrapContext context,
            StringBuilder builder) throws IOException {
        JsonObject appConfig = context.getApplicationParameters();

        boolean isDebug = !context.getSession().getConfiguration()
                .isProductionMode();

        if (isDebug) {
            /*
             * Add tracking needed for getting bootstrap metrics to the client
             * side Profiler if another implementation hasn't already been
             * added.
             */
            builder.append("if (typeof window.__gwtStatsEvent != 'function') {\n");
            builder.append("vaadin.gwtStatsEvents = [];\n");
            builder.append("window.__gwtStatsEvent = function(event) {vaadin.gwtStatsEvents.push(event); return true;};\n");
            builder.append("}\n");
        }

        builder.append("vaadin.initApplication(\"");
        builder.append(context.getAppId());
        builder.append("\",");
        appendJsonObject(builder, appConfig, isDebug);
        builder.append(");\n");
    }

    private static void appendJsonObject(StringBuilder builder,
            JsonObject jsonObject, boolean isDebug) {
        if (isDebug) {
            builder.append(JsonUtil.stringify(jsonObject, 4));
        } else {
            builder.append(JsonUtil.stringify(jsonObject));
        }
    }

    protected JsonObject getApplicationParameters(BootstrapContext context) {
        VaadinRequest request = context.getRequest();
        VaadinSession session = context.getSession();
        VaadinService vaadinService = request.getService();

        JsonObject appConfig = Json.createObject();

        String themeName = context.getThemeName();
        if (themeName != null) {
            appConfig.put("theme", themeName);
        }

        // Ignore restartApplication that might be passed to UI init
        if (request
                .getParameter(VaadinService.URL_PARAMETER_RESTART_APPLICATION) != null) {
            appConfig.put("extraParams", "&" + IGNORE_RESTART_PARAM + "=1");
        }

        JsonObject versionInfo = Json.createObject();
        versionInfo.put("vaadinVersion", Version.getFullVersion());
        String atmosphereVersion = AtmospherePushConnection
                .getAtmosphereVersion();
        if (atmosphereVersion != null) {
            versionInfo.put("atmosphereVersion", atmosphereVersion);
        }

        appConfig.put("versionInfo", versionInfo);
        appConfig.put("widgetset", context.getWidgetsetName());

        // Use locale from session if set, else from the request
        Locale locale = ServletPortletHelper.findLocale(null,
                context.getSession(), context.getRequest());
        // Get system messages
        SystemMessages systemMessages = vaadinService.getSystemMessages(locale,
                request);
        if (systemMessages != null) {
            // Write the CommunicationError -message to client
            JsonObject comErrMsg = Json.createObject();
            putValueOrNull(comErrMsg, "caption",
                    systemMessages.getCommunicationErrorCaption());
            putValueOrNull(comErrMsg, "message",
                    systemMessages.getCommunicationErrorMessage());
            putValueOrNull(comErrMsg, "url",
                    systemMessages.getCommunicationErrorURL());

            appConfig.put("comErrMsg", comErrMsg);

            JsonObject authErrMsg = Json.createObject();
            putValueOrNull(authErrMsg, "caption",
                    systemMessages.getAuthenticationErrorCaption());
            putValueOrNull(authErrMsg, "message",
                    systemMessages.getAuthenticationErrorMessage());
            putValueOrNull(authErrMsg, "url",
                    systemMessages.getAuthenticationErrorURL());

            appConfig.put("authErrMsg", authErrMsg);

            JsonObject sessExpMsg = Json.createObject();
            putValueOrNull(sessExpMsg, "caption",
                    systemMessages.getSessionExpiredCaption());
            putValueOrNull(sessExpMsg, "message",
                    systemMessages.getSessionExpiredMessage());
            putValueOrNull(sessExpMsg, "url",
                    systemMessages.getSessionExpiredURL());

            appConfig.put("sessExpMsg", sessExpMsg);
        }

        // getStaticFileLocation documented to never end with a slash
        // vaadinDir should always end with a slash
        String vaadinDir = vaadinService.getStaticFileLocation(request)
                + "/VAADIN/";
        appConfig.put(ApplicationConstants.VAADIN_DIR_URL, vaadinDir);

        if (!session.getConfiguration().isProductionMode()) {
            appConfig.put("debug", true);
        }

        if (vaadinService.isStandalone(request)) {
            appConfig.put("standalone", true);
        }

        appConfig.put("heartbeatInterval", vaadinService
                .getDeploymentConfiguration().getHeartbeatInterval());

        String serviceUrl = getServiceUrl(context);
        if (serviceUrl != null) {
            appConfig.put(ApplicationConstants.SERVICE_URL, serviceUrl);
        }

        boolean sendUrlsAsParameters = vaadinService
                .getDeploymentConfiguration().isSendUrlsAsParameters();
        if (!sendUrlsAsParameters) {
            appConfig.put("sendUrlsAsParameters", false);
        }

        return appConfig;
    }

    protected abstract String getServiceUrl(BootstrapContext context);

    /**
     * Get the URI for the application theme.
     *
     * A portal-wide default theme is fetched from the portal shared resource
     * directory (if any), other themes from the portlet.
     *
     * @param context
     * @param themeName
     *
     * @return
     */
    public String getThemeUri(BootstrapContext context, String themeName) {
        VaadinRequest request = context.getRequest();
        final String staticFilePath = request.getService()
                .getStaticFileLocation(request);
        return staticFilePath + "/" + VaadinServlet.THEME_DIR_PATH + '/'
                + themeName;
    }

    /**
     * Override if required
     *
     * @param context
     * @return
     */
    public String getThemeName(BootstrapContext context) {
        UICreateEvent event = new UICreateEvent(context.getRequest(),
                context.getUIClass());
        return context.getBootstrapResponse().getUIProvider().getTheme(event);
    }

    /**
     * Do not override.
     *
     * @param context
     * @return
     */
    public String findAndEscapeThemeName(BootstrapContext context) {
        String themeName = getThemeName(context);
        if (themeName == null) {
            VaadinRequest request = context.getRequest();
            themeName = request.getService().getConfiguredTheme(request);
        }

        // XSS preventation, theme names shouldn't contain special chars anyway.
        // The servlet denies them via url parameter.
        themeName = VaadinServlet.stripSpecialChars(themeName);

        return themeName;
    }

    protected void writeError(VaadinResponse response, Throwable e)
            throws IOException {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                e.getLocalizedMessage());
    }

    private void putValueOrNull(JsonObject object, String key, String value) {
        assert object != null;
        assert key != null;
        if (value == null) {
            object.put(key, Json.createNull());
        } else {
            object.put(key, value);
        }
    }
}


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

<title>Conditional</title>
<meta name="date" content="2017-02-26">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

kariminf.faris.knowledge

Class Conditional

java.lang.Object

kariminf.faris.knowledge.Idea

kariminf.faris.knowledge.Conditional

public class Conditional
extends Idea

Author:

Abdelkrime Aries (kariminfo0@gmail.com)

         Copyright (c) 2015 Abdelkrime Aries

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

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

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

Field Summary

Fields

Modifier and Type
Field and Description

private Idea
condition

private Idea
predicate

Constructor Summary

Constructors

Modifier
Constructor and Description

protected
Conditional(Idea condition,
           Idea predicate)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
generate(Generator gr)

java.lang.String
toString()

Methods inherited from class kariminf.faris.knowledge.Idea

addIdea

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

condition

private Idea condition

predicate

private Idea predicate

Constructor Detail

Conditional

protected Conditional(Idea condition,
                      Idea predicate)

Parameters:

condition -

predicate -

Method Detail

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

generate

public void generate(Generator gr)

Specified by:

generate in class Idea

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

redpajama_set_name: RedPajamaGithub


text:
import { ChangeDetectionStrategy, ChangeDetectorRef, Component } from '@angular/core';

@Component({
  selector: 'header-task',
  template: `

      <nz-badge [nzDot]="true">

      </nz-badge>

    <nz-dropdown-menu #taskMenu="nzDropdownMenu">

<nz-spin></nz-spin>

        <nz-card *ngIf="!loading" nzTitle="Notifications" nzBordered="false" class="ant-card__body-nopadding">
          <ng-template #extra></ng-template>

              <nz-avatar [nzSrc]="'./assets/tmp/img/1.png'"></nz-avatar>

              cipchk

Please tell me what happened in a few words, don't go into details.

              <nz-avatar [nzSrc]="'./assets/tmp/img/2.png'"></nz-avatar>

              はなさき

ハルカソラトキヘダツヒカリ

              <nz-avatar [nzSrc]="'./assets/tmp/img/3.png'"></nz-avatar>

              苏先生

请告诉我,我应该说点什么好?

              <nz-avatar [nzSrc]="'./assets/tmp/img/4.png'"></nz-avatar>

              Kent

Please tell me what happened in a few words, don't go into details.

              <nz-avatar [nzSrc]="'./assets/tmp/img/5.png'"></nz-avatar>

              Jefferson

Please tell me what happened in a few words, don't go into details.

See All

        </nz-card>

    </nz-dropdown-menu>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class HeaderTaskComponent {
  loading = true;

  constructor(private cdr: ChangeDetectorRef) {}

  change(): void {
    setTimeout(() => {
      this.loading = false;
      this.cdr.detectChanges();
    }, 500);
  }
}


text:
from Proto import SortedMessage, CompareWrite, RecordNesting

TYPE_ENUM       = 0
TYPE_INT32      = 1
TYPE_INT64      = 2
TYPE_UINT32     = 3
TYPE_UINT64     = 4
TYPE_FIXEDPOINT = 5
TYPE_DOUBLE     = 6
TYPE_FLOAT      = 7
TYPE_BOOL       = 8
TYPE_BYTES      = 9
TYPE_STRING     = 10
TYPE_SYMBOL     = 11
TYPE_OBJECT     = 12
TYPE_VARIANT    = 13
TYPE_LIST       = 14
TYPE_DICT       = 15
TYPE_PYTHON     = 16
MAX_FIELD_TYPE  = 17

def _GenerateVariant(name, properties, codes, types):
	from typy.google.protobuf.internal.encoder import _TagSize
	from typy.google.protobuf.internal.wire_format import PackTag
	from Type import Type

	fields = []
	for i, (a, p) in enumerate(SortedMessage(properties, None)):
		if not isinstance(p, Type):
			print "[Cpp] Warning: Variant type expect Typy, but get %s %s." % (a, p)
		wire_type, field_type, typy_type = _GetCpyFromTypy(p, codes, types)
		fields.append("""
	('%s', %d, %d, %d, %d, %s),""" % ((a, PackTag(i + 1, wire_type), _TagSize(i + 1), wire_type, field_type, typy_type)))

	codes.append("""
%s = _typyd.Variant('%s', (%s
))""" % (name, name, ''.join(fields)))
	types.add(name)

def _GetCpyFromTypy(p, codes, types, nesting = False):
	from Object import MetaObject
	from Type import pb, Enum, Integer, Long, Float, Double, Boolean, String, Bytes, Symbol
	from Type import Instance, List, Dict, FixedPoint, Python
	from typy.google.protobuf.internal import wire_format
	if isinstance(p, Enum):
		if p.pyType.__name__ not in types:
			codes.append("""
%s = _typyd.Enum('%s')""" % (p.pyType.__name__, p.pyType.__name__))
			types.add(p.pyType.__name__)
		return wire_format.WIRETYPE_VARINT, TYPE_ENUM, p.pyType.__name__
	elif isinstance(p, FixedPoint):
		fixedpoint = 'FixedPoint_%d_%s%d' % (p.precision, '' if p.floor > 0 else 's', p.floor if p.floor > 0 else -p.floor)
		if fixedpoint not in types:
			codes.append("""
%s = _typyd.FixedPoint(%d, %d)""" % (fixedpoint, p.precision, p.floor))
			types.add(fixedpoint)
		return wire_format.WIRETYPE_VARINT, TYPE_FIXEDPOINT, fixedpoint
	elif isinstance(p, Python):
		if p.pyType.__name__ not in types:
			codes.append("""
%s = _typyd.Python('%s')""" % (p.pyType.__name__, p.pyType.__name__))
			types.add(p.pyType.__name__)
		return wire_format.WIRETYPE_LENGTH_DELIMITED, TYPE_PYTHON, p.pyType.__name__
	elif isinstance(p, Integer):
		return wire_format.WIRETYPE_VARINT, TYPE_INT32, ''
	elif isinstance(p, Long):
		return wire_format.WIRETYPE_VARINT, TYPE_INT64, ''
	elif isinstance(p, Float):
		return wire_format.WIRETYPE_FIXED32, TYPE_FLOAT, ''
	elif isinstance(p, Double):
		return wire_format.WIRETYPE_FIXED64, TYPE_DOUBLE, ''
	elif isinstance(p, Boolean):
		return wire_format.WIRETYPE_VARINT, TYPE_BOOL, ''
	elif isinstance(p, String):
		return wire_format.WIRETYPE_LENGTH_DELIMITED, TYPE_STRING, ''
	elif isinstance(p, Bytes):
		return wire_format.WIRETYPE_LENGTH_DELIMITED, TYPE_BYTES, ''
	elif isinstance(p, Symbol):
		return wire_format.WIRETYPE_LENGTH_DELIMITED, TYPE_SYMBOL, ''
	elif isinstance(p, Instance):
		if len(p.pyType) == 1 and p.pyType[0].__name__ in MetaObject.Objects:
			if p.pyType[0].__name__ not in types:
				_GenerateObject(p.pyType[0].__name__, MetaObject.Objects[p.pyType[0].__name__], codes, types)
			return wire_format.WIRETYPE_LENGTH_DELIMITED, TYPE_OBJECT, p.pyType[0].__name__
		elif len(p.pyType) < 1 or (not nesting and pb not in p.____keywords__):
			pass
		else:
			variant, properties = RecordNesting('V', p.pyType)
			if variant not in types:
				_GenerateVariant(variant, properties, codes, types)
				types.add(variant)
			return wire_format.WIRETYPE_LENGTH_DELIMITED, TYPE_VARIANT, variant
		if 'PyObject' not in types:
			codes.append("""
PyObject = _typyd.Python('PyObject')""")
			types.add('PyObject')
		return wire_format.WIRETYPE_LENGTH_DELIMITED, TYPE_PYTHON, 'PyObject'
	elif isinstance(p, List):
		list_type, _ = RecordNesting('L', [p.elementType])
		if list_type not in types:
			wire_type, field_type, typy_type = _GetCpyFromTypy(p.elementType, codes, types, True)
			codes.append("""
%s = _typyd.List('%s', (%d, %d, %s))""" % (list_type, list_type, wire_type, field_type, typy_type))
			types.add(list_type)
		return wire_format.WIRETYPE_LENGTH_DELIMITED, TYPE_LIST, list_type
	elif isinstance(p, Dict):
		dict_type, _ = RecordNesting('D', [p.keyType, p.valueType])
		if dict_type not in types:
			key_wire_type, key_field_type, key_typy_type = _GetCpyFromTypy(p.keyType, codes, types, True)
			value_wire_type, value_field_type, value_typy_type = _GetCpyFromTypy(p.valueType, codes, types, True)
			codes.append("""
%s = _typyd.Dict('%s', (%d, %d, %s), (%d, %d, %s))""" % (dict_type, dict_type,
				key_wire_type, key_field_type, key_typy_type,
				value_wire_type, value_field_type, value_typy_type))
			types.add(dict_type)
		return wire_format.WIRETYPE_LENGTH_DELIMITED, TYPE_DICT, dict_type

def _GenerateObject(name, cls, codes, types):
	from typy.google.protobuf.internal.encoder import _TagSize
	from typy.google.protobuf.internal.wire_format import PackTag
	from Type import pb

	fields = []
	sortedProperties = SortedMessage(cls.____properties__, getattr(cls, '____propertySequence__', None))
	tag = 0
	for a, p in sortedProperties:
		if pb not in p.____keywords__: continue
		tag += 1
		wire_type, field_type, typy_type = _GetCpyFromTypy(p, codes, types)
		fields.append("""
	('%s', %d, %d, %d, %d, %s),""" % ((a, PackTag(tag, wire_type), _TagSize(tag), wire_type, field_type, typy_type)))
	for a, p in sortedProperties:
		if pb in p.____keywords__: continue
		wire_type, field_type, typy_type = _GetCpyFromTypy(p, codes, types)
		fields.append("""
	('%s', %d, %d, %d, %d, %s),""" % ((a, 0, 0, wire_type, field_type, typy_type)))

	codes.append("""
%s = _typyd.Object('%s', (%s
))""" % (name, name, ''.join(fields)))
	types.add(name)

def GenerateDescriptor(_typyDir = None):
	import os
	import codecs
	if _typyDir is None:
		_typyDir = os.path.dirname(__file__)
	path = os.path.abspath(_typyDir) + '/_typy.py'

	from Object import MetaObject
	codes = []
	types = set()
	for name, cls in sorted(MetaObject.Objects.iteritems(), key = lambda (k, v): k):
		if name not in types:
			_GenerateObject(name, cls, codes, types)

	CompareWrite(path, TYPY_PY__ % ''.join(codes))

TYPY_PY__ = ur"""#-*- coding: utf-8 -*-
# Generated by the typy Cpp.GenerateExtention.  DO NOT EDIT!

import _typyd
setDefaultEncodingUTF8 = _typyd.setDefaultEncodingUTF8
%s
"""


text:
require_relative "utils"

if defined?(OpenSSL)

class OpenSSL::TestX509Certificate < OpenSSL::TestCase
  def setup
    super
    @rsa1024 = Fixtures.pkey("rsa1024")
    @rsa2048 = Fixtures.pkey("rsa2048")
    @dsa256  = Fixtures.pkey("dsa256")
    @dsa512  = Fixtures.pkey("dsa512")
    @ca = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=CA")
    @ee1 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=EE1")
  end

  def test_serial
    [1, 2**32, 2**100].each{|s|
      cert = issue_cert(@ca, @rsa2048, s, [], nil, nil)
      assert_equal(s, cert.serial)
      cert = OpenSSL::X509::Certificate.new(cert.to_der)
      assert_equal(s, cert.serial)
    }
  end

  def test_public_key
    exts = [
      ["basicConstraints","CA:TRUE",true],
      ["subjectKeyIdentifier","hash",false],
      ["authorityKeyIdentifier","keyid:always",false],
    ]

    [
      @rsa1024, @rsa2048, @dsa256, @dsa512,
    ].each{|pk|
      cert = issue_cert(@ca, pk, 1, exts, nil, nil)
      assert_equal(cert.extensions.sort_by(&:to_s)[2].value,
                   OpenSSL::TestUtils.get_subject_key_id(cert))
      cert = OpenSSL::X509::Certificate.new(cert.to_der)
      assert_equal(cert.extensions.sort_by(&:to_s)[2].value,
                   OpenSSL::TestUtils.get_subject_key_id(cert))
    }
  end

  def test_validity
    now = Time.at(Time.now.to_i + 0.9)
    cert = issue_cert(@ca, @rsa2048, 1, [], nil, nil,
                      not_before: now, not_after: now+3600)
    assert_equal(Time.at(now.to_i), cert.not_before)
    assert_equal(Time.at(now.to_i+3600), cert.not_after)

    now = Time.at(now.to_i)
    cert = issue_cert(@ca, @rsa2048, 1, [], nil, nil,
                      not_before: now, not_after: now+3600)
    assert_equal(now.getutc, cert.not_before)
    assert_equal((now+3600).getutc, cert.not_after)

    now = Time.at(0)
    cert = issue_cert(@ca, @rsa2048, 1, [], nil, nil,
                      not_before: now, not_after: now)
    assert_equal(now.getutc, cert.not_before)
    assert_equal(now.getutc, cert.not_after)

    now = Time.at(0x7fffffff)
    cert = issue_cert(@ca, @rsa2048, 1, [], nil, nil,
                      not_before: now, not_after: now)
    assert_equal(now.getutc, cert.not_before)
    assert_equal(now.getutc, cert.not_after)
  end

  def test_extension
    ca_exts = [
      ["basicConstraints","CA:TRUE",true],
      ["keyUsage","keyCertSign, cRLSign",true],
      ["subjectKeyIdentifier","hash",false],
      ["authorityKeyIdentifier","keyid:always",false],
    ]
    ca_cert = issue_cert(@ca, @rsa2048, 1, ca_exts, nil, nil)
    ca_cert.extensions.each_with_index{|ext, i|
      assert_equal(ca_exts[i].first, ext.oid)
      assert_equal(ca_exts[i].last, ext.critical?)
    }

    ee1_exts = [
      ["keyUsage","Non Repudiation, Digital Signature, Key Encipherment",true],
      ["subjectKeyIdentifier","hash",false],
      ["authorityKeyIdentifier","keyid:always",false],
      ["extendedKeyUsage","clientAuth, emailProtection, codeSigning",false],
      ["subjectAltName","email:ee1@ruby-lang.org",false],
    ]
    ee1_cert = issue_cert(@ee1, @rsa1024, 2, ee1_exts, ca_cert, @rsa2048)
    assert_equal(ca_cert.subject.to_der, ee1_cert.issuer.to_der)
    ee1_cert.extensions.each_with_index{|ext, i|
      assert_equal(ee1_exts[i].first, ext.oid)
      assert_equal(ee1_exts[i].last, ext.critical?)
    }
  end

  def test_sign_and_verify_rsa_sha1
    cert = issue_cert(@ca, @rsa2048, 1, [], nil, nil, digest: "sha1")
    assert_equal(false, cert.verify(@rsa1024))
    assert_equal(true,  cert.verify(@rsa2048))
    assert_equal(false, certificate_error_returns_false { cert.verify(@dsa256) })
    assert_equal(false, certificate_error_returns_false { cert.verify(@dsa512) })
    cert.serial = 2
    assert_equal(false, cert.verify(@rsa2048))
  end

  def test_sign_and_verify_rsa_md5
    cert = issue_cert(@ca, @rsa2048, 1, [], nil, nil, digest: "md5")
    assert_equal(false, cert.verify(@rsa1024))
    assert_equal(true, cert.verify(@rsa2048))

    assert_equal(false, certificate_error_returns_false { cert.verify(@dsa256) })
    assert_equal(false, certificate_error_returns_false { cert.verify(@dsa512) })
    cert.subject = @ee1
    assert_equal(false, cert.verify(@rsa2048))
  rescue OpenSSL::X509::CertificateError # RHEL7 disables MD5
  end

  def test_sign_and_verify_dsa
    cert = issue_cert(@ca, @dsa512, 1, [], nil, nil)
    assert_equal(false, certificate_error_returns_false { cert.verify(@rsa1024) })
    assert_equal(false, certificate_error_returns_false { cert.verify(@rsa2048) })
    assert_equal(false, cert.verify(@dsa256))
    assert_equal(true,  cert.verify(@dsa512))
    cert.not_after = Time.now
    assert_equal(false, cert.verify(@dsa512))
  end

  def test_sign_and_verify_rsa_dss1
    cert = issue_cert(@ca, @rsa2048, 1, [], nil, nil, digest: OpenSSL::Digest::DSS1.new)
    assert_equal(false, cert.verify(@rsa1024))
    assert_equal(true, cert.verify(@rsa2048))
    assert_equal(false, certificate_error_returns_false { cert.verify(@dsa256) })
    assert_equal(false, certificate_error_returns_false { cert.verify(@dsa512) })
    cert.subject = @ee1
    assert_equal(false, cert.verify(@rsa2048))
  rescue OpenSSL::X509::CertificateError
  end if defined?(OpenSSL::Digest::DSS1)

  def test_sign_and_verify_dsa_md5
    assert_raise(OpenSSL::X509::CertificateError){
      issue_cert(@ca, @dsa512, 1, [], nil, nil, digest: "md5")
    }
  end

  def test_dsa_with_sha2
    cert = issue_cert(@ca, @dsa256, 1, [], nil, nil, digest: "sha256")
    assert_equal("dsa_with_SHA256", cert.signature_algorithm)
    # TODO: need more tests for dsa + sha2

    # SHA1 is allowed from OpenSSL 1.0.0 (0.9.8 requires DSS1)
    cert = issue_cert(@ca, @dsa256, 1, [], nil, nil, digest: "sha1")
    assert_equal("dsaWithSHA1", cert.signature_algorithm)
  end

  def test_check_private_key
    cert = issue_cert(@ca, @rsa2048, 1, [], nil, nil)
    assert_equal(true, cert.check_private_key(@rsa2048))
  end

  def test_read_from_file
    cert = issue_cert(@ca, @rsa2048, 1, [], nil, nil)
    Tempfile.create("cert") { |f|
      f << cert.to_pem
      f.rewind
      assert_equal cert.to_der, OpenSSL::X509::Certificate.new(f).to_der
    }
  end

  def test_eq
    now = Time.now
    cacert = issue_cert(@ca, @rsa1024, 1, [], nil, nil,
                        not_before: now, not_after: now + 3600)
    cert1 = issue_cert(@ee1, @rsa2048, 2, [], cacert, @rsa1024,
                       not_before: now, not_after: now + 3600)
    cert2 = issue_cert(@ee1, @rsa2048, 2, [], cacert, @rsa1024,
                       not_before: now, not_after: now + 3600)
    cert3 = issue_cert(@ee1, @rsa2048, 3, [], cacert, @rsa1024,
                       not_before: now, not_after: now + 3600)
    cert4 = issue_cert(@ee1, @rsa2048, 2, [], cacert, @rsa1024,
                       digest: "sha512", not_before: now, not_after: now + 3600)

    assert_equal false, cert1 == 12345
    assert_equal true, cert1 == cert2
    assert_equal false, cert1 == cert3
    assert_equal false, cert1 == cert4
    assert_equal false, cert3 == cert4
  end

  private

  def certificate_error_returns_false
    yield
  rescue OpenSSL::X509::CertificateError
    false
  end
end

end


text:
<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of fileSystemUtility
 *
 * @author COMUNE-INTRANET\d59495
 */
class fileSystemUtility {

    static function cleantmp() {
        $seconds_old = 86400; //Un giorno
        $directory = sys_get_temp_dir();

        if (!$dirhandle = @opendir($directory))
            return;

        while (false !== ($filename = readdir($dirhandle))) {
            if ($filename != "." && $filename != "..") {
                $filename = $directory . "/" . $filename;

                if (@filemtime($filename) < (time() - $seconds_old))
                    @unlink($filename);
            }
        }
    }

}

?>


text:
"""
        PUT HERE SOME DOC
"""

import commands
import logging
import re
import threading
import StringIO
import urllib
import urllib2

from autopyfactory.interfaces import MonitorInterface

try:
    import json as json
except ImportError, err:
    # Not critical (yet) - try simplejson
    log = logging.getLogger('autopyfactory.monitor')
    log.debug('json package not installed. Trying to import simplejson as json')
    import simplejson as json

#  ==================================================
#
#       CLASSES TO HANDLE HTTP CALLS BETTER
#
#  ==================================================

class NoExceptionHTTPHandler(urllib2.BaseHandler):
    """
    A substitute/supplement to urllib2.HTTPErrorProcessor
    that doesn't raise exceptions on status codes 201,204,206
    For example, when a registration operation (via HTTP PUT command)
    is successful, a code 201 CREATED is returned.
    urllib2 interprets that as an ERROR, and raises an exception.
    To avoid it we override the behavior of http_err_<RC> methods.
    """

    def http_error_201(self, request, response, code, msg, hdrs):
        return response
    def http_error_204(self, request, response, code, msg, hdrs):
        return response
    def http_error_206(self, request, response, code, msg, hdrs):
        return response

class RequestWithMethod(urllib2.Request):
    """
    To be used insted of urllib2.Request
    This class gets the HTTP method (i.e. 'PUT') during the initlization
    """

    def __init__(self, method, *args, **kwargs):
        self._method = method
        urllib2.Request.__init__(self, *args, **kwargs)

    def get_method(self):
        return self._method

#  ==================================================
# This class is just to make the name of the HTTP
# methods ("POST", "GET", etc) to look like macros

class http:
    GET = "GET"
    POST = "POST"
    PUT = "PUT"
    DELETE = "DELETE"

#  ==================================================

class _apf(MonitorInterface):
    """
    Notifies a monitoring webservice about condor jobs
    """

    def __init__(self, apfqueue, config, section):

        #monitor_id = config.generic_get(section, "monitorsection")
        monitor_id = section
        self.log = logging.getLogger('autopyfactory.monitor.%s' %apfqueue.apfqname)
        self.log.debug("Start...")

        self.qcl = apfqueue.factory.qcl
        self.fcl = apfqueue.factory.fcl
        self.mcl = apfqueue.factory.mcl

        self.fid = self.fcl.generic_get('Factory','factoryId')
        self.version = apfqueue.factory.version
        self.email = self.fcl.generic_get('Factory','factoryAdminEmail')
        self.baselogurl = self.fcl.generic_get('Factory','baseLogDirUrl')

        self.monurl = self.mcl.generic_get(monitor_id, 'monitorURL')

        self.log.debug('Instantiated monitor')
        self.registerFactory()
        self.registeredlabels = self._getLabels() # list of labels registered
        self.log.debug('Done.')

    def registerFactory(self):
        """
        First check if the factory is already registered.
        If not, then register it.
        """

        self.log.debug('Starting')

        #if self._isFactoryRegistered():
        #    self.log.debug('factory is already registered')
        #    out = None
        #else:
        #    self.log.info('factory is not registered yet. Registering.')
        #    out = self._registerFactory()
        out = self._registerFactory()

        self.log.debug('Leaving')
        return out

    def _isFactoryRegistered(self):
        """
        queries for the list of factories.
        URL looks like http://py-front.lancs.ac.uk/api/factories
        Output of query looks like (as JSON string):

        [
          {
            "active": true,
            "email": "admin1@matrix.net",
            "factory_type": "AutoPyFactory",
            "id": 137,
            "ip": "127.0.0.1",
            "last_cycle": 0,
            "last_modified": "2013-03-28T13:19:56Z",
            "last_ncreated": 0,
            "last_startup": "2013-03-28T13:19:56Z",
            "name": "dev-factory",
            "url": "http://localhost/",
            "version": "0.0.1"
          },
          {
            "active": true,
            "email": "admin2@matrix.net",
            "factory_type": "AutoPyFactory",
            "id": 5,
            "ip": "130.199.3.165",
            "last_cycle": 0,
            "last_modified": "2013-03-25T19:33:57Z",
            "last_ncreated": 0,
            "last_startup": "2013-03-25T19:33:57Z",
            "name": "bnl-gridui99-factory",
            "url": "http://gridui99.usatlas.bnl.gov:25880",
            "version": "0.0.1"
          },
          ]
        """

        url = self.monurl + '/factories'
        out = self._call(http.GET, url)
        out = json.loads(out.read())
        factories = [ factory['name'] for factory in out ]
        self.log.debug('list of registered factories = %s' %factories)

        return self.fid in factories

    def _registerFactory(self):
        """
        register the factory
        """

        self.log.debug('Starting')

        url = self.monurl + '/factories/' + self.fid

        data = {}
        data["version"] = self.version
        data["email"] = self.email
        data["url"] =  self.baselogurl
        data = json.dumps(data)

        out = self._call(http.PUT, url, data)

        self.log.debug('Leaving')
        return out

    def _getLabels(self):
        """
        queries for the list of labels registered for this factory.
        URL looks like
            http://py-front.lancs.ac.uk/api/labels?factory=bnl-gridui99-factory
        Output of query looks like (as JSON string):
            [
              {
                "factory": "bnl-gridui99-factory",
                "id": 512,
                "last_modified": "2013-03-28T14:47:20Z",
                "localqueue": "",
                "msg": "",
                "name": "label-1",
                "ncreated": 100,
                "ndone": 0,
                "nexiting": 0,
                "nfault": 0,
                "nrunning": 50,
                "resource": ""
              },
              {
                "factory": "bnl-gridui99-factory",
                "id": 513,
                "last_modified": "2013-03-28T15:02:56Z",
                "localqueue": "",
                "msg": "",
                "name": "label-2",
                "ncreated": 0,
                "ndone": 0,
                "nexiting": 0,
                "nfault": 0,
                "nrunning": 0,
                "resource": ""
              }
            ]
        """

        self.log.debug('Starting')

        url = self.monurl + '/labels?factory=' + self.fid
        out = self._call(http.GET, url)
        out = json.loads(out.read())
        labels = [ label['name'] for label in out ]
        self.log.debug('list of registered labels = %s' %labels)

        self.log.debug('Leaving')
        return labels

    def registerLabel(self, apfqueue):
        """
        First check if the label is already registered.
        If not, then register it.

        Label is the name of the section in queues.conf

        We pass apfqueue as input because this class is a singleton,
        so the apfqueue object passed by __init__() may not be the same
        apfqueue object calling this method.
        """

        #####################################################
        #
        #   QUESTION:
        #
        #       We are registering a new label
        #       when registering jobs.
        #       So new labels are registered one by one
        #       if needed.
        #
        #       Should be done at the __init__() at once?
        #       Like getting current list, get all labels
        #       from qcl, and register all missing ones.
        #
        #####################################################

        self.log.debug('Starting')

        label = apfqueue.apfqname

        if self._isLabelRegistered(label):
            self.log.debug('label %s is already registered' %label)
            out = None
        else:
            self.log.info('label %s is not registered yet. Registering.' %label)
            out = self._registerLabel(apfqueue)

        self.log.debug('Leaving')
        return out

    def _isLabelRegistered(self, label):
        return label in self.registeredlabels

    def _registerLabel(self, apfqueue):
        """
        We pass apfqueue as input because this class is a singleton,
        so the apfqueue object passed by __init__() may not be the same
        apfqueue object calling this method.
        """

        self.log.debug('Starting')

        url = self.monurl + '/labels'

        data = []

        label = {}
        label['name'] = apfqueue.apfqname
        label['factory'] = self.fid
        label['wmsqueue'] = ''
        label['batchqueue'] = ''
        label['resource'] = ''
        label['localqueue'] = ''

        data.append(label)
        data = json.dumps(data)

        out = self._call(http.PUT, url, data)

        self.registeredlabels.append(apfqueue.apfqname)

        self.log.debug('Leaving')
        return out

    def registerJobs(self, apfqueue, jobinfolist):
        """
        Take a list of JobInfo objects and translate to APFMonitor messages.

        We pass apfqueue as one of the inputs because this class is a singleton,
        so the apfqueue object passed by __init__() may not be the same
        apfqueue object calling this method.

        jobinfolist is the output of submit() method.
        It is a list of JobInfo objects
        """

        self.log.debug('Starting for apfqueue %s with info list %s' %(apfqueue.apfqname,
                                                                     jobinfolist))

        url = self.monurl + '/jobs'

        # jobs can not be registered unless the label is already registered
        self.registerLabel(apfqueue)

        out = None

        if jobinfolist:
        # ensure jobinfolist has any content, and is not None
            apfqname = apfqueue.apfqname

            data = []

            for ji in jobinfolist:

                job = {}

                job['cid'] = ji.jobid
                job['label'] = apfqname
                job['factory'] = self.fid

                data.append(job)

                self.log.debug('updateJobs: adding data (%s, %s, %s)' %(ji.jobid, self.fid, apfqname))

            data = json.dumps(data)
            out = self._call(http.PUT, url, data=data)

        self.log.debug('Leaving.')
        return out

#    def updateLabel(self, label, n):
#        """
#        update each label (==apfqname) in the monitor
#        n is the number of new pilots being submitted
#        """
#
#        self.log.debug('Starting for label %s and number of pilots %s' %(label, n))
#
#        url = "%s/labels/%s:%s" %(self.monurl, self.fid, label)
#        msg = "Attempt to submit %s pilots" %n
#        data = {'status': msg}
#        data = urllib.urlencode(data)
#        self._call(http.POST, url, data=data)
#
#        self.log.debug('Leaving')

    def updateLabel(self, label, msg):
        """
        update each label (==apfqname) in the monitor
        """

        self.log.debug('Starting for label %s and message %s' %(label, msg))

        url = "%s/labels/%s:%s" %(self.monurl, self.fid, label)
        data = {'status': msg}
        data = urllib.urlencode(data)
        self._call(http.POST, url, data=data)

        self.log.debug('Leaving')

    def _call(self, method, url, data=None):
        """
        make the HTTP call
        method is "PUT", "GET", "POST" or "DELETE"
        """

        self.log.debug('Starting. method=%s, url=%s, data=%s' %(method, url, data))

        opener = urllib2.build_opener(NoExceptionHTTPHandler)
        if data:
            request = RequestWithMethod(method, url, data)
        else:
            request = RequestWithMethod(method, url)

        try:
            out = opener.open(request)
        except Exception, e:
            self.log.debug('HTTP call failed with error %s' %e)
            out = None  # Is this OK?

        self.log.debug('Leaving with output %s' %out)
        return out

# =============================================================================
#   Singleton wrapper
# =============================================================================

class APF(object):

    instances = {}

    def __new__(cls, *k, **kw):

        # ---------------------------
        # get the id:
        #
        # for APF monitor plugins,
        # the id is the name of the section
        # in monitor.conf
        apfqueue = k[0]
        conf = k[1]
        section = k[2]
        id = conf.generic_get(section, 'monitorsection')
        # ---------------------------

        if not id in APF.instances.keys():
            APF.instances[id] = _apf(*k, **kw)
        return APF.instances[id]


text:
package com.lmax.disruptor.support;

import com.lmax.disruptor.AlertException;
import com.lmax.disruptor.DataProvider;
import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.EventProcessor;
import com.lmax.disruptor.Sequence;
import com.lmax.disruptor.SequenceBarrier;
import com.lmax.disruptor.TimeoutException;

import java.util.concurrent.atomic.AtomicBoolean;

public class MultiBufferBatchEventProcessor<T>
    implements EventProcessor
{
    private final AtomicBoolean isRunning = new AtomicBoolean(false);
    private final DataProvider<T>[] providers;
    private final SequenceBarrier[] barriers;
    private final EventHandler<T> handler;
    private final Sequence[] sequences;
    private long count;

    public MultiBufferBatchEventProcessor(
        final DataProvider<T>[] providers,
        final SequenceBarrier[] barriers,
        final EventHandler<T> handler)
    {
        if (providers.length != barriers.length)
        {
            throw new IllegalArgumentException();
        }

        this.providers = providers;
        this.barriers = barriers;
        this.handler = handler;

        this.sequences = new Sequence[providers.length];
        for (int i = 0; i < sequences.length; i++)
        {
            sequences[i] = new Sequence(-1);
        }
    }

    @Override
    public void run()
    {
        if (!isRunning.compareAndSet(false, true))
        {
            throw new RuntimeException("Already running");
        }

        for (SequenceBarrier barrier : barriers)
        {
            barrier.clearAlert();
        }

        final int barrierLength = barriers.length;

        while (true)
        {
            try
            {
                for (int i = 0; i < barrierLength; i++)
                {
                    long available = barriers[i].waitFor(-1);
                    Sequence sequence = sequences[i];

                    long nextSequence = sequence.get() + 1;

                    for (long l = nextSequence; l <= available; l++)
                    {
                        handler.onEvent(providers[i].get(l), l, nextSequence == available);
                    }

                    sequence.set(available);

                    count += available - nextSequence + 1;
                }

                Thread.yield();
            }
            catch (AlertException e)
            {
                if (!isRunning())
                {
                    break;
                }
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            catch (TimeoutException e)
            {
                e.printStackTrace();
            }
            catch (Exception e)
            {
                e.printStackTrace();
                break;
            }
        }
    }

    @Override
    public Sequence getSequence()
    {
        throw new UnsupportedOperationException();
    }

    public long getCount()
    {
        return count;
    }

    public Sequence[] getSequences()
    {
        return sequences;
    }

    @Override
    public void halt()
    {
        isRunning.set(false);
        barriers[0].alert();
    }

    @Override
    public boolean isRunning()
    {
        return isRunning.get();
    }
}


text:
package client

import (
	"fmt"
	"io"
	"strings"
	"sync"
	"text/tabwriter"
	"time"

	"golang.org/x/net/context"

	Cli "github.com/docker/docker/cli"
	"github.com/docker/engine-api/types"
	"github.com/docker/engine-api/types/events"
	"github.com/docker/engine-api/types/filters"
)

// CmdStats displays a live stream of resource usage statistics for one or more containers.
//
// This shows real-time information on CPU usage, memory usage, and network I/O.
//
// Usage: docker stats [OPTIONS] [CONTAINER...]
func (cli *DockerCli) CmdStats(args ...string) error {
	cmd := Cli.Subcmd("stats", []string{"[CONTAINER...]"}, Cli.DockerCommands["stats"].Description, true)
	all := cmd.Bool([]string{"a", "-all"}, false, "Show all containers (default shows just running)")
	noStream := cmd.Bool([]string{"-no-stream"}, false, "Disable streaming stats and only pull the first result")

	cmd.ParseFlags(args, true)

	names := cmd.Args()
	showAll := len(names) == 0
	closeChan := make(chan error)

	// monitorContainerEvents watches for container creation and removal (only
	// used when calling `docker stats` without arguments).
	monitorContainerEvents := func(started chan<- struct{}, c chan events.Message) {
		f := filters.NewArgs()
		f.Add("type", "container")
		options := types.EventsOptions{
			Filters: f,
		}
		resBody, err := cli.client.Events(context.Background(), options)
		// Whether we successfully subscribed to events or not, we can now
		// unblock the main goroutine.
		close(started)
		if err != nil {
			closeChan <- err
			return
		}
		defer resBody.Close()

		decodeEvents(resBody, func(event events.Message, err error) error {
			if err != nil {
				closeChan <- err
				return nil
			}
			c <- event
			return nil
		})
	}

	// waitFirst is a WaitGroup to wait first stat data's reach for each container
	waitFirst := &sync.WaitGroup{}

	cStats := stats{}
	// getContainerList simulates creation event for all previously existing
	// containers (only used when calling `docker stats` without arguments).
	getContainerList := func() {
		options := types.ContainerListOptions{
			All: *all,
		}
		cs, err := cli.client.ContainerList(options)
		if err != nil {
			closeChan <- err
		}
		for _, container := range cs {
			s := &containerStats{Name: container.ID[:12]}
			if cStats.add(s) {
				waitFirst.Add(1)
				go s.Collect(cli.client, !*noStream, waitFirst)
			}
		}
	}

	if showAll {
		// If no names were specified, start a long running goroutine which
		// monitors container events. We make sure we're subscribed before
		// retrieving the list of running containers to avoid a race where we
		// would "miss" a creation.
		started := make(chan struct{})
		eh := eventHandler{handlers: make(map[string]func(events.Message))}
		eh.Handle("create", func(e events.Message) {
			if *all {
				s := &containerStats{Name: e.ID[:12]}
				if cStats.add(s) {
					waitFirst.Add(1)
					go s.Collect(cli.client, !*noStream, waitFirst)
				}
			}
		})

		eh.Handle("start", func(e events.Message) {
			s := &containerStats{Name: e.ID[:12]}
			if cStats.add(s) {
				waitFirst.Add(1)
				go s.Collect(cli.client, !*noStream, waitFirst)
			}
		})

		eh.Handle("die", func(e events.Message) {
			if !*all {
				cStats.remove(e.ID[:12])
			}
		})

		eventChan := make(chan events.Message)
		go eh.Watch(eventChan)
		go monitorContainerEvents(started, eventChan)
		defer close(eventChan)
		<-started

		// Start a short-lived goroutine to retrieve the initial list of
		// containers.
		getContainerList()
	} else {
		// Artificially send creation events for the containers we were asked to
		// monitor (same code path than we use when monitoring all containers).
		for _, name := range names {
			s := &containerStats{Name: name}
			if cStats.add(s) {
				waitFirst.Add(1)
				go s.Collect(cli.client, !*noStream, waitFirst)
			}
		}

		// We don't expect any asynchronous errors: closeChan can be closed.
		close(closeChan)

		// Do a quick pause to detect any error with the provided list of
		// container names.
		time.Sleep(1500 * time.Millisecond)
		var errs []string
		cStats.mu.Lock()
		for _, c := range cStats.cs {
			c.mu.Lock()
			if c.err != nil {
				errs = append(errs, fmt.Sprintf("%s: %v", c.Name, c.err))
			}
			c.mu.Unlock()
		}
		cStats.mu.Unlock()
		if len(errs) > 0 {
			return fmt.Errorf("%s", strings.Join(errs, ", "))
		}
	}

	// before print to screen, make sure each container get at least one valid stat data
	waitFirst.Wait()

	w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
	printHeader := func() {
		if !*noStream {
			fmt.Fprint(cli.out, "\033[2J")
			fmt.Fprint(cli.out, "\033[H")
		}
		io.WriteString(w, "CONTAINER\tCPU %\tMEM USAGE / LIMIT\tMEM %\tNET I/O\tBLOCK I/O\tPIDS\n")
	}

	for range time.Tick(500 * time.Millisecond) {
		printHeader()
		toRemove := []int{}
		cStats.mu.Lock()
		for i, s := range cStats.cs {
			if err := s.Display(w); err != nil && !*noStream {
				toRemove = append(toRemove, i)
			}
		}
		for j := len(toRemove) - 1; j >= 0; j-- {
			i := toRemove[j]
			cStats.cs = append(cStats.cs[:i], cStats.cs[i+1:]...)
		}
		if len(cStats.cs) == 0 && !showAll {
			return nil
		}
		cStats.mu.Unlock()
		w.Flush()
		if *noStream {
			break
		}
		select {
		case err, ok := <-closeChan:
			if ok {
				if err != nil {
					// this is suppressing "unexpected EOF" in the cli when the
					// daemon restarts so it shutdowns cleanly
					if err == io.ErrUnexpectedEOF {
						return nil
					}
					return err
				}
			}
		default:
			// just skip
		}
	}
	return nil
}


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity
*/
class Cochera extends Unidad{
	/**
	* @ORM\Column(type="integer")
	* @ORM\Id
	* @ORM\GeneratedValue(strategy="AUTO")
	*/
	protected $id;

	/**
	* @ORM\Column(type="integer", nullable=true)
	*/
	protected $numero;

	/**
	* @ORM\Column(type="string", length=2, nullable=true)
	*/
	protected $categoria;

	/**
	* @ORM\Column(type="integer", nullable=true)
	*/
	protected $distancia_ascensor;

	/**
	* @ORM\Column(type="integer", nullable=true)
	*/
	protected $distancia_escalera_caracol;

	/**
	* @ORM\Column(type="integer", nullable=true)
	*/
	protected $distancia_escalera_bristol;

	/**
	* @ORM\Column(type="integer", nullable=true)
	*/
	protected $distancia_escalera_izq;

	/**
	* @ORM\Column(type="integer", nullable=true)
	*/
	protected $distancia_escalera_der;

	/**
	* @ORM\Column(type="decimal", scale=2, nullable=true)
	*/
	protected $ancho;

	/**
	* @ORM\Column(type="decimal", scale=2, nullable=true)
	*/
	protected $largo;

	/**
	* @ORM\Column(type="integer", scale=2, nullable=true)
	*/
	protected $subsuelo;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->disponibilidades = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Set numero
     *
     * @param integer $numero
     *
     * @return Cochera
     */
    public function setNumero($numero)
    {
        $this->numero = $numero;

        return $this;
    }

    /**
     * Get numero
     *
     * @return integer
     */
    public function getNumero()
    {
        return $this->numero;
    }

    /**
     * Set categoria
     *
     * @param string $categoria
     *
     * @return Cochera
     */
    public function setCategoria($categoria)
    {
        $this->categoria = $categoria;

        return $this;
    }

    /**
     * Get categoria
     *
     * @return string
     */
    public function getCategoria()
    {
        return $this->categoria;
    }

    /**
     * Set distanciaAscensor
     *
     * @param integer $distanciaAscensor
     *
     * @return Cochera
     */
    public function setDistanciaAscensor($distanciaAscensor)
    {
        $this->distancia_ascensor = $distanciaAscensor;

        return $this;
    }

    /**
     * Get distanciaAscensor
     *
     * @return integer
     */
    public function getDistanciaAscensor()
    {
        return $this->distancia_ascensor;
    }

    /**
     * Set distanciaEscaleraCaracol
     *
     * @param integer $distanciaEscaleraCaracol
     *
     * @return Cochera
     */
    public function setDistanciaEscaleraCaracol($distanciaEscaleraCaracol)
    {
        $this->distancia_escalera_caracol = $distanciaEscaleraCaracol;

        return $this;
    }

    /**
     * Get distanciaEscaleraCaracol
     *
     * @return integer
     */
    public function getDistanciaEscaleraCaracol()
    {
        return $this->distancia_escalera_caracol;
    }

    /**
     * Set distanciaEscaleraBristol
     *
     * @param integer $distanciaEscaleraBristol
     *
     * @return Cochera
     */
    public function setDistanciaEscaleraBristol($distanciaEscaleraBristol)
    {
        $this->distancia_escalera_bristol = $distanciaEscaleraBristol;

        return $this;
    }

    /**
     * Get distanciaEscaleraBristol
     *
     * @return integer
     */
    public function getDistanciaEscaleraBristol()
    {
        return $this->distancia_escalera_bristol;
    }

    /**
     * Set distanciaEscaleraIzq
     *
     * @param integer $distanciaEscaleraIzq
     *
     * @return Cochera
     */
    public function setDistanciaEscaleraIzq($distanciaEscaleraIzq)
    {
        $this->distancia_escalera_izq = $distanciaEscaleraIzq;

        return $this;
    }

    /**
     * Get distanciaEscaleraIzq
     *
     * @return integer
     */
    public function getDistanciaEscaleraIzq()
    {
        return $this->distancia_escalera_izq;
    }

    /**
     * Set distanciaEscaleraDer
     *
     * @param integer $distanciaEscaleraDer
     *
     * @return Cochera
     */
    public function setDistanciaEscaleraDer($distanciaEscaleraDer)
    {
        $this->distancia_escalera_der = $distanciaEscaleraDer;

        return $this;
    }

    /**
     * Get distanciaEscaleraDer
     *
     * @return integer
     */
    public function getDistanciaEscaleraDer()
    {
        return $this->distancia_escalera_der;
    }

    /**
     * Set ancho
     *
     * @param string $ancho
     *
     * @return Cochera
     */
    public function setAncho($ancho)
    {
        $this->ancho = $ancho;

        return $this;
    }

    /**
     * Get ancho
     *
     * @return string
     */
    public function getAncho()
    {
        return $this->ancho;
    }

    /**
     * Set largo
     *
     * @param string $largo
     *
     * @return Cochera
     */
    public function setLargo($largo)
    {
        $this->largo = $largo;

        return $this;
    }

    /**
     * Get largo
     *
     * @return string
     */
    public function getLargo()
    {
        return $this->largo;
    }

    /**
     * Set subsuelo
     *
     * @param integer $subsuelo
     *
     * @return Cochera
     */
    public function setSubsuelo($subsuelo)
    {
        $this->subsuelo = $subsuelo;

        return $this;
    }

    /**
     * Get subsuelo
     *
     * @return integer
     */
    public function getSubsuelo()
    {
        return $this->subsuelo;
    }

    /**
     * Add disponibilidade
     *
     * @param \AppBundle\Entity\Disponibilidad $disponibilidade
     *
     * @return Cochera
     */
    public function addDisponibilidade(\AppBundle\Entity\Disponibilidad $disponibilidade)
    {
        $this->disponibilidades[] = $disponibilidade;

        return $this;
    }

    /**
     * Remove disponibilidade
     *
     * @param \AppBundle\Entity\Disponibilidad $disponibilidade
     */
    public function removeDisponibilidade(\AppBundle\Entity\Disponibilidad $disponibilidade)
    {
        $this->disponibilidades->removeElement($disponibilidade);
    }

    /**
     * Get disponibilidades
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getDisponibilidades()
    {
        return $this->disponibilidades;
    }

    /**
     * Add autorizacione
     *
     * @param \AppBundle\Entity\Autorizacion $autorizacione
     *
     * @return Cochera
     */
    public function addAutorizacione(\AppBundle\Entity\Autorizacion $autorizacione)
    {
        $this->autorizaciones[] = $autorizacione;

        return $this;
    }

    /**
     * Remove autorizacione
     *
     * @param \AppBundle\Entity\Autorizacion $autorizacione
     */
    public function removeAutorizacione(\AppBundle\Entity\Autorizacion $autorizacione)
    {
        $this->autorizaciones->removeElement($autorizacione);
    }

    /**
     * Get autorizaciones
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getAutorizaciones()
    {
        return $this->autorizaciones;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

		<meta http-equiv="content-type" content="text/html; charset=utf-8" />
		<meta http-equiv="Pragma" content="no-cache" />
		<meta name="robots" content="noindex, nofollow" />

		<title>Sitengine - <?=$this->html($this->translate('labelsPageTitle'));?></title>

		<link rel="stylesheet" type="text/css" href="<?=$this->_controller->getEnv()->getMediaRequestDir();?>/Backend/Styles/Global.css" />
		<link rel="stylesheet" type="text/css" href="<?=$this->_controller->getEnv()->getMediaRequestDir();?>/Backend/Styles/Forms.css" />

			<?require 'Sitengine/Env/_Templates/HeaderSection.html';?>
			<?require 'Sitengine/Env/_Templates/BreadcrumbsSection.html';?>
			<?require 'Sitengine/Env/_Templates/AbstractSection.html';?>
			<?require 'Sitengine/Env/_Templates/ActionsSection.html';?>
			<?require 'Sitengine/Env/_Templates/StatusSection.html';?>

							<?if($this->SECTIONS->VIEWFORM->inputMode == Sitengine_Env::INPUTMODE_UPDATE):?>
								<a href="<?=$this->SECTIONS->VIEWFORM->queryUpdate;?>">
									<?=$this->html($this->SECTIONS->VIEWFORM->title);?>

							<?else:?>
								<?=$this->html($this->SECTIONS->VIEWFORM->title);?>
							<?endif;?>

					<form method="post" action="<?=$this->SECTIONS->VIEWFORM->submitUri;?>" enctype="multipart/form-data" name="viewForm" class="viewForm">
						<?=$this->SECTIONS->VIEWFORM->hiddens;?>

						<?if($this->SECTIONS->VIEWFORM->inputMode == Sitengine_Env::INPUTMODE_UPDATE):?>

							<?if(sizeof($this->SECTIONS->VIEWFORM->PAYLOADNAV) > 0):?>
								<?$count = 0;?>
								<?foreach($this->SECTIONS->VIEWFORM->PAYLOADNAV as $navItem):?>
									<?if($count > 0):?> • <?endif;?>
									<a href="<?=$navItem->uri;?>"><?=$navItem->label;?>
									<?$count++;?>
								<?endforeach;?>
								 --
							<?endif;?>

							<?$count = 0;?>
							<?foreach($this->SECTIONS->VIEWFORM->CHILDACTIONS as $navItem):?>
								<?if($count > 0):?> • <?endif;?>
								<a href="<?=$navItem->uri;?>"><?=$navItem->label;?>
								<?if($navItem->postfix):?><?=$navItem->postfix;?><?endif;?>
								<?$count++;?>
							<?endforeach;?>

						<?endif;?>

						<?require $this->SETTINGS->editorSnippet;?>

						<?if($this->SECTIONS->VIEWFORM->Payloads->isMain()):?>

<?=$this->html($this->SECTIONS->VIEWFORM->contentSectionTitle);?>

								<?$fieldName = 'titleLang'.$this->SECTIONS->VIEWFORM->Payloads->getTranscriptIndex();?>

										<label for="<?=$fieldName;?>" class="viewFormRequiredLabel">
											<?=$this->html($this->translate('formViewFieldsTitle'));?>

										<?=$this->formText($fieldName, $this->SECTIONS->VIEWFORM->DATA->$fieldName, array('size' => 40));?>

								<?
									$path = $this->_controller->getEnv()->getIncludesDir().'/Sitengine/Env/_Templates/FormFileSection.html';
									$this->setScriptPath(dirname($path));
									$vars = array(
										'name' => 'file1Original',
										'displayDeleteCheckbox' => 1,
										'fileSource' => $this->SECTIONS->VIEWFORM->DATA->file1OriginalSource,
										'fileName' => $this->SECTIONS->VIEWFORM->DATA->file1OriginalName,
										'fileWidth' => $this->SECTIONS->VIEWFORM->DATA->file1OriginalWidth,
										'fileHeight' => $this->SECTIONS->VIEWFORM->DATA->file1OriginalHeight,
										'fileIsImage' => $this->SECTIONS->VIEWFORM->DATA->file1OriginalIsImage,
										'fileSizeKb' => $this->SECTIONS->VIEWFORM->DATA->file1OriginalSizeKb,
										'fileMime' => $this->SECTIONS->VIEWFORM->DATA->file1OriginalMime,
										'filePath' => $this->SECTIONS->VIEWFORM->DATA->file1OriginalUri,
										'fileInfoFilesize' => $this->translate('viewFormFileInfoFilesize'),
										'fileInfoDoctype' => $this->translate('viewFormFileInfoDoctype'),
										'fileInfoWidth' => $this->translate('viewFormFileInfoWidth'),
										'fileInfoHeight' => $this->translate('viewFormFileInfoHeight'),
										'fileInfoSourcename' => $this->translate('viewFormFileInfoSourcename'),
										'fileInfoFilename' => $this->translate('viewFormFileInfoFilename'),
										'fileInfoRemoveFile' => $this->translate('viewFormFileInfoRemoveFile'),
										'fileInfoFilesize' => $this->translate('viewFormFileInfoFilesize'),
										'fileInfoFilesize' => $this->translate('viewFormFileInfoFilesize'),
										'fileInfoFilesize' => $this->translate('viewFormFileInfoFilesize'),
										'fileNewWidth' => 200
									);
								?>

											<?=$this->html($this->translate('formViewFieldsFile1Original'));?>

<?=$this->html($this->translate('formViewFieldsFile1OriginalHint'));?>

										<?=$this->partial(basename($path), $vars);?>

								<?
									$path = $this->_controller->getEnv()->getIncludesDir().'/Sitengine/Env/_Templates/FormFileSection.html';
									$this->setScriptPath(dirname($path));
									$vars = array(
										'name' => 'file2Original',
										'displayDeleteCheckbox' => 1,
										'fileSource' => $this->SECTIONS->VIEWFORM->DATA->file2OriginalSource,
										'fileName' => $this->SECTIONS->VIEWFORM->DATA->file2OriginalName,
										'fileWidth' => $this->SECTIONS->VIEWFORM->DATA->file2OriginalWidth,
										'fileHeight' => $this->SECTIONS->VIEWFORM->DATA->file2OriginalHeight,
										'fileIsImage' => $this->SECTIONS->VIEWFORM->DATA->file2OriginalIsImage,
										'fileSizeKb' => $this->SECTIONS->VIEWFORM->DATA->file2OriginalSizeKb,
										'fileMime' => $this->SECTIONS->VIEWFORM->DATA->file2OriginalMime,
										'filePath' => $this->SECTIONS->VIEWFORM->DATA->file2OriginalUri,
										'fileInfoFilesize' => $this->translate('viewFormFileInfoFilesize'),
										'fileInfoDoctype' => $this->translate('viewFormFileInfoDoctype'),
										'fileInfoWidth' => $this->translate('viewFormFileInfoWidth'),
										'fileInfoHeight' => $this->translate('viewFormFileInfoHeight'),
										'fileInfoSourcename' => $this->translate('viewFormFileInfoSourcename'),
										'fileInfoFilename' => $this->translate('viewFormFileInfoFilename'),
										'fileInfoRemoveFile' => $this->translate('viewFormFileInfoRemoveFile'),
										'fileInfoFilesize' => $this->translate('viewFormFileInfoFilesize'),
										'fileInfoFilesize' => $this->translate('viewFormFileInfoFilesize'),
										'fileInfoFilesize' => $this->translate('viewFormFileInfoFilesize'),
										'fileNewWidth' => 200
									);
								?>

											<?=$this->html($this->translate('formViewFieldsFile2Original'));?>

<?=$this->html($this->translate('formViewFieldsFile2OriginalHint'));?>

										<?=$this->partial(basename($path), $vars);?>

<?=$this->html($this->translate('viewFormMetaSectionTitle'));?>

											<?=$this->html($this->translate('formViewFieldsType'));?>

										<?=
											$this->formSelect(
												'type',
												$this->SECTIONS->VIEWFORM->DATA->type,
												array(),
												$this->_controller->getTranslate()->translateGroup('fieldValsType')->toArray()
											);
										?>

											<?=$this->html($this->translate('formViewFieldsSorting'));?>

<?=$this->html($this->translate('formViewFieldsSortingHint'));?>

										<?=
											$this->formText(
												'sorting',
												$this->SECTIONS->VIEWFORM->DATA->sorting,
												array('size' => 5)
											);
										?>

											<?=$this->html($this->translate('formViewFieldsDisplayThis'));?>

										<?
											print
												($this->SECTIONS->VIEWFORM->DATA->displayThis) ?
												$this->formCheckbox('displayThis', null, array('checked' => true)) :
												$this->formCheckbox('displayThis')
											;
										?>

											<?=$this->html($this->translate('formViewFieldsPublish'));?>

										<?
											print
												($this->SECTIONS->VIEWFORM->DATA->publish) ?
												$this->formCheckbox('publish', null, array('checked' => true)) :
												$this->formCheckbox('publish')
											;
										?>

											<?=$this->html($this->translate('formViewFieldsLocked'));?>

										<?
											print
												($this->SECTIONS->VIEWFORM->DATA->locked) ?
												$this->formCheckbox('locked', null, array('checked' => true)) :
												$this->formCheckbox('locked')
											;
										?>

							<?
								if($this->SECTIONS->VIEWFORM->displayPermissionSettings)
								{
									$path = $this->_controller->getEnv()->getIncludesDir().'/Sitengine/Env/_Templates/FormPermissionSection.html';
									$this->setScriptPath(dirname($path));
									$vars = array(
										'uid' => $this->SECTIONS->VIEWFORM->DATA->uid,
										'gid' => $this->SECTIONS->VIEWFORM->DATA->gid,
										'rag' => $this->SECTIONS->VIEWFORM->DATA->rag,
										'raw' => $this->SECTIONS->VIEWFORM->DATA->raw,
										'uag' => $this->SECTIONS->VIEWFORM->DATA->uag,
										'uaw' => $this->SECTIONS->VIEWFORM->DATA->uaw,
										'dag' => $this->SECTIONS->VIEWFORM->DATA->dag,
										'daw' => $this->SECTIONS->VIEWFORM->DATA->daw,
										'uidOptions' => $this->SECTIONS->VIEWFORM->DATA->uidOptions->toArray(),
										'gidOptions' => $this->SECTIONS->VIEWFORM->DATA->gidOptions->toArray(),
										'permissionSectionTitle' => $this->translate('viewFormPermissionSectionTitle'),
										'permissionSectionUid' => $this->translate('viewFormPermissionSectionUid'),
										'permissionSectionGid' => $this->translate('viewFormPermissionSectionGid'),
										'permissionSectionWorld' => $this->translate('viewFormPermissionSectionWorld'),
										'permissionSectionRead' => $this->translate('viewFormPermissionSectionRead'),
										'permissionSectionUpdate' => $this->translate('viewFormPermissionSectionUpdate'),
										'permissionSectionDelete' => $this->translate('viewFormPermissionSectionDelete'),
									);
									print $this->partial(basename($path), $vars);
								}
							?>

						<?else:?>

									<?=$this->html($this->SECTIONS->VIEWFORM->contentSectionTitle);?>

								<?
									$labelClass
										= ($this->SECTIONS->VIEWFORM->Payloads->isDefaultTranscript())
										? 'viewFormRequiredLabel'
										: 'viewFormDefaultLabel'
									;
								?>

								<?$fieldName = 'titleLang'.$this->SECTIONS->VIEWFORM->Payloads->getTranscriptIndex();?>

										<label for="title" class="<?=$labelClass?>">
											<?=$this->html($this->translate('formViewFieldsTitle'));?>

										<?=$this->formText($fieldName, $this->SECTIONS->VIEWFORM->DATA->$fieldName, array('size' => 40));?>

								<?$fieldName = 'textLang'.$this->SECTIONS->VIEWFORM->Payloads->getTranscriptIndex();?>

											<?=$this->html($this->translate('formViewFieldsText'));?>

										<?=
											$this->formTextarea(
												$fieldName,
												$this->SECTIONS->VIEWFORM->DATA->$fieldName,
												array('id' => 'textTextarea')
											);
										?>

						<?endif;?>

						<?if($this->SECTIONS->VIEWFORM->inputMode == Sitengine_Env::INPUTMODE_UPDATE):?>

							<?
								require_once 'Zend/Date.php';
								$date = new Zend_Date($this->SECTIONS->VIEWFORM->DATA->cdate, 'yyyy-MM-dd HH:mm:ss');
								$date->setTimezone($this->_controller->getPreferences()->getTimezone());
								$cdate  = $date->get(Zend_Date::DATE_LONG, $this->_controller->getLocale());
								$cdate .= ' '.$date->get(Zend_Date::TIME_LONG, $this->_controller->getLocale());

								$date = new Zend_Date($this->SECTIONS->VIEWFORM->DATA->mdate, 'yyyy-MM-dd HH:mm:ss');
								$date->setTimezone($this->_controller->getPreferences()->getTimezone());
								$mdate  = $date->get(Zend_Date::DATE_LONG, $this->_controller->getLocale());
								$mdate .= ' '.$date->get(Zend_Date::TIME_LONG, $this->_controller->getLocale());
							?>

								<?=$this->html($this->translate('viewFormDateSectionCdate'));?>
								<?=$this->html($cdate);?>

								<?=$this->html($this->translate('viewFormDateSectionMdate'));?>
								<?=$this->html($mdate);?>

						<?endif;?>

							<?if($this->SECTIONS->VIEWFORM->inputMode == Sitengine_Env::INPUTMODE_UPDATE):?>
								<input type="submit" value="<?=$this->html($this->translate('formViewUpdateSubmit'));?>" />
							<?else:?>
								<input type="submit" value="<?=$this->html($this->translate('formViewInsertSubmit'));?>" />
							<?endif;?>

					</form>

			<?require 'Sitengine/Env/_Templates/FooterSection.html';?>


text:
<configuration>
    <property>
      <name>mapreduce.admin.map.child.java.opts</name>
      <value>-server -XX:NewRatio=8 -Djava.net.preferIPv4Stack=true -Dhdp.version=${hdp.version}</value>
    </property>

    <property>
      <name>mapreduce.admin.reduce.child.java.opts</name>
      <value>-server -XX:NewRatio=8 -Djava.net.preferIPv4Stack=true -Dhdp.version=${hdp.version}</value>
    </property>

    <property>
      <name>mapreduce.admin.user.env</name>
      <value>LD_LIBRARY_PATH=/usr/hdp/${hdp.version}/hadoop/lib/native:/usr/hdp/${hdp.version}/hadoop/lib/native/Linux-amd64-64</value>
    </property>

    <property>
      <name>mapreduce.am.max-attempts</name>
      <value>2</value>
    </property>

    <property>
      <name>mapreduce.application.classpath</name>
      <value>$PWD/mr-framework/hadoop/share/hadoop/mapreduce/*:$PWD/mr-framework/hadoop/share/hadoop/mapreduce/lib/*:$PWD/mr-framework/hadoop/share/hadoop/common/*:$PWD/mr-framework/hadoop/share/hadoop/common/lib/*:$PWD/mr-framework/hadoop/share/hadoop/yarn/*:$PWD/mr-framework/hadoop/share/hadoop/yarn/lib/*:$PWD/mr-framework/hadoop/share/hadoop/hdfs/*:$PWD/mr-framework/hadoop/share/hadoop/hdfs/lib/*:/usr/hdp/${hdp.version}/hadoop/lib/hadoop-lzo-0.6.0.${hdp.version}.jar:/etc/hadoop/conf/secure</value>
    </property>

    <property>
      <name>mapreduce.application.framework.path</name>
      <value>/hdp/apps/${hdp.version}/mapreduce/mapreduce.tar.gz#mr-framework</value>
    </property>

    <property>
      <name>mapreduce.cluster.administrators</name>
      <value> hadoop</value>
    </property>

    <property>
      <name>mapreduce.framework.name</name>
      <value>yarn</value>
    </property>

		<!-- Tech Preview: Store MapReduce operational metrics in Timeline Server -->
    <property>
      <name>mapreduce.job.emit-timeline-data</name>
      <value>false</value>
    </property>

    <property>
      <name>mapreduce.job.reduce.slowstart.completedmaps</name>
      <value>0.05</value>
    </property>

    <property>
      <name>mapreduce.jobhistory.address</name>
      <value>localhost:10020</value>
    </property>

    <property>
      <name>mapreduce.jobhistory.bind-host</name>
      <value>0.0.0.0</value>
    </property>

    <property>
      <name>mapreduce.jobhistory.done-dir</name>
      <value>/mr-history/done</value>
    </property>

		<!-- This configures the HTTP endpoint for JobHistoryServer web UI. The following
					values are supported:
					- HTTP_ONLY : Service is provided only on http
					- HTTPS_ONLY : Service is provided only on https
		-->
    <property>
      <name>mapreduce.jobhistory.http.policy</name>
      <value>HTTP_ONLY</value>
    </property>

    <property>
      <name>mapreduce.jobhistory.intermediate-done-dir</name>
      <value>/mr-history/tmp</value>
    </property>

		<property>
      <name>mapreduce.jobhistory.webapp.address</name>
      <value>localhost:19888</value>
    </property>

    <property>
      <name>mapreduce.map.output.compress</name>
      <value>false</value>
    </property>

    <!-- If Mapreduce output compression is enabled, then use Snappy -->
    <property>
      <name>mapreduce.map.output.compress.codec</name>
      <value>org.apache.hadoop.io.compress.SnappyCodec</value>
    </property>

    <property>
      <name>mapreduce.map.sort.spill.percent</name>
      <value>0.7</value>
    </property>

    <property>
      <name>mapreduce.map.speculative</name>
      <value>false</value>
    </property>

    <property>
      <name>mapreduce.output.fileoutputformat.compress</name>
      <value>false</value>
    </property>

    <property>
      <name>mapreduce.output.fileoutputformat.compress.type</name>
      <value>BLOCK</value>
    </property>

    <property>
      <name>mapreduce.reduce.input.buffer.percent</name>
      <value>0.0</value>
    </property>

		<property>
      <name>mapreduce.reduce.shuffle.fetch.retry.enabled</name>
      <value>1</value>
    </property>

    <property>
      <name>mapreduce.reduce.shuffle.fetch.retry.interval-ms</name>
      <value>1000</value>
    </property>

    <property>
      <name>mapreduce.reduce.shuffle.fetch.retry.timeout-ms</name>
      <value>30000</value>
    </property>

    <property>
      <name>mapreduce.reduce.shuffle.input.buffer.percent</name>
      <value>0.7</value>
    </property>

		<property>
      <name>mapreduce.reduce.shuffle.merge.percent</name>
      <value>0.66</value>
    </property>

    <property>
      <name>mapreduce.reduce.shuffle.parallelcopies</name>
      <value>30</value>
    </property>

    <property>
      <name>mapreduce.reduce.speculative</name>
      <value>false</value>
    </property>

    <property>
      <name>mapreduce.shuffle.port</name>
      <value>13562</value>
    </property>

    <property>
      <name>mapreduce.task.timeout</name>
      <value>300000</value>
    </property>

    <property>
      <name>yarn.app.mapreduce.am.admin-command-opts</name>
      <value>-Dhdp.version=${hdp.version}</value>
    </property>

    <property>
      <name>yarn.app.mapreduce.am.command-opts</name>
      <value>-Xmx819m -Dhdp.version=${hdp.version}</value>
    </property>

    <property>
      <name>yarn.app.mapreduce.am.log.level</name>
      <value>INFO</value>
    </property>

    <property>
      <name>yarn.app.mapreduce.am.staging-dir</name>
      <value>/user</value>
    </property>

    <property>
      <name>mapreduce.reduce.log.level</name>
      <value>INFO</value>
    </property>

		<!--
		MANDATORY:
					Use the documentation or configuration tool to determine the memory
					settings according to the environment HDP is being deployed to
		-->

    <property>
      <name>mapreduce.map.java.opts</name>
      <value>-Xmx2048m</value> <!-- Example: "-Xmx546m" -->
    </property>

    <property>
      <name>mapreduce.map.memory.mb</name>
      <value>2560</value> <!-- Example: "682" -->
    </property>

    <property>
      <name>mapreduce.reduce.java.opts</name>
      <value>-Xmx2048m</value> <!-- Example: "-Xmx546m" -->
    </property>

    <property>
      <name>mapreduce.reduce.memory.mb</name>
      <value>2560</value> <!-- Example: "682" -->
    </property>

    <property>
      <name>mapreduce.task.io.sort.factor</name>
      <value>100</value> <!-- Example: "100" -->
    </property>

    <property>
      <name>mapreduce.task.io.sort.mb</name>
      <value>1024</value> <!-- Example: "273" -->
    </property>

    <property>
      <name>yarn.app.mapreduce.am.resource.mb</name>
      <value>2560</value> <!-- Example: "682" -->
    </property>

    <property>
        <name>yarn.app.mapreduce.am.command-opts</name>
        <value>-Xmx2048m</value>
    </property>
    <!-- Memory settings end -->

<!--
		The following settings are applicable to Kerberos enabled clusters only.

		Secure cluster configurations section start

    <property>
      <name>mapreduce.jobhistory.keytab</name>
      <value>/etc/security/keytabs/jhs.service.keytab</value>
    </property>

    <property>
      <name>mapreduce.jobhistory.keytab.file</name>
      <value>/etc/security/keytabs/jhs.service.keytab</value>
    </property>

			- Value will be of form: <Principal name>/_<Node Host name>@<Kerberos domain name>
			- For example: jhs/_HOST@EXAMPLE.COM
    <property>
      <name>mapreduce.jobhistory.principal</name>
      <value>jhs/_HOST@TODO-KERBEROS-DOMAIN</value>
    </property>

    <property>
      <name>mapreduce.jobhistory.webapp.https.address</name>
      <value>TODO-JOBHISTORYNODE-HOSTNAME:19889</value>
    </property>

    <property>
      <name>mapreduce.jobhistory.webapp.spnego-keytab-file</name>
      <value>/etc/security/keytabs/spnego.service.keytab</value>
    </property>

			- Value will be of form: <Principal name>/_<Node Host name>@<Kerberos domain name>
			- For example: HTTP/_HOST@TODO-KERBEROS-DOMAIN
    <property>
      <name>mapreduce.jobhistory.webapp.spnego-principal</name>
      <value>HTTP/_HOST@TODO-KERBEROS-DOMAIN</value>
    </property>

  - Secure cluster configurations section end -->

</configuration>