text:
/*jslint evil: true */

"use strict";

var ReactCurrentOwner = require("./ReactCurrentOwner");
var ReactDOMIDOperations = require("./ReactDOMIDOperations");
var ReactID = require("./ReactID");
var ReactMount = require("./ReactMount");
var ReactOwner = require("./ReactOwner");
var ReactReconcileTransaction = require("./ReactReconcileTransaction");

var invariant = require("./invariant");
var keyMirror = require("./keyMirror");
var merge = require("./merge");

/**
 * Prop key that references a component's owner.
 * @private
 */
var OWNER = '{owner}';

/**
 * Every React component is in one of these life cycles.
 */
var ComponentLifeCycle = keyMirror({
  /**
   * Mounted components have a DOM node representation and are capable of
   * receiving new props.
   */
  MOUNTED: null,
  /**
   * Unmounted components are inactive and cannot receive new props.
   */
  UNMOUNTED: null
});

/**
 * Warn if there's no key explicitly set on dynamic arrays of children.
 * This allows us to keep track of children between updates.
 */

var CHILD_HAS_NO_IDENTITY =
  'Each child in an array should have a unique "key" prop. ' +
  'Check the render method of ';

var CHILD_CAME_FROM_ANOTHER_OWNER = '. It was passed a child from ';

var ownerHasWarned = {};

/**
 * Helpers for flattening child arguments onto a new array or use an existing
 * one.
 */

/**
 * Generate a unique key that identifies this child within a set.
 *
 * @param {*} Manually provided key.
 * @param {number} Index that is used if a manual key is not provided.
 * @param {?number} Grouping index if this is used in a nested array.
 * @return {string}
 */
function createKey(explicitKey, childIndex, groupingIndex) {
  return ReactCurrentOwner.getDepth() + ':' +
         (groupingIndex == null ? '' : groupingIndex + ':') +
         (explicitKey == null ? '' + childIndex : explicitKey);
}

/**
 * Returns true if this parameter type is considered an empty child slot.
 * Used to filter out empty slots and generate a compact array.
 *
 * @param {*} Child component or any value.
 * @return {boolean}
 */
function isEmptyChild(child) {
  return child == null || typeof child === 'boolean';
}

/**
 * Assign an internal identity to a child component.
 *
 * @param {number} Index of the current array grouping.
 * @param {*} Child component or any value.
 * @param {number} Index of the current child within it's grouping.
 */
function assignKey(groupingIndex, child, index) {
  // Only truthy internal keys are valid. If it's not, we assign one.
  if (ReactComponent.isValidComponent(child) && !child._key) {
      var key = child.props.key;
      child._key = createKey(key, index, groupingIndex);
  }
}

/**
 * Make sure all children have an internal identity. Returns true if this is
 * already a compact array.
 *
 * @param {array} Children of any type.
 * @return {boolean}
 */
function tryToReuseArray(children) {
  for (var i = 0; i < children.length; i++) {
    var child = children[i];
    if (isEmptyChild(child)) {
      return false;
    }
    assignKey(0, child, i);
  }
  return true;
}

/**
 * Append children from the source array to the target array. Make sure all
 * children have an internal identity assigned to it based on insertion point.
 *
 * @param {number} Index of the current array grouping.
 * @param {array} Source array.
 * @param {array} Target array that will be appended to.
 */
function appendNestedChildren(groupingIndex, sourceArray, targetArray) {
  for (var i = 0; i < sourceArray.length; i++) {
    var child = sourceArray[i];
    if (isEmptyChild(child)) {
      continue;
    }
    assignKey(groupingIndex, child, i);
    // TODO: Invalid components like strings could possibly need
    // keys assigned to them here. Usually they're not stateful but
    // CSS transitions and special events could make them stateful.
    targetArray.push(child);
  }
}

/**
 * Components are the basic units of composition in React.
 *
 * Every component accepts a set of keyed input parameters known as "props" that
 * are initialized by the constructor. Once a component is mounted, the props
 * can be mutated using `setProps` or `replaceProps`.
 *
 * Every component is capable of the following operations:
 *
 *   `mountComponent`
 *     Initializes the component, renders markup, and registers event listeners.
 *
 *   `receiveProps`
 *     Updates the rendered DOM nodes given a new set of props.
 *
 *   `unmountComponent`
 *     Releases any resources allocated by this component.
 *
 * Components can also be "owned" by other components. Being owned by another
 * component means being constructed by that component. This is different from
 * being the child of a component, which means having a DOM representation that
 * is a child of the DOM representation of that component.
 *
 * @class ReactComponent
 */
var ReactComponent = {

  /**
   * @param {?object} object
   * @return {boolean} True if `object` is a valid component.
   * @final
   */
  isValidComponent: function(object) {
    return !!(
      object &&
      typeof object.mountComponentIntoNode === 'function' &&
      typeof object.receiveProps === 'function'
    );
  },

  /**
   * @internal
   */
  LifeCycle: ComponentLifeCycle,

  /**
   * React references `ReactDOMIDOperations` using this property in order to
   * allow dependency injection.
   *
   * @internal
   */
  DOMIDOperations: ReactDOMIDOperations,

  /**
   * React references `ReactReconcileTransaction` using this property in order
   * to allow dependency injection.
   *
   * @internal
   */
  ReactReconcileTransaction: ReactReconcileTransaction,

  /**
   * @param {object} DOMIDOperations
   * @final
   */
  setDOMOperations: function(DOMIDOperations) {
    ReactComponent.DOMIDOperations = DOMIDOperations;
  },

  /**
   * @param {Transaction} ReactReconcileTransaction
   * @final
   */
  setReactReconcileTransaction: function(ReactReconcileTransaction) {
    ReactComponent.ReactReconcileTransaction = ReactReconcileTransaction;
  },

  /**
   * Base functionality for every ReactComponent constructor.
   *
   * @lends {ReactComponent.prototype}
   */
  Mixin: {

    /**
     * Checks whether or not this component is mounted.
     *
     * @return {boolean} True if mounted, false otherwise.
     * @final
     * @protected
     */
    isMounted: function() {
      return this._lifeCycleState === ComponentLifeCycle.MOUNTED;
    },

    /**
     * Returns the DOM node rendered by this component.
     *
     * @return {?DOMElement} The root node of this component.
     * @final
     * @protected
     */
    getDOMNode: function() {
      invariant(this.isMounted());
      return ReactID.getNode(this._rootNodeID);
    },

    /**
     * Sets a subset of the props.
     *
     * @param {object} partialProps Subset of the next props.
     * @final
     * @public
     */
    setProps: function(partialProps) {
      this.replaceProps(merge(this.props, partialProps));
    },

    /**
     * Replaces all of the props.
     *
     * @param {object} props New props.
     * @final
     * @public
     */
    replaceProps: function(props) {
      invariant(!this.props[OWNER]);
      var transaction = ReactComponent.ReactReconcileTransaction.getPooled();
      transaction.perform(this.receiveProps, this, props, transaction);
      ReactComponent.ReactReconcileTransaction.release(transaction);
    },

    /**
     * Base constructor for all React component.
     *
     * Subclasses that override this method should make sure to invoke
     * `ReactComponent.Mixin.construct.call(this, ...)`.
     *
     * @param {?object} initialProps
     * @param {*} children
     * @internal
     */
    construct: function(initialProps, children) {
      this.props = initialProps || {};
      // Record the component responsible for creating this component.
      this.props[OWNER] = ReactCurrentOwner.current;
      // All components start unmounted.
      this._lifeCycleState = ComponentLifeCycle.UNMOUNTED;

      // Children can be either an array or more than one argument
      if (arguments.length < 2) {
        return;
      }

      if (arguments.length === 2) {

        // A single string or number child is treated as content, not an array.
        var type = typeof children;
        if (children == null || type === 'string' || type === 'number') {
          this.props.children = children;
          return;
        }

        // A single array can be reused if it's already flat
        if (Array.isArray(children) && tryToReuseArray(children)) {
          this.props.children = children;
          return;
        }

      }

      // Subsequent arguments are rolled into one child array. Array arguments
      // are flattened onto it. This is inlined to avoid extra heap allocation.
      var targetArray = null;
      for (var i = 1; i < arguments.length; i++) {
        var child = arguments[i];
        if (Array.isArray(child)) {
          if (child.length === 0) {
            continue;
          }

          if (targetArray === null) {
            targetArray = [];
          }
          appendNestedChildren(i - 1, child, targetArray);

        } else if (!isEmptyChild(child)) {

          // Only truthy internal keys are valid. If it's not, we assign one.
          if (ReactComponent.isValidComponent(child) && !child._key) {
            // This is a static node and therefore safe to key by index.
            // No warning necessary.
            child._key = createKey(child.props.key, i - 1);
          }

          if (targetArray === null) {
            targetArray = [];
          }
          targetArray.push(child);

        }
      }
      this.props.children = targetArray;
    },

    /**
     * Initializes the component, renders markup, and registers event listeners.
     *
     * NOTE: This does not insert any nodes into the DOM.
     *
     * Subclasses that override this method should make sure to invoke
     * `ReactComponent.Mixin.mountComponent.call(this, ...)`.
     *
     * @param {string} rootID DOM ID of the root node.
     * @param {ReactReconcileTransaction} transaction
     * @return {?string} Rendered markup to be inserted into the DOM.
     * @internal
     */
    mountComponent: function(rootID, transaction) {
      invariant(!this.isMounted());
      var props = this.props;
      if (props.ref != null) {
        ReactOwner.addComponentAsRefTo(this, props.ref, props[OWNER]);
      }
      this._rootNodeID = rootID;
      this._lifeCycleState = ComponentLifeCycle.MOUNTED;
      // Effectively: return '';
    },

    /**
     * Releases any resources allocated by `mountComponent`.
     *
     * NOTE: This does not remove any nodes from the DOM.
     *
     * Subclasses that override this method should make sure to invoke
     * `ReactComponent.Mixin.unmountComponent.call(this)`.
     *
     * @internal
     */
    unmountComponent: function() {
      invariant(this.isMounted());
      var props = this.props;
      if (props.ref != null) {
        ReactOwner.removeComponentAsRefFrom(this, props.ref, props[OWNER]);
      }
      ReactID.purgeID(this._rootNodeID);
      this._rootNodeID = null;
      this._lifeCycleState = ComponentLifeCycle.UNMOUNTED;
    },

    /**
     * Updates the rendered DOM nodes given a new set of props.
     *
     * Subclasses that override this method should make sure to invoke
     * `ReactComponent.Mixin.receiveProps.call(this, ...)`.
     *
     * @param {object} nextProps Next set of properties.
     * @param {ReactReconcileTransaction} transaction
     * @internal
     */
    receiveProps: function(nextProps, transaction) {
      invariant(this.isMounted());
      var props = this.props;
      // If either the owner or a `ref` has changed, make sure the newest owner
      // has stored a reference to `this`, and the previous owner (if different)
      // has forgotten the reference to `this`.
      if (nextProps[OWNER] !== props[OWNER] || nextProps.ref !== props.ref) {
        if (props.ref != null) {
          ReactOwner.removeComponentAsRefFrom(this, props.ref, props[OWNER]);
        }
        // Correct, even if the owner is the same, and only the ref has changed.
        if (nextProps.ref != null) {
          ReactOwner.addComponentAsRefTo(this, nextProps.ref, nextProps[OWNER]);
        }
      }
    },

    /**
     * Mounts this component and inserts it into the DOM.
     *
     * @param {string} rootID DOM ID of the root node.
     * @param {DOMElement} container DOM element to mount into.
     * @param {boolean} shouldReuseMarkup If true, do not insert markup
     * @final
     * @internal
     * @see {ReactMount.renderComponent}
     */
    mountComponentIntoNode: function(rootID, container, shouldReuseMarkup) {
      var transaction = ReactComponent.ReactReconcileTransaction.getPooled();
      transaction.perform(
        this._mountComponentIntoNode,
        this,
        rootID,
        container,
        transaction,
        shouldReuseMarkup
      );
      ReactComponent.ReactReconcileTransaction.release(transaction);
    },

    /**
     * @param {string} rootID DOM ID of the root node.
     * @param {DOMElement} container DOM element to mount into.
     * @param {ReactReconcileTransaction} transaction
     * @param {boolean} shouldReuseMarkup If true, do not insert markup
     * @final
     * @private
     */
    _mountComponentIntoNode: function(
        rootID,
        container,
        transaction,
        shouldReuseMarkup) {
      invariant(container && container.nodeType === 1);
      var renderStart = Date.now();
      var markup = this.mountComponent(rootID, transaction);
      ReactMount.totalInstantiationTime += (Date.now() - renderStart);

      if (shouldReuseMarkup) {
        return;
      }

      var injectionStart = Date.now();
      // Asynchronously inject markup by ensuring that the container is not in
      // the document when settings its `innerHTML`.
      var parent = container.parentNode;
      if (parent) {
        var next = container.nextSibling;
        parent.removeChild(container);
        container.innerHTML = markup;
        if (next) {
          parent.insertBefore(container, next);
        } else {
          parent.appendChild(container);
        }
      } else {
        container.innerHTML = markup;
      }
      ReactMount.totalInjectionTime += (Date.now() - injectionStart);
    },

    /**
     * Unmounts this component and removes it from the DOM.
     *
     * @param {DOMElement} container DOM element to unmount from.
     * @final
     * @internal
     * @see {ReactMount.unmountAndReleaseReactRootNode}
     */
    unmountComponentFromNode: function(container) {
      this.unmountComponent();
      // http://jsperf.com/emptying-a-node
      while (container.lastChild) {
        container.removeChild(container.lastChild);
      }
    },

    /**
     * Checks if this component is owned by the supplied `owner` component.
     *
     * @param {ReactComponent} owner Component to check.
     * @return {boolean} True if `owners` owns this component.
     * @final
     * @internal
     */
    isOwnedBy: function(owner) {
      return this.props[OWNER] === owner;
    },

    /**
     * Gets another component, that shares the same owner as this one, by ref.
     *
     * @param {string} ref of a sibling Component.
     * @return {?ReactComponent} the actual sibling Component.
     * @final
     * @internal
     */
    getSiblingByRef: function(ref) {
      var owner = this.props[OWNER];
      if (!owner || !owner.refs) {
        return null;
      }
      return owner.refs[ref];
    }

  }

};

module.exports = ReactComponent;


text:
"""
Main URL settings page. See https://docs.djangoproject.com/en/1.10/topics/http/urls/ for more information.
"""

from django.conf import settings
from django.urls import path, include
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.auth.decorators import login_required
from django.contrib.sitemaps import views
from django.http import HttpResponse
from graphene_django.views import GraphQLView

from gollahalli_cms.gollahalli.schema import query
from gollahalli_cms.gollahalli.sitemaps import Sitemap, xsl_content_type, index_view
from gollahalli_cms.gollahalli.utils import *

sitemaps = {
    'pages': Sitemap(
        ['index'],
        [1.0],
        ['monthly'],
        [datetime.datetime.today()]
    ),

    'other': Sitemap(
        ['repo', 'change-log'],
        [0.5, 1.0],
        ['monthly', 'monthly'],
        [datetime.datetime.today(), github_date_time_format(get_version()['published_at'])]
    )
}

admin.autodiscover()
admin.site.login = login_required(admin.site.login)

urlpatterns = [
                  path('', include('viewer.urls')),
                  path('', include('editor.urls'), name='editor_urls'),
                  path('admin/', admin.site.urls, name='admin_urls'),
                  path('', include('authy_me.urls'), name="login"),
                  path('', include('welcome.urls')),
                  path('', include('blog.urls')),
                  path('robots.txt',
                       lambda x: HttpResponse(
                           "Sitemap: https://www.gollahalli.com/sitemap.xml\nUser-agent: *\nDisallow: "
                           "/admin/\nDisallow: /cdn-cgi/\nDisallow: /portal/",
                           content_type="text/plain"), name="robots_file"),
                  path('sitemap.xml', index_view, {'sitemaps': sitemaps, 'template_name': 'sitemap-index.xml'}),
                  path('sitemap-<section>.xml', views.sitemap,
                       {'sitemaps': sitemaps, 'template_name': 'sitemap.xml'},
                       name='django.contrib.sitemaps.views.sitemap'),
                  path('graphql', GraphQLView.as_view(graphiql=True, schema=query)),
                  path('sitemap.xsl', xsl_content_type, name='sitemap_xsl')
              ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

handler404 = 'viewer.views.page_not_found'
handler500 = 'viewer.views.server_error'

redpajama_set_name: RedPajamaGithub


text:
Thorlabs Pro 8000 modular laser driver
######################################

.. autoclass:: pymeasure.instruments.thorlabs.ThorlabsPro8000
    :members:
    :show-inheritance:


text:
// --------------------------------------------------------------------------------------------
// <copyright file="EffortConnectionMock.cs" company="Effort Team">
//     Copyright (C) Effort Team
//
//     Permission is hereby granted, free of charge, to any person obtaining a copy
//     of this software and associated documentation files (the "Software"), to deal
//     in the Software without restriction, including without limitation the rights
//     to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//     copies of the Software, and to permit persons to whom the Software is
//     furnished to do so, subject to the following conditions:
//
//     The above copyright notice and this permission notice shall be included in
//     all copies or substantial portions of the Software.
//
//     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//     IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//     FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//     AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//     LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//     THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------

namespace Effort.Test.Internal.Fakes
{
    using Effort.Provider;

    internal class EffortConnectionMock : EffortConnection
    {
        public bool IsUnregisterContainerCalled
        {
            get;
            private set;
        }

        internal override void UnregisterContainer()
        {
            this.IsUnregisterContainerCalled = true;
        }
    }
}


text:
import logging

from django.utils.functional import wraps
from django.utils.translation import ugettext as _

from desktop.lib.exceptions_renderable import PopupException

LOG = logging.getLogger(__name__)

def allow_admin_only(view_func):
  def decorate(request, *args, **kwargs):

    if not request.user.is_superuser:
      message = _("Permission denied. You are not an Administrator")
      raise PopupException(message)

    return view_func(request, *args, **kwargs)
  return wraps(view_func)(decorate)


text:
package net.ontrack.extension.git.client.plot;

import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.revplot.AbstractPlotRenderer;
import org.eclipse.jgit.revplot.PlotCommit;
import org.eclipse.jgit.revplot.PlotCommitList;
import org.eclipse.jgit.revplot.PlotLane;
import org.eclipse.jgit.revwalk.RevCommit;

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

public class GitPlotRenderer extends AbstractPlotRenderer<PlotLane, GColor> {

    public static final int DEFAULT_ROW_HEIGHT = 24;
    private final GPlot plot;
    private final List<RevCommit> commits;
    private final int rowHeight = DEFAULT_ROW_HEIGHT;
    private PlotCommit<PlotLane> currentCommit;
    private int rowIndex;

    public GitPlotRenderer(PlotCommitList<PlotLane> commitList) {
        // Plot to create
        plot = new GPlot();
        // List of commit IDs
        commits = new ArrayList<>();
        // Loops over the commits
        rowIndex = 0;
        for (PlotCommit<PlotLane> commit : commitList) {
            commits.add(commit);
            currentCommit = commit;
            paintCommit(commit, rowHeight);
            rowIndex++;
        }
    }

    public List<RevCommit> getCommits() {
        return commits;
    }

    public GPlot getPlot() {
        return plot;
    }

    @Override
    protected int drawLabel(int x, int y, Ref ref) {
        return 0;
    }

    @Override
    protected GColor laneColor(PlotLane myLane) {
        if (myLane == null) {
            return new GColor(0);
        } else {
            return new GColor(myLane.getPosition());
        }
    }

    @Override
    protected void drawLine(GColor color, int x1, int y1, int x2, int y2, int width) {
        plot.add(GLine.of(color, point(x1, y1), point(x2, y2), width));
    }

    @Override
    protected void drawCommitDot(int x, int y, int w, int h) {
        plot.add(
                GOval.of(
                        laneColor(currentCommit.getLane()),
                        point(x, y),
                        GDim.of(w, h)
                )
        );
    }

    @Override
    protected void drawBoundaryDot(int x, int y, int w, int h) {
    }

    @Override
    protected void drawText(String msg, int x, int y) {
    }

    private GPoint point(int x1, int y1) {
        return GPoint.of(x1, y1).ty(rowIndex * rowHeight);
    }
}


text:
<?php

namespace OpenCloud\Common\Exceptions;

class SnapshotError extends \Exception {}


text:
using System.Web.Mvc;

namespace Coral.Admin.Areas.ReportManage
{
    public class ReportManageAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "ReportManage";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
              this.AreaName + "_Default",
              this.AreaName + "/{controller}/{action}/{id}",
              new { area = this.AreaName, controller = "Home", action = "Index", id = UrlParameter.Optional },
              new string[] { "NFine.Web.Areas." + this.AreaName + ".Controllers" }
            );
        }
    }
}


text:
package org.wso2.carbon.identity.core.dao;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.core.IdentityRegistryResources;
import org.wso2.carbon.identity.core.model.SAMLSSOServiceProviderDO;
import org.wso2.carbon.identity.core.util.IdentityTenantUtil;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.jdbc.utils.Transaction;
import org.wso2.carbon.registry.core.session.UserRegistry;
import org.wso2.carbon.user.api.UserStoreException;

public class SAMLSSOServiceProviderDAO extends AbstractDAO<SAMLSSOServiceProviderDO> {

    private static Log log = LogFactory.getLog(SAMLSSOServiceProviderDAO.class);

    public SAMLSSOServiceProviderDAO(Registry registry) {
        this.registry = registry;
    }

    protected SAMLSSOServiceProviderDO resourceToObject(Resource resource) {
        SAMLSSOServiceProviderDO serviceProviderDO = new SAMLSSOServiceProviderDO();
        serviceProviderDO.setIssuer(resource
                .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER));
        serviceProviderDO.setAssertionConsumerUrls(resource.getPropertyValues(
                IdentityRegistryResources.PROP_SAML_SSO_ASSERTION_CONS_URLS));
        serviceProviderDO.setDefaultAssertionConsumerUrl(resource.getProperty(
                IdentityRegistryResources.PROP_DEFAULT_SAML_SSO_ASSERTION_CONS_URL));
        serviceProviderDO.setCertAlias(resource
                .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER_CERT_ALIAS));

        if (StringUtils.isNotEmpty(resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_SIGNING_ALGORITHM))) {
            serviceProviderDO.setSigningAlgorithmUri(resource.getProperty(IdentityRegistryResources
                    .PROP_SAML_SSO_SIGNING_ALGORITHM));
        }

        if (StringUtils.isNotEmpty(resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_DIGEST_ALGORITHM))) {
            serviceProviderDO.setDigestAlgorithmUri(resource.getProperty(IdentityRegistryResources
                    .PROP_SAML_SSO_DIGEST_ALGORITHM));
        }

        if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_SINGLE_LOGOUT) != null) {
            serviceProviderDO.setDoSingleLogout(new Boolean(resource.getProperty(
                    IdentityRegistryResources.PROP_SAML_SSO_DO_SINGLE_LOGOUT).trim()));
        }

        if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_NAMEID_FORMAT) != null) {
            serviceProviderDO.setNameIDFormat(resource.
                    getProperty(IdentityRegistryResources.PROP_SAML_SSO_NAMEID_FORMAT));
        }

        if (resource
                .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_NAMEID_CLAIMURI) != null) {
            if (new Boolean(resource.getProperty(
                    IdentityRegistryResources.PROP_SAML_SSO_ENABLE_NAMEID_CLAIMURI)
                    .trim())) {
                serviceProviderDO.setNameIdClaimUri(resource.
                        getProperty(IdentityRegistryResources.PROP_SAML_SSO_NAMEID_CLAIMURI));
            }
        }

        serviceProviderDO.setLoginPageURL(resource.
                getProperty(IdentityRegistryResources.PROP_SAML_SSO_LOGIN_PAGE_URL));

        if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_SIGN_RESPONSE) != null) {
            serviceProviderDO.setDoSignResponse(new Boolean(resource.getProperty(
                    IdentityRegistryResources.PROP_SAML_SSO_DO_SIGN_RESPONSE).trim()));
        }

        if (serviceProviderDO.isDoSingleLogout()) {
            serviceProviderDO.setSloResponseURL(resource.getProperty(IdentityRegistryResources
                                                                             .PROP_SAML_SLO_RESPONSE_URL));
            serviceProviderDO.setSloRequestURL(resource.getProperty(IdentityRegistryResources
                                                                            .PROP_SAML_SLO_REQUEST_URL));
        }

        if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_SIGN_ASSERTIONS) != null) {
            serviceProviderDO.setDoSignAssertions(new Boolean(resource.getProperty(
                    IdentityRegistryResources.PROP_SAML_SSO_DO_SIGN_ASSERTIONS).trim()));
        }

        if (resource
                .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ATTRIB_CONSUMING_SERVICE_INDEX) != null) {
            serviceProviderDO
                    .setAttributeConsumingServiceIndex(resource
                            .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ATTRIB_CONSUMING_SERVICE_INDEX));
        }

        if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_CLAIMS) != null) {
            serviceProviderDO.setRequestedClaims(resource
                    .getPropertyValues(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_CLAIMS));
        }

        if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_AUDIENCES) != null) {
            serviceProviderDO.setRequestedAudiences(resource
                    .getPropertyValues(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_AUDIENCES));
        }

        if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_RECIPIENTS) != null) {
            serviceProviderDO.setRequestedRecipients(resource
                    .getPropertyValues(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_RECIPIENTS));
        }

        if (resource
                .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_ATTRIBUTES_BY_DEFAULT) != null) {
            String enableAttrByDefault = resource
                    .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_ATTRIBUTES_BY_DEFAULT);
            if ("true".equals(enableAttrByDefault)) {
                serviceProviderDO.setEnableAttributesByDefault(true);
            } else {
                serviceProviderDO.setEnableAttributesByDefault(false);
            }
        }
        if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_IDP_INIT_SSO_ENABLED) != null) {
            serviceProviderDO.setIdPInitSSOEnabled(new Boolean(resource.getProperty(
                    IdentityRegistryResources.PROP_SAML_SSO_IDP_INIT_SSO_ENABLED).trim()));
        }
        if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SLO_IDP_INIT_SLO_ENABLED) != null) {
            serviceProviderDO.setIdPInitSLOEnabled(new Boolean(resource.getProperty(
                    IdentityRegistryResources.PROP_SAML_SLO_IDP_INIT_SLO_ENABLED).trim()));
            if (serviceProviderDO.isIdPInitSLOEnabled() && resource.getProperty(
                    IdentityRegistryResources.PROP_SAML_IDP_INIT_SLO_RETURN_URLS) != null) {
                serviceProviderDO.setIdpInitSLOReturnToURLs(resource.getPropertyValues(
                        IdentityRegistryResources.PROP_SAML_IDP_INIT_SLO_RETURN_URLS));
            }
        }
        if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_ENCRYPTED_ASSERTION) != null) {
            serviceProviderDO.setDoEnableEncryptedAssertion(new Boolean(resource.getProperty(
                    IdentityRegistryResources.PROP_SAML_SSO_ENABLE_ENCRYPTED_ASSERTION).trim()));
        }
        if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_VALIDATE_SIGNATURE_IN_REQUESTS) != null) {
            serviceProviderDO.setDoValidateSignatureInRequests(new Boolean(resource.getProperty(
                    IdentityRegistryResources.PROP_SAML_SSO_VALIDATE_SIGNATURE_IN_REQUESTS).trim()));
        }
        return serviceProviderDO;
    }

    public boolean addServiceProvider(SAMLSSOServiceProviderDO serviceProviderDO)
            throws IdentityException {
        String path = null;
        Resource resource;

        if (serviceProviderDO.getIssuer() != null) {
            path = IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS
                    + encodePath(serviceProviderDO.getIssuer());
        }

        boolean isTransactionStarted = Transaction.isStarted();
        try {
            if (registry.resourceExists(path)) {
                if (log.isDebugEnabled()) {
                    log.debug("Service Provider already exists with the same issuer name"
                            + serviceProviderDO.getIssuer());
                }
                return false;
            }

            resource = registry.newResource();
            resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER,
                    serviceProviderDO.getIssuer());
            resource.setProperty(IdentityRegistryResources.PROP_SAML_SSO_ASSERTION_CONS_URLS,
                                 serviceProviderDO.getAssertionConsumerUrlList());
            resource.addProperty(IdentityRegistryResources.PROP_DEFAULT_SAML_SSO_ASSERTION_CONS_URL,
                                 serviceProviderDO.getDefaultAssertionConsumerUrl());
            resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER_CERT_ALIAS,
                    serviceProviderDO.getCertAlias());
            resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_LOGIN_PAGE_URL,
                    serviceProviderDO.getLoginPageURL());
            resource.addProperty(
                    IdentityRegistryResources.PROP_SAML_SSO_NAMEID_FORMAT,
                    serviceProviderDO.getNameIDFormat());
            resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_SIGNING_ALGORITHM, serviceProviderDO
                    .getSigningAlgorithmUri());
            resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_DIGEST_ALGORITHM, serviceProviderDO
                    .getDigestAlgorithmUri());
            if (serviceProviderDO.getNameIdClaimUri() != null
                    && serviceProviderDO.getNameIdClaimUri().trim().length() > 0) {
                resource.addProperty(
                        IdentityRegistryResources.PROP_SAML_SSO_ENABLE_NAMEID_CLAIMURI,
                        "true");
                resource.addProperty(
                        IdentityRegistryResources.PROP_SAML_SSO_NAMEID_CLAIMURI,
                        serviceProviderDO.getNameIdClaimUri());
            } else {
                resource.addProperty(
                        IdentityRegistryResources.PROP_SAML_SSO_ENABLE_NAMEID_CLAIMURI,
                        "false");
            }

            String doSingleLogout = serviceProviderDO.isDoSingleLogout() ? "true" : "false";
            resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_SINGLE_LOGOUT, doSingleLogout);
            if(serviceProviderDO.isDoSingleLogout()) {
                if(StringUtils.isNotBlank(serviceProviderDO.getSloResponseURL())) {
                    resource.addProperty(IdentityRegistryResources.PROP_SAML_SLO_RESPONSE_URL,
                                         serviceProviderDO.getSloResponseURL());
                }
                if(StringUtils.isNotBlank(serviceProviderDO.getSloRequestURL())) {
                    resource.addProperty(IdentityRegistryResources.PROP_SAML_SLO_REQUEST_URL,
                                         serviceProviderDO.getSloRequestURL());
                }
            }

            String doSignResponse = serviceProviderDO.isDoSignResponse() ? "true" : "false";
            resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_SIGN_RESPONSE,
                    doSignResponse);
            String doSignAssertions = serviceProviderDO.isDoSignAssertions() ? "true" : "false";
            resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_SIGN_ASSERTIONS,
                    doSignAssertions);
            if (serviceProviderDO.getRequestedClaimsList() != null
                    && serviceProviderDO.getRequestedClaimsList().size() > 0) {
                resource.setProperty(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_CLAIMS,
                        serviceProviderDO.getRequestedClaimsList());
            }
            if (serviceProviderDO.getAttributeConsumingServiceIndex() != null) {
                resource.addProperty(
                        IdentityRegistryResources.PROP_SAML_SSO_ATTRIB_CONSUMING_SERVICE_INDEX,
                        serviceProviderDO.getAttributeConsumingServiceIndex());
            }
            if (serviceProviderDO.getRequestedAudiencesList() != null
                    && serviceProviderDO.getRequestedAudiencesList().size() > 0) {
                resource.setProperty(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_AUDIENCES,
                        serviceProviderDO.getRequestedAudiencesList());
            }
            if (serviceProviderDO.getRequestedRecipientsList() != null
                    && serviceProviderDO.getRequestedRecipientsList().size() > 0) {
                resource.setProperty(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_RECIPIENTS,
                        serviceProviderDO.getRequestedRecipientsList());
            }

            String enableAttributesByDefault = serviceProviderDO.isEnableAttributesByDefault() ? "true"
                    : "false";
            resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_ATTRIBUTES_BY_DEFAULT,
                    enableAttributesByDefault);
            String idPInitSSOEnabled = serviceProviderDO.isIdPInitSSOEnabled() ? "true" : "false";
            resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_IDP_INIT_SSO_ENABLED,
                    idPInitSSOEnabled);
            resource.addProperty(IdentityRegistryResources.PROP_SAML_SLO_IDP_INIT_SLO_ENABLED,
                                 serviceProviderDO.isIdPInitSLOEnabled() ? "true" : "false");
            if(serviceProviderDO.isIdPInitSLOEnabled() && serviceProviderDO.getIdpInitSLOReturnToURLList().size() > 0) {
                resource.setProperty(IdentityRegistryResources.PROP_SAML_IDP_INIT_SLO_RETURN_URLS,
                                     serviceProviderDO.getIdpInitSLOReturnToURLList());
            }
            String enableEncryptedAssertion = serviceProviderDO.isDoEnableEncryptedAssertion() ? "true" : "false";
            resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_ENCRYPTED_ASSERTION,
                    enableEncryptedAssertion);

            String validateSignatureInRequests = serviceProviderDO.isDoValidateSignatureInRequests() ? "true" : "false";
            resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_VALIDATE_SIGNATURE_IN_REQUESTS,
                    validateSignatureInRequests);
            try {
                if (!isTransactionStarted) {
                    registry.beginTransaction();
                }

                registry.put(path, resource);

                if (!isTransactionStarted) {
                    registry.commitTransaction();
                }

            } catch (RegistryException e) {
                if (!isTransactionStarted) {
                    registry.rollbackTransaction();
                }
                throw e;
            }

        } catch (RegistryException e) {
            log.error("Error While adding Service Provider", e);
            throw new IdentityException("Error while adding Service Provider", e);
        }

        if (log.isDebugEnabled()) {
            log.debug("Service Provider " + serviceProviderDO.getIssuer()
                    + " is added successfully.");
        }
        return true;
    }

    public SAMLSSOServiceProviderDO[] getServiceProviders() throws IdentityException {
        SAMLSSOServiceProviderDO[] serviceProvidersList = new SAMLSSOServiceProviderDO[0];
        try {
            if (registry.resourceExists(IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS)) {
                String[] providers = (String[]) registry.get(
                        IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS).getContent();
                if (providers != null) {
                    serviceProvidersList = new SAMLSSOServiceProviderDO[providers.length];
                    for (int i = 0; i < providers.length; i++) {
                        serviceProvidersList[i] = resourceToObject(registry.get(providers[i]));
                    }
                }
            }
        } catch (RegistryException e) {
            log.error("Error reading Service Providers from Registry", e);
            throw new IdentityException("Error reading Service Providers from Registry", e);
        }
        return serviceProvidersList;
    }

    /**
     * Remove the service provider with the given name
     *
     * @param issuer
     * @throws IdentityException
     */
    public boolean removeServiceProvider(String issuer) throws IdentityException {

        if (issuer == null || StringUtils.isEmpty(issuer.trim())) {
            throw new IllegalArgumentException("Trying to delete issuer \'" + issuer + "\'");
        }

        String path = IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS + encodePath(issuer);
        boolean isTransactionStarted = Transaction.isStarted();
        try {
            if (registry.resourceExists(path)) {
                try {
                    if (!isTransactionStarted) {
                        registry.beginTransaction();
                    }

                    registry.delete(path);

                    if (!isTransactionStarted) {
                        registry.commitTransaction();
                    }

                    return true;

                } catch (RegistryException e) {
                    if (!isTransactionStarted) {
                        registry.rollbackTransaction();
                    }
                    throw e;
                }
            }
        } catch (RegistryException e) {
            log.error("Error removing the service provider from the registry", e);
            throw new IdentityException("Error removing the service provider from the registry", e);
        }

        return false;
    }

    /**
     * Get the service provider
     *
     * @param issuer
     * @return
     * @throws IdentityException
     */
    public SAMLSSOServiceProviderDO getServiceProvider(String issuer) throws IdentityException {

        String path = IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS + encodePath(issuer);
        SAMLSSOServiceProviderDO serviceProviderDO = null;

        UserRegistry userRegistry = null;
        String tenantDomain = null;
        try {
            userRegistry = (UserRegistry) registry;
            tenantDomain = IdentityTenantUtil.getRealmService().getTenantManager().getDomain(userRegistry.getTenantId());
            if (registry.resourceExists(path)) {
                serviceProviderDO = resourceToObject(registry.get(path));
                serviceProviderDO.setTenantDomain(tenantDomain);
            }
        } catch (RegistryException e) {
            throw new IdentityException("Error occurred while checking if resource path \'" + path + "\' exists in " +
                    "registry for tenant domain : " + tenantDomain, e);
            } catch (UserStoreException e) {
                throw new IdentityException("Error occurred while getting tenant domain from tenant ID : " +
                    userRegistry.getTenantId(), e);
        }

        return serviceProviderDO;
    }

    private String encodePath(String path) {
        String encodedStr = new String(Base64.encodeBase64(path.getBytes()));
        return encodedStr.replace("=", "");
    }

}


text:
require 'test_helper'

module PettanrPettanProtectedV01Licenses
  class CreditPictureTest < ActiveSupport::TestCase
    # test "the truth" do
    #   assert true
    # end
  end
end


text:
if (module.hot) {
	module.hot.accept();
}

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import configureStore from './store';

import App from './components/App/App';

const store = configureStore();

store.subscribe(() => {
});

ReactDOM.render(
	<Provider store={store}>
		<App />
	</Provider>,
	document.getElementById('app')
);


text:
<?php namespace Isimmons\Sgd;

use Symfony\Component\Console\Formatter\OutputFormatterInterface;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Output\OutputInterface;

class Welcome implements OutputInterface {
   /**
     * {@inheritdoc}
     */
    public function setFormatter(OutputFormatterInterface $formatter)
    {
        $this->formatter = $formatter;
    }

    /**
     * {@inheritdoc}
     */
    public function getFormatter()
    {
        return $this->formatter;
    }

    /**
     * {@inheritdoc}
     */
    public function setDecorated($decorated)
    {
        $this->formatter->setDecorated($decorated);
    }

    /**
     * {@inheritdoc}
     */
    public function isDecorated()
    {
        return $this->formatter->isDecorated();
    }

    /**
     * {@inheritdoc}
     */
    public function setVerbosity($level)
    {
        $this->verbosity = (int) $level;
    }

    /**
     * {@inheritdoc}
     */
    public function getVerbosity()
    {
        return $this->verbosity;
    }

    public function isQuiet()
    {
        return self::VERBOSITY_QUIET === $this->verbosity;
    }

    public function isVerbose()
    {
        return self::VERBOSITY_VERBOSE <= $this->verbosity;
    }

    public function isVeryVerbose()
    {
        return self::VERBOSITY_VERY_VERBOSE <= $this->verbosity;
    }

    public function isDebug()
    {
        return self::VERBOSITY_DEBUG <= $this->verbosity;
    }

    /**
     * {@inheritdoc}
     */
    public function writeln($messages, $type = self::OUTPUT_NORMAL)
    {
        $this->write($messages, true, $type);
    }

    /**
     * {@inheritdoc}
     */
    public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL)
    {
        if (self::VERBOSITY_QUIET === $this->verbosity) {
            return;
        }

        $messages = (array) $messages;

        foreach ($messages as $message) {
            switch ($type) {
                case OutputInterface::OUTPUT_NORMAL:
                    $message = $this->formatter->format($message);
                    break;
                case OutputInterface::OUTPUT_RAW:
                    break;
                case OutputInterface::OUTPUT_PLAIN:
                    $message = strip_tags($this->formatter->format($message));
                    break;
                default:
                    throw new \InvalidArgumentException(sprintf('Unknown output type given (%s)', $type));
            }

            $this->doWrite($message, $newline);
        }
    }

    /**
     * Writes a message to the output.
     *
     * @param string  $message A message to write to the output
     * @param Boolean $newline Whether to add a newline or not
     */
    protected function doWrite($message, $newline);
}


text:
package io.fabric8.api;

import java.util.Map;

/**
 * A builder for an attributable object.
 *
 * @author thomas.diesler@jboss.com
 * @since 18-Apr-2014
 */
public interface AttributableBuilder<B extends AttributableBuilder<B>> extends Builder<B>{

    B addAttribute(String key, String value);

    B setAttributes(Map<String, String> attributes);
}


text:
title: Gluster Support
category: feature
authors: ekohl, rmiddle, sahina, sandrobonazzola, shireesh
wiki_category: Feature|Gluster Support
wiki_title: Features/Gluster Support
wiki_revision_count: 9
wiki_last_updated: 2014-12-22
feature_name: Gluster management
feature_modules: engine,gluster
feature_status: Completed
---

# Gluster Support

## Summary

This feature provides support for provisioning and managing Gluster based storage clusters in oVirt. Inital support was added to oVirt 3.1. glusterfs repo is available at <http://download.gluster.org/pub/gluster/glusterfs/>

## Owner

*   Feature owner: Shireesh Anjal <sanjal@redhat.com>
    -   GUI Component owner: Gilad Chaplik <gchaplik@redhat.com>
    -   REST Component owner: Shireesh Anjal
    -   Engine Component owner: Shireesh Anjal
    -   VDSM Component owner: Balamurugan Arumugam <barumuga@redhat.com>
    -   QA Owner: Ujjwala Thimmaiah <ujjwala@redhat.com>

## Current Status

*   Status: Available since oVirt 3.2
*   Last updated date: ,
*   Requires : glusterfs >= 3.3

## Detailed Description

This feature will introduce the capability of creating a storage cluster based on GlusterFS from the oVirt UI. Administrator will be able to perform Gluster management fuctionality like:

*   Create a cluster with Gluster capabilities
*   Create Gluster volumes on any cluster that exposes Gluster capabilities
*   Add / remove bricks to / from Gluster volumes
*   Perform volume operations like
    -   start
    -   stop
    -   rebalance
    -   replace-brick
*   Configure volumes by setting / changing "Volume Options"
*   Monitor status of Gluster volumes and bricks

### Approach

With this feature, oVirt will start supporting multiple services exposed by the cluster. These services may require different monitoring and bootstrapping strategies for hosts of the cluster. It will also require conditionally displaying / hiding certain UI components based on the services supported by the cluster. These will be achieved by:

*   Mapping the services supported by a cluster in the database
*   Using strategy pattern for arriving at the appropriate monitoring strategy for a host based on the services exposed by it's cluster
*   Enhancing the webadmin UI to display / hide appropriate components based on services supported by the cluster in context
*   Enhancing the bootstrapping mechanism in VDSM to perform different steps based on the service(s) requested

### Entity Description

#### Gluster Volume

Gluster Volume is a new searchable entity in the system, which has following properties:

*   Volume ID
*   Cluster ID (Cluster to which the volume belongs)
*   Name
*   Type
*   Replica Count
*   Stripe Count
*   Transport Type
*   Access Protocols (list)
*   Bricks (list)
*   Options (list)

#### Gluster Brick

Brick is the building block of a volume, and has following properties:

*   Server
*   Brick Directory

#### Gluster Volume Option

An Option is a configuration on the Volume, that can fine-tune the way a Volume behaves e.g. The value of the option "auth.allow" defines the IP addresses of the client machines that should be allowed to access the Volume. It has following properties:

*   Option Key
*   Option Value

#### Cluster

The Cluster entity will be enhanced to capture information about the services it exposes. e.g. A cluster can expose

*   Virtualization Service
*   Gluster Service
*   Both

### User Interface

New tabs, nodes and screens related to Gluster will be added to the User Interface. These will be displayed only when the Cluster in context supports Gluster service. Similarly, the existing Virtualization related UI components will be displayed only if the Cluster in context supports Virtualization service. Following are the new UI components related to Gluster:

*   New tab "Gluster Volumes" at Cluster level.
*   New node "Gluster Volumes" in the system tree under the Cluster node
    -   displayed only if the cluster supports Gluster service
    -   Every Gluster Volume will be displayed as a child node under "Gluster Volumes"
*   Main tabs when user selects a Volume in the system tree
    -   General
    -   Bricks
    -   Options
    -   Permissions

Same tabs will also be displayed as sub-tabs when user selects a volume from the "Gluster Volumes" tab.

*   Actions on "Gluster Volumes" tab:
    -   New
    -   Start
    -   Stop
    -   Delete
    -   Add Bricks
    -   Remove Bricks
    -   Migrate Brick
    -   Rebalance
    -   Add Option

Except the "New" option, all others will also be available from the "Gluster Volume -> General" sub-tab

*   Actions on "Bricks" tab / sub-tab:
    -   Add Bricks
    -   Remove Bricks
    -   Migrate Brick
*   Actions on "Options" tab / sub-tab:
    -   Add
    -   Edit
    -   Reset to default (selected option)
*   New dialog boxes
    -   New Gluster Volume
    -   Add Bricks to Volume
    -   New Gluster Volume -> Choose Bricks (re-used from Volume -> Add Bricks)
    -   Migrate Brick of a Volume
    -   Add / Modify Volume Option
*   Modified screens
    -   Cluster creation screen will have two checkboxes for "Gluster" and "Virtualization", with at least one selection mandatory
    -   Gluster related events will be added to the Event Notifications subscription screen

### Audit

All operations that result in creation, modification or deletion of Gluster Volumes, and any errors that may occur during the same will be audited. The audit log messages will be available in the "Events" tab.

### Notifications

All the Gluster related events that are audited will be available to be subscribed for email notifications. A new category "GlusterVolume" will be added to the notification subscription screen with following events:

*   Gluster Volume created
*   Gluster Volume creation failed
*   Gluster Volume deleted
*   Gluster Volume deletion failed
*   Gluster Volume started
*   Gluster Volume start failed
*   Gluster Volume stopped
*   Gluster Volume stop failed
*   Brick(s) added to Gluster Volume
*   Brick(s) addition to Gluster Volume failed
*   Brick(s) removed from Gluster Volume
*   Brick(s) removal from Gluster Volume failed
*   Gluster Volume Option set
*   Gluster Volume Option set failed
*   Gluster Volume Replace Brick started
*   Gluster Volume Replace Brick start failed
*   Gluster Volume Replace Brick aborted
*   Gluster Volume Replace Brick abort failed
*   Gluster Volume Replace Brick paused
*   Gluster Volume Replace Brick pause failed
*   Gluster Volume Replace Brick committed
*   Gluster Volume Replace Brick commit failed
*   Gluster Volume Rebalance started
*   Gluster Volume Rebalance start failed
*   Gluster Volume Rebalance stopped
*   Gluster Volume Rebalance stop failed

### Host Bootstrapping (VDSM)

The host bootstrapping feature of VDSM will be enhanced to support bootstrapping based on the service(s) requested from the host.

       SELinux should be set to permissive on the node running gluster

### Roles

A new pre-defined role "Gluster Admin" will be introduced with permissions for all Gluster Management actions.

### Installation/Upgrade

When upgrading from an existing installation, all existing clusters will be mapped to only the "Virtualization" service by default.

## Benefits to oVirt

oVirt would be able to provision Gluster storage. This would also enable a tighter KVM - Gluster integration which would enable virtualization admins to leverage the scale-out storage capabilities of Gluster.

## Dependencies / Related Features and Projects

Affected oVirt projects:

*   Engine-core
*   Webadmin
*   VDSM
*   API
*   CLI

## Documentation / External references

GlusterFS : <http://www.gluster.org/community/documentation/index.php/Main_Page>

## Future Work

*   LVM Configuration - Planned in 3.6
*   Support for managing Gluster clusters in AWS environment
*   Support for Gluster Unified File and Object Storage
*   Support for Hardware RAID configuration
*   Gluster Volume monitoring with Gluster top commands
*   Gluster Volume Quota configuration
*   Gluster snapshot management - Planned in 3.6
*   Log management
*   Reporting

[Gluster Support](/develop/release-management/features/) [Gluster Support](/develop/release-management/releases/3.2/feature/)


text:
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.hackvg.android.views.activities.DrawerActivity"
    >

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="#ff54646c"
        tools:context=".MainActivity"
        >

        <View
            android:id="@+id/activity_movies_background_view"
            android:layout_width="match_parent"
            android:layout_height="@dimen/activity_movies_background_view_height"
            android:background="@color/theme_primary"
            />

        <com.hackvg.android.views.custom_views.AutofitRecyclerView
            android:id="@+id/activity_movies_recycler"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="@dimen/activity_movies_margins"
            android:layout_marginRight="@dimen/activity_movies_margins"
            android:paddingTop="@dimen/activity_vertical_margin"
            android:columnWidth="@dimen/item_movie_width"
            android:clipToPadding="false"
            />

        <android.support.v7.widget.Toolbar
            android:id="@+id/activity_movies_toolbar"
            android:layout_height="64dp"
            android:layout_width="match_parent"
            android:minHeight="?attr/actionBarSize"
            android:background="@color/theme_primary"
            >

            <com.hackvg.android.views.custom_views.LobsterTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/app_name"
                android:textSize="22sp"
                android:textColor="#FFF"
                />
        </android.support.v7.widget.Toolbar>

        <ProgressBar
            android:id="@+id/activity_movies_progress"
            android:layout_width="55dp"
            android:layout_height="55dp"
            android:layout_marginTop="@dimen/activity_vertical_margin"
            android:layout_gravity="center"
            android:visibility="gone"
            style="?android:attr/progressBarStyleLarge"
            />

    </FrameLayout>

    <fragment
        android:id="@+id/navigation_drawer"
        android:layout_width="@dimen/navigation_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:name="com.hackvg.android.views.fragments.NavigationDrawerFragment"
        tools:layout="@layout/fragment_navigation_drawer"
        />

</android.support.v4.widget.DrawerLayout>


text:
package jdb.jms.priority.producer;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Producer {

	private static final Logger logger = LoggerFactory
			.getLogger(Producer.class);

	private Connection connection;
	private Session session;
	private MessageProducer producer;

	public void openConnection() throws JMSException {
		// Create a new connection factory
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
				ActiveMQConnection.DEFAULT_BROKER_URL);
		connection = connectionFactory.createConnection();
	}

	public void closeConnection() throws JMSException {
		// Always close the connection
		connection.close();
	}

	public void createProducer(String queue) throws JMSException {
		// Create a session for sending messages
		session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

		// Create the destination to which messages will be sent
		Destination destination = session.createQueue(queue);

		// Create a MessageProducer for sending the messages
		producer = session.createProducer(destination);
	}

	public void send(String text) throws JMSException {
		TextMessage message = session.createTextMessage(text);
		producer.send(message);

		logger.info(text + " sent with default priority(=4)");
	}

	public void send(String text, int priority) throws JMSException {
		TextMessage message = session.createTextMessage(text);
		// Note: setting the priority directly on the JMS Message does not work
		// as in that case the priority of the producer is taken
		producer.send(message, DeliveryMode.PERSISTENT, priority, 0);

		logger.info(text + " sent with priority=" + priority);
	}
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Levels" >

    <Button
        android:id="@+id/button_mexico"
        android:layout_width="250dp"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="120dp"
        android:layout_marginTop="57dp"
        android:background="@android:color/transparent"
        android:onClick="showLevelMexico"
        android:visibility="visible" />

    <Button
        android:id="@+id/button_rlyeh"
        android:layout_width="fill_parent"
        android:layout_height="70dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="18dp"
        android:layout_marginRight="51dp"
        android:background="@android:color/transparent"
        android:onClick="showLevelRlyeh"
        android:visibility="visible" />

    <Button
        android:id="@+id/button_egypt"
        android:layout_width="80dp"
        android:layout_height="fill_parent"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="22dp"
        android:background="@android:color/transparent"
        android:onClick="showLevelEgypt"
        android:visibility="visible" />

</RelativeLayout>
<!-- From: file:/home/quiin/Development/android/AndroidstudioProjects/GCrusher/app/src/main/res/layout/activity_levels.xml -->


text:
package codegen

import (
	"bytes"
	"strings"
	"text/template"
)

const (
	commentLinePrefix = "// "
)

func applyTemplate(tmpl string, i any) (string, error) {
	t := template.New("tmpl").Funcs(template.FuncMap{
		"wordWrap":     wordWrap,
		"commentBlock": commentBlock,
		"hasPrefix":    strings.HasPrefix,
	})

	t2 := template.Must(t.Parse(tmpl))

	var b bytes.Buffer
	if err := t2.Execute(&b, i); err != nil {
		return "", err
	}

	return b.String(), nil
}

func commentBlock(in []string, indentTabs int) string {
	// Copy the input array.
	in = append([]string{}, in...)

	// Apply the tabs and comment prefix to each line.
	for lineIndex := range in {
		prefix := ""
		for tabIndex := 0; lineIndex > 0 && tabIndex < indentTabs; tabIndex++ {
			prefix += "\t"
		}
		prefix += commentLinePrefix
		in[lineIndex] = prefix + in[lineIndex]
	}

	// Join the lines with carriage returns.
	return strings.Join(in, "\n")
}

func wordWrap(in string, maxLineLength int) []string {
	// First, split the input based on any user-created lines (i.e. the string contains "\n").
	inputLines := strings.Split(in, "\n")
	outputLines := make([]string, 0)

	line := ""
	for i, inputLine := range inputLines {
		if i > 0 {
			// Process a user-defined carriage return.
			outputLines = append(outputLines, line)
			line = ""
		}

		words := strings.Split(inputLine, " ")

		for len(words) > 0 {
			// Take the next word.
			word := words[0]
			words = words[1:]

			if len(line)+len(word) > maxLineLength {
				// Need to word wrap - emit the current line.
				outputLines = append(outputLines, line)
				line = ""
			}

			// Add the word to the current line.
			if len(line) > 0 {
				line += " "
			}
			line += word
		}
	}

	// Emit the final line
	outputLines = append(outputLines, line)

	return outputLines
}


text:
using sar.Tools;
using System.Threading;

namespace WinServiceLauncher.Launchers
{
	public class OnStartup : Schedule
	{
		private bool launchComplete;

		public OnStartup(Launcher parent) : base(parent)
		{
		}

		public OnStartup(Launcher parent, XML.Reader reader) : base(parent, reader)
		{
		}

		protected override void ServiceLauncher()
		{
			if (!launchComplete)
			{
				this.Launch();
				launchComplete = true;
			}
			else
			{
				Thread.Sleep(200);
			}
		}

		internal override void Serialize(XML.Writer writer)
		{
			writer.WriteStartElement("OnStartup");
			writer.WriteEndElement();   // OnStartup
		}
	}
}


text:
package token

import (
	"github.com/chanxuehong/util/random"
)

func NewTokenId() string {
	return string(random.NewRandomEx())
}

func ExpirationAccess(timestamp int64) int64 {
	return timestamp + 7200
}

func ExpirationRefresh(timestamp int64) int64 {
	return timestamp + 31556952
}


text:
import concurrent.futures as futures
import contextlib
import inspect
import logging
import pathlib
import platform
import sys
import time

from zplib import datafile
from zplib.image import threaded_io
from elegant import load_data

from ..util import log_util
from ..util import timer
from . import metadata_util

class DummyIO:
    def __init__(self, logger):
        self.logger = logger
    def write(self, *args, **kws):
        self.logger.warning('Trying to write files, but file writing was disabled!')
    def wait(self):
        return

class TimepointHandler:
    IMAGE_COMPRESSION = threaded_io.COMPRESSION.DEFAULT
    LOG_LEVEL = logging.INFO
    IO_THREADS = 4
    MAX_IO_JOBS = 256 # max pending image writes before the threaded IO will block.

    def __init__(self, data_dir, log_level=None, scope_host='127.0.0.1', dry_run=False):
        """Setup the basic code to take a single timepoint from a timecourse experiment.

        Parameters:
            data_dir: directory where the data and metadata-files should be read/written.
            io_threads: number of threads to use to save image data out.
            loglevel: level from logging library at which to log information to the
                logfile in data_dir. (Subclasses can log information with self.logger)
                If not specified, fall back to the class attribute LOG_LEVEL. This
                allows a subclass to set a default log level, which still can be
                over-ridden from the command line.
            scope_host: IP address to connect to the scope server. If None, run without
                a scope server.
            dry_run: if True, do not write any files (including log files; log entries
                will be printed to the console).
        """
        self.data_dir = pathlib.Path(data_dir).resolve() # get an absolute path
        self.experiment_metadata_path, self.experiment_metadata = metadata_util.get_experiment_metadata(self.data_dir)
        self.experiment_metadata['node'] = platform.node()

        self.positions = self.experiment_metadata['positions'] # dict mapping names to (x,y,z) stage positions

        self.skip_positions = set()
        annotations = load_data.read_annotations(self.data_dir)
        for position in self.positions.keys():
            if position in annotations:
                position_annotations, timepoint_annotations = annotations[position]
                if position_annotations.get('exclude'):
                    self.skip_positions.add(position)
                else:
                    for annotation in timepoint_annotations.values():
                        if annotation.get('stage') == 'dead':
                            self.skip_positions.add(position)
                            break

        if scope_host is not None:
            from .. import scope_client
            self.scope = scope_client.ScopeClient(scope_host)
            if hasattr(self.scope, 'camera'):
                self.scope.camera.return_to_default_state()
        else:
            self.scope = None
        self.write_files = not dry_run
        self.logger = log_util.get_logger(str(data_dir))
        if log_level is None:
            log_level = self.LOG_LEVEL
        elif isinstance(log_level, str):
            log_level = getattr(logging, log_level)
        self.logger.setLevel(log_level)
        if self.write_files:
            self.image_io = threaded_io.ThreadedIO(self.IO_THREADS, self.MAX_IO_JOBS)
            handler = logging.FileHandler(str(self.data_dir/'acquisitions.log'))
        else:
            self.image_io = DummyIO(self.logger)
            handler = logging.StreamHandler()
        handler.setFormatter(log_util.get_formatter())
        self.logger.addHandler(handler)
        self._job_thread = None

    def heartbeat(self):
        print('heartbeat') # write a line to stdout to serve as a heartbeat

    @contextlib.contextmanager
    def heartbeat_timer(self):
        heartbeat_timer = timer.Timer(self.heartbeat, interval=60)
        yield
        heartbeat_timer.stop()

    @contextlib.contextmanager
    def debug_timing(self, task):
        t0 = time.time()
        yield
        self.logger.debug(f'{task} complete ({{:.1f}} seconds)', time.time() - t0)

    def run_timepoint(self, scheduled_start):
        try:
            self.heartbeat()
            self.timepoint_prefix = time.strftime('%Y-%m-%dt%H%M')
            self.scheduled_start = scheduled_start
            self.start_time = time.time()
            self._job_futures = []
            self.logger.info('Starting timepoint {} ({:.0f} minutes after scheduled)', self.timepoint_prefix,
                (self.start_time-self.scheduled_start)/60)
            # record the timepoint prefix and timestamp for this timepoint into the
            # experiment metadata
            self.experiment_metadata.setdefault('timepoints', []).append(self.timepoint_prefix)
            self.experiment_metadata.setdefault('timestamps', []).append(self.start_time)
            self.logger.info('Configuring timepoint')
            with self.debug_timing('Configuration'):
                self.configure_timepoint()
            self.heartbeat()
            self.run_all_positions()
            self.finalize_timepoint()
            self.heartbeat()
            self.end_time = time.time()
            self.experiment_metadata.setdefault('durations', []).append(self.end_time - self.start_time)
            if self.write_files:
                self._write_atomic_json(self.experiment_metadata_path, self.experiment_metadata)
            run_again = self.skip_positions != self.positions.keys() # don't run again if we're skipping all the positions
            # wait for all queued background jobs to complete.
            with self.debug_timing('Image IO'), self.heartbeat_timer():
                self.image_io.wait()
            if self._job_futures:
                # wait for all queued background jobs to complete.
                with self.debug_timing('Background jobs'), self.heartbeat_timer():
                    futures.wait(self._job_futures)
                # now get the result() from each future, which will raise any errors encountered
                # during the execution.
                [f.result() for f in self._job_futures]
            self.cleanup()
            self.logger.info('Timepoint {} ended ({:.0f} minutes after starting)', self.timepoint_prefix,
                             (time.time()-self.start_time)/60)
            if run_again:
                return self.get_next_run_time()
        except:
            self.logger.error('Exception in timepoint:', exc_info=True)
            raise

    def run_all_positions(self):
        for position_name, position_coords in sorted(self.positions.items()):
            if position_name not in self.skip_positions:
                self.logger.info(f'Acquiring Position {position_name}')
                with self.debug_timing(f'Position {position_name}'):
                    self.run_position(position_name, position_coords)
                self.heartbeat()

    def add_background_job(self, function, *args, **kws):
        """Add a function with parameters *args and **kws to a queue to be completed
        asynchronously with the rest of the timepoint acquisition. This will be
        run in a background thread, so make sure that the function acts in a
        threadsafe manner. (NB: self.logger *is* thread-safe.)

        All queued functions will be waited for completion before the timepoint
        ends. Any exceptions will be propagated to the foreground after all
        functions queued either finish or raise an exception.
        """
        if self._job_thread is None:
            self._job_thread = futures.ThreadPoolExecutor(max_workers=1)
        self._job_futures.append(self._job_thread.submit(function, *args, **kws))

    def run_position(self, position_name, position_coords):
        """Do everything required for taking a timepoint at a single position
        EXCEPT focusing / image acquisition. This includes moving the stage to
        the right x,y position, loading and saving metadata, and saving image
        data, as generated by acquire_images()"""
        timestamp = time.time()
        position_dir, metadata_path, position_metadata = metadata_util.get_position_metadata(self.data_dir, position_name)
        position_dir.mkdir(exist_ok=True)
        if self.scope is not None:
            with self.debug_timing('Stage positioning'):
                # approach from below for maximum repeatability
                x, y, z = position_coords
                self.scope.stage.position = x, y, z-0.2
                self.scope.stage.z = z
        images, image_names, new_metadata = self.acquire_images(position_name, position_dir, position_metadata)
        new_metadata['timestamp'] = timestamp
        new_metadata['timepoint'] = self.timepoint_prefix
        position_metadata.append(new_metadata)
        self.finalize_acquisition(position_name, position_dir, position_metadata)
        image_paths = [position_dir / (self.timepoint_prefix + ' ' + name) for name in image_names]
        if new_metadata is None:
            new_metadata = {}
        if self.write_files:
            self.image_io.write(images, image_paths, self.IMAGE_COMPRESSION)
            self._write_atomic_json(metadata_path, position_metadata)

    def _write_atomic_json(self, out_path, data):
        datafile.json_encode_atomic_legible_to_file(data, out_path)

    def configure_timepoint(self):
        """Override this method with global configuration for the image acquisitions
        (e.g. camera configuration). Member variables 'scope', 'experiment_metadata',
        'timepoint_prefix', and 'positions' may be specifically useful."""
        pass

    def finalize_timepoint(self):
        """Override this method with global finalization after the images have been
        acquired for each position. Useful for altering the self.experiment_metadata
        dictionary before it is saved out.
        """
        pass

    def finalize_acquisition(self, position_name, position_dir, position_metadata):
        """Called after acquiring images for a single postiion.

        Parameters:
            position_name: name of the position in the experiment metadata file.
            position_dir: pathlib.Path object representing the directory where
                position-specific data files and outputs are written. Useful for
                reading previous image data.
            position_metadata: list of all the stored position metadata from the
                previous timepoints, in chronological order. This includes data
                from the latest timepoint, accessible as: position_metadata[-1].
        """
        pass

    def cleanup(self):
        """Override this method with any global cleanup/finalization tasks
        that may be necessary."""
        pass

    def get_next_run_time(self):
        """Override this method to return when the next timepoint run should be
        scheduled. Returning None means no future runs will be scheduled."""
        return None

    def acquire_images(self, position_name, position_dir, position_metadata):
        """Override this method in a subclass to define the image-acquisition sequence.

        All most subclasses will need to do is return the following as a tuple:
        (images, image_names, new_metadata), where:
            images is a list of the acquired images
            image_names is a list of the generic names for each of these images
                (not timepoint- or position-specific; e.g. 'GFP.png' or some such)
            new_metadata is a dictionary of timepoint-specific information, such
                as the latest focal plane z-position or similar. This will be
                made available to future acquisition runs via the 'position_metadata'
                argument described below.

        The images and metadata will be written out by the superclass, and
        must not be written by the overriding subclass.

        Optionally, subclasses may choose to enter 'position_name' into the
        self.skip_positions set to indicate that in the future this position
        should not be acquired. (E.g. the worm is dead.)

        Parameters:
            position_name: identifier for this image-acquisition position. Useful
                for adding this position to the skip_positions set.
            position_dir: pathlib.Path object representing the directory where
                position-specific data files and outputs should be written. Useful
                only if additional data needs to be read in or out during
                acquisition. (E.g. a background model or similar.)
            position_metadata: list of all the stored position metadata from the
                previous timepoints, in chronological order. In particular, this
                dictionary is guaranteed to contain 'timestamp' which is the
                time.time() at which that acquisition was started. Other values
                (such as the latest focal plane) stored by previous acquisition
                runs will also be available. The most recent metadata will be in
                position_metadata[-1].
        """
        raise NotImplementedError()

    @classmethod
    def main(cls, timepoint_dir=None, **cls_init_args):
        """Main method to run a timepoint.

        Parse sys.argv to find an (optional) scheduled_start time as a positional
        argument. Any arguments that contain an '=' will be assumed to be
        python variable definitions to pass to the class init method. (Leading
        '-' or '--' will be stripped, and internal '-'s will be converted to '_'.)

        e.g. this allows the following usage: ./acquire.py --dry-run=True --log-level=logging.DEBUG

        Parameters:
            timepoint_dir: location of timepoint directory. If not specified, default
                to the parent dir of the file that defines the class that this
                method is called on.
            **cls_init_args: dict of arguments to pass to the class init method.
        """
        if timepoint_dir is None:
            timepoint_dir = pathlib.Path(inspect.getfile(cls)).parent
        scheduled_start = None
        for arg in sys.argv[1:]:
            if arg.count('='):
                while arg.startswith('-'):
                    arg = arg[1:]
                arg = arg.replace('-', '_')
                # execute the argument in a restricted namespace containing only 'logging', and store the
                # result in the args to pass to the class.
                exec(arg, dict(logging=logging), cls_init_args)
            elif scheduled_start is None:
                scheduled_start = float(arg)
            else:
                raise ValueError('More than one schedule start time provided')

        if scheduled_start is None:
            scheduled_start = time.time()
        handler = cls(timepoint_dir, **cls_init_args)
        next_run_time = handler.run_timepoint(scheduled_start)
        if next_run_time:
            print('next run:{}'.format(next_run_time))


text:
require ("prototypes.fatcontroller_annimation")

data:extend({

{
    type = "player",
    name = "fatcontroller",
    icon = "__base__/graphics/icons/player.png",
    flags = {"pushable", "placeable-player", "placeable-off-grid", "not-repairable", "not-on-map"},
    max_health = 100,
    healing_per_tick = 100,
    collision_box = {{-0.2, -0.2}, {0.2, 0.2}},
   collision_mask = {"ghost-layer"},
    --selection_box = {{-0.4, -1.4}, {0.4, 0.2}},
    crafting_categories = {"crafting"},
    mining_categories = {"basic-solid"},
    damage_hit_tint = {r = 1, g = 0, b = 0, a = 0},
    inventory_size = 0,
    build_distance = 0,
    drop_item_distance = 0,
    reach_distance = 0,
    reach_resource_distance = 0,
    ticks_to_keep_gun = 0,
    ticks_to_keep_aiming_direction = 0,
    running_speed = 0,
    distance_per_frame = 0,
    maximum_corner_sliding_distance = 0,

    subgroup = "creatures",
    order="z",
    eat =
    {
      {
        filename = "__TheFatController__/sound/empty.ogg",
        volume = 1
      }
    },
    heartbeat =
    {
      {
        filename = "__TheFatController__/sound/empty.ogg"
      }
    },
    animations = fcanimations,
   mining_speed = 0,
   mining_with_hands_particles_animation_positions = {0, 0},
    mining_with_tool_particles_animation_positions = {0},
    running_sound_animation_positions = {0, 0}
  }

 })


text:
package com.thoughtworks.go.helper;

import com.thoughtworks.go.util.LogFixture;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.Is.is;
import org.junit.After;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
import static org.junit.matchers.JUnitMatchers.containsString;

public class RandomPortTest {
    private LogFixture logFixture;

    @Before
    public void setUp() throws Exception {
        logFixture = LogFixture.startListening();
        LogFixture.enableDebug();
    }

    @After
    public void testDown() {
        logFixture.stopListening();
    }

    @Test
    public void shouldOpenRandomPort() {
        int port = RandomPort.find("foo");
        assertThat(port, is(not(RandomPort.find("foo"))));
    }

    @Test
    public void shouldLogPortsAllocated() {
        int port = RandomPort.find("foo");
        assertThat(logFixture.getLog(), containsString("RandomPort: Allocating port " + port + " for 'foo'"));
    }

}


text:
module Archetype
  module Module
    extend ActiveSupport::Concern

    included do
      attr_reader :controller
    end

    module ClassMethods
      def module_name
        @module_name ||= name.split('::')[1].underscore.to_sym
      end
    end

    def initialize(controller)
      @controller = controller
      @defaults = []
    end

    def configuration
      @configuration || configure
    end

    def configure
      @configuration = build_class.configure(controller)
    end

    def build_block(&block)
      build_class.class_exec(controller, &block)
    end

    def set_build_class(klass)
      @build_class = klass
    end

    def build_class
      @build_class ||= generate_build_class
    end

    # Defaults need refactoring
    Default = Struct.new(:block)

    def defaults(*args, &block)
      opts = args.extract_options!
      @defaults += [Default.new(block)]
    end

    def apply_defaults(klass)
      @defaults.each do |default|
        klass.class_exec(controller, &default.block)
      end
    end

    private

    def generate_build_class
      return @builder_name.to_s.constantize if @builder_name.present?
      Class.new(base_build_class).tap do |klass|
        apply_defaults(klass)
      end
    end

    def base_build_class
      raise NotImplementedError
    end
  end
end


text:
require "spec_helper"

describe KeyboardFirmwareGenerator::Keyboard do
  describe '#new' do
    it "takes a block and instance_evals it" do
      this = nil
      KeyboardFirmwareGenerator::Keyboard.new do
        this = self
      end
      expect(this).to be_a(KeyboardFirmwareGenerator::Keyboard)
    end
  end

  describe '#layer' do
    it 'initializes the given layer' do
      layer = nil

      keyboard = KeyboardFirmwareGenerator::Keyboard.new do
        layer(4) do
          layer = self
        end
      end

      expect(keyboard.layers.first).to be_a(KeyboardFirmwareGenerator::Layer)
      expect(keyboard.layers.first).to be(layer)
      expect(keyboard.layers.first.index).to eq(4)
    end

    it 'reopens the given layer' do
      keyboard = KeyboardFirmwareGenerator::Keyboard.new do
        layer 4 do
          hand('left') {}
        end

        layer 4 do
          hand('right') {}
        end
      end

      expect(keyboard.layers.length).to eq(1)
      expect(keyboard.layers.first.hands.length).to eq(2)
    end
  end
end


text:
package org.apache.pulsar.broker.delayed;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.apache.pulsar.broker.delayed.proto.DelayedMessageIndexBucketSnapshotFormat.SnapshotMetadata;
import org.apache.pulsar.broker.delayed.proto.DelayedMessageIndexBucketSnapshotFormat.SnapshotSegment;

public interface BucketSnapshotStorage {

    /**
     * Create a delayed message index bucket snapshot with metadata and bucketSnapshotSegments.
     *
     * @param snapshotMetadata the metadata of snapshot
     * @param bucketSnapshotSegments the list of snapshot segments
     * @return the future with bucketId(ledgerId).
     */
    CompletableFuture<Long> createBucketSnapshot(SnapshotMetadata snapshotMetadata,
                                                 List<SnapshotSegment> bucketSnapshotSegments);

    /**
     * Get delayed message index bucket snapshot metadata.
     *
     * @param bucketId the bucketId of snapshot
     * @return the future with snapshot expanded metadata
     */
    CompletableFuture<SnapshotMetadata> getBucketSnapshotMetadata(long bucketId);

    /**
     * Get a sequence of delayed message index bucket snapshot segments.
     *
     * @param bucketId the bucketId of snapshot
     * @param firstSegmentEntryId  entryId of first segment of sequence
     * @param lastSegmentEntryId  entryId of last segment of sequence
     * @return the future with snapshot segment
     */
    CompletableFuture<List<SnapshotSegment>> getBucketSnapshotSegment(long bucketId, long firstSegmentEntryId,
                                                                      long lastSegmentEntryId);

    /**
     * Get total byte length of delayed message index bucket snapshot.
     *
     * @param bucketId the bucketId of snapshot
     * @return the future with byte length of snapshot
     */
    CompletableFuture<Long> getBucketSnapshotLength(long bucketId);

    /**
     * Delete delayed message index bucket snapshot by bucketId.
     *
     * @param bucketId the bucketId of snapshot
     */
    CompletableFuture<Void> deleteBucketSnapshot(long bucketId);

    /**
     * Start the bucket snapshot storage service.
     */
    void start() throws Exception;

    /**
     * Close the bucket snapshot storage service.
     */
    void close() throws Exception;
}


text:
<component name="libraryTable">
  <library name="Maven: javax.websocket:javax.websocket-api:1.1">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/javax/websocket/javax.websocket-api/1.1/javax.websocket-api-1.1.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/javax/websocket/javax.websocket-api/1.1/javax.websocket-api-1.1-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/javax/websocket/javax.websocket-api/1.1/javax.websocket-api-1.1-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">

  <title>Qt 4.3: List of All Members for QXmlLexicalHandler</title>
  <link href="classic.css" rel="stylesheet" type="text/css" />

  	Home · All Classes · Main Classes · Grouped Classes · Modules · Functions

List of All Members for QXmlLexicalHandler

This is the complete list of members for QXmlLexicalHandler, including inherited members.

~QXmlLexicalHandler ()

comment ( const QString & ) : bool

endCDATA () : bool

endDTD () : bool

endEntity ( const QString & ) : bool

errorString () const : QString

startCDATA () : bool

startDTD ( const QString &, const QString &, const QString & ) : bool

startEntity ( const QString & ) : bool

<address>

Copyright © 2008 Trolltech
Trademarks

Qt 4.3.5

</address>


text:
+++
date = "2017-02-06T21:37:17+01:00"
title = "Cookie based authentication in golang"

tags = [
    "golang",
    "tutorial",
]

draft = true
+++

While there is a huge amount of "How to build a RESTful API in golang?" tutorials
available on the web - searching for "Authentication in golang tutorial" leads
to almost no results. This motivated me to create a tutorial about a basic
authentification system in golang that uses the standard library and common
golang design patterns where possible.

In this example we will protect a single route/site of a website via a cookie based
authentification system. The authentification will work through a login and
logout http form.

For orientation it is recommended to follow along with the full code
that is available on [login_logut](https://github.com/MrToBe/login_logout).

## Setup

The project setup consists of one main.go file and three golang html templates
(*.gohtml files) that are bundled in one 'templates' directory.

```
main.go
templates/index.gohtml
templates/login.gohtml
templates/logout.gohtml
```

Except for googles uuid package only standard lib packages are used and
imported:

```go
package main

import (
    "context"
    "html/template"
    "log"
    "net/http"
    "time"

    "github.com/google/uuid"
)
```

## What is athentication?

Authentification literature fills thousands of books and posts - so
this tutorial will not go deep into the theory of authentification but rather
outline practical golang code.

Authentification is all about user recognision to restrict interaction with a
program to a set amount of users. When a program identifies a user
by his password a session is opened and a key is passed to the user. The user
can then interact with the program as long as he shows the key. After a set time or
a user initiated end of the session the key becomes invalid.

The most essential models of a authentification system are therefore users (with a secret), keys and sessions.

### Users

In golang users are usually represented by a struct. In this example users will
only hold a username and a password:

```go
type User struct {
    Name string
    Pass string
}
```

The available users are stored in a global `users` variable that maps
'registered' users to a string. In this example the username is used as the key
of the map. Another typical option would be to use a id.

```go
var users = map[string]User{}
```

The available users will be registered in `func init()` - a special golang function that is called once after the program is started (`$ go run main.go`). This makes it a perfect
place for one-off setup tasks like creating a predefined set of users:

```go
func init() {
    users["oana"] = User{"oana", "anao"}
    users["tobi"] = User{"tobi", "toto"}
}
```

When the amount of useres of a system grow it is common practice to save the
users in a database instead of an in memory variable.

### Keys

Keys in programming are ususally represented by a unique and random string. This
helps to avoid duplicate (e.g. two users get the same key) and
predictable keys (e.g. someone could predict a valid key) which would create
security issues for the program.

In addition to these criteria the key should have a considerable amount of
characters to avoid bruce force attacks (e.g. someone is trying
out keys until he finds a valid one.)

Universally unique identifier ([uuid](https://en.wikipedia.org/wiki/Universally_unique_identifier)) libraries are typically resolving these needs by generating unique and
random strings. To achive this they are using a combination of the current time
and with randomness. In this tutorial the uuid library of google is used.

A key is then generated by calling the `New()` function of the uuid package:

```go
key := uuid.New()
```


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="reference" name="DC.Type" />
<meta name="DC.Title" content="Login failure exceptions with user authentication" />
<meta name="abstract" content="If user authentication is turned on and a valid user name and password are not provided, SQLException 08004 is raised." />
<meta name="description" content="If user authentication is turned on and a valid user name and password are not provided, SQLException 08004 is raised." />
<meta scheme="URI" name="DC.Relation" content="cseccsecure42374.html" />
<meta scheme="URI" name="DC.Relation" content="cseccsecure41285.html" />
<meta scheme="URI" name="DC.Relation" content="cseccsecurenativeauth.html" />
<meta scheme="URI" name="DC.Relation" content="cseccsecure21561.html" />
<meta scheme="URI" name="DC.Relation" content="rseccsecure557.html" />
<meta scheme="URI" name="DC.Relation" content="cseccsecure79358.html" />
<meta scheme="URI" name="DC.Relation" content="csecnetservauthent.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="rseccsecure305" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>Login failure exceptions with user authentication</title>

Login failure exceptions with user authentication

If user authentication is turned on and a valid user name and password
are not provided, SQLException 08004 is raised.

ERROR 08004: Connection refused : Invalid authentication.

Parent topic: Configuring user authentication

Related concepts

Configuring LDAP authentication

Configuring NATIVE authentication

Specifying authentication with a user-defined class

Programming applications for Derby user authentication

Configuring Network Server authentication in special circumstances

Related reference

List of user authentication properties