text:
"""Model classes for app_text

Customizing the templates for application specific needs can be done
at several levels.  This module houses tables used to generate
app specific strings.  Values are imported and exported through the
SitePersistence mechanism, and looked up in a template using the
`app_text(string)` method.

"""

from abc import ABCMeta, abstractmethod
from builtins import str
from string import Formatter
import timeit
from urllib.parse import parse_qsl, urlencode, urlparse

from flask import current_app
from flask_babel import gettext
import requests
from requests.exceptions import ConnectionError, InvalidURL, MissingSchema

from ..cache import FIVE_MINS, cache
from ..database import db

def time_request(url, params=None):
    """Wrap the requests.get(url) and log the timing"""
    start = timeit.default_timer()
    response = requests.get(url, params)
    duration = timeit.default_timer() - start
    message = ('TIME {duration:.4f} seconds to GET {url}'.format(
        url=url, duration=duration))
    if duration > 5.0:
        current_app.logger.error(message)
    elif duration > 2.0:
        current_app.logger.warning(message)
    else:
        current_app.logger.debug(message)
    return response

def get_terms(locale_code, org=None, role=None, research_study_id=0):
    """Shortcut to lookup correct terms given org and role"""
    if org:
        try:
            terms = VersionedResource(
                app_text(WebsiteConsentTermsByOrg_ATMA.name_key(
                    organization=org, role=role,
                    research_study_id=research_study_id)),
                locale_code=locale_code)
        except UndefinedAppText:
            terms = VersionedResource(
                app_text(InitialConsent_ATMA.name_key()),
                locale_code=locale_code)

    else:
        terms = VersionedResource(
            app_text(InitialConsent_ATMA.name_key()),
            locale_code=locale_code)

    return terms

def localize_url(url, locale_code):
    """Append language tag to URL and return"""
    if not locale_code:
        return url
    if url and 'languageId' not in url:
        delimiter = '&' if '?' in url else '?'
        return "{url}{delimiter}languageId={locale_code}".format(
            url=url, delimiter=delimiter, locale_code=locale_code)
    return url

class AppText(db.Model):
    """Model representing application specific strings for customization

    The portal (shared services) can be configured to support a number
    of specific sites.  This class provides a mechanism to store and lookup
    any text string needing to be customized.

    """
    __tablename__ = 'apptext'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text, unique=True, nullable=False)
    custom_text = db.Column(db.Text, nullable=True)

    def __repr__(self):
        return "{} ({}, {})".format(self.__class__.__name__,
                                    self.name, self)

    def __str__(self):
        if self.custom_text:
            return self.custom_text
        return self.name

    def __unicode__(self):
        if self.custom_text:
            return self.custom_text
        return self.name

    @classmethod
    def from_json(cls, data):
        app_text = cls()
        return app_text.update_from_json(data)

    def update_from_json(self, data):
        if 'name' not in data:
            raise ValueError("missing required 'name' field")
        if 'id' in data:
            self.id = data['id']
        self.name = data['name']
        self.custom_text = data.get('custom_text')
        return self

    def as_json(self):
        d = {}
        d['resourceType'] = 'AppText'
        d['name'] = self.name
        if self.custom_text:
            d['custom_text'] = self.custom_text
        return d

class AppTextModelAdapter(object, metaclass=ABCMeta):
    """Several special purpose patterns used for lookups

    Make access consistent and easy for model classes where appropriate

    Abstract base class - defining methods each model adapter needs
    """

    @abstractmethod
    def name_key(**kwargs):
        """Return the named key as used by AppText for the type"""
        raise NotImplemented

class ConsentByOrg_ATMA(AppTextModelAdapter):
    """AppTextModelAdapter for Consent agreements - namely the URL per org"""

    @staticmethod
    def name_key(**kwargs):
        """Generate AppText name key for a consent agreement

        :param organization: for which the consent agreement applies
        :returns: string for AppText.name field

        """
        organization = kwargs.get('organization')
        if not organization:
            raise ValueError("required organization parameter not defined")
        return "{} organization consent URL".format(organization.name)

class WebsiteConsentTermsByOrg_ATMA(AppTextModelAdapter):
    @staticmethod
    def name_key(**kwargs):
        """Generate AppText name key for website consent terms

        :param organization: for which the consent agreement applies
        :param role: for specific role selections, but only if
          it makes sense.  (i.e. on ePROMs, staff see different content)

        :returns: string for AppText.name field

        """
        from .research_study import ResearchStudy

        default = "patient website consent URL"

        # try research study first
        research_study_id = kwargs.get('research_study_id', 0)
        research_study = ResearchStudy.query.get(research_study_id)
        study_title = research_study.title if research_study else ""
        specialized = " ".join((study_title, default))
        query = AppText.query.filter_by(name=specialized)
        if query.count() == 1:
            return specialized

        organization = kwargs.get('organization')
        if not organization:
            raise ValueError("required organization parameter not defined")

        role = kwargs.get('role')
        if role:
            return "{} {} website consent URL".format(
                organization.name, role)
        return "{} organization website consent URL".format(organization.name)

class InitialConsent_ATMA(AppTextModelAdapter):
    """AppTextModelAdapter for Initial Consent Terms"""

    @staticmethod
    def name_key(**kwargs):
        """Generate AppText name key for a Initial Consent Terms

        Not expecting any args at this time - may specialize per study
        or organization in the future as needed.

        :returns: string for AppText.name field

        """
        return "Initial Consent Terms URL"

class Terms_ATMA(AppTextModelAdapter):
    """AppTextModelAdapter for Terms Of Use agreements, used for /terms"""

    @staticmethod
    def name_key(**kwargs):
        """Generate AppText name key for a Terms and Conditions

        :param organization: optional, present in tandem to role parameter
        :param role: optional, role of the user
        :returns: string for AppText.name field

        """
        if kwargs.get('organization') and kwargs.get('role'):
            return "{} {} terms and conditions URL". \
                format(kwargs.get('organization').name, kwargs.get('role'))
        elif kwargs.get('role'):
            return "{} terms and conditions URL".format(kwargs.get('role'))
        return "Terms and Conditions URL"

class WebsiteDeclarationForm_ATMA(AppTextModelAdapter):
    """AppTextModelAdapter for Website Declaraion Form"""

    @staticmethod
    def name_key(**kwargs):
        """Generate AppText name key for a Website Declaration Form

        :param organization: required
        :returns: string for AppText.name field

        """
        if not kwargs.get('organization'):
            raise ValueError("required 'organization' parameter not defined")
        else:
            return "{} website declaration form URL". \
                format(kwargs.get('organization').name)

class StaffRegistrationEmail_ATMA(AppTextModelAdapter):
    """AppTextModelAdapter for Staff Registration Email Content"""

    @staticmethod
    def name_key(**kwargs):
        """Generate AppText name key for a Website Declaration Form

        :param organization: required
        :returns: string for AppText.name field

        """
        if not kwargs.get('organization'):
            raise ValueError("required 'organization' parameter not defined")
        else:
            return "{} staff registraion email URL". \
                format(kwargs.get('organization').name)

class UserInviteEmail_ATMA(AppTextModelAdapter):
    """AppTextModelAdapter for User Invite Email Content"""

    @staticmethod
    def name_key(**kwargs):
        """Generate AppText name key for User Invite Email Content

        Some organizations and research studies supply customized content,
        which is indexed by adding the org or study name to the end of the
        app_text pattern.
        `patient invite email`

        :param org: Typically top level org name - used to look for
         customized content.
        :param research_study_id: Optionally included for studies with
         tailored content.  If provided, the study is consulted FIRST.

        :returns: string for AppText.name field

        """
        from .research_study import ResearchStudy
        default = "patient invite email"
        # First try the study (if provided)
        if kwargs.get('research_study_id'):
            study_title = ResearchStudy.query.get(
                kwargs.get('research_study_id')).title
            specialized = " ".join((default, study_title))
            query = AppText.query.filter_by(name=specialized)
            if query.count() == 1:
                return specialized

        # See if content is available with the given org as the suffix
        if kwargs.get('org'):
            specialized = " ".join((default, kwargs.get('org')))
            query = AppText.query.filter_by(name=specialized)
            if query.count() == 1:
                return specialized
        return default

class UserReminderEmail_ATMA(AppTextModelAdapter):
    """AppTextModelAdapter for User Reminder Email Content"""

    @staticmethod
    def name_key(**kwargs):
        """Generate AppText name key for User Reminder Email Content

        Some organizations supply customized content - which is indexed
        by adding the org name to the end of the app_text pattern
        `patient reminder email`

        :param org: Typically top level org name - used to look for
        customized content.

        :returns: string for AppText.name field

        """
        default = "patient reminder email"
        # See if content is available with the given org as the suffix
        if kwargs.get('org'):
            specialized = " ".join((default, kwargs.get('org')))
            query = AppText.query.filter_by(name=specialized)
            if query.count() == 1:
                return specialized
        return default

class SiteSummaryEmail_ATMA(AppTextModelAdapter):
    """AppTextModelAdapter for Site Summary Email Content"""

    @staticmethod
    def name_key(**kwargs):
        """Generate AppText name key for Site Summary Email Content

        Not expecting any args at this time - may specialize per study
        or organization in the future as needed.

        :returns: string for AppText.name field

        """
        # If there's an org specialized version, use it.
        if kwargs.get('org'):
            specialized = "site summary email {}".format(kwargs.get('org'))

        query = AppText.query.filter_by(name=specialized)
        if query.count() == 1:
            return specialized

        return "site summary email"

class AboutATMA(AppTextModelAdapter):
    """AppTextModelAdapter for `About` - namely the URL"""

    @staticmethod
    def name_key(**kwargs):
        """Generate AppText name key for `about` URL

        :param subject: required subject, i.e. 'TrueNTH' or 'Movember'
        :returns: string for AppText.name field

        """
        if not kwargs.get('subject'):
            raise ValueError("required 'subject' parameter not defined")
        return "About {} URL".format(kwargs.get('subject'))

class PrivacyATMA(AppTextModelAdapter):
    """AppTextModelAdapter for Privacy - namely the URL"""

    @staticmethod
    def name_key(**kwargs):
        """Generate AppText name key for privacy URL

        :param organization: optional, present in tandem to role
        :param role: optional
        :returns: string for AppText.name field

        """
        if kwargs.get('organization') and not kwargs.get('role'):
            raise ValueError("'role' parameter not defined")
        elif kwargs.get('role') and not kwargs.get('organization'):
            raise ValueError("'organization' parameter not defined")
        elif kwargs.get('organization') and kwargs.get('role'):
            return "{} {} privacy URL".format(
                kwargs.get('organization').name, kwargs.get('role'))
        return "Privacy URL"

class UnversionedResource(object):
    "Like VersionedResource for non versioned URLs (typically local)"

    def __init__(self, url, asset=None, variables=None):
        """Initialize based on requested URL

        Attempts to fetch asset and mock a versioned URL

        :param url: the URL to pull details and asset from
        :param asset: if given, use as asset, otherwise, download

        :attribute asset: will contain the html asset downloaed, found in the
            cache, or the error message if that fails.
        :attribute editor_url: always None
        :attribute url: the original url.

        """
        self._asset, self.error_msg, self.editor_url = None, None, None
        self.url = url
        self.variables = variables or {}
        if asset:
            self._asset = str(asset)
        else:
            try:
                response = time_request(url)
                self._asset = response.text
            except (MissingSchema, InvalidURL):
                if current_app.config.get('TESTING'):
                    self._asset = '[TESTING - fake response]'
                else:
                    self.error_msg = (
                        "Could not retrieve remote content - Invalid URL")
            except ConnectionError:
                self.error_msg = (
                    "Could not retrieve remove content - Server could not be "
                    "reached")

        if self.error_msg:
            current_app.logger.error(self.error_msg + ": {}".format(url))

    @property
    def asset(self):
        """Return asset if available else error message"""
        if self._asset:
            try:
                return self._asset.format(**self.variables)
            except KeyError as e:
                self.error_msg = "Missing asset variable {}".format(e)
                current_app.logger.error(self.error_msg +
                                         ": {}".format(self.url))
        return self.error_msg

class VersionedResource(object):
    """Helper to manage versioned resource URLs (typically on Liferay)"""

    def __init__(self, url, locale_code, variables=None):
        """Initialize based on requested URL

        Attempts to fetch the asset, permanent version of URL and link
        for content editing.

        In the event of an error, details are logged, and self.error_msg
        will be defined, and returned in a request for the asset attribute.

        :param url: the URL to pull details and asset from
        :param locale_code: typically the user's preferred language

        :attribute asset: will contain the html asset downloaed, found in the
            cache, or the error message if that fails.
        :attribute editor_url: defined if such was available, else None
        :attribute url: the `permanent url` for the resource if available,
            otherwise the original url.

        """
        self._asset, self.error_msg, self.editor_url = None, None, None
        self.url = localize_url(url, locale_code)
        self.variables = variables or {}
        try:
            response = time_request(self.url)
            self._asset = response.json().get('asset')
            self.url = self._permanent_url(
                generic_url=self.url, version=response.json().get('version'))
            self.editor_url = response.json().get('editorUrl')
        except (MissingSchema, InvalidURL):
            if current_app.config.get('TESTING'):
                self._asset = '[TESTING - fake response]'
            else:
                self.error_msg = (
                    "Could not retrieve remote content - Invalid URL")
        except ValueError:  # raised when no json is available in response
            if response.status_code == 200:
                self._asset = response.text
            else:
                self.error_msg = (
                    "Could not retrieve remote content - " "{} {}".format(
                        response.status_code, response.reason))
        except ConnectionError:
            self.error_msg = (
                "Could not retrieve remove content - Server could not be "
                "reached")

        if self.error_msg:
            current_app.logger.error(self.error_msg + ": {}".format(self.url))

    @property
    def asset(self):
        """Return asset if available else error message"""
        if self._asset:
            try:
                return self._asset.format(**self.variables)
            except KeyError as e:
                self.error_msg = "Missing asset variable {}".format(e)
                current_app.logger.error(self.error_msg +
                                         ": {}".format(self.url))
        return self.error_msg

    def _permanent_url(self, generic_url, version):
        """Produce a permanent url from the metadata provided

        Resources are versioned - but the link maintained in the app_text
        table is not.

        When requesting the detailed resource, the effective version number is
        returned.  This method returns a permanent URL including the version
        number, useful for audit and tracking information.

        """
        parsed = urlparse(generic_url)
        qs = dict(parse_qsl(parsed.query))
        if version:
            qs['version'] = version

        path = parsed.path
        if path.endswith('/detailed'):
            path = path[:-(len('/detailed'))]
        format_dict = {
            'scheme': parsed.scheme,
            'netloc': parsed.netloc,
            'path': path,
            'qs': urlencode(qs)}
        url = "{scheme}://{netloc}{path}?{qs}".format(**format_dict)
        return url

class MailResource(object):
    """Helper to manage versioned mail resource URLs (typically on Liferay)"""

    def __init__(self, url, locale_code, variables=None):
        """Initialize based on requested URL

        Attempts to fetch the mail fields, permanent version of URL and link
        for content editing.

        In the event of an error, details are logged, and self.error_msg
        will be defined, and returned in a request for the asset attribute.

        :param url: the URL to pull details and asset from
        :param locale_code: typically the user's preferred language

        :attribute subject: will contain the email subject download, found
            in the cache, or the error message if that fails.
        :attribute body: will contain the email subject body, found
            in the cache, or the error message if that fails.
        :attribute editor_url: defined if such was available, else None
        :attribute url: the `permanent url` for the resource if available,
            otherwise the original url.

        """
        self._subject, self._body, self._footer = None, None, None
        self.error_msg, self.editor_url = None, None
        self.url = localize_url(url, locale_code)
        self.variables = variables or {}
        try:
            response = time_request(self.url)
            self._subject = response.json().get('subject')
            self._body = response.json().get('body')
            if current_app.config.get("DEBUG_EMAIL", False):
                self._body += '{debug_slot}'
            self._footer = response.json().get('footer')
            self.url = self._permanent_url(
                generic_url=self.url, version=response.json().get('version'))
            self.editor_url = response.json().get('editorUrl')
        except (MissingSchema, InvalidURL):
            if current_app.config.get('TESTING'):
                self._subject = 'TESTING SUBJECT'
                self._body = 'TESTING BODY'
                self._footer = 'TESTING FOOTER'
            else:
                self.error_msg = (
                    "Could not retrieve remote content - Invalid URL")
        except ValueError:  # raised when no json is available in response
            if response.status_code == 200:
                self._subject = response.text
                self._body = response.text
            else:
                self.error_msg = (
                    "Could not retrieve remote content - " "{} {}".format(
                        response.status_code, response.reason))
        except ConnectionError:
            self.error_msg = (
                "Could not retrieve remove content - Server could not be "
                "reached")

        if self.error_msg:
            current_app.logger.error(self.error_msg + ": {}".format(self.url))

    @property
    def subject(self):
        """Return subject if available else error message"""
        if self._subject:
            try:
                if hasattr(self.variables, 'minimal_subdict'):
                    formatted = (self._subject).format(
                        **self.variables.minimal_subdict(self._subject))
                else:
                    formatted = (self._subject).format(**self.variables)
                return formatted
            except KeyError as e:
                self.error_msg = "Missing subject variable {}".format(e)
                current_app.logger.error(self.error_msg +
                                         ": {}".format(self.url))
                raise
        raise ValueError(self.error_msg)

    @property
    def body(self):
        """Return body if available else error message"""
        if self._body:
            try:
                if hasattr(self.variables, 'minimal_subdict'):
                    formatted = (self._body).format(
                        **self.variables.minimal_subdict(self._body))
                else:
                    formatted = (str(self._body)).format(**self.variables)
                if self._footer:
                    formatted += "\n"
                    formatted += self.footer
                return formatted
            except KeyError as e:
                self.error_msg = "Missing body variable {}".format(e)
                current_app.logger.error(self.error_msg +
                                         ": {}".format(self.url))
                raise
        raise ValueError(self.error_msg)

    @property
    def footer(self):
        """Return optional footer if available"""
        if self._footer:
            try:
                if hasattr(self.variables, 'minimal_subdict'):
                    formatted = (self._footer).format(
                        **self.variables.minimal_subdict(self._footer))
                else:
                    formatted = (self._footer).format(**self.variables)
                return formatted
            except KeyError as e:
                self.error_msg = "Missing footer variable {}".format(e)
                current_app.logger.error(self.error_msg +
                                         ": {}".format(self.url))
                raise

    @property
    def variable_list(self):
        var_list = set()
        if self._subject:
            var_list.update(
                [v[1] for v in Formatter().parse(self._subject) if v[1]])
        if self._body:
            var_list.update(
                [v[1] for v in Formatter().parse(self._body) if v[1]])
        if self._footer:
            var_list.update(
                [v[1] for v in Formatter().parse(self._footer) if v[1]])
        return list(var_list)

    def _permanent_url(self, generic_url, version):
        """Produce a permanent url from the metadata provided

        Resources are versioned - but the link maintained in the app_text
        table is not.

        When requesting the detailed resource, the effective version number is
        returned.  This method returns a permanent URL including the version
        number, useful for audit and tracking information.

        """
        parsed = urlparse(generic_url)
        qs = dict(parse_qsl(parsed.query))
        if version:
            qs['version'] = version

        path = parsed.path
        if path.endswith('/detailed'):
            path = path[:-(len('/detailed'))]
        format_dict = {
            'scheme': parsed.scheme,
            'netloc': parsed.netloc,
            'path': path,
            'qs': urlencode(qs)}
        url = "{scheme}://{netloc}{path}?{qs}".format(**format_dict)
        return url

class UndefinedAppText(Exception):
    """Exception raised when requested AppText isn't defined"""
    pass

@cache.memoize(timeout=FIVE_MINS)
def app_text(name, *args):
    """Look up and return customized application text string

    May be embedded directly in jinja2 templates.  Call `app_text()`
    with the 'name' to uniquely identify the custom string to lookup
    and return.

    Custom strings may contain an arbitrary number of additional parameters.
    They should be embedded as zero indexed curly brackets for inclusion.

    For example, given AppText(name='ex', custom_text='Hello {0}. {1} {0}'), a
    call to `app_text('ex', 'Bob', 'Gooday')` would return:
        'Hello Bob. Gooday Bob'

    Custom strings may also reference configuration variables.  For example,
    to include the configured value of USER_APP_NAME in the custom_text,
    given:
        AppText(name='config example',
                custom_text='Welcome to {config[USER_APP_NAME]}")

    a call to `app_text('config example')` would produce something like:
        'Welcome to TrueNTH'

    NB javascript variables are not evaluated till the client browser sees
    the page, therefore any javascript variables will not be available in time
    for app_text() to use them.

    :raises UndefinedAppText: if the `name` isn't found.

    """
    item = AppText.query.filter_by(name=name).first()
    if not item:
        if current_app.config.get('TESTING'):
            return "[TESTING - ignore missing app_text '{}']".format(name)
        raise UndefinedAppText(
            "unknown customized app string '{}'".format(name))

    text = str(item)
    try:
        if 'config[' in text:
            return gettext(text.format(*args, config=current_app.config))
        return gettext(text.format(*args))
    except IndexError:
        if not args:
            args = ('<None>',)
        raise ValueError(
            "AppText with name '{}' defines more parameters "
            "than provided: `{}`".format(name, *args))


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

using System;
using iSynaptic.Modeling.Domain;

namespace iSynaptic.TestDomain
{
    // This is a poor example of an aggregate since it is devoid of much logic and exposes state.
    // It exists only to facilitate testing of the framework around aggregates
    public partial class HomogeneousRole<TRoleIdentifier> : IHomogeneousRole<TRoleIdentifier>
    {
        public HomogeneousRole(TRoleIdentifier id, String name)
        {
            ApplyRegistered(name, id);
        }

        public void StartApproval()
        {
            ApplyStatusChanged(HomogeneousRoleStatus.PendingApproval);
        }

        public void Approve()
        {
            ApplyStatusChanged(HomogeneousRoleStatus.Approved);
        }

        public void Retire()
        {
            ApplyStatusChanged(HomogeneousRoleStatus.Retired);
        }

        private void On(Registered @event)
        {
            Name = @event.Name;
            Status = HomogeneousRoleStatus.New;
        }

        private void On(StatusChanged @event)
        {
            Status = @event.Status;
        }

        // these exists ONLY for testing purposes; aggregates should not expose state
        public String Name { get; private set; }
        public HomogeneousRoleStatus Status { get; private set; }
    }

    public interface IHomogeneousRole<out TRoleIdentifier> : IAggregate<TRoleIdentifier>
        where TRoleIdentifier : RoleIdentifier, IEquatable<TRoleIdentifier>
    {
        void StartApproval();
        void Approve();
        void Retire();

        // these exists ONLY for testing purposes; aggregates should not expose state
        String Name { get; }
        HomogeneousRoleStatus Status { get; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<component name="libraryTable">
  <library name="Maven: org.jboss.shrinkwrap.descriptors:shrinkwrap-descriptors-spi:2.0.0-alpha-8">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/org/jboss/shrinkwrap/descriptors/shrinkwrap-descriptors-spi/2.0.0-alpha-8/shrinkwrap-descriptors-spi-2.0.0-alpha-8.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/org/jboss/shrinkwrap/descriptors/shrinkwrap-descriptors-spi/2.0.0-alpha-8/shrinkwrap-descriptors-spi-2.0.0-alpha-8-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/org/jboss/shrinkwrap/descriptors/shrinkwrap-descriptors-spi/2.0.0-alpha-8/shrinkwrap-descriptors-spi-2.0.0-alpha-8-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
public class Solution {
    public String convertToTitle(int n) {
        StringBuilder res = new StringBuilder();
        while(n > 0) {
            n--;
            res.insert(0, (char) (n % 26 + 'A'));
            n /= 26;
        }
        return res.toString();
    }
}


text:
import {GET_ARTICLE, GET_ARTICLE_FAILURE, CLEAR_ARTICLE} from '../mutation-types'

const state = {
  content: '',
  title: ''
}

const mutations = {

  [GET_ARTICLE] (state, data) {
    state.content = data.content
    state.title = data.title
  },
  [GET_ARTICLE_FAILURE] (state) {
    return state
  },
  [CLEAR_ARTICLE] (state) {
    state.content = ''
    state.title = ''
  }
}

export default {
  state,
  mutations
}


text:
require 'test_helper'

class Users::OmniauthCallbacksControllerTest < ActionController::TestCase
  include Devise::TestHelpers

  setup do
    request.env["devise.mapping"] = Devise.mappings[:user]
    request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:github]
  end

  test "make user feel good when legit email address" do
    stub_oauth_user('legit@legit.com')
    get :github
    assert flash[:notice] == I18n.t("devise.omniauth_callbacks.success",
                                    :kind => "GitHub")
  end

  test "redirect to user page and inform when bad e-mail address" do
    user = stub_oauth_user('awful e-mail address')
    get :github
    assert flash[:notice] == I18n.t("devise.omniauth_callbacks.bad_email_success",
                                    :kind => "GitHub")
    assert_redirected_to edit_user_path(user)
  end

  def stub_oauth_user(email)
    user = User.new(:email => email)
    user.stubs(:persisted?).returns(true)
    User.stubs(:find_for_github_oauth).returns(user)
    user
  end
end


text:
var config = require('config.json');
var express = require('express');
var router = express.Router();
var questionService = require('services/question.service');

// routes
router.post('/addQ', addQuestion);
router.get('/getQ', getQuestion);

module.exports = router;

function getQuestion() {
    questionService.getQuestion()
        .then(function (question) {
            if (question) {
                res.send(question);
            } else {
                res.sendStatus(404);
            }
        })
        .catch(function (err) {
            res.status(400).send(err);
        });
}

function addQuestion(req, res) {
    questionService.addQuestion(req.body)
        .then(function () {
            res.sendStatus(200);
        })
        .catch(function (err) {
            res.status(400).send(err);
        });
}


text:
============================
OSPC Multi-Country Tax Model
============================

This repository includes the data used to calibrate the model along with all the necessary Python code to solve and simulate.

The Model
=========
This project builds, calibrates and simulates the effects of changes in various taxes on multiple economies in the context of a dynamic overlapping generations general equilibrium model.  This project builds on the work of Fehr et al. (2008), Fehr et al. (2011), Fehr et al. (2013) and Benzell et al. (2015).  Laurence J. Kotlikoff of Boston University has been a major contributor to those papers and to this project.

Disclaimer
==========
The model is currently under development. Users should be forewarned that the model componenents could change significantly. Therefore, there is NO GUARANTEE OF ACCURACY. THE CODE SHOULD NOT CURRENTLY BE USED FOR PUBLICATIONS, JOURNAL ARTICLES, OR RESEARCH PURPOSES. Essentially, you should assume the calculations are unreliable until we finish the code re-architecture and have checked the results against other existing implementations of the tax code. The package will have released versions, which will be checked against existing code prior to release. Stay tuned for an upcoming release!

Current Contributors
====================

- Richard W. Evans (University of Chicago)

- James Olmstead (Brigham Young University)

- Kerk Phillips (Brigham Young University)

Contributors to Earlier Work
============================

- Seth Benzell (Boston University)

- Jeff Clawson (University of Maryland)

- Laurence J. Kotlikoff (Boston University)

- Keena Li (Brigham Young University)

About OSPC
==========
The Open-Source Policy Center (OSPC) seeks to make policy analysis more transparent, trustworthy, and collaborative by harnessing open-source methods to build cutting-edge economic models.


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.3.1"/>
<title>Rdio.framework: Main Page</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Rdio.framework

Main Page

Related Pages

Data Structures

Files

Rdio.framework Documentation

The Rdio iOS SDK lets developers call the web service API, authenticate users, and play full song streams or 30 second samples.

 To get started:

Visit http://developer.rdio.com to register a developer account and apply for a key

Download the sample app

Download the framework

Drag the Rdio framework into your XCode project

Add the following frameworks to your project:

CoreGraphics

CFNetwork

CoreMedia

SystemConfiguration

AudioToolbox

Security

Add -all_load under Other Linker Flags in the project build info

Try the following code in your app delegate:

#import <Rdio/Rdio.h>

Rdio *rdio = [[Rdio alloc] initWithConsumerKey:@"YOUR KEY" andSecret:@"YOUR SECRET" delegate:nil];

[rdio.player playSource:@"t2742133"];

Please direct feature requests and bug reports to Developer Support or the Rdio API Google Group.

<address class="footer">
Generated on Fri Jun 21 2013 10:30:25 for Rdio.framework by

 1.8.3.1
</address>


text:
<?php

namespace App\Controller;

use Cake\Controller\Controller;
use Cake\Event\Event;

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @link http://book.cakephp.org/3.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {

    /**
     * Initialization hook method.
     *
     * Use this method to add common initialization code like loading components.
     *
     * e.g. `$this->loadComponent('Security');`
     *
     * @return void
     */
    public function initialize() {
        parent::initialize();

        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');
        $this->loadComponent('Auth', [
            'authorize' => ['Controller'],
            'authenticate' => [
                'Form' => [
                    'fields' => [
                        'username' => 'email',
                        'password' => 'password'
                    ],
                    'finder' => 'auth'
                ]
            ],
            'loginAction' => [
                'controller' => 'Users',
                'action' => 'login'
            ],
            'authError' => '',
            'loginRedirect' => [
                'controller' => 'Users',
                'action' => 'home'
            ],
            'logoutRedirect' => [
                'controller' => 'Users',
                'action' => 'login'
            ],
            'unauthorizedRedirect' => $this->referer()
        ]);
    }

    /**
     * Before render callback.
     *
     * @param \Cake\Event\Event $event The beforeRender event.
     * @return \Cake\Network\Response|null|void
     */
    public function beforeRender(Event $event) {
        if (!array_key_exists('_serialize', $this->viewVars) &&
                in_array($this->response->type(), ['application/json', 'application/xml'])
        ) {
            $this->set('_serialize', true);
        }
    }

    public function beforeFilter(Event $event) {
        $this->set('current_user', $this->Auth->user());
    }

    public function isAuthorized($user) {
        if (isset($user['role']) and $user['role'] === 'admin') {
            return true;
        }

        return false;
    }

}


text:
import {Rx} from '@cycle/core';
import {h} from '@cycle/web';
import {propHook} from '../utils';

function vrenderHeader(todosData) {
  return h('header#header', [
    h('h1', 'todos'),
    h('input#new-todo', {
      type: 'text',
      value: '',
      attributes: {placeholder: 'What needs to be done?'},
      autofocus: true,
      name: 'newTodo'
    })
  ]);
}

function vrenderMainSection(todosData) {
  let allCompleted = todosData.list.reduce((x, y) => x && y.completed, true);
  return h('section#main', {
    style: {'display': todosData.list.length ? '' : 'none'}
  }, [
    h('input#toggle-all', {
      type: 'checkbox',
      checked: allCompleted
    }),
    h('ul#todo-list', todosData.list
      .filter(todosData.filterFn)
      .map(todoData =>
        h('todo-item.todo-item', {
          key: todoData.id,
          todoid: todoData.id,
          content: todoData.title,
          completed: todoData.completed
        })
      )
    )
  ])
}

function vrenderFooter(todosData) {
  let amountCompleted = todosData.list
    .filter(todoData => todoData.completed)
    .length;
  let amountActive = todosData.list.length - amountCompleted;
  return h('footer#footer', {
    style: {'display': todosData.list.length ? '' : 'none'}
  }, [
    h('span#todo-count', [
      h('strong', String(amountActive)),
      ' item' + (amountActive !== 1 ? 's' : '') + ' left'
    ]),
    h('ul#filters', [
      h('li', [
        h('a' + (todosData.filter === '' ? '.selected' : ''), {
          attributes: {'href': '#/'}
        }, 'All')
      ]),
      h('li', [
        h('a' + (todosData.filter === 'active' ? '.selected' : ''), {
          attributes: {'href': '#/active'}
        }, 'Active')
      ]),
      h('li', [
        h('a' + (todosData.filter === 'completed' ? '.selected' : ''), {
          attributes: {'href': '#/completed'}
        }, 'Completed')
      ])
    ]),
    (amountCompleted > 0 ?
      h('button#clear-completed', 'Clear completed (' + amountCompleted + ')')
      : null
    )
  ])
}

export default function view(todos$) {
  return {
    DOM: todos$.map(todos =>
      h('div', [
        vrenderHeader(todos),
        vrenderMainSection(todos),
        vrenderFooter(todos)
      ])
    )
  };
};


text:
import './toast-sk';
import './toast-sk.scss';


text:
/**
 * Homepage selectors
 */

import { createSelector } from 'reselect';

const selectMapPage = (state) => state.get('mapPage');

const makeSelectLoaded = () => createSelector(
  selectMapPage,
  (MapPageState) => MapPageState.get('loaded')
);

const makeSelectMap = () => createSelector(
  selectMapPage,
  (MapPageState) => MapPageState.get('map')
);

const makeSelectGoogle = () => createSelector(
  selectMapPage,
  (MapPageState) => MapPageState.get('google')
);

const makeSelectCategories = () => createSelector(
  selectMapPage, // eslint-disable-line
  (MapPageState) => MapPageState.get('categories')
);

const makeSelectCategoryForDirections = () => createSelector(
  selectMapPage, // eslint-disable-line
  (MapPageState) => MapPageState.get('categoryForDirections')
);

const makeSelectSearchResults = () => createSelector(
  selectMapPage, // eslint-disable-line
  (MapPageState) => MapPageState.get('searchResults')
);

const makeSelectDirectionResults = () => createSelector(
  selectMapPage, // eslint-disable-line
  (MapPageState) => MapPageState.get('directionResults')
);

export {
  selectMapPage,
  makeSelectLoaded,
  makeSelectMap,
  makeSelectGoogle,
  makeSelectCategories,
  makeSelectCategoryForDirections,
  makeSelectSearchResults,
  makeSelectDirectionResults,
};


text:
package org.openfact.ubl.ubl21.invoice;

import oasis.names.specification.ubl.schema.xsd.invoice_21.InvoiceType;
import org.openfact.ubl.UBLCustomizator;

public interface UBLInvoiceCustomizatorFactory<T extends InvoiceType> extends UBLCustomizator<T> {
}


text:
package pl.dpawlak.flocoge.generator;

import static org.mockito.Mockito.mock;
import static pl.dpawlak.flocoge.model.TestModels.*;
import static pl.dpawlak.flocoge.generator.TestCodeModels.*;

import org.junit.Test;

import pl.dpawlak.flocoge.config.Configuration;
import pl.dpawlak.flocoge.generator.util.TestCodeModel;
import pl.dpawlak.flocoge.generator.util.TestCodeModelsMatchingValidator;
import pl.dpawlak.flocoge.log.Logger;
import pl.dpawlak.flocoge.model.FlocogeModel;

public class CodeGeneratorTest {

    @Test
    public void testFileCodeModelGeneration() throws CodeGenerationException {
        generateAndValidate(createTestFileModelTransformed(), createTestFileCodeModel());
    }

    @Test
    public void testComplexCodeModelGeneration() throws CodeGenerationException {
        generateAndValidate(createTransformedComplexModel(), createComplexCodeModel());
    }

    @Test
    public void testAdditionalCodeModelGeneration() throws CodeGenerationException {
        generateAndValidate(createTransformedAdditionalModel(), createAdditionalCodeModel());
    }

    @Test
    public void testGenerationWithEmptyIf() throws CodeGenerationException {
        generateAndValidate(createTransformedModelWithEmptyIf(), createCodeModelWithEmptyIf());
    }

    @Test
    public void testGenerationWithEmptyElse() throws CodeGenerationException {
        generateAndValidate(createTransformedModelWithEmptyElse(), createCodeModelWithEmptyElse());
    }

    @Test
    public void testGenerationWithEmptyIfAndElse() throws CodeGenerationException {
        generateAndValidate(createTransformedModelWithEmptyIfAndElse(), createCodeModelWithEmptyIfAndElse());
    }

    private void generateAndValidate(FlocogeModel model, TestCodeModel expectedCodeModel)
            throws CodeGenerationException {
        TestCodeModel codeModel = new TestCodeModel();
        new CodeGenerator(mock(Configuration.class), mock(Logger.class), codeModel).generate(model);
        new TestCodeModelsMatchingValidator(expectedCodeModel, codeModel).validate();
    }
}


text:
/*
Package maputil provides tools and utilites for maps, e.g. ordered serialization.
*/
package maputil


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>CoderDeck Sample</title>
	<meta name="viewport" content="width=1024">

	<link rel="stylesheet" href="src/deck.js/core/deck.core.css" type="text/css">

	<link rel="stylesheet" href="src/deck.js/extensions/navigation/deck.navigation.css">
	<link rel="stylesheet" href="src/deck.js/extensions/status/deck.status.css">
	<link rel="stylesheet" href="src/deck.js/extensions/hash/deck.hash.css">
	<link rel="stylesheet" href="src/deck.js/extensions/menu/deck.menu.css">
	<link rel="stylesheet" href="src/css/prettify.css">
	<link rel="stylesheet" href="src/css/deck.coder.css">

	<link rel="stylesheet" id='style-theme-link' href="src/css/coderdeck.css" type="text/css" >

	<link rel="stylesheet" href="src/codemirror/lib/codemirror.css">
	<link rel="stylesheet" href="src/codemirror/theme/default.css">

CoderDeck

http://github.com/cykod/CoderDeck

	create interactive live-coding presentations for the web.

	use the arrow-keys go between slides.

Basic Code Editor

Basic split code editor is created by adding a class of "coder-editor" to a textarea.
   Press run, then modify some code and press "run" again

<textarea class='coder-editor'>

My Site!

Link 1

Link 2

Blog Post 1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac elit at nisl sagittis consequat sed eget tellus. Aliquam gravida, nunc sit amet viverra dictum, nibh justo semper massa

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac elit at nisl sagittis consequat sed eget tellus. Aliquam gravida, nunc sit amet viverra dictum, nibh justo semper massa

  Link 1 | Link 2

</textarea>

How to use it?

Download a release and modify the index.html with your slide. Slides are created with by adding a class='slide' to any element. CoderDeck areas are created
	by adding a class of 'coder-editor' to a text area, for example (prettyprint is also bundled, so, as below just use a <pre class='prettyprint'>.. to highlight static code):

<article class='slide slide-list'>
  <h2>This is a second level heading!</h2>
  <p>Here is some descriptive text, followed by a split editor. </p>
  <textarea class='coder-editor'>
    <script>
       alert("Yay!");
    </script>
  <textarea>
</article>

Full Page Code Editor

Basic full page code editor is created by adding a class of "coder-editor-full" along with "coder-editor" to a textarea.
   Press run, then press "back", then modify some code and press "run" again

<textarea class='coder-editor coder-editor-full'>

My Site!

Link 1

Link 2

Blog Post 1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac elit at nisl sagittis consequat sed eget tellus. Aliquam gravida, nunc sit amet viverra dictum, nibh justo semper massa

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac elit at nisl sagittis consequat sed eget tellus. Aliquam gravida, nunc sit amet viverra dictum, nibh justo semper massa

  Link 1 | Link 2

</textarea>

Pulling from Gists

Use a class of 'gist' and an attribute of data-gist-id for the Gist ID

Custom template and custom language

You can create custom reusable templates for wrapping the editor code with custom <script> tags. You can also specify the mode the editor should display (xml, css, javascript or the default htmlmixed )

<textarea class='coder-editor' data-coder-template="coderdeck-style-example" data-language="css">
h1 { color:blue; }
h2 { color:red;}
p  { color:pink;}
.stuff  { color:purple;}
#my-div { color:teal;}
</textarea>

Instant Update Sample

Try modifying any of the HTML on the left, the right side should updated periodically as you type. This is done by adding a class of "coder-editor-instant" to the textarea

<textarea class='coder-editor coder-editor-instant' data-coder-template="coderdeck-style-example" data-language="css">
h1 { color:blue; }
h2 { color:red;}
p  { color:pink;}
.stuff  { color:purple;}
#my-div { color:teal;}
</textarea>

Javascript/jQuery Example

 Javascript works normally as well, libraries and external css (including jquery) can be included in the coderdeck template.

<textarea class='coder-editor'>

</textarea>

Local Storage

  If you want your changes to a slide to survive between page reloads you can define a data-save attribute which will save it to the attributes value in localstorage. Make a code change, hit run/save and reload this slide.

 You can also use the same 'data-save'  attribute on mulitiple slides to keep the same code moving forwad

<textarea class='coder-editor' data-save='dummy'>

This is some dummy content..

</textarea>

Solutions

If you want to add a solution to an exercise, you can add a coderdeck-solution script tag in the slide

<textarea class='coder-editor'>

</textarea>


text:
===================
libtorrent Examples
===================

:Author: Arvid Norberg, arvid@rasterbar.com
:Version: 1.0.2

.. contents:: Table of contents
  :depth: 2
  :backlinks: none

examples
========

Except for the example programs in this manual, there's also a bigger example
of a (little bit) more complete client, ``client_test``. There are separate
instructions for how to use it here__ if you'd like to try it. Note that building
``client_test`` also requires boost.regex and boost.program_options library.

__ client_test.html

simple client
-------------

This is a simple client. It doesn't have much output to keep it simple:

.. include:: ../examples/simple_client.cpp
	:code: c++
	:tab-width: 2
	:start-after: */

make_torrent
------------

Shows how to create a torrent from a directory tree:

.. include:: ../examples/make_torrent.cpp
	:code: c++
	:tab-width: 2
	:start-after: */

dump_torrent
------------

This is an example of a program that will take a torrent-file as a parameter and
print information about it to std out:

.. include:: ../examples/dump_torrent.cpp
	:code: c++
	:tab-width: 2
	:start-after: */


text:
architect-restify [![build status](https://secure.travis-ci.org/bimedia-fr/architect-restify.png)](https://travis-ci.org/bimedia-fr/architect-restify) [![NPM version](https://img.shields.io/npm/v/architect-restify.svg)](https://www.npmjs.com/package/architect-restify)
=================

expose restify server *rest* as architect plugin.

### Installation

```sh
npm install --save architect-restify
```
### Config Format

```js
{
  "packagePath": "architect-restify",
  port: process.env.PORT || 8080,
  host: process.env.IP || "0.0.0.0"
}
```
Or With plugins :

```js
{
  packagePath: "architect-restify",
  port: process.env.PORT || 8080,
  host: process.env.IP || "0.0.0.0"
  plugins: {
    bodyParser : {
      mapParams : false
    }
  }
}
```

### Usage

Boot [Architect](https://github.com/c9/architect) :

```js
var path = require('path');
var architect = require("architect");

var configPath = path.join(__dirname, "config.js");
var config = architect.loadConfig(configPath);

architect.createApp(config, function (err, app) {
    if (err) {
        throw err;
    }
    console.log("app ready");
});
```

Configure Architect with `config.js` :

```js
module.exports = [{
    packagePath: "architect-restify",
    port: process.env.PORT || 8080,
    host: process.env.IP || "0.0.0.0"
}, './routes'];
```

And register your routes in `./routes/index.js` :

```js
module.exports = function setup(options, imports, register) {
    var rest = imports.rest;

    // register routes
    rest.get('/catalogue', function (req, res, next) {
        res.write("{'message':'hello, world'}");
	res.end();
    });

    register();
};
// Consume rest plugin
module.exports.consumes=['rest'];
```

### Options
* port : tcp port to listent to
* host : host to listen to
* socket: unix socket to listen
* interface : network interface name to listen to (must match `os.networkInterfaces`)
* family : interface address family to listen to (with `interface`)
* plugins: a hash containing either a [restify bundled plugin](http://mcavage.me/node-restify/#Bundled-Plugins) or a function that returns a plugin.


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Janelas.Fase;

/**
 *
 * @author Douglas
 */
public class Historico_Fase extends javax.swing.JInternalFrame {

    /**
     * Creates new form HistoricoFase
     */
    public Historico_Fase() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jButton4 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setClosable(true);
        setMaximizable(true);
        setResizable(true);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("Janelas/Strings"); // NOI18N
        setTitle(bundle.getString("Historico_Fases")); // NOI18N

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/Add2.png"))); // NOI18N
        jButton1.setText(bundle.getString("Avancar_Fase")); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setText(bundle.getString("Historico_Fases")); // NOI18N

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/Cancel2.png"))); // NOI18N
        jButton4.setText(bundle.getString("Fechar")); // NOI18N
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addGap(226, 226, 226)
                        .addComponent(jButton4)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton4))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        Mudar_Fase cadastro = new Mudar_Fase(null, true);
        cadastro.setVisible(true);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_jButton4ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}


text:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, NavigationEnd, NavigationStart, Router } from '@angular/router';
import { SwUpdate } from '@angular/service-worker';
import { Observable } from 'rxjs';
import { filter, map, switchMap } from 'rxjs/operators';
import { CheckForUpdateService } from './check-for-update.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'app works!';
  currentComponent: any = {
    label: '',
    tstitle: '',
    htmltitle: '',
    csstitle: '',
    tsgist: '',
    htmlgist: '',
    cssgist: false
  };
  active = 1;
  links = []
  singleSelectionList = [];
  singleSelectionselectedItems = [];
  singleSelectionSettings = {};

  basicExampleList = [];
  basicExampleSelectedItems = [];
  basicExampleSettings = {};

  selectedItems3 = [];
  dropdownSettings3 = {};

  limitSelectionSelectedItems = [];
  limitSelectionSettings = {};

  disableModeSelectedItems = [];
  disableModeSettings = {};

  placeholderExampleList = [];
  placeholderExampleSelectedItems = [];
  placeholderExampleSettings = {};

  resetExampleList = [];
  resetExampleSelectedItems = [];
  resetExampleSettings = {};

  groupByExampleList = [];
  groupByExampleSelectedItems = [];
  groupByExampleSettings = {};

  templatingExampleList = [];
  templatingExampleSelectedItems = [];
  templatingExampleSettings = {};
  routeData$: Observable<any>;

  constructor(public updates: SwUpdate, private checkForUpdateService: CheckForUpdateService,
     private router: Router, private activatedRoute: ActivatedRoute){
    this.updates.available.subscribe((event) => {
      this.updateToLatest();
    });
    this.updates.activated.subscribe(event => {
      console.log('old version was', event.previous);
      console.log('new version is', event.current);
    });
    console.log(this.router.config)
    this.links = this.router.config;
    this.routeData$ = router.events.pipe(
      filter(routeEvent => routeEvent instanceof NavigationEnd),
      map(() => activatedRoute),
      map(activatedRoute => activatedRoute.firstChild),
      switchMap(firstChild => firstChild.data),
      map((data: any) => data)
      );
      this.routeData$.subscribe(data => {
        this.active = 1;
        this.currentComponent = Object.assign({}, data);
      })
  }
  showInfo(link){
    console.log(link)
  }
  updateToLatest(): void {
    console.log('Updating to latest version.');
    this.updates.activateUpdate().then(() => document.location.reload());
  }
  ngOnInit(){
    this.singleSelectionList = [
                          {"id":1,"itemName":"India"},
                          {"id":2,"itemName":"Singapore"},
                          {"id":3,"itemName":"Australia"},
                          {"id":4,"itemName":"Canada"},
                          {"id":5,"itemName":"South Korea"}
                        ];

    this.singleSelectionselectedItems = [
                          {"id":2,"itemName":"Singapore"}];
    this.singleSelectionSettings = {singleSelection: true, text:"Select Country"};

    this.basicExampleList = [
                          {"id":1,"itemName":"India"},
                          {"id":2,"itemName":"Singapore"},
                          {"id":3,"itemName":"Australia"},
                          {"id":4,"itemName":"Canada"},
                          {"id":5,"itemName":"South Korea"},
                          {"id":6,"itemName":"Brazil"}
                        ];

    this.basicExampleSelectedItems = [
                          {"id":1,"itemName":"India"},
                          {"id":2,"itemName":"Singapore"},
                          {"id":3,"itemName":"Australia"},
                          {"id":4,"itemName":"Canada"}];
    this.basicExampleSettings = {
                              text:"Select Countries",
                              selectAllText:'Select All',
                              unSelectAllText:'UnSelect All',
                              enableSearchFilter: true,
                              classes:"myclass custom-class"
                            };

    this.selectedItems3 = [
                          {"id":1,"itemName":"India"},
                          {"id":2,"itemName":"Singapore"},
                          {"id":4,"itemName":"Canada"},
                          {"id":5,"itemName":"South Korea"}];

    this.dropdownSettings3 = { singleSelection: false,
                              text:"Select Countries",
                              selectAllText:'Select All',
                              unSelectAllText:'UnSelect All',
                              enableSearchFilter: true,
                              badgeShowLimit: 3
                            };
    this.limitSelectionSelectedItems = [
                          {"id":1,"itemName":"India"},
                          {"id":2,"itemName":"Singapore"},
                          {"id":3,"itemName":"Australia"},
                          {"id":4,"itemName":"Canada"}];
    this.limitSelectionSettings = {
                              text:"Select Countries",
                              selectAllText:'Select All',
                              unSelectAllText:'UnSelect All',
                              enableSearchFilter: false,
                              classes:"myclass custom-class",
                              limitSelection: 4
                            };
    this.disableModeSelectedItems = [
                          {"id":1,"itemName":"India"},
                          {"id":2,"itemName":"Singapore"},
                          {"id":3,"itemName":"Australia"},
                          {"id":4,"itemName":"Canada"}];
    this.disableModeSettings = {
                              text:"Select Countries",
                              selectAllText:'Select All',
                              unSelectAllText:'UnSelect All',
                              enableSearchFilter: false,
                              classes:"myclass custom-class",
                              limitSelection: 2,
                              disabled: true
                            };

    this.placeholderExampleList = [
                          {"id":1,"itemName":"India"},
                          {"id":2,"itemName":"Singapore"},
                          {"id":3,"itemName":"Australia"},
                          {"id":4,"itemName":"Canada"},
                          {"id":5,"itemName":"South Korea"}
                        ];

    this.placeholderExampleSelectedItems = [
                          {"id":1,"itemName":"India"},
                          {"id":2,"itemName":"Singapore"},
                          {"id":3,"itemName":"Australia"},
                          {"id":4,"itemName":"Canada"}];
    this.placeholderExampleSettings = {
                              text:"Select Countries",
                              selectAllText:'Select All',
                              unSelectAllText:'UnSelect All',
                              enableSearchFilter: true,
                              classes:"myclass custom-class",
                              searchPlaceholderText: "Custom Placeholder text"
                            };
    this.resetExampleList = [
                          {"id":1,"itemName":"India"},
                          {"id":2,"itemName":"Singapore"},
                          {"id":3,"itemName":"Australia"},
                          {"id":4,"itemName":"Canada"},
                          {"id":5,"itemName":"South Korea"}
                        ];

    this.resetExampleSelectedItems = [
                          {"id":1,"itemName":"India"},
                          {"id":2,"itemName":"Singapore"},
                          {"id":3,"itemName":"Australia"},
                          {"id":4,"itemName":"Canada"}];
    this.resetExampleSettings = {
                              text:"Select Countries",
                              selectAllText:'Select All',
                              unSelectAllText:'UnSelect All',
                              enableSearchFilter: false,
                              classes:"myclass custom-class"
                            };
    this.groupByExampleList = [
                          {"id":1,"itemName":"India","category":"asia"},
                          {"id":2,"itemName":"Singapore","category":"asia pacific"},
                          {"id":3,"itemName":"Germany","category":"Europe"},
                          {"id":4,"itemName":"France","category":"Europe"},
                          {"id":5,"itemName":"South Korea","category":"asia"},
                          {"id":6,"itemName":"Sweden","category":"Europe"}
                        ];

    this.groupByExampleSelectedItems = [
                          {"id":1,"itemName":"India"},
                          {"id":2,"itemName":"Singapore"},
                          {"id":3,"itemName":"Germany"},
                          {"id":4,"itemName":"France"}];
    this.groupByExampleSettings = {
                              text:"Select Countries",
                              selectAllText:'Select All',
                              unSelectAllText:'UnSelect All',
                              enableSearchFilter: true,
                              classes:"myclass custom-class",
                              groupBy: "category"
                            };

  this.groupByExampleSettings = {
singleSelection: false,
text:"Select Fields",
selectAllText:'Select All',
unSelectAllText:'UnSelect All',
searchPlaceholderText: 'Search Fields',
enableSearchFilter: true,
badgeShowLimit: 5,
groupBy:"category"
};

this.templatingExampleList = [
                          {"id":1,"itemName":"India","capital":"Delhi","image":"http://www.sciencekids.co.nz/images/pictures/flags96/India.jpg"},
                          {"id":2,"itemName":"Singapore", "capital":"Singapore","image":"http://www.sciencekids.co.nz/images/pictures/flags96/Singapore.jpg"},
                          {"id":3,"itemName":"United Kingdom", "capital":"London","image":"http://www.sciencekids.co.nz/images/pictures/flags96/United_Kingdom.jpg"},
                          {"id":4,"itemName":"Canada","capital":"Ottawa","image":"http://www.sciencekids.co.nz/images/pictures/flags96/Canada.jpg"},
                          {"id":5,"itemName":"South Korea","capital":"Seoul","image":"http://www.sciencekids.co.nz/images/pictures/flags96/South_Korea.jpg"},
                          {"id":6,"itemName":"Brazil","capital":"Brasilia","image":"http://www.sciencekids.co.nz/images/pictures/flags96/Brazil.jpg"}
                        ];

    this.templatingExampleSelectedItems = [
                          {"id":1,"itemName":"India"},
                          {"id":2,"itemName":"Singapore"},
                          {"id":3,"itemName":"United Kingdom"},
                          {"id":4,"itemName":"Canada"}];
    this.templatingExampleSettings = {
                              text:"Select Countries",
                              selectAllText:'Select All',
                              unSelectAllText:'UnSelect All',
                              enableSearchFilter: true,
                              classes:"myclass custom-class",
                              showCheckbox: true
                            };

  }
  onItemSelect(item:any){
    console.log(item);
    console.log(this.basicExampleSelectedItems);
  }
  OnItemDeSelect(item:any){
    console.log(item);
    console.log(this.basicExampleSelectedItems);
  }
  onSelectAll(items: any){
    console.log(items);
  }
   onDeSelectAll(items: any){
    console.log(items);
  }
  showModel(){
    console.log(this.singleSelectionselectedItems);
  }
  changeData(){
    this.resetExampleSelectedItems = [];
  }
}


text:
import CardGroup from '../CardGroup.svelte';
import { render, cleanup } from '@testing-library/svelte';

beforeEach(cleanup);

describe('CardGroup', () => {
  test('should render correctly', () => {
    const { container } = render(CardGroup);
    const component = container.querySelector('.card-group');
    expect(component.className).toBe('card-group');
  });

  test('should render custom class', () => {
    const { container } = render(CardGroup, { props: { class: 'boogie' } });

    const component = container.querySelector('.card-group');
    expect(component.className).toBe('boogie card-group');
  });
});


text:
using System.Security.Claims;
using IntelliTect.Coalesce.TypeDefinition;
using System.Collections.Concurrent;

namespace IntelliTect.Coalesce.Mapping
{
    public static class Mapper
    {
#if NETCOREAPP
        [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull("obj")]
#endif
        public static TDto? MapToDto<T, TDto>(this T? obj, IMappingContext context, IncludeTree? tree = null)
            where T : class
            where TDto : class, IClassDto<T>, new()
        {
            if (obj == null) return default;

            // See if the object is already created, but only if we aren't restricting by an includes tree.
            // If we do have an IncludeTree, we know the exact structure of our return data, so we don't need to worry about circular refs.
            if (tree == null && context.TryGetMapping(obj, out TDto? existing)) return existing;

            var dto = new TDto();
            if (tree == null) context.AddMapping(obj, dto);

            dto.MapFrom(obj, context, tree);

            return dto;
        }

        public static T MapToModel<T, TDto>(this TDto dto, T entity, IMappingContext context)
            where T : class
            where TDto : class, IClassDto<T>, new()
        {
            dto.MapTo(entity, context);
            return entity;
        }
    }
}


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

<title>GeolocationTest</title>
<meta name="date" content="2017-11-13">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.wsfmn.view.model

Class GeolocationTest

java.lang.Object

junit.framework.Assert

junit.framework.TestCase

android.test.InstrumentationTestCase

android.test.ActivityTestCase

android.test.ActivityInstrumentationTestCase2

com.wsfmn.view.model.GeolocationTest

All Implemented Interfaces:

junit.framework.Test

public class GeolocationTest
extends android.test.ActivityInstrumentationTestCase2

Created by ${WeiLi5} on ${12}.

Constructor Summary

Constructors

Constructor and Description

GeolocationTest()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
testGetAddress()

void
testGetLatlng()

void
testSetAddress()

void
testSetLatLng()

Methods inherited from class android.test.ActivityInstrumentationTestCase2

getActivity, runTest, setActivityInitialTouchMode, setActivityIntent, setUp, tearDown

Methods inherited from class android.test.ActivityTestCase

scrubClass, setActivity

Methods inherited from class android.test.InstrumentationTestCase

getInstrumentation, injectInsrumentation, injectInstrumentation, launchActivity, launchActivityWithIntent, runTestOnUiThread, sendKeys, sendKeys, sendRepeatedKeys

Methods inherited from class junit.framework.TestCase

countTestCases, createResult, getName, run, run, runBare, setName, toString

Methods inherited from class junit.framework.Assert

assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail, failNotEquals, failNotSame, failSame, format

Methods inherited from class java.lang.Object

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

Constructor Detail

GeolocationTest

public GeolocationTest()

Method Detail

testGetAddress

public void testGetAddress()

testGetLatlng

public void testGetLatlng()

testSetAddress

public void testSetAddress()

testSetLatLng

public void testSetLatLng()

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
kunalvarma.in
=============

Source for my personal site.


text:
package com.intellij.execution.actions;

import com.intellij.execution.*;
import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.execution.executors.ExecutorGroup;
import com.intellij.execution.impl.EditConfigurationsDialog;
import com.intellij.execution.impl.RunManagerImpl;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.actionSystem.ex.ComboBoxAction;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.ui.SizedIcon;
import com.intellij.ui.components.panels.NonOpaquePanel;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.util.PlatformUtils;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

public class RunConfigurationsComboBoxAction extends ComboBoxAction implements DumbAware {
  private static final String BUTTON_MODE = "ButtonMode";

  public static final Icon CHECKED_ICON = JBUIScale.scaleIcon(new SizedIcon(AllIcons.Actions.Checked, 16, 16));
  public static final Icon CHECKED_SELECTED_ICON = JBUIScale.scaleIcon(new SizedIcon(AllIcons.Actions.Checked_selected, 16, 16));
  public static final Icon EMPTY_ICON = EmptyIcon.ICON_16;

  public static boolean hasRunCurrentFileItem(@NotNull Project project) {
    if (RunManager.getInstance(project).isRunWidgetActive()) {
      // Run Widget shows up only in Rider. In other IDEs it's a secret feature backed by the "ide.run.widget" Registry key.
      // The 'Run Current File' feature doesn't look great together with the Run Widget.
      return false;
    }

    if (PlatformUtils.isIntelliJ()) return true;
    if (PlatformUtils.isPhpStorm()) return true;
    if (PlatformUtils.isWebStorm()) return true;
    if (PlatformUtils.isRubyMine()) return true;
    if (PlatformUtils.isPyCharmPro()) return true;
    if (PlatformUtils.isPyCharmCommunity()) return true;

    return Registry.is("run.current.file.item.in.run.configurations.combobox");
  }

  @Override
  public @NotNull ActionUpdateThread getActionUpdateThread() {
    return ActionUpdateThread.BGT;
  }

  @Override
  public void update(@NotNull AnActionEvent e) {
    Presentation presentation = e.getPresentation();
    Project project = e.getData(CommonDataKeys.PROJECT);
    if (ActionPlaces.isMainMenuOrActionSearch(e.getPlace())) {
      presentation.setDescription(ExecutionBundle.messagePointer("choose.run.configuration.action.description"));
    }
    try {
      if (project == null || project.isDisposed() || !project.isOpen()) {
        updatePresentation(null, null, null, presentation, e.getPlace());
        presentation.setEnabled(false);
      }
      else {
        updatePresentation(getSelectedExecutionTarget(e),
                           getSelectedConfiguration(e),
                           project,
                           presentation,
                           e.getPlace());
        presentation.setEnabled(true);
      }
    }
    catch (IndexNotReadyException e1) {
      presentation.setEnabled(false);
    }
  }

  protected @Nullable ExecutionTarget getSelectedExecutionTarget(AnActionEvent e) {
    Project project = e.getProject();
    return project == null ? null : ExecutionTargetManager.getActiveTarget(project);
  }

  protected @Nullable RunnerAndConfigurationSettings getSelectedConfiguration(AnActionEvent e) {
    Project project = e.getProject();
    return project == null ? null : RunManager.getInstance(project).getSelectedConfiguration();
  }

  protected static void updatePresentation(@Nullable ExecutionTarget target,
                                         @Nullable RunnerAndConfigurationSettings settings,
                                         @Nullable Project project,
                                         @NotNull Presentation presentation,
                                         String actionPlace) {
    presentation.putClientProperty(BUTTON_MODE, null);
    if (project != null && target != null && settings != null) {
      String name = Executor.shortenNameIfNeeded(settings.getName());
      if (target != DefaultExecutionTarget.INSTANCE && !target.isExternallyManaged()) {
        name += " | " + target.getDisplayName();
      } else {
        if (!ExecutionTargetManager.canRun(settings.getConfiguration(), target)) {
          name += " | " + ExecutionBundle.message("run.configurations.combo.action.nothing.to.run.on");
        }
      }
      presentation.setText(name, false);
      if (!ApplicationManager.getApplication().isUnitTestMode()) {
        setConfigurationIcon(presentation, settings, project);
      }
    }
    else {
      if (project != null && hasRunCurrentFileItem(project)) {
        presentation.setText(ExecutionBundle.messagePointer("run.configurations.combo.run.current.file.selected"));
        presentation.setIcon(null);
        return;
      }

      presentation.putClientProperty(BUTTON_MODE, Boolean.TRUE);
      presentation.setText(ExecutionBundle.messagePointer("action.presentation.RunConfigurationsComboBoxAction.text"));
      presentation.setDescription(ActionsBundle.actionDescription(IdeActions.ACTION_EDIT_RUN_CONFIGURATIONS));
      if (ActionPlaces.TOUCHBAR_GENERAL.equals(actionPlace))
        presentation.setIcon(AllIcons.General.Add);
      else
        presentation.setIcon(null);
    }
  }

  protected static void setConfigurationIcon(final Presentation presentation,
                                           final RunnerAndConfigurationSettings settings,
                                           final Project project) {
    try {
      presentation.setIcon(RunManagerEx.getInstanceEx(project).getConfigurationIcon(settings, true));
    }
    catch (IndexNotReadyException ignored) {
    }
  }

  @Override
  public void actionPerformed(@NotNull AnActionEvent e) {
    if (ActionPlaces.TOUCHBAR_GENERAL.equals(e.getPlace())) {
      final Presentation presentation = e.getPresentation();
      if (Boolean.TRUE.equals(presentation.getClientProperty(BUTTON_MODE))) {
        InputEvent inputEvent = e.getInputEvent();
        Component component = inputEvent != null ? inputEvent.getComponent() : null;
        if (component != null) {
          performWhenButton(component, ActionPlaces.TOUCHBAR_GENERAL);
        }
        return;
      }
    }
    super.actionPerformed(e);
  }

  @Override
  protected boolean shouldShowDisabledActions() {
    return true;
  }

  @NotNull
  @Override
  public JComponent createCustomComponent(@NotNull final Presentation presentation, @NotNull String place) {
    ComboBoxButton button = new RunConfigurationsComboBoxButton(presentation);
    NonOpaquePanel panel = new NonOpaquePanel(new BorderLayout());
    Border border = UIUtil.isUnderDefaultMacTheme() ?
                    JBUI.Borders.empty(0, 2) : JBUI.Borders.empty(0, 5, 0, 4);

    panel.setBorder(border);
    panel.add(button);
    return panel;
  }

  private static void performWhenButton(@NotNull Component src, String place) {
    ActionManager manager = ActionManager.getInstance();
    manager.tryToExecute(manager.getAction(IdeActions.ACTION_EDIT_RUN_CONFIGURATIONS),
      new MouseEvent(src, MouseEvent.MOUSE_PRESSED, System.currentTimeMillis(), 0, 0, 0, 0,false, 0),
      src, place, true
    );
  }

  @Override
  @NotNull
  protected DefaultActionGroup createPopupActionGroup(final JComponent button) {
    final DefaultActionGroup allActionsGroup = new DefaultActionGroup();
    final Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(button));
    if (project == null) {
      return allActionsGroup;
    }

    AnAction editRunConfigurationAction = getEditRunConfigurationAction();
    if(editRunConfigurationAction != null) {
      allActionsGroup.add(editRunConfigurationAction);
    }
    allActionsGroup.add(new SaveTemporaryAction());
    allActionsGroup.addSeparator();

    addTargetGroup(project, allActionsGroup);

    allActionsGroup.add(new RunCurrentFileAction());
    allActionsGroup.addSeparator(ExecutionBundle.message("run.configurations.popup.existing.configurations.separator.text"));

    for (Map<String, List<RunnerAndConfigurationSettings>> structure : RunManagerImpl.getInstanceImpl(project).getConfigurationsGroupedByTypeAndFolder(true).values()) {
      final DefaultActionGroup actionGroup = new DefaultActionGroup();
      for (Map.Entry<String, List<RunnerAndConfigurationSettings>> entry : structure.entrySet()) {
        @NlsSafe String folderName = entry.getKey();
        DefaultActionGroup group = folderName == null ? actionGroup : DefaultActionGroup.createPopupGroup(() -> folderName);
        group.getTemplatePresentation().setIcon(AllIcons.Nodes.Folder);
        for (RunnerAndConfigurationSettings settings : entry.getValue()) {
          group.add(createFinalAction(settings, project));
        }
        if (group != actionGroup) {
          actionGroup.add(group);
        }
      }

      allActionsGroup.add(actionGroup);
      allActionsGroup.addSeparator();
    }
    return allActionsGroup;
  }

  protected void addTargetGroup(Project project, DefaultActionGroup allActionsGroup) {
    RunnerAndConfigurationSettings selected = RunManager.getInstance(project).getSelectedConfiguration();
    if (selected != null) {
      ExecutionTarget activeTarget = ExecutionTargetManager.getActiveTarget(project);
      for (ExecutionTarget eachTarget : ExecutionTargetManager.getTargetsToChooseFor(project, selected.getConfiguration())) {
        allActionsGroup.add(new SelectTargetAction(project, eachTarget, eachTarget.equals(activeTarget)));
      }
      allActionsGroup.addSeparator();
    }
  }

  protected @Nullable AnAction getEditRunConfigurationAction() {
    return ActionManager.getInstance().getAction(IdeActions.ACTION_EDIT_RUN_CONFIGURATIONS);
  }

  protected AnAction createFinalAction(@NotNull final RunnerAndConfigurationSettings configuration, @NotNull final Project project) {
    return new SelectConfigAction(configuration, project);
  }

  public class RunConfigurationsComboBoxButton extends ComboBoxButton {

    public RunConfigurationsComboBoxButton(@NotNull Presentation presentation) {
      super(presentation);
    }

    @Override
    public Dimension getPreferredSize() {
      Dimension d = super.getPreferredSize();
      d.width = Math.max(d.width, JBUIScale.scale(75));
      return d;
    }

    @Override
    protected void doShiftClick() {
      DataContext context = DataManager.getInstance().getDataContext(this);
      final Project project = CommonDataKeys.PROJECT.getData(context);
      if (project != null && !ActionUtil.isDumbMode(project)) {
        new EditConfigurationsDialog(project).show();
        return;
      }
      super.doShiftClick();
    }

    @Override
    protected void fireActionPerformed(ActionEvent event) {
      if (Boolean.TRUE.equals(getPresentation().getClientProperty(BUTTON_MODE))) {
        performWhenButton(this, ActionPlaces.UNKNOWN);
        return;
      }

      super.fireActionPerformed(event);
    }

    @Override
    protected boolean isArrowVisible(@NotNull Presentation presentation) {
      return !Boolean.TRUE.equals(presentation.getClientProperty(BUTTON_MODE));
    }
  }

  private static final class SaveTemporaryAction extends DumbAwareAction {
    SaveTemporaryAction() {
      Presentation presentation = getTemplatePresentation();
      presentation.setIcon(AllIcons.Actions.MenuSaveall);
    }

    @Override
    public void actionPerformed(@NotNull final AnActionEvent e) {
      final Project project = e.getData(CommonDataKeys.PROJECT);
      if (project != null) {
        RunnerAndConfigurationSettings settings = chooseTempSettings(project);
        if (settings != null) {
          final RunManager runManager = RunManager.getInstance(project);
          runManager.makeStable(settings);
        }
      }
    }

    @Override
    public void update(@NotNull final AnActionEvent e) {
      final Presentation presentation = e.getPresentation();
      final Project project = e.getData(CommonDataKeys.PROJECT);
      if (project == null) {
        disable(presentation);
        return;
      }
      RunnerAndConfigurationSettings settings = chooseTempSettings(project);
      if (settings == null) {
        disable(presentation);
      }
      else {
        presentation.setText(ExecutionBundle.messagePointer("save.temporary.run.configuration.action.name", Executor.shortenNameIfNeeded(settings.getName())));
        //noinspection DialogTitleCapitalization
        presentation.setDescription(presentation.getText());
        presentation.setEnabledAndVisible(true);
      }
    }

    private static void disable(final Presentation presentation) {
      presentation.setEnabledAndVisible(false);
    }

    @Nullable
    private static RunnerAndConfigurationSettings chooseTempSettings(@NotNull Project project) {
      RunnerAndConfigurationSettings selectedConfiguration = RunManager.getInstance(project).getSelectedConfiguration();
      if (selectedConfiguration != null && selectedConfiguration.isTemporary()) {
        return selectedConfiguration;
      }
      return ContainerUtil.getFirstItem(RunManager.getInstance(project).getTempConfigurationsList());
    }
  }

  private static void addExecutorActions(@NotNull DefaultActionGroup group,
                                         @NotNull Function<? super Executor, ? extends ExecutorRegistryImpl.ExecutorAction> actionCreator) {
    for (Executor executor : Executor.EXECUTOR_EXTENSION_NAME.getExtensionList()) {
      if (executor instanceof ExecutorGroup) {
        for (Executor childExecutor : ((ExecutorGroup<?>)executor).childExecutors()) {
          group.addAction(actionCreator.apply(childExecutor));
        }
      }
      else {
        group.addAction(actionCreator.apply(executor));
      }
    }
  }

  private static class RunCurrentFileAction extends DefaultActionGroup implements DumbAware {
    private RunCurrentFileAction() {
      super(ExecutionBundle.messagePointer("run.configurations.combo.run.current.file.item.in.dropdown"),
            ExecutionBundle.messagePointer("run.configurations.combo.run.current.file.description"),
            null);

      setPopup(true);
      getTemplatePresentation().setPerformGroup(true);

      addSubActions();
    }

    private void addSubActions() {
      // Add actions similar to com.intellij.execution.actions.ChooseRunConfigurationPopup.ConfigurationActionsStep#buildActions
      addExecutorActions(this, ExecutorRegistryImpl.RunCurrentFileExecutorAction::new);
      addSeparator();
      addAction(new ExecutorRegistryImpl.EditRunConfigAndRunCurrentFileExecutorAction(DefaultRunExecutor.getRunExecutorInstance()));
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
      e.getPresentation().setEnabledAndVisible(e.getProject() != null && hasRunCurrentFileItem(e.getProject()));
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      Project project = e.getProject();
      if (project == null) return;

      RunManager.getInstance(project).setSelectedConfiguration(null);
      updatePresentation(null, null, project, e.getPresentation(), e.getPlace());
    }
  }

  private static final class SelectTargetAction extends AnAction {
    private final Project myProject;
    private final ExecutionTarget myTarget;

    SelectTargetAction(final Project project, final ExecutionTarget target, boolean selected) {
      myProject = project;
      myTarget = target;

      String name = target.getDisplayName();
      Presentation presentation = getTemplatePresentation();
      presentation.setText(name, false);
      presentation.setDescription(ExecutionBundle.message("select.0", name));

      presentation.setIcon(selected ? CHECKED_ICON : EMPTY_ICON);
      presentation.setSelectedIcon(selected ? CHECKED_SELECTED_ICON : EMPTY_ICON);
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      ExecutionTargetManager.setActiveTarget(myProject, myTarget);
      updatePresentation(ExecutionTargetManager.getActiveTarget(myProject),
                         RunManager.getInstance(myProject).getSelectedConfiguration(),
                         myProject,
                         e.getPresentation(),
                         e.getPlace());
    }

    @Override
    public boolean isDumbAware() {
      RunnerAndConfigurationSettings configuration = RunManager.getInstance(myProject).getSelectedConfiguration();
      return configuration == null || configuration.getType().isDumbAware();
    }
  }

  private static final class SelectConfigAction extends DefaultActionGroup implements DumbAware {
    private final RunnerAndConfigurationSettings myConfiguration;
    private final Project myProject;

    SelectConfigAction(final RunnerAndConfigurationSettings configuration, final Project project) {
      myConfiguration = configuration;
      myProject = project;

      setPopup(true);
      getTemplatePresentation().setPerformGroup(true);

      String name = Executor.shortenNameIfNeeded(configuration.getName());
      if (name.isEmpty()) {
        name = " ";
      }
      final Presentation presentation = getTemplatePresentation();
      presentation.setText(name, false);
      presentation.setDescription(ExecutionBundle.message("select.0.1", configuration.getType().getConfigurationTypeDescription(), name));
      updateIcon(presentation);

      // Secondary menu for the existing run configurations is not directly related to the 'Run Current File' feature.
      // We may reconsider changing this to `if (!RunManager.getInstance(project).isRunWidgetActive()) { addSubActions(); }`
      if (hasRunCurrentFileItem(project)) {
        addSubActions();
      }
    }

    private void updateIcon(final Presentation presentation) {
      setConfigurationIcon(presentation, myConfiguration, myProject);
    }

    private void addSubActions() {
      // Add actions similar to com.intellij.execution.actions.ChooseRunConfigurationPopup.ConfigurationActionsStep#buildActions
      addExecutorActions(this, executor -> new ExecutorRegistryImpl.RunSpecifiedConfigExecutorAction(executor, myConfiguration, false));
      addSeparator();

      Executor runExecutor = DefaultRunExecutor.getRunExecutorInstance();
      addAction(new ExecutorRegistryImpl.RunSpecifiedConfigExecutorAction(runExecutor, myConfiguration, true));

      if (myConfiguration.isTemporary()) {
        String actionName = ExecutionBundle.message("choose.run.popup.save");
        String description = ExecutionBundle.message("choose.run.popup.save.description");
        addAction(new AnAction(actionName, description, AllIcons.Actions.MenuSaveall) {
          @Override
          public void actionPerformed(@NotNull AnActionEvent e) {
            RunManager.getInstance(myProject).makeStable(myConfiguration);
          }
        });
      }

      String actionName = ExecutionBundle.message("choose.run.popup.delete");
      String description = ExecutionBundle.message("choose.run.popup.delete.description");
      addAction(new AnAction(actionName, description, AllIcons.Actions.Cancel) {
        @Override
        public void actionPerformed(@NotNull AnActionEvent e) {
          ChooseRunConfigurationPopup.deleteConfiguration(myProject, myConfiguration, null);
        }
      });
    }

    @Override
    public void actionPerformed(@NotNull final AnActionEvent e) {
      RunManager.getInstance(myProject).setSelectedConfiguration(myConfiguration);
      updatePresentation(ExecutionTargetManager.getActiveTarget(myProject), myConfiguration, myProject, e.getPresentation(), e.getPlace());
    }

    @Override
    public void update(@NotNull final AnActionEvent e) {
      super.update(e);
      updateIcon(e.getPresentation());
    }
  }
}


text:
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/user"
	"path/filepath"

	"go4.org/wkfs"
	_ "go4.org/wkfs/gcs"
)

// This is a test comment for github syncing.

const githubSSHKeyGCS = "/gcs/camlistore-website-resource/id_github_camlistorebot_push"

var (
	githubSSHKey string // Also used to detect whether we do the syncs to github
	hostSSHDir   string // path to the ssh config dir on the host
)

func githubSSHConfig(filename string) string {
	return `
Host github.com
  User git
  IdentityFile ~/.ssh/` + filename + `
  IdentitiesOnly yes
`
}

func initGithubSyncing() error {
	if !inProd {
		return nil
	}
	keyData, err := wkfs.ReadFile(githubSSHKeyGCS)
	if err != nil {
		log.Printf("Not syncing to github, because no ssh key found: %v", err)
		return nil
	}
	u, err := user.Current()
	if err != nil {
		return fmt.Errorf("can't look up user: %v", err)
	}

	sshDir := filepath.Join(u.HomeDir, ".ssh")
	if err := os.MkdirAll(sshDir, 0700); err != nil {
		return fmt.Errorf("failed to create ssh config dir %v: %v", sshDir, err)
	}
	keyFileName := filepath.Base(githubSSHKeyGCS)
	keyFile := filepath.Join(sshDir, keyFileName)
	if err := ioutil.WriteFile(keyFile, keyData, 0600); err != nil {
		return fmt.Errorf("failed to create temp github SSH key %v: %v", keyFile, err)
	}
	if err := ioutil.WriteFile(
		filepath.Join(sshDir, "config"),
		[]byte(githubSSHConfig(keyFileName)),
		0600); err != nil {
		return fmt.Errorf("failed to create github SSH config: %v", err)
	}
	hostSSHDir = sshDir
	githubSSHKey = keyFileName
	return nil
}

// githubHEAD returns the hash of the HEAD commit on the github repo.
// The gerritHEAD argument is used as an optimization in the request to github:
// if it is found as the HEAD commit, the request is not counted in our
// non-authenticated requests quota.
func githubHEAD(gerritHEAD string) (string, error) {
	const (
		headAPI  = "https://api.github.com/repos/camlistore/camlistore/commits/HEAD"
		mimeType = "application/vnd.github.VERSION.sha"
	)
	req, err := http.NewRequest("GET", headAPI, nil)
	if err != nil {
		return "", err
	}
	req.Header.Add("If-None-Match", `"`+gerritHEAD+`"`)
	req.Header.Add("Accept", mimeType)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	if resp.StatusCode == http.StatusNotModified {
		return gerritHEAD, nil
	}
	ghCommit, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return string(ghCommit), nil
}

func syncToGithub(dir, gerritHEAD string) error {
	gh, err := githubHEAD(gerritHEAD)
	if err != nil {
		return fmt.Errorf("error looking up the github HEAD commit: %v", err)
	}
	log.Printf("HEAD commits: on github=%v, on gerrit=%v", gh, gerritHEAD)
	if gh == gerritHEAD {
		return nil
	}
	mounts := map[string]string{
		hostSSHDir: "/root/.ssh",
	}
	cmd := execGit(dir, mounts, "push", "git@github.com:camlistore/camlistore.git", "master:master")
	out, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("error running git push to github: %v\n%s", err, out)
	}
	log.Printf("Successfully pushed commit %v to github", gerritHEAD)
	return nil
}