text:
package org.springframework.security.ldap.userdetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.naming.directory.SearchControls;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.ldap.SpringSecurityLdapTemplate;
import org.springframework.util.Assert;

/**
 * The default strategy for obtaining user role information from the directory.
 *

 * It obtains roles by performing a search for "groups" the user is a member of.
 *

 * A typical group search scenario would be where each group/role is specified using the
 * <tt>groupOfNames</tt> (or <tt>groupOfUniqueNames</tt>) LDAP objectClass and the user's
 * DN is listed in the <tt>member</tt> (or <tt>uniqueMember</tt>) attribute to indicate
 * that they should be assigned that role. The following LDIF sample has the groups stored
 * under the DN <tt>ou=groups,dc=springframework,dc=org</tt> and a group called
 * "developers" with "ben" and "luke" as members:
 *
 *

 * dn: ou=groups,dc=springframework,dc=org
 * objectClass: top
 * objectClass: organizationalUnit
 * ou: groups
 *
 * dn: cn=developers,ou=groups,dc=springframework,dc=org
 * objectClass: groupOfNames
 * objectClass: top
 * cn: developers
 * description: Spring Security Developers
 * member: uid=ben,ou=people,dc=springframework,dc=org
 * member: uid=luke,ou=people,dc=springframework,dc=org
 * ou: developer
 *

 *

 * The group search is performed within a DN specified by the <tt>groupSearchBase</tt>
 * property, which should be relative to the root DN of its <tt>ContextSource</tt>. If the
 * search base is null, group searching is disabled. The filter used in the search is
 * defined by the <tt>groupSearchFilter</tt> property, with the filter argument {0} being
 * the full DN of the user. You can also optionally use the parameter {1}, which will be
 * substituted with the username. You can also specify which attribute defines the role
 * name by setting the <tt>groupRoleAttribute</tt> property (the default is "cn").
 *

 * The configuration below shows how the group search might be performed with the above
 * schema.
 *
 *

 * <bean id="ldapAuthoritiesPopulator"
 *       class="org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator">
 *   <constructor-arg ref="contextSource"/>
 *   <constructor-arg value="ou=groups"/>
 *   <property name="groupRoleAttribute" value="ou"/>
 * <!-- the following properties are shown with their default values -->
 *   <property name="searchSubtree" value="false"/>
 *   <property name="rolePrefix" value="ROLE_"/>
 *   <property name="convertToUpperCase" value="true"/>
 * </bean>
 *

 *
 * A search for roles for user "uid=ben,ou=people,dc=springframework,dc=org" would return
 * the single granted authority "ROLE_DEVELOPER".
 *

 * The single-level search is performed by default. Setting the <tt>searchSubTree</tt>
 * property to true will enable a search of the entire subtree under
 * <tt>groupSearchBase</tt>.
 *
 * @author Luke Taylor
 * @author Filip Hanik
 */
public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator {
	// ~ Static fields/initializers
	// =====================================================================================

	private static final Log logger = LogFactory
			.getLog(DefaultLdapAuthoritiesPopulator.class);

	// ~ Instance fields
	// ================================================================================================

	/**
	 * A default role which will be assigned to all authenticated users if set
	 */
	private GrantedAuthority defaultRole;

	/**
	 * Template that will be used for searching
	 */
	private final SpringSecurityLdapTemplate ldapTemplate;

	/**
	 * Controls used to determine whether group searches should be performed over the full
	 * sub-tree from the base DN. Modified by searchSubTree property
	 */
	private final SearchControls searchControls = new SearchControls();

	/**
	 * The ID of the attribute which contains the role name for a group
	 */
	private String groupRoleAttribute = "cn";

	/**
	 * The base DN from which the search for group membership should be performed
	 */
	private String groupSearchBase;

	/**
	 * The pattern to be used for the user search. {0} is the user's DN
	 */
	private String groupSearchFilter = "(member={0})";
	/**
	 * The role prefix that will be prepended to each role name
	 */
	private String rolePrefix = "ROLE_";
	/**
	 * Should we convert the role name to uppercase
	 */
	private boolean convertToUpperCase = true;

	// ~ Constructors
	// ===================================================================================================

	/**
	 * Constructor for group search scenarios. <tt>userRoleAttributes</tt> may still be
	 * set as a property.
	 *
	 * @param contextSource supplies the contexts used to search for user roles.
	 * @param groupSearchBase if this is an empty string the search will be performed from
	 * the root DN of the context factory. If null, no search will be performed.
	 */
	public DefaultLdapAuthoritiesPopulator(ContextSource contextSource,
			String groupSearchBase) {
		Assert.notNull(contextSource, "contextSource must not be null");
		this.ldapTemplate = new SpringSecurityLdapTemplate(contextSource);
		getLdapTemplate().setSearchControls(getSearchControls());
		this.groupSearchBase = groupSearchBase;

		if (groupSearchBase == null) {
			logger.info("groupSearchBase is null. No group search will be performed.");
		}
		else if (groupSearchBase.length() == 0) {
			logger.info(
					"groupSearchBase is empty. Searches will be performed from the context source base");
		}
	}

	// ~ Methods
	// ========================================================================================================

	/**
	 * This method should be overridden if required to obtain any additional roles for the
	 * given user (on top of those obtained from the standard search implemented by this
	 * class).
	 *
	 * @param user the context representing the user who's roles are required
	 * @return the extra roles which will be merged with those returned by the group
	 * search
	 */

	protected Set<GrantedAuthority> getAdditionalRoles(DirContextOperations user,
			String username) {
		return null;
	}

	/**
	 * Obtains the authorities for the user who's directory entry is represented by the
	 * supplied LdapUserDetails object.
	 *
	 * @param user the user who's authorities are required
	 * @return the set of roles granted to the user.
	 */
	@Override
	public final Collection<GrantedAuthority> getGrantedAuthorities(
			DirContextOperations user, String username) {
		String userDn = user.getNameInNamespace();

		if (logger.isDebugEnabled()) {
			logger.debug("Getting authorities for user " + userDn);
		}

		Set<GrantedAuthority> roles = getGroupMembershipRoles(userDn, username);

		Set<GrantedAuthority> extraRoles = getAdditionalRoles(user, username);

		if (extraRoles != null) {
			roles.addAll(extraRoles);
		}

		if (this.defaultRole != null) {
			roles.add(this.defaultRole);
		}

		List<GrantedAuthority> result = new ArrayList<>(roles.size());
		result.addAll(roles);

		return result;
	}

	public Set<GrantedAuthority> getGroupMembershipRoles(String userDn, String username) {
		if (getGroupSearchBase() == null) {
			return new HashSet<>();
		}

		Set<GrantedAuthority> authorities = new HashSet<>();

		if (logger.isDebugEnabled()) {
			logger.debug("Searching for roles for user '" + username + "', DN = " + "'"
					+ userDn + "', with filter " + this.groupSearchFilter
					+ " in search base '" + getGroupSearchBase() + "'");
		}

		Set<String> userRoles = getLdapTemplate().searchForSingleAttributeValues(
				getGroupSearchBase(), this.groupSearchFilter,
				new String[] { userDn, username }, this.groupRoleAttribute);

		if (logger.isDebugEnabled()) {
			logger.debug("Roles from search: " + userRoles);
		}

		for (String role : userRoles) {

			if (this.convertToUpperCase) {
				role = role.toUpperCase();
			}

			authorities.add(new SimpleGrantedAuthority(this.rolePrefix + role));
		}

		return authorities;
	}

	protected ContextSource getContextSource() {
		return getLdapTemplate().getContextSource();
	}

	protected String getGroupSearchBase() {
		return this.groupSearchBase;
	}

	/**
	 * Convert the role to uppercase
	 */
	public void setConvertToUpperCase(boolean convertToUpperCase) {
		this.convertToUpperCase = convertToUpperCase;
	}

	/**
	 * The default role which will be assigned to all users.
	 *
	 * @param defaultRole the role name, including any desired prefix.
	 */
	public void setDefaultRole(String defaultRole) {
		Assert.notNull(defaultRole, "The defaultRole property cannot be set to null");
		this.defaultRole = new SimpleGrantedAuthority(defaultRole);
	}

	public void setGroupRoleAttribute(String groupRoleAttribute) {
		Assert.notNull(groupRoleAttribute, "groupRoleAttribute must not be null");
		this.groupRoleAttribute = groupRoleAttribute;
	}

	public void setGroupSearchFilter(String groupSearchFilter) {
		Assert.notNull(groupSearchFilter, "groupSearchFilter must not be null");
		this.groupSearchFilter = groupSearchFilter;
	}

	/**
	 * Sets the prefix which will be prepended to the values loaded from the directory.
	 * Defaults to "ROLE_" for compatibility with <tt>RoleVoter</tt>.
	 */
	public void setRolePrefix(String rolePrefix) {
		Assert.notNull(rolePrefix, "rolePrefix must not be null");
		this.rolePrefix = rolePrefix;
	}

	/**
	 * If set to true, a subtree scope search will be performed. If false a single-level
	 * search is used.
	 *
	 * @param searchSubtree set to true to enable searching of the entire tree below the
	 * <tt>groupSearchBase</tt>.
	 */
	public void setSearchSubtree(boolean searchSubtree) {
		int searchScope = searchSubtree ? SearchControls.SUBTREE_SCOPE
				: SearchControls.ONELEVEL_SCOPE;
		this.searchControls.setSearchScope(searchScope);
	}

	/**
	 * Sets the corresponding property on the underlying template, avoiding specific
	 * issues with Active Directory.
	 *
	 * @see LdapTemplate#setIgnoreNameNotFoundException(boolean)
	 */
	public void setIgnorePartialResultException(boolean ignore) {
		getLdapTemplate().setIgnorePartialResultException(ignore);
	}

	/**
	 * Returns the current LDAP template. Method available so that classes extending this
	 * can override the template used
	 * @return the LDAP template
	 * @see org.springframework.security.ldap.SpringSecurityLdapTemplate
	 */
	protected SpringSecurityLdapTemplate getLdapTemplate() {
		return this.ldapTemplate;
	}

	/**
	 * Returns the attribute name of the LDAP attribute that will be mapped to the role
	 * name Method available so that classes extending this can override
	 * @return the attribute name used for role mapping
	 * @see #setGroupRoleAttribute(String)
	 */
	protected final String getGroupRoleAttribute() {
		return this.groupRoleAttribute;
	}

	/**
	 * Returns the search filter configured for this populator Method available so that
	 * classes extending this can override
	 * @return the search filter
	 * @see #setGroupSearchFilter(String)
	 */
	protected final String getGroupSearchFilter() {
		return this.groupSearchFilter;
	}

	/**
	 * Returns the role prefix used by this populator Method available so that classes
	 * extending this can override
	 * @return the role prefix
	 * @see #setRolePrefix(String)
	 */
	protected final String getRolePrefix() {
		return this.rolePrefix;
	}

	/**
	 * Returns true if role names are converted to uppercase Method available so that
	 * classes extending this can override
	 * @return true if role names are converted to uppercase.
	 * @see #setConvertToUpperCase(boolean)
	 */
	protected final boolean isConvertToUpperCase() {
		return this.convertToUpperCase;
	}

	/**
	 * Returns the default role Method available so that classes extending this can
	 * override
	 * @return the default role used
	 * @see #setDefaultRole(String)
	 */
	private GrantedAuthority getDefaultRole() {
		return this.defaultRole;
	}

	/**
	 * Returns the search controls Method available so that classes extending this can
	 * override the search controls used
	 * @return the search controls
	 */
	private SearchControls getSearchControls() {
		return this.searchControls;
	}
}


text:
#ifndef AGG_CONV_SMOOTH_POLY1_INCLUDED
#define AGG_CONV_SMOOTH_POLY1_INCLUDED

#include "agg_basics.h"
#include "agg_vcgen_smooth_poly1.h"
#include "agg_conv_adaptor_vcgen.h"
#include "agg_conv_curve.h"

namespace agg
{

    //-------------------------------------------------------conv_smooth_poly1
    template<class VertexSource>
    struct conv_smooth_poly1 :
    public conv_adaptor_vcgen<VertexSource, vcgen_smooth_poly1>
    {
        typedef conv_adaptor_vcgen<VertexSource, vcgen_smooth_poly1> base_type;

        conv_smooth_poly1(VertexSource& vs) :
            conv_adaptor_vcgen<VertexSource, vcgen_smooth_poly1>(vs)
        {
        }

        void   smooth_value(double v) { base_type::generator().smooth_value(v); }
        double smooth_value() const { return base_type::generator().smooth_value(); }

    private:
        conv_smooth_poly1(const conv_smooth_poly1<VertexSource>&);
        const conv_smooth_poly1<VertexSource>&
            operator = (const conv_smooth_poly1<VertexSource>&);
    };

    //-------------------------------------------------conv_smooth_poly1_curve
    template<class VertexSource>
    struct conv_smooth_poly1_curve :
    public conv_curve<conv_smooth_poly1<VertexSource> >
    {
        conv_smooth_poly1_curve(VertexSource& vs) :
            conv_curve<conv_smooth_poly1<VertexSource> >(m_smooth),
            m_smooth(vs)
        {
        }

        void   smooth_value(double v) { m_smooth.generator().smooth_value(v); }
        double smooth_value() const { return m_smooth.generator().smooth_value(); }

    private:
        conv_smooth_poly1_curve(const conv_smooth_poly1_curve<VertexSource>&);
        const conv_smooth_poly1_curve<VertexSource>&
            operator = (const conv_smooth_poly1_curve<VertexSource>&);

        conv_smooth_poly1<VertexSource> m_smooth;
    };

}

#endif

redpajama_set_name: RedPajamaGithub


text:
package com.sdl.dxa.modules.ish.services;

import com.sdl.dxa.tridion.pcaclient.ApiClientProvider;
import com.sdl.dxa.tridion.pcaclient.GraphQLUtils;
import com.sdl.web.pca.client.ApiClient;
import com.sdl.web.pca.client.contentmodel.Pagination;
import com.sdl.web.pca.client.contentmodel.enums.ContentNamespace;
import com.sdl.web.pca.client.contentmodel.generated.CustomMeta;
import com.sdl.web.pca.client.contentmodel.generated.CustomMetaConnection;
import com.sdl.web.pca.client.contentmodel.generated.CustomMetaEdge;
import com.sdl.web.pca.client.contentmodel.generated.Publication;
import com.sdl.web.pca.client.contentmodel.generated.PublicationConnection;
import com.sdl.webapp.common.api.localization.Localization;
import com.sdl.webapp.common.controller.exception.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Profile("!cil.providers.active")
public class GraphQLPublicationService implements PublicationService {

    private static final String PublicationTitleMeta = "publicationtitle.generated.value";
    private static final String PublicationProductfamilynameMeta = "FISHPRODUCTFAMILYNAME.logical.value";
    private static final String PublicationProductreleasenameMeta = "FISHPRODUCTRELEASENAME.version.value";
    private static final String PublicationVersionrefMeta = "ishversionref.object.id";
    private static final String PublicationLangMeta = "FISHPUBLNGCOMBINATION.lng.value";
    private static final String PublicationOnlineStatusMeta = "FISHDITADLVRREMOTESTATUS.lng.element";
    private static final String PublicationOnlineValue = "VDITADLVRREMOTESTATUSONLINE";
    private static final String PublicationCratedonMeta = "CREATED-ON.version.value";
    private static final String PublicationVersionMeta = "VERSION.version.value";
    private static final String PublicationLogicalId = "ishref.object.value";

    private static final String CustomMetaFilter = "requiredMeta:" + PublicationTitleMeta + ","
            + PublicationProductfamilynameMeta+ "," + PublicationProductreleasenameMeta + ","
            + PublicationVersionrefMeta + "," + PublicationLangMeta + "," + PublicationOnlineStatusMeta + ","
            + PublicationCratedonMeta + "," + PublicationVersionMeta + "," + PublicationLogicalId;

    @Autowired
    private ApiClientProvider apiClientProvider;

    @Override
    @Cacheable(value = "ish", key = "{ #publicationId, #localization.id }", condition = "#localization != null && #localization.id != null")
    public List<com.sdl.dxa.modules.ish.model.Publication> getPublicationList(Localization localization) {
        ApiClient client = apiClientProvider.getClient();
        ContentNamespace contentNamespace = GraphQLUtils.convertUriToGraphQLContentNamespace(localization.getCmUriScheme());
        PublicationConnection publications = client.getPublications(contentNamespace,
                new Pagination(),
                null,
                CustomMetaFilter,
                null);
        if (publications.getEdges().isEmpty()) {
            return Collections.emptyList();
        }
        List<com.sdl.dxa.modules.ish.model.Publication> result = publications.getEdges()
                .stream()
                .filter(publicationEdge -> isPublicationOnline(publicationEdge.getNode()))
                .map(publicationEdge -> buildPublicationFrom(publicationEdge.getNode()))
                .collect(Collectors.toList());
        if (result.isEmpty()) {
            LOG.warn("There are no online publications found (no {}={})",
                    PublicationOnlineStatusMeta, PublicationOnlineValue);
            return Collections.emptyList();
        }
        LOG.debug("There are {} online publications found", result.size());
        return result;
    }

    public boolean isPublicationOnline(Publication publication) {
        CustomMetaConnection customMeta = publication.getCustomMetas();
        if (customMeta == null) return false;
        for (CustomMetaEdge customMetaEdge : customMeta.getEdges()) {
            CustomMeta node = customMetaEdge.getNode();
            if (PublicationOnlineStatusMeta.equals(node.getKey())) {
                return PublicationOnlineValue.equals(node.getValue());
            }
        }
        return false;
    }

    private void checkPublicationOnlineInternal(int publicationId, Localization localization, int attempt, Exception[] exceptionHolder) {
        attempt--;
        if (attempt < 0) {
            String message = "Unable to find publication or its metadata for publication " + publicationId + " after 3 attempts";
            if (exceptionHolder[0] != null) throw new NotFoundException(message, exceptionHolder[0]);
            else throw new NotFoundException(message);
        }
        ContentNamespace contentNamespace = GraphQLUtils.convertUriToGraphQLContentNamespace(localization.getCmUriScheme());
        boolean isOffline = false;
        try {
            Publication publication = apiClientProvider.getClient().getPublication(
                    contentNamespace,
                    publicationId,
                    "requiredMeta:" + PublicationOnlineStatusMeta,
                    null);
            isOffline = publication == null ||
                        publication.getCustomMetas() == null ||
                        !publication.getCustomMetas()
                                .getEdges()
                                .stream()
                                .anyMatch(meta -> PublicationOnlineValue.equals(meta.getNode().getValue()));
        } catch (Exception e) {
            if (exceptionHolder[0] == null) exceptionHolder[0] = e;
            try {
                Thread.sleep(200);
                checkPublicationOnlineInternal(publicationId, localization, attempt, exceptionHolder);
                LOG.error("Couldn't find publication metadata for id: " + publicationId + ", attempt: " + attempt);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
                LOG.error("Interrupted");
                throw e;
            }
        }
        if (isOffline) {
            throw new NotFoundException("Unable to find publication " + publicationId);
        }
    }

    public void checkPublicationOnline(int publicationId, Localization localization) throws NotFoundException {
        Exception[] exceptionHolder = new Exception[1];
        checkPublicationOnlineInternal(publicationId, localization, 3, exceptionHolder);
    }

    private com.sdl.dxa.modules.ish.model.Publication buildPublicationFrom(Publication publication) {
        com.sdl.dxa.modules.ish.model.Publication result = new com.sdl.dxa.modules.ish.model.Publication();
        result.setId(String.valueOf(publication.getItemId()));
        result.setTitle(publication.getTitle());

        CustomMetaConnection customMeta = publication.getCustomMetas();
        if (customMeta == null) return result;

        for (CustomMetaEdge customMetaEdge : customMeta.getEdges()) {
            String value = customMetaEdge.getNode().getValue();
            String key = customMetaEdge.getNode().getKey();
            switch (key) {
                case PublicationTitleMeta:
                    result.setTitle(value);
                    break;
                case PublicationLangMeta:
                    result.setLanguage(value);
                    break;
                case PublicationProductfamilynameMeta:
                    if (result.getProductFamily() == null) {
                        result.setProductFamily(new ArrayList<>());
                    }
                    if (result.getProductFamilyEncoded() == null) {
                        result.setProductFamilyEncoded(new ArrayList<>());
                    }
                    result.getProductFamily().add(value);
                    result.getProductFamilyEncoded().add(getEncodedProductFamily(value));
                    break;
                case PublicationProductreleasenameMeta:
                    if (result.getProductReleaseVersion() == null) {
                        result.setProductReleaseVersion(new ArrayList<>());
                    }
                    result.getProductReleaseVersion().add(value);
                    break;
                case PublicationCratedonMeta:
                    //result.setCreatedOn(DateTime.parse(value, dateTimeFormat));
                    result.setCreatedOn(value);
                    break;
                case PublicationVersionMeta:
                    result.setVersion(value);
                    break;
                case PublicationVersionrefMeta:
                    result.setVersionRef(value);
                    break;
                case PublicationLogicalId:
                    result.setLogicalId(value);
                    break;
                default:
                    LOG.trace("Ignoring {}={}", key, value);
                    break;
            }
        }

        return result;
    }
}


text:
require 'rails_helper'

RSpec.describe UserTotal, type: :model do
  skip 'put some tests here'
end


text:
This product is the creation of a landing page for organizations - these are groups of users that share credit for group contributions to KBase.

### Story/Description
In order to attract third party contributions, both data and tools, we need prominent branding of organizations so that data and tool contributions can be properly credited to an institution.  This is part of the larger problem of enabling groups in KBase, but much more specific, and may not necessarily imply sharing privileges.

A User should be able to create an Organization, serve as an Organization admin, and allow users to be associated to the organization.  A landing page for each group should be available that allows a logo, description, links to be attached.  Tools and public workspaces can then be attached to the organization.  The organization page should display these contributions with usage statistics and organization team members.  Tools and workspaces in KBase should also be branded and linked to the organization page appropriately.

### User stories
As a user, I want to be able to create an organization and own it.

As a user, I want to request to join (or leave) an organization.

As an org admin, I want to invite and admit users into my organization.

As an org admin, I want to remove users from my organization.

As an org admin, I want to add branding to my organization's page. This would include images, links, and text about my organization.

As a user, I want to see organization information on that landing page, including the branding information, which apps are owned by that organization, and which public Narratives (and data) are owned by that organization.

### Narrative Mockup

N/A - a page mockup is in progress.

### Timeline

Approximately 1 sprint.

### Test plan

Testing will be done with paper mockups at least locally before implementation.

### Citations

N/A


text:
.include <minix.own.mk>

SUBDIR= ${ARCH}

INCSYMLINKS= ${MACHINE} /usr/include/machine

.include <minix.kinc.mk>


text:
/*
 * WARNING: DO NOT EDIT THIS FILE. This is a generated file that is synchronized
 * by MyEclipse Hibernate tool integration.
 *
 * Created Wed Feb 08 15:38:04 CST 2006 by MyEclipse Hibernate Tool.
 */
package com.frameworkset.platform.sysmgrcore.entity;

import java.io.Serializable;

/**
 * A class representing a composite primary key id for the td_sm_usergroup
 * table.  This object should only be instantiated for use with instances
 * of the Usergroup class.
 */
public class UsergroupKey
    implements Serializable
{
    /** The cached hash code value for this instance.  Settting to 0 triggers re-calculation. */
    private volatile int hashValue = 0;

    /** The value of the GROUP_ID component of this composite id. */
    private int groupId;

    /** The value of the USER_ID component of this composite id. */
    private Integer userId;

    /**
     * Simple constructor of UsergroupKey instances.
     */
    public UsergroupKey()
    {
    }

    /**
     * Returns the value of the groupId property.
     * @return String
     */
    public int getGroupId()
    {
        return groupId;
    }

    /**
     * Sets the value of the groupId property.
     * @param groupId
     */
    public void setGroupId(int groupId)
    {
        hashValue = 0;
        this.groupId = groupId;
    }

    /**
     * Returns the value of the userId property.
     * @return String
     */
    public Integer getUserId()
    {
        return userId;
    }

    /**
     * Sets the value of the userId property.
     * @param userId
     */
    public void setUserId(Integer userId)
    {
        hashValue = 0;
        this.userId = userId;
    }

    /**
     * Implementation of the equals comparison on the basis of equality of the id components.
     * @param rhs
     * @return boolean
     */
    public boolean equals(Object rhs)
    {
        if (rhs == null)
            return false;
        if (! (rhs instanceof UsergroupKey))
            return false;
        UsergroupKey that = (UsergroupKey) rhs;
        if (this.getGroupId() != that.getGroupId() )
        {
           return false;
        }
         if (this.getUserId() != that.getUserId())
        {
            return false;
        }

        return true;
    }

    /**
     * Implementation of the hashCode method conforming to the Bloch pattern with
     * the exception of array properties (these are very unlikely primary key types).
     * @return int
     */
    public int hashCode()
    {
        if (this.hashValue == 0)
        {
            int result = 17;

            result = result * 37 + this.groupId;
            int userIdValue = this.getUserId() == null ? 0 : this.getUserId().hashCode();
            result = result * 37 + userIdValue;
            this.hashValue = result;
        }
        return this.hashValue;
    }
}


text:
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect
from django.views.generic import View, ListView, CreateView
from django.views.generic.edit import ModelFormMixin
from django.contrib.auth.mixins import LoginRequiredMixin

from rest_framework.parsers import FormParser

from braces.views import CsrfExemptMixin

from twilio.rest import TwilioRestClient

from contacts.models import Contact
from texts.models import Text
from texts.forms import TextForm, NewTextForm

import os

class ProcessHookView(CsrfExemptMixin, View):
    """Processing request from Twilio."""

    def post(self, request, *kwargs):
        parser = FormParser()
        query_dict = parser.parse(request)
        contact = Contact.objects.filter(number=query_dict["From"]).first()
        if not contact:
            contact = Contact(number=query_dict["From"])
            contact.save()
        if contact.number != os.environ["TWILIO_NUMBER"]:
            sender = "them"
        else:
            sender = "you"
        text = Text(sender=sender, contact=contact, body=query_dict["Body"])
        text.save()
        return HttpResponse()

class TextView(LoginRequiredMixin, CreateView):
    """A view for the texts."""

    login_url = '/login/'
    model = Text
    form_class = TextForm
    template_name = "texts/texting.html"

    def get_context_data(self, **kwargs):
        ctx = super(TextView, self).get_context_data(**kwargs)
        ctx['contact'] = Contact.objects.get(pk=self.kwargs.get("pk"))
        # import pdb;pdb.set_trace()
        return ctx

    def post(self, request, *args, **kwargs):
        """Post response."""
        self.object = None
        self.form = self.get_form(self.form_class)

        # Here ou may consider creating a new instance of form_class(),
        # so that the form will come clean.
        text = self.form.save()
        text.sender = 'you'
        text.contact = Contact.objects.get(pk=int(self.kwargs.get('pk')))
        account_sid = os.environ["ACCOUNT_SID"]
        auth_token = os.environ["AUTH_TOKEN"]
        twilio_number = os.environ["TWILIO_NUMBER"]
        client = TwilioRestClient(account_sid, auth_token)
        client.messages.create(
            to=str(text.contact.number),
            from_=twilio_number,
            body=text.body
        )
        text.save()
        return self.get(request, *args, **kwargs)

class NewTextView(LoginRequiredMixin, CreateView):
    """View to create a new contact."""

    login_url = '/login/'
    model = Contact
    form_class = NewTextForm
    template_name = "texts/new_text.html"

    def post(self, request, *args, **kwargs):
        """Post response."""
        self.object = None
        self.form = self.get_form(self.form_class)

        number = request.POST['number']
        if len(number) > 11 or number.isalpha():
            return self.get(request, *args, **kwargs)
        number = "+" + number
        if Contact.objects.filter(number=number):
            contact = Contact.objects.filter(number=number).first()
        else:
            contact = Contact(number=number)
            contact.save()
        pk = contact.pk
        return redirect(reverse_lazy('contact_detail', kwargs={'pk': pk}))

class MessageListView(LoginRequiredMixin, ListView):
    """View to show all text message conversations."""

    login_url = '/login/'
    template_name = 'texts/message_list.html'
    context_object_name = "contacts"
    model = Contact

    def get_queryset(self):
        return sorted(Contact.objects.exclude(texts__isnull=True),
                      key=lambda a: a.most_recent_text_id(),
                      reverse=True)


text:
package org.apache.flink.runtime.operators.testutils;

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.MutableObjectIterator;

/** A simple iterator that returns an infinite amount of (0, 0) tuples. */
public class InfiniteIntTupleIterator implements MutableObjectIterator<Tuple2<Integer, Integer>> {

    @Override
    public Tuple2<Integer, Integer> next(Tuple2<Integer, Integer> reuse) {
        return next();
    }

    @Override
    public Tuple2<Integer, Integer> next() {
        return new Tuple2<Integer, Integer>(0, 0);
    }
}


text:
% pop_fileio() - import data files into EEGLAB using FileIO
%
% Usage:
%   >> OUTEEG = pop_fileio; % pop up window
%   >> OUTEEG = pop_fileio( filename );
%
% Inputs:
%   filename - [string] file name
%
% Optional inputs:
%   'channels'   - [integer array] list of channel indices
%   'samples'    - [min max] sample point limits for importing data.
%   'trials'     - [min max] trial's limit for importing data.
%
% Outputs:
%   OUTEEG   - EEGLAB data structure
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2008-
%
% Note: FILEIO toolbox must be installed.

% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD, arno@salk.edu
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

function [EEG, command] = pop_fileio(filename, varargin);
EEG = [];
command = '';

if nargin < 1
	% ask user
    ButtonName = questdlg2('Do you want to import a file or a folder?', ...
                           'FILE-IO import', ...
                           'Folder', 'File', 'File');
    if strcmpi(ButtonName, 'file')
        [filename, filepath] = uigetfile('*.*', 'Choose a file or header file -- pop_fileio()');
        drawnow;
        if filename(1) == 0 return; end;
        filename = fullfile(filepath, filename);
    else
        filename = uigetfile('*.*', 'Choose a folder -- pop_fileio()');
        drawnow;
        if filename(1) == 0 return; end;
    end;

    % open file to get infos
    % ----------------------
    disp('Reading data file header...');
    dat = ft_read_header(filename);
    uilist   = { { 'style' 'text' 'String' 'Channel list (defaut all):' } ...
                 { 'style' 'edit' 'string' '' } ...
                 { 'style' 'text' 'String' [ 'Data range (in sample points) (default all [1 ' int2str(dat.nSamples) '])' ] } ...
                 { 'style' 'edit' 'string' '' }  };
    geom = { [3 1] [3 1] };
    if dat.nTrials > 1
        uilist{end+1} = { 'style' 'text' 'String' [ 'Trial range (default all [1 ' int2str(dat.nTrials) '])' ] };
        uilist{end+1} = { 'style' 'edit' 'string' '' };
        geom = { geom{:} [3 1] };
    end;
    result = inputgui( geom, uilist, 'pophelp(''pop_fileio'')', 'Load data using FILE-IO -- pop_fileio()');
    if length(result) == 0 return; end;

    options = {};
    result = { result{:} '' };
    if ~isempty(result{1}), options = { options{:} 'channels' eval( [ '[' result{1} ']' ] ) }; end;
    if ~isempty(result{2}), options = { options{:} 'samples'  eval( [ '[' result{2} ']' ] ) }; end;
    if ~isempty(result{3}), options = { options{:} 'trials'   eval( [ '[' result{3} ']' ] ) }; end;
else
    dat = ft_read_header(filename);
    options = varargin;
end;

% decode imput parameters
% -----------------------
g = finputcheck( options, { 'samples'     'integer' [1 Inf]    [];
                            'trials'      'integer' [1 Inf]    [];
                            'channels'    'integer' [1 Inf]    [] }, 'pop_fileio');
if isstr(g), error(g); end;

% import data
% -----------
EEG = eeg_emptyset;
fprintf('Reading data ...\n');
dataopts = {};
if ~isempty(g.channels), dataopts = { dataopts{:} 'chanindx', g.channels }; end;
if ~isempty(g.samples ), dataopts = { dataopts{:} 'begsample', g.samples(1), 'endsample', g.samples(2)}; end;
if ~isempty(g.trials  ), dataopts = { dataopts{:} 'begtrial', g.trials(1), 'endtrial', g.trials(2)}; end;
alldata = ft_read_data(filename, 'header', dat, dataopts{:});

% convert to seconds for sread
% ----------------------------
EEG.srate           = dat.Fs;
EEG.nbchan          = dat.nChans;
EEG.data            = alldata;
EEG.setname 		= '';
EEG.comments        = [ 'Original file: ' filename ];
EEG.xmin = -dat.nSamplesPre/EEG.srate;
EEG.trials          = dat.nTrials;
EEG.pnts            = dat.nSamples;
if isfield(dat, 'label') && ~isempty(dat.label)
    EEG.chanlocs = struct('labels', dat.label);
end

% extract events
% --------------
disp('Reading events...');
try
    event = ft_read_event(filename);
catch, disp(lasterr); event = []; end;
if ~isempty(event)
    subsample = 0;

    if ~isempty(g.samples), subsample = g.samples(1); end;

    for index = 1:length(event)
        offset = fastif(isempty(event(index).offset), 0, event(index).offset);
        EEG.event(index).type     = event(index).value;
        EEG.event(index).value    = event(index).type;
        EEG.event(index).latency  = event(index).sample+offset+subsample;
        EEG.event(index).duration = event(index).duration;
        if EEG.trials > 1
            EEG.event(index).epoch = ceil(EEG.event(index).latency/EEG.pnts);
        end;
    end;

    EEG = eeg_checkset(EEG, 'eventconsistency');
else
    disp('Warning: no event found. Events might be embeded in a data channel.');
    disp('         To extract events, use menu File > Import Event Info > From data channel');
end;

% convert data to single if necessary
% -----------------------------------
EEG = eeg_checkset(EEG,'makeur');   % Make EEG.urevent field

% history
% -------
if isempty(options)
    command = sprintf('EEG = pop_fileio(''%s'');', filename);
else
    command = sprintf('EEG = pop_fileio(''%s'', %s);', filename, vararg2str(options));
end;


text:
<!DOCTYPE html>

    <title>CSS Backgrounds and Borders Test: background-size - initial value</title>
    <link rel="author" title="Intel" href="http://www.intel.com">
    <link rel="reviewer" title="Gérard Talbot" href="http://www.gtalbot.org/BrowserBugsSection/css21testsuite/">
    <link rel="help" href="http://www.w3.org/TR/css3-background/#the-background-size" title="3.9. Sizing Images: the 'background-size' property">
    <link rel="match" href="reference/background-size-002-ref.html">
    <meta name="flags" content="image">
    <meta name="assert" content="Check if 'background-size' with initial value implies to the intrinsic width and height of the image are to be used. Therefore the used width and height of the background-size in this test should be 60px and 60px.">

Test passes if there is a filled green square and no red.


text:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule } from '../../../../../';

import { AppComponent } from './app.component';
import { ComponentsModule } from '../pages/components/components.module';
import {AssistiveTouchComponentModule} from '../components/assistive-touch/assistive-touch.module';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(AppComponent, {}),
    ComponentsModule,
    AssistiveTouchComponentModule
  ],
  bootstrap: [IonicApp]
})
export class AppModule {}


text:
title: Lolo the Wedding Planner
author: David Hogge
layout: post
permalink: /usa/lolo-the-wedding-planner.html
thumbnail: http://farm1.static.flickr.com/61/200998219_4374fc69f4
thumbnail_alt: The Wedding Planner
geo_latitude:
  - 38.8951118
geo_longitude:
  - -77.0363658
geo_address:
  - Washington, District of Columbia, United States
geo_enabled:
  - 1
geo_public:
  - 1
categories:
  - USA
tags:
  - wedding day
  - Wedding Planner
---
How do you know that you are some one's good friend? When they ask you to manage their wedding.

How does someone know when you are their *very* good friend? When there are almost five hundred people attending your wedding, and you say "Yes".

One of the reasons we chose the dates we did for our return was to make it to the wedding of our friends Jeanne and Abbie. Since we were planning on being in the area and aren't yet encumbered by jobs, we offered to help in any way we could with getting ready for the big wedding day. Jeanne asked if she could employ us on the wedding day itself to kind of manage things behind the scene, so while she didn't actually plan anything and there was no radio headset to be worn, I mockingly called her Jeanne's "Wedding Planner".

And I wasn't the only one. At the wedding rehearsal the night before several of Jeanne's out-of-town friends took her to be a pro. "How many wedding do you do a year?" they asked, "This is my first", (concerned look on out-of-town friends face) "Oh, umm", whereupon LeeAnne explains that she's doing Jeanne a "solid" in repayment for the many "solids" we have already received from her in the past.

Then there was a very disconcerting moment in the rehearsal when Jeanne asked both LeeAnne and myself to stand up, and said in front of the eighty people at the wedding rehearsal (Because when you wedding is huge, your wedding rehearsal has to be also disproportionately large), "If any of you have any questions tomorrow at all, find LeeAnne or Dave and they can answer them for you". Whoa, that's the first I've heard of that. I have a hard time keeping track of myself at these events – this is not good.

The day of the wedding itself remains a blur as much for ourselves as I'm sure it was for Jeanne and Abbie. Some of the events that do remain in my memory include:

*   Flower children showing up for the service about three seconds before the march down the aisle begins
*   Guests showing up to the service forty-five minutes after it's begun and wondering why it's hard to find a seat
*   The Ethiopian band showing up 30 minutes after they're supposed to play the traditional wedding song and introduce the newylwed couple at the reception
*   The wedding band learning to play a [Junkyard Band][1] Go-Go song in about five minutes before the reception
*   The power cutting out right before the wedding bands big finale
*   A wedding band of the goofiest middle age white people you've ever met preforming a Go-Go song

Somewhat surprisingly, it all went off. Everything happened, there were toasts, the cake was cut, people were sat at tables, everyone worked together and made things happen. And all this with out J-Lo, and her headset. It was a great time and certainly worth changing around a schedule a bit and taking on (way) more responsibility than we thought we'd have.

 [1]: http://en.wikipedia.org/wiki/Junkyard_Band


text:
using System;

namespace ASC.Feed
{
    [Flags]
    public enum FeedAction
    {
        Created = 0,
        Updated = 1,
        Commented = 2,
        AllDayEventCreated = 3
    }
}


text:
set -e
set -x

if [[ $(arch) == "aarch64" ]]; then
  echo "ERROR: not supported on Linux Arm64"
  exit 1
fi

if [[ ! -f "/etc/os-release" ]]; then
  echo "ERROR: cannot install on unknown linux distribution (/etc/os-release is missing)"
  exit 1
fi

ID=$(bash -c 'source /etc/os-release && echo $ID')
if [[ "${ID}" != "ubuntu" ]]; then
  echo "ERROR: cannot install on $ID distribution - only Ubuntu is supported"
  exit 1
fi

# 1. make sure to remove old beta if any.
if dpkg --get-selections | grep -q "^google-chrome-beta[[:space:]]*install$" >/dev/null; then
  apt-get remove -y google-chrome-beta
fi

# 2. Update apt lists (needed to install curl and chrome dependencies)
apt-get update

# 3. Install curl to download chrome
if ! command -v curl >/dev/null; then
  apt-get install -y curl
fi

# 4. download chrome beta from dl.google.com and install it.
cd /tmp
curl -O https://dl.google.com/linux/direct/google-chrome-beta_current_amd64.deb
apt-get install -y ./google-chrome-beta_current_amd64.deb
rm -rf ./google-chrome-beta_current_amd64.deb
cd -
google-chrome-beta --version


text:
#include "tensorflow/compiler/tf2xla/literal_util.h"

#include "tensorflow/compiler/tf2xla/shape_util.h"
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/core/common_runtime/dma_helper.h"

namespace tensorflow {

Status HostTensorToBorrowingLiteral(const Tensor& host_tensor,
                                    xla::BorrowingLiteral* literal) {
  xla::Shape xla_shape;
  TF_RETURN_IF_ERROR(TensorShapeToXLAShape(host_tensor.dtype(),
                                           host_tensor.shape(), &xla_shape));
  return HostTensorToBorrowingLiteral(xla_shape, host_tensor, literal);
}

Status HostTensorToBorrowingLiteral(const xla::Shape& xla_shape,
                                    const Tensor& host_tensor,
                                    xla::BorrowingLiteral* literal) {
  const auto& tshape = host_tensor.shape();
  TF_RET_CHECK(tshape.IsFullyDefined() &&
               tshape.dims() == xla_shape.dimensions_size() &&
               tshape.dim_sizes() == xla_shape.dimensions())
      << "Provided xla::Shape must have the same dims as the Tensor shape.";
  *literal = xla::BorrowingLiteral(
      static_cast<const char*>(DMAHelper::base(&host_tensor)), xla_shape);
  return Status::OK();
}

StatusOr<xla::Literal> HostTensorToLiteral(const Tensor& host_tensor) {
  xla::BorrowingLiteral literal;
  TF_RETURN_IF_ERROR(HostTensorToBorrowingLiteral(host_tensor, &literal));
  return literal.Clone();
}

Status HostTensorToMutableBorrowingLiteral(
    Tensor* host_tensor, xla::MutableBorrowingLiteral* literal) {
  xla::Shape xla_shape;
  TF_RETURN_IF_ERROR(TensorShapeToXLAShape(host_tensor->dtype(),
                                           host_tensor->shape(), &xla_shape));
  return HostTensorToMutableBorrowingLiteral(xla_shape, host_tensor, literal);
}

Status HostTensorToMutableBorrowingLiteral(
    const xla::Shape& xla_shape, Tensor* host_tensor,
    xla::MutableBorrowingLiteral* literal) {
  *literal = xla::MutableBorrowingLiteral(
      static_cast<const char*>(DMAHelper::base(host_tensor)), xla_shape);

  return Status::OK();
}

Status HostTensorsToBorrowingLiteralTuple(absl::Span<const Tensor> host_tensors,
                                          xla::BorrowingLiteral* literal) {
  std::vector<const char*> buf_ptrs;
  buf_ptrs.reserve(host_tensors.size());
  std::vector<xla::Shape> tensor_shapes(host_tensors.size());

  for (int i = 0, end = host_tensors.size(); i < end; i++) {
    // Validate runtime shapes and fail if it doesn't match the contract.
    const Tensor* tensor = &host_tensors[i];
    buf_ptrs.emplace_back(static_cast<const char*>(DMAHelper::base(tensor)));
    TF_RETURN_IF_ERROR(TensorShapeToXLAShape(tensor->dtype(), tensor->shape(),
                                             &tensor_shapes[i]));
  }

  *literal = xla::BorrowingLiteral(
      buf_ptrs, xla::ShapeUtil::MakeTupleShape(tensor_shapes));

  return Status::OK();
}

Status CopyLiteralToHostTensor(const xla::LiteralSlice& literal,
                               Tensor* host_tensor) {
  TF_RET_CHECK(literal.shape().IsArray() &&
               xla::ShapeUtil::ElementsIn(literal.shape()) ==
                   host_tensor->NumElements());
  xla::PrimitiveType primitive_type;
  TF_RETURN_IF_ERROR(
      DataTypeToPrimitiveType(host_tensor->dtype(), &primitive_type));
  if (literal.shape().element_type() != primitive_type) {
    return errors::InvalidArgument(
        "Cannot convert literal of type ",
        xla::PrimitiveType_Name(literal.shape().element_type()),
        " to tensor of type ", DataTypeString(host_tensor->dtype()));
  }
  size_t total_bytes = host_tensor->TotalBytes();
  if (total_bytes > 0) {
    const void* src_ptr = literal.untyped_data();
    void* dst_ptr = DMAHelper::base(host_tensor);
    memcpy(dst_ptr, src_ptr, total_bytes);
  }
  return Status::OK();
}

Status LiteralToHostTensor(const xla::LiteralSlice& literal,
                           DataType target_type, Tensor* host_tensor) {
  TensorShape shape;
  TF_RETURN_IF_ERROR(XLAShapeToTensorShape(literal.shape(), &shape));
  *host_tensor = Tensor(target_type, shape);
  return CopyLiteralToHostTensor(literal, host_tensor);
}

}  // namespace tensorflow


text:
#ifndef BERRYEDITORDESCRIPTOR_H_
#define BERRYEDITORDESCRIPTOR_H_

#include "berryIEditorDescriptor.h"
#include "berryIMemento.h"

#include <berryIConfigurationElement.h>

namespace berry
{

struct IEditorPart;

/**
 * \ingroup org_blueberry_ui_internal
 *
 * @see IEditorDescriptor
 */
class BERRY_UI EditorDescriptor : public IEditorDescriptor
{ //, Serializable, IPluginContribution {

public:
  berryObjectMacro(EditorDescriptor);

  // @issue the following constants need not be public; see bug 47600
  /**
   * Open internal constant.  Value 0x01.
   */
  static const int OPEN_INTERNAL; // = 0x01;

  /**
   * Open in place constant.  Value 0x02.
   */
  static const int OPEN_INPLACE; // = 0x02;

  /**
   * Open external constant.  Value 0x04.
   */
  static const int OPEN_EXTERNAL; // = 0x04;

private:

  std::string editorName;

  std::string imageFilename;

  mutable SmartPointer<ImageDescriptor> imageDesc;

  mutable bool testImage;

  std::string className;

  std::string launcherName;

  std::string fileName;

  std::string id;

  bool matchingStrategyChecked;
  IEditorMatchingStrategy::Pointer matchingStrategy;

  //Program program;

  //The id of the plugin which contributed this editor, null for external editors
  std::string pluginIdentifier;

  int openMode;

  IConfigurationElement::Pointer configurationElement;

  /**
   * Create a new instance of an editor descriptor. Limited
   * to internal framework calls.
   * @param element
   * @param id2
   */
  /* package */
public: EditorDescriptor(const std::string& id2, IConfigurationElement::Pointer element);

  /**
   * Create a new instance of an editor descriptor. Limited
   * to internal framework calls.
   */
  /* package */
public: EditorDescriptor();

  /**
   * Creates a descriptor for an external program.
   *
   * @param filename the external editor full path and filename
   * @return the editor descriptor
   */
  //public: static EditorDescriptor::Pointer CreateForProgram(const std::string& filename) {
  //        if (filename == null) {
  //            throw new IllegalArgumentException();
  //        }
  //        EditorDescriptor editor = new EditorDescriptor();
  //
  //        editor.setFileName(filename);
  //        editor.setID(filename);
  //        editor.setOpenMode(OPEN_EXTERNAL);
  //
  //        //Isolate the program name (no directory or extension)
  //        int start = filename.lastIndexOf(File.separator);
  //        String name;
  //        if (start != -1) {
  //            name = filename.substring(start + 1);
  //        } else {
  //            name = filename;
  //        }
  //        int end = name.lastIndexOf('.');
  //        if (end != -1) {
  //            name = name.substring(0, end);
  //        }
  //        editor.setName(name);
  //
  //        // get the program icon without storing it in the registry
  //        ImageDescriptor imageDescriptor = new ProgramImageDescriptor(filename,
  //                0);
  //        editor.setImageDescriptor(imageDescriptor);
  //
  //        return editor;
  //    }

  /**
   * Return the program called programName. Return null if it is not found.
   * @return org.blueberry.swt.program.Program
   */
  //private: static Program FindProgram(const std::string& programName) {
  //
  //        Program[] programs = Program.getPrograms();
  //        for (int i = 0; i < programs.length; i++) {
  //            if (programs[i].getName().equals(programName)) {
  //        return programs[i];
  //      }
  //        }
  //
  //        return null;
  //    }

  /**
   * Create the editor action bar contributor for editors of this type.
   *
   * @return the action bar contributor, or null
   */
//public: IEditorActionBarContributor::Pointer CreateActionBarContributor();

  /**
   * Return the editor class name.
   *
   * @return the class name
   */
public: std::string GetEditorClassName() const;

  /**
   * Return the configuration element used to define this editor, or null.
   *
   * @return the element or null
   */
public: IConfigurationElement::Pointer GetConfigurationElement() const;

  /**
   * Create an editor part based on this descriptor.
   *
   * @return the editor part
   * @throws CoreException thrown if there is an issue creating the editor
   */
public: SmartPointer<IEditorPart> CreateEditor();

  /**
   * Return the file name of the command to execute for this editor.
   *
   * @return the file name to execute
   */
public: std::string GetFileName() const;

  /**
   * Return the id for this editor.
   *
   * @return the id
   */
public: std::string GetId() const;

  /**
   * Return the image descriptor describing this editor.
   *
   * @return the image descriptor
   */
public: SmartPointer<ImageDescriptor> GetImageDescriptor() const;

  /**
   * Verifies that the image descriptor generates an image.  If not, the
   * descriptor is replaced with the default image.
   *
   * @since 3.1
   */
private: void VerifyImage() const;

  /**
   * The name of the image describing this editor.
   *
   * @return the image file name
   */
public: std::string GetImageFilename() const;

  /**
   * Return the user printable label for this editor.
   *
   * @return the label
   */
public: std::string GetLabel() const;

  /**
   * Returns the class name of the launcher.
   *
   * @return the launcher class name
   */
public: std::string GetLauncher() const;

  /**
   * Return the contributing plugin id.
   *
   * @return the contributing plugin id
   */
public: std::string GetPluginID() const;

  /**
   * Get the program for the receiver if there is one.
   * @return Program
   */
  //public: Program GetProgram() {
  //        return this.program;
  //    }

  /* (non-Javadoc)
   * @see org.blueberry.ui.IEditorDescriptor#isInternal
   */
public: bool IsInternal() const;

  /* (non-Javadoc)
   * @see org.blueberry.ui.IEditorDescriptor#isOpenInPlace
   */
public: bool IsOpenInPlace() const;

  /* (non-Javadoc)
   * @see org.blueberry.ui.IEditorDescriptor#isOpenExternal
   */
public: bool IsOpenExternal() const;

  /**
   * Load the object properties from a memento.
   *
   * @return true if the values are valid, false otherwise
   */
protected: bool LoadValues(IMemento::Pointer memento);

  /**
   * Save the object values in a IMemento
   */
protected: void SaveValues(IMemento::Pointer memento);

  /**
   * Return the open mode of this editor.
   *
   * @return the open mode of this editor
   * @since 3.1
   */
private: int GetOpenMode() const;

  /**
   * Set the class name of an internal editor.
   */
  /* package */public: void SetClassName(const std::string& newClassName);

  /**
   * Set the configuration element which contributed this editor.
   */
  /* package */public: void SetConfigurationElement(
      IConfigurationElement::Pointer newConfigurationElement);

  /**
   * Set the filename of an external editor.
   */
  /* package */public: void SetFileName(const std::string& aFileName);

  /**
   * Set the id of the editor.
   * For internal editors this is the id as provided in the extension point
   * For external editors it is path and filename of the editor
   */
  /* package */public: void SetID(const std::string& anID);

  /**
   * The Image to use to repesent this editor
   */
  /* package */
  //    public : void SetImageDescriptor(ImageDescriptor desc) {
  //        imageDesc = desc;
  //        testImage = true;
  //    }

  /**
   * The name of the image to use for this editor.
   */
  /* package */
  //    public: void SetImageFilename(const std::string& aFileName) {
  //        imageFilename = aFileName;
  //    }

  /**
   * Sets the new launcher class name
   *
   * @param newLauncher the new launcher
   */
  /* package */public: void SetLauncher(const std::string& newLauncher);

  /**
   * The label to show for this editor.
   */
  /* package */public: void SetName(const std::string& newName);

  /**
   * Sets the open mode of this editor descriptor.
   *
   * @param mode the open mode
   *
   * @issue this method is public as a temporary fix for bug 47600
   */
public: void SetOpenMode(int mode);

  /**
   * The id of the plugin which contributed this editor, null for external editors.
   */
  /* package */public: void SetPluginIdentifier(const std::string& anID);

  /**
   * Set the receivers program.
   * @param newProgram
   */
  /* package */
  //    public: void SetProgram(Program newProgram) {
  //
  //        this.program = newProgram;
  //        if (editorName == null) {
  //      setName(newProgram.getName());
  //    }
  //    }

  /**
   * For debugging purposes only.
   */
public: std::string ToString() const;

  /* (non-Javadoc)
   * @see org.blueberry.ui.activities.support.IPluginContribution#getLocalId()
   */
public: std::string GetLocalId() const;

  /* (non-Javadoc)
   * @see org.blueberry.ui.activities.support.IPluginContribution#getPluginId()
   */
public: std::string GetPluginId() const;

  /* (non-Javadoc)
   * @see org.blueberry.ui.IEditorDescriptor#getEditorManagementPolicy()
   */
public: IEditorMatchingStrategy::Pointer GetEditorMatchingStrategy();

};

}

#endif /*BERRYEDITORDESCRIPTOR_H_*/


text:
<!--
  ~ Copyright (c) 2016-2017 Evolveum
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->
<role oid="c545323c-5d68-11e7-acba-2b32ef514121"
        xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
        xmlns:t="http://prism.evolveum.com/xml/ns/public/types-3"
        xmlns:org='http://midpoint.evolveum.com/xml/ns/public/common/org-3'>
    <name>Manager User Admin</name>
    <description>
    	Role that gives access to the organizational units and objects stored
    	there for organizational unit managers. A manager can read everything in
    	the units that he is managing. And it can change all contained users.
    </description>
    <authorization>
    	<name>autz-read</name>
    	<action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#read</action>
    	<object>
    		<orgRelation>
    			<subjectRelation>org:manager</subjectRelation>
    			<scope>allDescendants</scope>
    			<includeReferenceOrg>true</includeReferenceOrg>
    		</orgRelation>
    	</object>
    </authorization>
    <authorization>
    	<name>autz-user-write</name>
    	<action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#modify</action>
    	<action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#add</action>
    	<action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#delete</action>
    	<object>
    		<type>UserType</type>
    		<orgRelation>
    			<subjectRelation>org:manager</subjectRelation>
    		</orgRelation>
    	</object>
    </authorization>
    <authorization>
    	<name>autz-shadow-read</name>
    	<action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#read</action>
    	<object>
    		<type>ShadowType</type>
    		<owner>
    			<orgRelation>
	    			<subjectRelation>org:manager</subjectRelation>
	    		</orgRelation>
    		</owner>
    	</object>
    </authorization>
    <authorization>
    	<name>autz-shadow-write</name>
    	<action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#modify</action>
    	<action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#add</action>
    	<action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#delete</action>
    	<phase>execution</phase>
    	<object>
    		<type>ShadowType</type>
    		<owner>
    			<orgRelation>
	    			<subjectRelation>org:manager</subjectRelation>
	    		</orgRelation>
    		</owner>
    	</object>
    </authorization>
</role>


text:
package error

import (
	"encoding/json"
	"fmt"
	"net/http"
)

var errors = map[int]string{
	// command related errors
	EcodeKeyNotFound:      "Key not found",
	EcodeTestFailed:       "Compare failed", //test and set
	EcodeNotFile:          "Not a file",
	EcodeNoMorePeer:       "Reached the max number of peers in the cluster",
	EcodeNotDir:           "Not a directory",
	EcodeNodeExist:        "Key already exists", // create
	EcodeRootROnly:        "Root is read only",
	EcodeKeyIsPreserved:   "The prefix of given key is a keyword in etcd",
	EcodeDirNotEmpty:      "Directory not empty",
	EcodeExistingPeerAddr: "Peer address has existed",

	// Post form related errors
	EcodeValueRequired:        "Value is Required in POST form",
	EcodePrevValueRequired:    "PrevValue is Required in POST form",
	EcodeTTLNaN:               "The given TTL in POST form is not a number",
	EcodeIndexNaN:             "The given index in POST form is not a number",
	EcodeValueOrTTLRequired:   "Value or TTL is required in POST form",
	EcodeTimeoutNaN:           "The given timeout in POST form is not a number",
	EcodeNameRequired:         "Name is required in POST form",
	EcodeIndexOrValueRequired: "Index or value is required",
	EcodeIndexValueMutex:      "Index and value cannot both be specified",
	EcodeInvalidField:         "Invalid field",

	// raft related errors
	EcodeRaftInternal: "Raft Internal Error",
	EcodeLeaderElect:  "During Leader Election",

	// etcd related errors
	EcodeWatcherCleared:     "watcher is cleared due to etcd recovery",
	EcodeEventIndexCleared:  "The event in requested index is outdated and cleared",
	EcodeStandbyInternal:    "Standby Internal Error",
	EcodeInvalidActiveSize:  "Invalid active size",
	EcodeInvalidRemoveDelay: "Standby remove delay",

	// client related errors
	EcodeClientInternal: "Client Internal Error",
}

const (
	EcodeKeyNotFound      = 100
	EcodeTestFailed       = 101
	EcodeNotFile          = 102
	EcodeNoMorePeer       = 103
	EcodeNotDir           = 104
	EcodeNodeExist        = 105
	EcodeKeyIsPreserved   = 106
	EcodeRootROnly        = 107
	EcodeDirNotEmpty      = 108
	EcodeExistingPeerAddr = 109

	EcodeValueRequired        = 200
	EcodePrevValueRequired    = 201
	EcodeTTLNaN               = 202
	EcodeIndexNaN             = 203
	EcodeValueOrTTLRequired   = 204
	EcodeTimeoutNaN           = 205
	EcodeNameRequired         = 206
	EcodeIndexOrValueRequired = 207
	EcodeIndexValueMutex      = 208
	EcodeInvalidField         = 209

	EcodeRaftInternal = 300
	EcodeLeaderElect  = 301

	EcodeWatcherCleared     = 400
	EcodeEventIndexCleared  = 401
	EcodeStandbyInternal    = 402
	EcodeInvalidActiveSize  = 403
	EcodeInvalidRemoveDelay = 404

	EcodeClientInternal = 500
)

type Error struct {
	ErrorCode int    `json:"errorCode"`
	Message   string `json:"message"`
	Cause     string `json:"cause,omitempty"`
	Index     uint64 `json:"index"`
}

func NewError(errorCode int, cause string, index uint64) *Error {
	return &Error{
		ErrorCode: errorCode,
		Message:   errors[errorCode],
		Cause:     cause,
		Index:     index,
	}
}

func Message(code int) string {
	return errors[code]
}

// Only for error interface
func (e Error) Error() string {
	return e.Message + " (" + e.Cause + ")"
}

func (e Error) toJsonString() string {
	b, _ := json.Marshal(e)
	return string(b)
}

func (e Error) Write(w http.ResponseWriter) {
	w.Header().Add("X-Etcd-Index", fmt.Sprint(e.Index))
	// 3xx is raft internal error
	status := http.StatusBadRequest
	switch e.ErrorCode {
	case EcodeKeyNotFound:
		status = http.StatusNotFound
	case EcodeNotFile, EcodeDirNotEmpty:
		status = http.StatusForbidden
	case EcodeTestFailed, EcodeNodeExist:
		status = http.StatusPreconditionFailed
	default:
		if e.ErrorCode/100 == 3 {
			status = http.StatusInternalServerError
		}
	}
	w.WriteHeader(status)
	fmt.Fprintln(w, e.toJsonString())
}


text:
<?php

class basicOrderRequest extends orderRequestMain
{
	protected $allOrNone;
	protected $quantity;
	protected $reserveOrder;
	protected $reserveQuantity;
}

?>


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
 * Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/licenses/publicdomain/
 * Contributor: Blake Kaplan
 */

//-----------------------------------------------------------------------------
var BUGNUMBER = 428366;
var summary = 'Do not assert deleting eval 16 times';
var actual = '';
var expect = '';

printBugNumber(BUGNUMBER);
printStatus (summary);

this.__proto__.x = eval;
for (i = 0; i < 16; ++i) delete eval;
(function w() { x = 1; })();

reportCompare(expect, actual, summary);


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('review', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='review',
            name='review_author',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='review', to=settings.AUTH_USER_MODEL),
        ),
    ]


text:
from timeit import default_timer as timer

from ray.train.torch.torch_checkpoint import TorchCheckpoint
import torch
import torchvision

from ray.air import session

import ray.train as train
from ray.air.config import ScalingConfig
from ray.train.torch.torch_trainer import TorchTrainer

def test_torch_amp_performance(ray_start_4_cpus_2_gpus):
    def train_func(config):
        train.torch.accelerate(amp=config["amp"])

        start_time = timer()
        model = torchvision.models.resnet101()
        model = train.torch.prepare_model(model)

        dataset_length = 1000
        dataset = torch.utils.data.TensorDataset(
            torch.randn(dataset_length, 3, 224, 224),
            torch.randint(low=0, high=1000, size=(dataset_length,)),
        )
        dataloader = torch.utils.data.DataLoader(dataset, batch_size=64)
        dataloader = train.torch.prepare_data_loader(dataloader)

        optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
        optimizer = train.torch.prepare_optimizer(optimizer)

        model.train()
        for epoch in range(1):
            for images, targets in dataloader:
                optimizer.zero_grad()

                outputs = model(images)
                loss = torch.nn.functional.cross_entropy(outputs, targets)

                train.torch.backward(loss)
                optimizer.step()
        end_time = timer()
        session.report({"latency": end_time - start_time})

    def latency(amp: bool) -> float:
        trainer = TorchTrainer(
            train_func,
            train_loop_config={"amp": amp},
            scaling_config=ScalingConfig(num_workers=2, use_gpu=True),
        )
        results = trainer.fit()
        return results.metrics["latency"]

    # Training should be at least 5% faster with AMP.
    assert 1.05 * latency(amp=True) < latency(amp=False)

def test_checkpoint_torch_model_with_amp(ray_start_4_cpus_2_gpus):
    """Test that model with AMP is serializable."""

    def train_func():
        train.torch.accelerate(amp=True)

        model = torchvision.models.resnet101()
        model = train.torch.prepare_model(model)

        session.report({}, checkpoint=TorchCheckpoint.from_model(model))

    trainer = TorchTrainer(
        train_func, scaling_config=ScalingConfig(num_workers=2, use_gpu=True)
    )
    results = trainer.fit()
    assert results.checkpoint
    assert results.checkpoint.get_model()

if __name__ == "__main__":
    import sys

    import pytest

    sys.exit(pytest.main(["-v", "-x", "-s", __file__]))


text:
export * from './unique-id';
export * from './sort';


text:
#include <aws/email/model/CustomMailFromStatus.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace SES
  {
    namespace Model
    {
      namespace CustomMailFromStatusMapper
      {

        static const int Pending_HASH = HashingUtils::HashString("Pending");
        static const int Success_HASH = HashingUtils::HashString("Success");
        static const int Failed_HASH = HashingUtils::HashString("Failed");
        static const int TemporaryFailure_HASH = HashingUtils::HashString("TemporaryFailure");

        CustomMailFromStatus GetCustomMailFromStatusForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == Pending_HASH)
          {
            return CustomMailFromStatus::Pending;
          }
          else if (hashCode == Success_HASH)
          {
            return CustomMailFromStatus::Success;
          }
          else if (hashCode == Failed_HASH)
          {
            return CustomMailFromStatus::Failed;
          }
          else if (hashCode == TemporaryFailure_HASH)
          {
            return CustomMailFromStatus::TemporaryFailure;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<CustomMailFromStatus>(hashCode);
          }

          return CustomMailFromStatus::NOT_SET;
        }

        Aws::String GetNameForCustomMailFromStatus(CustomMailFromStatus enumValue)
        {
          switch(enumValue)
          {
          case CustomMailFromStatus::Pending:
            return "Pending";
          case CustomMailFromStatus::Success:
            return "Success";
          case CustomMailFromStatus::Failed:
            return "Failed";
          case CustomMailFromStatus::TemporaryFailure:
            return "TemporaryFailure";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return "";
          }
        }

      } // namespace CustomMailFromStatusMapper
    } // namespace Model
  } // namespace SES
} // namespace Aws


text:
namespace foundation    { class IAbortSwitch; }
namespace renderer      { class OIIOErrorHandler; }
namespace renderer      { class OIIOTextureSystem; }
namespace renderer      { class OSLShadingSystem; }
namespace renderer      { class Project; }
namespace renderer      { class RendererServices; }
namespace renderer      { class TextureStore; }

namespace renderer
{

//
// Base renderer, handles rendering of a given project.
//

class APPLESEED_DLLSYMBOL BaseRenderer
  : public foundation::NonCopyable
{
  public:
    // Destructor.
    ~BaseRenderer();

    // Return the parameters of the base renderer.
    ParamArray& get_parameters();
    const ParamArray& get_parameters() const;

    bool initialize_shading_system(
        TextureStore&               texture_store,
        foundation::IAbortSwitch&   abort_switch);

  protected:
    Project&                        m_project;
    ParamArray                      m_params;
    OIIOErrorHandler*               m_error_handler;
    OIIOTextureSystem*              m_texture_system;

    RendererServices*               m_renderer_services;
    OSLShadingSystem*               m_shading_system;

    // Constructor.
    BaseRenderer(
        Project&                    project,
        const ParamArray&           params);

  private:
    void initialize_oiio();

    bool initialize_osl(
        TextureStore&               texture_store,
        foundation::IAbortSwitch&   abort_switch);
};

}       // namespace renderer

#endif  // !APPLESEED_RENDERER_KERNEL_RENDERING_BASERENDERER_H


text:
---
layout: page
title: Notifications
permalink: /:path/
sort_idx: 70
---
{% include variables.md %}

* TOC
{:toc}

The Kaa **Notification subsystem** is used to deliver messages from [Kaa cluster]({{root_url}}Glossary/#kaa-cluster) to [endpoints]({{root_url}}Glossary/#endpoint-ep).
Unlike configuration data that represents the desired endpoint state, notifications are used as calls for a dynamic endpoint action.
For example, a notification can cause a [Kaa client]({{root_url}}Glossary/#kaa-client) to display a UI message (a user notification).

## Prerequisites

To use the examples below, you need to first set up either a [Kaa Sandbox]({{root_url}}Glossary/#kaa-sandbox) or a full-blown [Kaa cluster]({{root_url}}Glossary/#kaa-cluster).
After that, you need to create a tenant with tenant admin, and an application.
To do this, you can use the server REST API ([tenant]({{root_url}}Programming-guide/Server-REST-APIs/#/Tenant), [tenant admin]({{root_url}}Programming-guide/Server-REST-APIs/#!/User/editUser), [application]({{root_url}}Programming-guide/Server-REST-APIs/#/Application)).

It is strongly recommended that you first read the [Data collection]({{root_url}}Programming-guide/Key-platform-features/Data-collection) and [Endpoint groups]({{root_url}}Programming-guide/Key-platform-features/Endpoint-groups) sections before you proceed.

## Notification management

The following diagram illustrates the basic entities and data flows in scope of the notification management:

* Notifications are generated based on the [notification schema](#notification-schema) configured by the application developer.
* The user or administrator sends a notification using the [server REST API]({{root_url}}Programming-guide/Server-REST-APIs/#!/Notifications/sendNotification) call or the Administration UI (see [Send notifications](#send-notifications)).

![Basic architecture](images/basic_architecture_notification.png)

### Notification schema

The Kaa notifications functionality allows transferring any data to endpoints.
The structure of the notification data is defined by the notification schema selected and configured on the [Kaa server]({{root_url}}Glossary/#kaa-server).
The notification schema is defined similarly to the [endpoint profile]({{root_url}}Programming-guide/Key-platform-features/Endpoint-profiles) schema.
For more information about using schemas in Kaa, see [Common type library]({{root_url}}Programming-guide/Key-platform-features/Common-Type-Library).

In addition to the [common type]({{root_url}}Glossary/#common-type-ct) schema and its version, notifications are characterized by type that can be either **system** or **user**.
System notifications are processed by the prepackaged endpoint functions, while user notifications are sent to the Kaa client using the the endpoint API.

Since the data structure requirements may evolve throughout the Kaa-based system lifetime, the Kaa server can be configured to simultaneously handle notification schemas of multiple versions.
In this case, a notification will have multiple schema versions associated with it, as well as multiple sets of notification data so that each schema version is covered.
To deliver such a notification to an endpoint, the server chooses the schema version supported by the endpoint.

The default notification schema installed for [Kaa applications]({{root_url}}Glossary/#kaa-application) is empty.

For the purpose of this guide, a simple notification schema is shown in the example below.

```json
{
    "type":"record",
    "name":"ExampleNotification",
    "namespace":"org.kaaproject.kaa.schema.sample.notification",
    "fields":[
        {
            "name":"message",
            "type":"string"
        }
    ]
}
```

As a tenant developer, you can create new notification schemas for an application.
To do this, use the [server REST API]({{root_url}}Programming-guide/Server-REST-APIs/#!/Notifications/saveNotificationSchema) or open the **Notification** page of the application and follow the same steps as described in [Setting client-side EP profile schema]({{root_url}}Programming-guide/Key-platform-features/Endpoint-profiles/#setting-client-side-ep-profile-schema).

![Add Notification Schema 1](images/add_notification_schema_1.png)

### Notification topics

Notifications in Kaa are organized into topics.
Every topic can be associated with one or more endpoint groups.
To receive a notification, the endpoint must belong to one or more groups that are associated with the corresponding notification topic.

Topics can be mandatory or optional.
Mandatory topic notifications are delivered to the endpoints by default, whereas optional topics require a subscription.
For more information, see [Subscribe to optional topics](#subscribe-to-optional-topics).

To edit a notification topic, use the [server REST API]({{root_url}}Programming-guide/Server-REST-APIs/#!/Notifications/editTopic) or select the topic from the **Notification topics** page under the **Schema** section of the application.

![Add Notification Topic 1](images/add_notification_topic_1.png)

To create a notification topic, click the **Add notification topic** button.

![Add Notification Topic 2](images/add_notification_topic_2.png)

### Add notification topic to endpoint group

After you created a notification topic, you can assign it to the endpoint group.
To do this, use the [server REST API]({{root_url}}Programming-guide/Server-REST-APIs/#!/Notifications/editTopic) or use the Administration UI:

1. Open the **Notification topics** page of the application, **Add notification topic**.

2. Enter the notification topic details and click **Add**.

3. Open the **Endpoint groups** page of the application and select the endpoint group from the list.

4. Under the **Notification topics** section, click the **Add notification topic** button, select the topic from the pop-up window and click **Add**.
Now all endpoints belonging to the selected group will be subscribed to notifications on these topics.

	![Add topic to endpoint group](images/add_topic_to_endpoint_group.png)

If you previously created custom endpoint groups as described in the [Endpoint groups]({{root_url}}Programming-guide/Key-platform-features/Endpoint-groups/#custom-endpoint-groups) section, the following table illustrates how you can assign notification topics to the endpoint groups.

        Topic id
        Endpoint Group Name

        All
        Android Froyo endpoints
        Android endpoints
        iOS 8 endpoints
        3.0 RC1 QA group endpoints

        Android notifications
        false
        true
        true
        false
        false

        iOS 8 notifications
        false
        false
        false
        true
        false

        All devices notifications
        true
        false
        false
        false
        false

### Send notifications

To send a notification, use the [server REST API]({{root_url}}Programming-guide/Server-REST-APIs/#!/Notifications/sendNotification) or use the Administration UI:

1. Select the topic from the **Notification topics** page of the application and click **Send notification**.

2. On the **Notification details** page, create a notification either by using the **Notification body** record form or by uploading a JSON file.
The data structure of your JSON file must match the corresponding notification schema.

	![Send Notification](images/send_notification.png)

3. Click **Send** to send the notification.

Below is an example of the uploaded file contents that will match the default Sandbox notification schema.

```
{"message": "Hello from Kaa!"}
```

A notification will be queued for delivery until the time you specified in the **Expires at** field of the **Notification details** page.
If you leave this field blank, the message will be queued until the default time-to-live (TTL) period expires.
For more information, see [Notification pipelines](#notification-pipelines).

If you specified an endpoint ID in the **Endpoint KeyHash** field, the notification will only be sent to that specific endpoint.
If you leave this field blank, the notification will be sent to all endpoints subscribed to the selected notification topic.

## Notification pipelines

Notifications are processed by Kaa server using the **notification pipelines**.

The server uses these pipelines to manage individual notifications within a topic.
A notification remains queued in the pipeline until its time-to-live (TTL) expires, after that the notification will be deleted.

Two types of pipelines are used depending on the scope of notifications delivery: **multicast** and **unicast** pipelines.
A multicast pipeline manages notifications for unlimited number of endpoints, while a unicast pipeline manages notifications for a single specific endpoint.

### Multicast pipelines

When you send a notification to a topic that more than one endpoint is subscribed to, that notification is added to a multicast pipeline with a unique sequential index.
Every endpoint maintains its position independently in the pipelines by storing the last sequential index received from each pipeline.

### Unicast pipelines

When you send a notification to a single endpoint by entering its KeyHash (see [Send notifications](#send-notifications)), that notification is added to a unicast pipeline with a unique ID.
Every endpoint handled by a unicast pipeline maintains its pipeline by reporting the received notification ID.
The server removes the notification from the pipeline once it receives a receipt confirmation from the endpoint.
Make sure that the endpoint you specified is subscribed to the corresponding notification topic, otherwise the notification will not be delivered.

## Notifications API

This section provides code samples to illustrate practical usage of notifications in Kaa.

### Get available topics

Below are code examples of how to get a list of available topics:

Java

C++

C

Objective-C

```java
import org.kaaproject.kaa.client.KaaClient;
import org.kaaproject.kaa.client.DesktopKaaPlatformContext;
import org.kaaproject.kaa.common.endpoint.gen.Topic;

...
KaaClient kaaClient = Kaa.newClient(new DesktopKaaPlatformContext(), new SimpleKaaClientStateListener(), true)
// Start Kaa client
kaaClient.start()
...

List<Topic> topics = kaaClient.getTopics();

for (Topic topic : topics) {
    System.out.printf("Id: %s, name: %s, type: %s"
            , topic.getId(), topic.getName(), topic.getSubscriptionType());
}
```

```c++
#include <iostream>
#include <kaa/Kaa.hpp>
#include <kaa/IKaaClient.hpp>
#include <kaa/logging/LoggingUtils.hpp>

...

// Create an endpoint instance
auto kaaClient = kaa::Kaa::newClient();
// Start an endpoint
kaaClient->start();

// Get available topics
const auto& topics = kaaClient->getTopics();
for (const auto& topic : topics) {
    std::cout << "Id: " << topic.id << ", name: " << topic.name
              << ", type: " << kaa::LoggingUtils::TopicSubscriptionTypeToString(topic.subscriptionType) << std::endl;
}
```

```c
#include <extensions/notification/kaa_notification_manager.h>
#include <kaa/kaa_notification_manager.h>

kaa_client_t *kaa_client = /* ... */;

void on_topic_list_uploaded(void *context, kaa_list_t *topics)
{
    kaa_list_node_t *it = kaa_list_begin(topics);
    while (it) {
         kaa_topic_t *topic = (kaa_topic_t *) kaa_list_get_data(it);
         printf("Id: %lu, name: %s, type: %s\n", topic->id, topic->name, (topic->subscription_type == OPTIONAL_SUBSCRIPTION)? "OPTIONAL":"MANDATORY");
         it = kaa_list_next(it);
    }
}

kaa_list_t *topics_list = NULL;
kaa_error_t error_core = kaa_get_topics(kaa_client_get_context(kaa_client)->notification_manager, &topics_list);
on_topic_list_uploaded(NULL, topics_list);
```

```objc
@import Kaa;

...
    id<KaaClient> kaaClient = [Kaa client]
...
    // Start Kaa client
    [kaaClient start]
...
    NSArray *topics = [kaaClient getTopics];

    for (Topic *topic in topics) {
        NSLog(@"%lld %@ %u", topic.id, topic.name, topic.subscriptionType);
    }
```

### Subscribe to optional topics

To receive notifications on optional topic, you need to subscribe to that topic.

Java

C++

C

Objective-C

```java
import org.kaaproject.kaa.client.KaaClient;
...
// Add notification listener(s) (optional)
...
// Subscribe
kaaClient.subscribeToTopic("Android notifications", true);
...
// Unsubscribe. All added listeners will be removed automatically
kaaClient.unsubscribeFromTopic("Android notifications", true);
```

```c++
#include <kaa/Kaa.hpp>

...

// Subscribe
kaaClient->subscribeToTopic(1);

...

// Unsubscribe
kaaClient->unsubscribeFromTopic(1);
```

```c
#include <extensions/notification/kaa_notification_manager.h>
#include <kaa/platform/ext_notification_receiver.h>
// Assume we have some optional topic
uint64_t topic_id = 12345;

// Subcribe
kaa_error_t error_code = kaa_subscribe_to_topic(kaa_client_get_context(kaa_client)->notification_manager, &topic_id, true);

// Unsubscribe. All added listeners will be removed automatically
error_code = kaa_unsubscribe_from_topic(kaa_client_get_context(kaa_client)->notification_manager, &topic_id, true);
```

```objc
@import Kaa;

...
// Add notification listener(s) (optional)

// Subscribe
[kaaClient subscribeToTopicWithId:@"iOS notifications" forceSync:YES];
...
// Unsubscribe. All added listeners will be removed automatically
[kaaClient unsubscribeFromTopicWithId:@"iOS notifications" forceSync:YES];
```

You can work with a list of optional topics in a similar way as with the list of available topics.

Java

C++

C

Objective-C

```java
// Add notification listener(s) (optional)
...
// Subscribe
kaaClient.subscribeToTopics(Arrays.asList("iOS 8 notifications", "another_optional_topic_id"), true);
...
// Unsubscribe
kaaClient.unsubscribeFromTopics(Arrays.asList("iOS 8 notifications", "another_optional_topic_id"), true);
```

```c++
#include <kaa/Kaa.hpp>

...

// Subscribe
kaaClient->subscribeToTopics({1, 2});

...

// Unsubscribe
kaaClient->unsubscribeFromTopics({1, 2});
```

```c
#include <extensions/notification/kaa_notification_manager.h>
#include <kaa/platform/ext_notification_receiver.h>

// Assume we have some optional topics
uint64_t topic_ids[] = { 12345, 6789 };

// Subscribe
kaa_error_t error_code = kaa_subscribe_to_topics(kaa_client_get_context(kaa_client)->notification_manager, topic_ids, sizeof(topic_ids) / sizeof(uint64_t), true);

// Unsubscribe
error_code = kaa_unsubscribe_from_topics(kaa_client_get_context(kaa_client)->notification_manager, topic_ids, topics_count, true);
```

```objc
@import Kaa;

 ...
// Add notification listener(s) (optional)

// Subscribe
[kaaClient subscribeToTopicsWithIDs:@[@"iOS 8 notifications", @"another_optional_topic_id"] forceSync:YES];
...
// Unsubscribe
[kaaClient unsubscribeFromTopicsWithIDs:@[@"iOS 8 notifications", @"another_optional_topic_id"] forceSync:YES];
```

### Subscribe to updates on available topics

To receive updates for the available topics list, add at least one listener as shown in the example below.
You can create unlimited number of listeners.

Java

C++

C

Objective-C

```java
import org.kaaproject.kaa.client.KaaClient;
import org.kaaproject.kaa.client.KaaDesktop;
import org.kaaproject.kaa.client.notification.NotificationManager;
import org.kaaproject.kaa.client.notification.NotificationTopicListListener;
import org.kaaproject.kaa.common.endpoint.gen.Topic;

...
// Add listener
kaaClient.addTopicListListener(new NotificationTopicListListener() {
    @Override
    public void onListUpdated(List<Topic> topics) {
        for (Topic topic : topics) {
            System.out.printf("Id: %s, name: %s, type: %s",
            topic.getId(), topic.getName(), topic.getSubscriptionType());
    }
}});

...
// Remove listener
kaaClient.removeTopicListListener(someOtherTopicUpdateListener);
```

```c++
#include <iostream>
#include <memory>
#include <kaa/Kaa.hpp>
#include <kaa/logging/LoggingUtils.hpp>
#include <kaa/notification/INotificationTopicListListener.hpp>

class NotificationTopicListListener : public kaa::INotificationTopicListListener {
public:
    virtual void onListUpdated(const kaa::Topics& topics)
    {
        for (const auto& topic : topics) {
            std::cout << "Id: " << topic.id << ", name: " << topic.name
              << ", type: " << kaa::LoggingUtils::TopicSubscriptionTypeToString(topic.subscriptionType) << std::endl;
        }
    }
};

...

// Create a listener which receives the list of available topics.
std::unique_ptr<NotificationTopicListListener> topicListListener(new NotificationTopicListListener());

// Add a listener
kaaClient->addTopicListListener(*topicListListener);

...

// Remove a listener
kaaClient->removeTopicListListener(*topicListListener);
```

```c
#include <extensions/notification/kaa_notification_manager.h>
#include <kaa/platform/ext_notification_receiver.h>
kaa_topic_listener_t topic_listener = { &on_topic_list_uploaded, NULL };
uint32_t topic_listener_id = 0;

// Add listener
kaa_error_t error_code = kaa_add_topic_list_listener(kaa_client_get_context(kaa_client)->notification_manager, &topic_listener, &topic_listener_id);

// Remove listener
error_code = kaa_remove_topic_list_listener(kaa_client_get_context(kaa_client)->notification_manager, &topic_listener_id);
```

```objc
@import Kaa;

@interface ViewController() <NotificationTopicListDelegate>

...
    // Add listener
    [self.kaaClient addTopicListDelegate:self];
...

- (void)onListUpdated:(NSArray *)list {
    for (Topic *topic in topics) {
        NSLog([NSString stringWithFormat:@"%lld %@ %u", topic.id, topic.name, topic.subscriptionType]);
    }
}
...
    // Remove listener
    [self.kaaClient removeTopicListDelegate:self];
```

To accommodate for simultaneous change of several subscription topics, consider the following approach to optimize performance.

Java

C++

C

Objective-C

```java
import org.kaaproject.kaa.client.notification.NotificationManager;

...
// Do subscription changes with parameter forceSync set to false
kaaClient.subscribeToTopics(Arrays.asList("iOS 8 notifications", "another_optional_topic_id"), false);
kaaClient.unsubscribeFromTopic("boring_optional_topic_id", false);
...
// Add notification listener(s) (optional)
...
// Synchronizes new topic subscriptions.
kaaClient.syncTopicsList();
```

```c++
#include <kaa/Kaa.hpp>

...

// Subscribe to the list of topics and unsubscribe from one topic.
// By setting the second parameter to false an endpoint postpones sending a subscription request till a user calls syncTopicSubscriptions().
kaaClient->subscribeToTopics({1, 2}, false);
kaaClient->unsubscribeFromTopic(1, false);

...

// Sending a subscription request
kaaClient->syncTopicSubscriptions();
```

```c
#include <extensions/notification/kaa_notification_manager.h>
#include <kaa/platform/ext_notification_receiver.h>
// Assume we have some optional topics
uint64_t topic_ids[] = { 12345, 6789 };

// Subscribe to the list of topics and unsubscribe from one topic.
// By setting the second parameter to false an endpoint postpones sending a subscription request till a user calls syncTopicSubscriptions().
kaa_error_t error_code = kaa_subscribe_to_topics(kaa_client_get_context(kaa_client)->notification_manager, topic_ids, sizeof(topic_ids) / sizeof(uint64_t), false);
error_code = kaa_unsubscribe_from_topic(kaa_client_get_context(kaa_client)->notification_manager, topic_ids, false);

// Sending a subscription request
error_code = kaa_sync_topic_subscriptions(kaa_client_get_context(kaa_client)->notification_manager);
```

```objc
@import Kaa;

...
    // Do subscription changes with parameter forceSync set to false
    NSArray *topicIds = @[@"iOS 8 notifications", @"another_optional_topic_id"];
    [kaaClient subscribeToTopicsWithIDs:topicIds forceSync:NO];
    [kaaClient unsubscribeFromTopicWithId:@"boring_optional_topic_id" forceSync:NO];
    ...

    // Add notification listener(s) (optional)
    ...

    // Synchronizes new topic subscriptions.
    [kaaClient syncTopicsList];
```

### Default notification listener

There are two types of topic notification listeners: default and topic-specific.
To receive notifications, add at least one default listener.
As a result, the listener will receive notifications from all topics (all mandatory and all optional topics) that the endpoint group is subscribed to.

Java

C++

C

Objective-C

```java
import org.kaaproject.kaa.client.KaaClient;
import org.kaaproject.kaa.client.notification.NotificationListener;
import org.kaaproject.kaa.schema.sample.notification.ExampleNotification;

...
public class BasicNotificationListener implements NotificationListener {

    @Override
    public void onNotification(String topicId, ExampleNotification notification) {
        System.out.println("Received a notification: " + notification.toString());
    }
}
...
BasicNotificationListener listener = new BasicNotificationListener();
// Add listener
kaaClient.addNotificationListener(listener);
...
// Remove listener
kaaClient.removeNotificationListener(listener);
```

```c++
#include <cstdint>
#include <iostream>
#include <memory>
#include <kaa/Kaa.hpp>
#include <kaa/notification/INotificationListener.hpp>

class BasicNotificationListener : public kaa::INotificationListener {
public:
    virtual void onNotification(const std::int64_t topicId, const kaa::KaaNotification& notification)
    {
        std::cout << "Received notification on topic: id '"<< topicId << "', message: " << notification.message << std::endl;
    }
};

...

// Creates the listener which receives notifications on all available topics.
std::unique_ptr<BasicNotificationListener> listener(new BasicNotificationListener());

// Adds listener
kaaClient->addNotificationListener(*listener);

// Remove listener
kaaClient->removeNotificationListener(*listener);
```

```c
#include <extensions/notification/kaa_notification_manager.h>
#include <kaa/platform/ext_notification_receiver.h>
void on_notification(void *context, uint64_t *topic_id, kaa_notification_t *notification)
{
    printf("Received notification on topic %llu: message='%s'\n", topic_id, notification->message);
}

kaa_notification_listener_t notification_listener = { &on_notification, NULL };
uint32_t notification_listener_id = 0;

// Add listener
kaa_error_t error_code = kaa_add_notification_listener(kaa_client_get_context(kaa_client)->notification_manager, &notification_listener, &notification_listener_id);

// Remove listener
error_code = kaa_remove_notification_listener(kaa_client_get_context(kaa_client)->notification_manager, &notification_listener_id);
```

```objc
@import Kaa;

@interface ViewController () <NotificationDelegate>

...
     // Add listener
    [kaaClient addNotificationDelegate:self];
...

- (void)onNotification:(KAASampleNotification *)notification withTopicId:(NSString *)topicId {
    NSLog(@"Received a notification: %@", notification);
}

...
    // Remove listener
    [kaaClient removeNotificationDelegate:self];
```

### Topic specific notification listener

To receive notifications on some specific topic (either mandatory or optional), you can use topic-specific listeners instead of the default listener.

Java

C++

C

Objective-C

```java
import org.kaaproject.kaa.client.KaaClient;
import org.kaaproject.kaa.schema.sample.notification.Notification;

...
BasicNotificationListener specificListener = new BasicNotificationListener();
// Add listener
kaaClient.addNotificationListener("All devices notifications", listener);
...
// Remove listener
kaaClient.removeNotificationListener("All devices notifications", listener);
```

```c++
#include <memory>
#include <kaa/Kaa.hpp>

...

// Create the listener which receives notifications on the specified optional topic.
std::unique_ptr<BasicNotificationListener> listener(new BasicNotificationListener());

// Add listener
kaaClient->addNotificationListener(1, *listener);

// Remove listener
kaaClient->removeNotificationListener(1, *listener);
```

```c
#include <extensions/notification/kaa_notification_manager.h>
#include <kaa/platform/ext_notification_receiver.h>

// Assume we have some topic
uint64_t topic_id = 12345;
kaa_notification_listener_t notification_listener = { &on_notification, NULL };
uint32_t notification_listener_id = 0;

// Add listener
kaa_error_t error_code = kaa_add_optional_notification_listener(kaa_client_get_context(kaa_client)->notification_manager, &notification_listener, &topic_id, &notification_listener_id);

// Remove listener
error_code = kaa_remove_optional_notification_listener(kaa_client_get_context(kaa_client)->notification_manager, &topic_id, &notification_listener_id);
```

```objc
@import Kaa;

...
// Add listener
[kaaClient addNotificationDelegate:self forTopicId:@"All devices notifications"];
...
// Remove listener
[kaaClient removeNotificationDelegate:self forTopicId:@"All devices notifications"];
```


text:
package com.GuoGuo.JuicyChat.server.request;

/**
 * Created by AMing on 15/12/24.
 * Company RongCloud
 */
public class LoginRequest {

	private String account;
	private String password;

	public LoginRequest(String account, String password) {
		this.account = account;
		this.password = password;
	}

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}


text:
//
//  RoomTemperatureRule.hpp
//  HomeControl
//
//  Created by Bartłomiej on 23/01/17.
//  Copyright © 2017 Imagination Systems. All rights reserved.
//

#ifndef RoomTemperatureRule_hpp
#define RoomTemperatureRule_hpp

#include <stdio.h>
#include "logic/rules/LogicRule.hpp"
#include "logic/Logic.hpp"

class RoomTemperatureRule : public LogicRule {
  public:
    RoomTemperatureRule(shared_ptr<Logic> logic, string stoveStateName);

    void setStoveStateName(const string& name);
    virtual void execute() override;
  private:
    shared_ptr<Logic> logic;
    string stoveStateName;

    double getTemperatureInRoom(shared_ptr<Room> room, bool& measured);
};

#endif /* RoomTemperatureRule_hpp */