text:
var TogglClient = require('toggl-api');
var CurrentEntry = require('./current-entry');
var TogglEntry = require('./toggl-entry');
var toggl;

module.exports = {

    config: {
      togglApiKey: {
        type: 'string',
        default: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
      }
    },

    activate: function (state) {

      // set Toggl Api Key
      if (atom.config.settings.toggl.togglApiKey) {
        toggl = new TogglClient({
          apiToken: atom.config.settings.toggl.togglApiKey
        });
      }
      else {
        atom.notifications.addError('No API Key available. Please set one in Package Settings Page');
        return;
      }
      atom.commands.add('atom-workspace', 'Toggl:Start', this.start)
      atom.commands.add('atom-workspace', 'Toggl:End', this.end)
      atom.commands.add('atom-workspace', 'Toggl:Current', this.current)
    },

    start: function () {
      // init new togglEntry
      var entry = new TogglEntry();
      var hasProjects = false;

      var projectSelector = entry.getTextInputs()[2];

      toggl.getClients(function (err, clients) {
        if (err)
          atom.notifications.addError(err.message);
        else if (clients) {
          entry.destroyLoader();
          atom.workspace.addBottomPanel({item: entry.getElement()});

          clients.forEach(function (client) {
            toggl.getClientProjects(client.id, true, function (err, projects) {
              if (err)
                atom.notifications.addError(err.message);
              else if (projects) {
                if (!hasProjects) {
                  hasProjects = true;
                  document.getElementById('projects-container').hidden = false;
                }
                projects.forEach(function (project) {
                  var option = document.createElement('option');
                  option.value = project.id;
                  option.innerHTML = project.name;
                  projectSelector.appendChild(option);
                });
              }
            });
          });
        }
        else {
          entry.destroyLoader();
          atom.workspace.addBottomPanel({item: entry.getElement()});
        }
      });

      entry.getTextInputs().forEach(function (input) {
        input.addEventListener('keydown', function (e) {
          if (e.which === 13) {
            // start a new time entry
            toggl.startTimeEntry({
              description: document.getElementById('togglInput').value,
              tags: document.getElementById('tagsInput').value.split(',').map(function (e) { return e.trim(); }),
              billable: document.getElementById('billableInput').checked,
              pid: document.getElementById('projectSelect').options[document.getElementById('projectSelect').selectedIndex].value
            }, function (err, timeEntry) {

              // handle error
              if (err)
                atom.notifications.addError(err.message);
              else {
                atom.notifications.addSuccess('New Toggl Entry created with id #' + timeEntry.id);
              }
            });
            entry.destroy();
          }
          // handle escape keypress
          else if (e.which === 27) {
            entry.destroy();
          }
        });
      });
      atom.workspace.addBottomPanel({item: entry.getLoader()});
    },

    end: function () {

      toggl.getCurrentTimeEntry(function (err, timeEntry) {
        if (err)
          atom.notifications.addError(err.message);
        else if (!timeEntry)
          atom.notifications.addError('No current Toggl Entry');
        else {
          // stop the current time entry
          toggl.stopTimeEntry(timeEntry.id, function (err) {

            // handle err
            if (err)
              atom.notifications.addError(err.message);
            else {
              timeEntry.tags = timeEntry.tags ? timeEntry.tags.push('finished') : ['finished'];
              toggl.updateTimeEntry(timeEntry.id, {tags: timeEntry.tags}, function(err) {
                if (err)
                  atom.notifications.addError(err.message);
                else {
                  atom.notifications.addSuccess('Finished Toggl Entry with id #' + timeEntry.id);
                  toggl.destroy()
                }
              });
            }
          });
        }
      })
    },

    current: function () {
      toggl.getCurrentTimeEntry(function (err, timeEntry) {
        if (err)
          atom.notifications.addError(err.message);
        else if (!timeEntry)
          atom.notifications.addInfo('No current Toggl Entry.');
        else {
          var current_entry = new CurrentEntry();
          var labels = current_entry.getLabels();
          labels.title.textContent = timeEntry.description;
          labels.tags.textContent = timeEntry.tags ? timeEntry.tags.join(', ') : '';
          var start_time = new Date(timeEntry.start);
          var now = new Date();
          var hours = now.getHours() - start_time.getHours();
          var minutes = now.getMinutes() - start_time.getMinutes();
          var seconds = now.getSeconds() - start_time.getSeconds();
          if (seconds < 0) {
            minutes += 1;
            seconds = 60 - Math.abs(seconds);
          }
          if (minutes < 0) {
            hours += 1;
            minutes = 60 - Math.abs(minutes);
          }
          labels.hours.textContent = hours + ':';
          labels.minutes.textContent = minutes + ':';
          labels.seconds.textContent = seconds;
          // if (timeEntry.pid) {
          //   toggl.getProjectData(timeEntry.pid, function (err, project) {
          //     if (err)
          //       atom.notifications.addError(err.message);
          //     else {
          //       labels.project.textContent = project.name;
          //       atom.workspace.addModalPanel({item: current_entry.getElement()});
          //     }
          //   });
          // }
          // else
          atom.workspace.addModalPanel({item: current_entry.getElement()});
        }
      });
    }
  }


text:
import React, { Component } from 'react';
import {Link} from 'react-router-dom';
import './MainPage.css'

class MainPage extends Component {

  render() {

    return (

PORVOON KUNTOAJOT 4.8. 2019 KLO 10.00

          Tervetuloa polkemaan idyllinen kuntoajo Itä-Uudenmaan kauniisiin jokilaaksoihin
          ja kumpuileviin maalaismaisemiin sunnuntaina 4.8.2019

          Ajajilta suurta kiitosta saaneissa Porvoon Kuntoajoissa on kaksi eri matkaa:

Pidempi reitti on 110 kilometriä ja luonteeltaan mäkinen ja vaativa.

Lyhyempi on 55 kilometriä ja reittinä helpompi ja sopii kaikille kuntoilijoille.

            Kaikkien sarjojen lähdöt toteutetaan yhteislähtöinä, joten tunnelmaa on suurten
            ajojen tyyliin lähdöstä maaliin asti.

            Varaa paikkasi ajoissa, sillä vain 400 ensimmäistä lunastaa paikkansa.

            Startti ja maali on Porvoon Amistolla, Perämiehentie 6, 06100 Porvoo.

Ilmoittautuminen

Ilmoittaudu mukaan tästä

Maksutapana nyt myös liikunta- ja kulttuurisetelit.
              Lähtöpaikalla maksuna käy käteinen tai pankki- ja luottokortti.

Hinnat

Ilmoittaudu ajoissa ja hyödynnä early-bird etusi!

                Matka
                Ennen 21.5
                Ennen 22.7
                Alkaen 22.7
                Käteinen lähtöpaikalla

                110 km
                50 €
                60 €
                70 €
                70 € (tasaraha)

                55 km
                40 €
                50 €
                60 €
                60 € (tasaraha)

    )
  }
}

export default MainPage

redpajama_set_name: RedPajamaGithub


text:
using Lucene.Net.Index;
using Lucene.Net.Search;
using System;
using System.Collections;
using System.Globalization;

namespace Lucene.Net.Queries.Function.ValueSources
{

    /// <summary>
    /// Obtains <see cref="short"/> field values from the <see cref="FieldCache"/>
    /// using <see cref="IFieldCache.GetInt16s(AtomicReader, string, FieldCache.IInt16Parser, bool)"/>
    /// and makes those values available as other numeric types, casting as needed.
    /// <para/>
    /// NOTE: This was ShortFieldSource in Lucene
    /// </summary>
    [Obsolete]
    public class Int16FieldSource : FieldCacheSource
    {
        private readonly FieldCache.IInt16Parser parser;

        public Int16FieldSource(string field)
            : this(field, null)
        {
        }

        public Int16FieldSource(string field, FieldCache.IInt16Parser parser)
            : base(field)
        {
            this.parser = parser;
        }

        public override string GetDescription()
        {
            return "short(" + m_field + ')';
        }

        public override FunctionValues GetValues(IDictionary context, AtomicReaderContext readerContext)
        {
            var arr = m_cache.GetInt16s(readerContext.AtomicReader, m_field, parser, false);
            return new FunctionValuesAnonymousInnerClassHelper(this, arr);
        }

        private class FunctionValuesAnonymousInnerClassHelper : FunctionValues
        {
            private readonly Int16FieldSource outerInstance;
            private readonly FieldCache.Int16s arr;

            public FunctionValuesAnonymousInnerClassHelper(Int16FieldSource outerInstance, FieldCache.Int16s arr)
            {
                this.outerInstance = outerInstance;
                this.arr = arr;
            }

            public override byte ByteVal(int doc)
            {
                return (byte)arr.Get(doc);
            }

            /// <summary>
            /// NOTE: This was shortVal() in Lucene
            /// </summary>
            public override short Int16Val(int doc)
            {
                return arr.Get(doc);
            }

            /// <summary>
            /// NOTE: This was floatVal() in Lucene
            /// </summary>
            public override float SingleVal(int doc)
            {
                return (float)arr.Get(doc);
            }

            /// <summary>
            /// NOTE: This was intVal() in Lucene
            /// </summary>
            public override int Int32Val(int doc)
            {
                return (int)arr.Get(doc);
            }

            /// <summary>
            /// NOTE: This was longVal() in Lucene
            /// </summary>
            public override long Int64Val(int doc)
            {
                return (long)arr.Get(doc);
            }

            public override double DoubleVal(int doc)
            {
                return arr.Get(doc);
            }

            public override string StrVal(int doc)
            {
                return Convert.ToString(arr.Get(doc), CultureInfo.InvariantCulture);
            }

            public override string ToString(int doc)
            {
                return outerInstance.GetDescription() + '=' + Int16Val(doc);
            }
        }

        public override bool Equals(object o)
        {
            if (!(o is Int16FieldSource other))
                return false;
            return base.Equals(other)
                && (parser == null ? other.parser == null :
                parser.GetType() == other.parser.GetType());
        }

        public override int GetHashCode()
        {
            var h = parser == null ? typeof(short?).GetHashCode() : parser.GetType().GetHashCode();
            h += base.GetHashCode();
            return h;
        }
    }
}


text: export * from './applet.info.service';


text:
package org.livetribe.aws.arn;

import java.util.HashSet;
import java.util.Set;

import static org.livetribe.aws.arn.ArnParser.parseArn;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;

/**
 * @author LiveTribe
 */
@Test
public class IamOidcProviderArnTest {
    public void testIamOidcProviderArn() {
        IamOidcProviderArn arn = new IamOidcProviderArn("123456789012", "GoogleProvider");
        assertEquals(arn.toString(), "arn:aws:iam::123456789012:oidc-provider/GoogleProvider");
    }

    public void testParseIamOidcProviderArn() throws ArnSyntaxException {
        assertEquals(parseArn("arn:aws:iam::123456789012:oidc-provider/GoogleProvider"),
                     new IamOidcProviderArn("123456789012", "GoogleProvider"));
    }

    public void testSet() {
        Set<Arn> arns = new HashSet<Arn>();

        arns.add(new IamOidcProviderArn("123456789012", "GoogleProvider"));
        arns.add(new IamOidcProviderArn("123456789012", "GoogleProvider"));

        assertEquals(arns.size(), 1);
    }

    public void testEquals() {
        Arn first = new IamOidcProviderArn("123456789012", "GoogleProvider");
        Arn second = new IamOidcProviderArn("123456789012", "GoogleProvider");

        assert first.equals(second);
    }
}


text:
//-----------------------------------------------------------------------------
// Filename: SIPProviderJSON.cs
//
// Description: A translation class to allow a SIP provider to be serialised to and from JSON. The
// Entity Framework derived SIPProvider class cannot be used to a shortcoming in the serialisation
// mechanism to do with IsReference classes. This will probably be fixed in the future making this
// class redundant.
//
// History:
// 27 Oct 2011	Aaron Clauson	    Created.
//
// License:
// This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php
//
// Copyright (c) 2011 Aaron Clauson (aaron@sipsorcery.com), SIPSorcery Pty Ltd, Hobart, Australia (www.sipsorcery.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of SIPSorcery Pty. Ltd.
// nor the names of its contributors may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using SIPSorcery.Sys;

namespace SIPSorcery.Entities
{
    [DataContractAttribute]
    public class SIPProviderJSON
    {
        [DataMember] public string ID { get; set; }
        [DataMember] public string ProviderName { get; set; }
        [DataMember] public string ProviderUsername { get; set; }
        [DataMember] public string ProviderPassword { get; set; }
        [DataMember] public string ProviderServer { get; set; }
        [DataMember] public string ProviderAuthUsername { get; set; }
        [DataMember] public string ProviderOutboundProxy { get; set; }
        [DataMember] public string ProviderType { get; set; }
        [DataMember] public string ProviderFrom { get; set; }
        [DataMember] public string CustomHeaders { get; set; }
        [DataMember] public string RegisterContact { get; set; }
        [DataMember] public int RegisterExpiry { get; set; }
        [DataMember] public string RegisterServer { get; set; }
        [DataMember] public string RegisterRealm { get; set; }
        [DataMember] public bool RegisterEnabled { get; set; }
        [DataMember] public string GVCallbackNumber { get; set; }
        [DataMember] public string GVCallbackPattern { get; set; }
        [DataMember] public string GVCallbackType { get; set; }

        public SIPProviderJSON()
        { }

        public SIPProvider ToSIPProvider()
        {
            var entitySIPProvider = new SIPProvider()
            {
                Owner = String.Empty,
                ID = ID,
                ProviderName = ProviderName,
                ProviderUsername = ProviderUsername,
                ProviderPassword = ProviderPassword,
                ProviderServer = ProviderServer,
                ProviderAuthUsername = ProviderAuthUsername,
                ProviderOutboundProxy = ProviderOutboundProxy,
                ProviderType = ProviderType,
                ProviderFrom = ProviderFrom,
                CustomHeaders = CustomHeaders,
                RegisterEnabled = RegisterEnabled,
                RegisterContact = RegisterContact,
                RegisterExpiry = RegisterExpiry,
                RegisterServer = RegisterServer,
                RegisterRealm = RegisterRealm,
                GVCallbackNumber = GVCallbackNumber,
                GVCallbackPattern = GVCallbackPattern,
                GVCallbackType = GVCallbackType
            };

            return entitySIPProvider;
        }
    }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.08.31 at 10:43:34 AM EDT
//

package org.slc.sli.test.edfi.entitiesR1;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 * A record of attendance.
 *                 date: Date for this
 *                 attendance event.
 *                 event: The occurred attendance event, such as
 *                 "Unexcused absence,"
 *                 "Excused absence," or "Tardy."
 *                 reason: The
 *                 reported reason for the event, such as a reason for absence.
 *
 *
 *
Java class for attendanceEvent complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="attendanceEvent">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="date" type="{http://www.w3.org/2001/XMLSchema}date"/>
 *         <element name="event" type="{http://slc-sli/ed-org/0.1}attendanceEventCategoryType"/>
 *         <element name="reason" type="{http://slc-sli/ed-org/0.1}attendanceEventReason" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "attendanceEvent", propOrder = {
    "date",
    "event",
    "reason"
})
public class AttendanceEvent {

    @XmlElement(required = true)
    @XmlJavaTypeAdapter(Adapter2 .class)
    @XmlSchemaType(name = "date")
    protected String date;
    @XmlElement(required = true)
    protected AttendanceEventCategoryType event;
    protected String reason;

    /**
     * Gets the value of the date property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDate() {
        return date;
    }

    /**
     * Sets the value of the date property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDate(String value) {
        this.date = value;
    }

    /**
     * Gets the value of the event property.
     *
     * @return
     *     possible object is
     *     {@link AttendanceEventCategoryType }
     *
     */
    public AttendanceEventCategoryType getEvent() {
        return event;
    }

    /**
     * Sets the value of the event property.
     *
     * @param value
     *     allowed object is
     *     {@link AttendanceEventCategoryType }
     *
     */
    public void setEvent(AttendanceEventCategoryType value) {
        this.event = value;
    }

    /**
     * Gets the value of the reason property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getReason() {
        return reason;
    }

    /**
     * Sets the value of the reason property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setReason(String value) {
        this.reason = value;
    }

}


text:
FOUNDATION_EXPORT double Pods_Dispatch_TestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_Dispatch_TestsVersionString[];


text:
package org.apache.geode.internal.admin.remote;

import org.apache.geode.distributed.internal.*;
import org.apache.geode.internal.i18n.LocalizedStrings;
// import org.apache.geode.*;
// import org.apache.geode.internal.*;
import java.io.*;
// import java.util.*;

/**
 * A message that is sent to a particular app vm to request the region statistics of a given region.
 */
public class RegionStatisticsRequest extends RegionAdminRequest {
  // instance variables

  /**
   * Returns a RegionStatisticsRequest to be sent to the specified recipient.
   */
  public static RegionStatisticsRequest create() {
    RegionStatisticsRequest m = new RegionStatisticsRequest();
    return m;
  }

  public RegionStatisticsRequest() {
    friendlyName =
        LocalizedStrings.RegionStatisticsRequest_FETCH_REGION_STATISTICS.toLocalizedString();
  }

  /**
   * Must return a proper response to this request.
   */
  @Override
  protected AdminResponse createResponse(DistributionManager dm) {
    return RegionStatisticsResponse.create(dm, this.getSender(), this.getRegion(dm.getSystem()));
  }

  public int getDSFID() {
    return REGION_STATISTICS_REQUEST;
  }

  @Override
  public void toData(DataOutput out) throws IOException {
    super.toData(out);
  }

  @Override
  public void fromData(DataInput in) throws IOException, ClassNotFoundException {
    super.fromData(in);
  }

  @Override
  public String toString() {
    return "RegionStatisticsRequest from " + getRecipient() + " region=" + getRegionName();
  }
}


text:
You all have great ideas, which you have fleshed out with a [paper prototype](http://www.paperprototyping.com/). For assignment 3, you will take a small part of your idea and make it more real and on the internet, where you can point to it in your portfolio. Over the next few weeks we will look at github, phonegap build and firebase as a way of creating a rapid prototype to try out part of your idea.

##Marking

21/25 of the total mark for getting something on your github page and on your phone.

###Extra Marks

These are my ideas for extra marks up to 25/25. You can also propose your own.

1. Animation - some sort of animation that fits with what you are trying to achieve.
2. Back end - connect to data in a back end like firebase
3. Semantic Web - consume a service from the internet like google maps
4. actual user testing - show your app to a potential user and capture their reaction in a way that you can submit with your prototype for marking

##Submission

Submit your app, by putting a file on the course's dropbox (it could be a test report or some other artifact). The comments for your file should point me to a github repository.


text:
package org.springframework.boot.autoconfigure.security.oauth2.client.reactive;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;

import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration;
import org.springframework.boot.test.context.FilteredClassLoader;
import org.springframework.boot.test.context.assertj.AssertableReactiveWebApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.oauth2.client.InMemoryReactiveOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.server.AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.server.OAuth2AuthorizationCodeGrantWebFilter;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.server.authentication.OAuth2LoginAuthenticationWebFilter;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.server.WebFilter;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for {@link ReactiveOAuth2ClientAutoConfiguration}.
 *
 * @author Madhura Bhave
 */
class ReactiveOAuth2ClientAutoConfigurationTests {

	private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
			.withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class,
					ReactiveSecurityAutoConfiguration.class));

	private static final String REGISTRATION_PREFIX = "spring.security.oauth2.client.registration";

	@Test
	void autoConfigurationShouldBackOffForServletEnvironments() {
		new WebApplicationContextRunner()
				.withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class))
				.run((context) -> assertThat(context).doesNotHaveBean(ReactiveOAuth2ClientAutoConfiguration.class));
	}

	@Test
	void clientRegistrationRepositoryBeanShouldNotBeCreatedWhenPropertiesAbsent() {
		this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ClientRegistrationRepository.class));
	}

	@Test
	void clientRegistrationRepositoryBeanShouldBeCreatedWhenPropertiesPresent() {
		this.contextRunner
				.withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd",
						REGISTRATION_PREFIX + ".foo.client-secret=secret", REGISTRATION_PREFIX + ".foo.provider=github")
				.run((context) -> {
					ReactiveClientRegistrationRepository repository = context
							.getBean(ReactiveClientRegistrationRepository.class);
					ClientRegistration registration = repository.findByRegistrationId("foo")
							.block(Duration.ofSeconds(30));
					assertThat(registration).isNotNull();
					assertThat(registration.getClientSecret()).isEqualTo("secret");
				});
	}

	@Test
	void authorizedClientServiceAndRepositoryBeansAreConditionalOnClientRegistrationRepository() {
		this.contextRunner.run((context) -> {
			assertThat(context).doesNotHaveBean(ReactiveOAuth2AuthorizedClientService.class);
			assertThat(context).doesNotHaveBean(ServerOAuth2AuthorizedClientRepository.class);
		});
	}

	@Test
	void configurationRegistersAuthorizedClientServiceAndRepositoryBeans() {
		this.contextRunner.withUserConfiguration(ReactiveClientRepositoryConfiguration.class).run((context) -> {
			assertThat(context).hasSingleBean(InMemoryReactiveOAuth2AuthorizedClientService.class);
			assertThat(context).hasSingleBean(AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository.class);
		});
	}

	@Test
	void authorizedClientServiceBeanIsConditionalOnMissingBean() {
		this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientRepositoryConfiguration.class)
				.run((context) -> {
					assertThat(context).hasSingleBean(ReactiveOAuth2AuthorizedClientService.class);
					assertThat(context).hasBean("testAuthorizedClientService");
				});
	}

	@Test
	void authorizedClientRepositoryBeanIsConditionalOnAuthorizedClientService() {
		this.contextRunner
				.run((context) -> assertThat(context).doesNotHaveBean(ServerOAuth2AuthorizedClientRepository.class));
	}

	@Test
	void configurationRegistersAuthorizedClientRepositoryBean() {
		this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientServiceConfiguration.class)
				.run((context) -> assertThat(context)
						.hasSingleBean(AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository.class));
	}

	@Test
	void authorizedClientRepositoryBeanIsConditionalOnMissingBean() {
		this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientRepositoryConfiguration.class)
				.run((context) -> {
					assertThat(context).hasSingleBean(ServerOAuth2AuthorizedClientRepository.class);
					assertThat(context).hasBean("testAuthorizedClientRepository");
				});
	}

	@Test
	void securityWebFilterChainBeanConditionalOnWebApplication() {
		this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientRepositoryConfiguration.class)
				.run((context) -> assertThat(context).doesNotHaveBean(SecurityWebFilterChain.class));
	}

	@Test
	void configurationRegistersSecurityWebFilterChainBean() { // gh-17949
		new ReactiveWebApplicationContextRunner()
				.withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class))
				.withUserConfiguration(ReactiveOAuth2AuthorizedClientServiceConfiguration.class,
						ServerHttpSecurityConfiguration.class)
				.run((context) -> {
					assertThat(hasFilter(context, OAuth2LoginAuthenticationWebFilter.class)).isTrue();
					assertThat(hasFilter(context, OAuth2AuthorizationCodeGrantWebFilter.class)).isTrue();
				});
	}

	@Test
	void autoConfigurationConditionalOnClassFlux() {
		assertWhenClassNotPresent(Flux.class);
	}

	@Test
	void autoConfigurationConditionalOnClassEnableWebFluxSecurity() {
		assertWhenClassNotPresent(EnableWebFluxSecurity.class);
	}

	@Test
	void autoConfigurationConditionalOnClassClientRegistration() {
		assertWhenClassNotPresent(ClientRegistration.class);
	}

	private void assertWhenClassNotPresent(Class<?> classToFilter) {
		FilteredClassLoader classLoader = new FilteredClassLoader(classToFilter);
		this.contextRunner.withClassLoader(classLoader)
				.withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd",
						REGISTRATION_PREFIX + ".foo.client-secret=secret", REGISTRATION_PREFIX + ".foo.provider=github")
				.run((context) -> assertThat(context).doesNotHaveBean(ReactiveOAuth2ClientAutoConfiguration.class));
	}

	@SuppressWarnings("unchecked")
	private boolean hasFilter(AssertableReactiveWebApplicationContext context, Class<? extends WebFilter> filter) {
		SecurityWebFilterChain filterChain = (SecurityWebFilterChain) context
				.getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN);
		List<WebFilter> filters = (List<WebFilter>) ReflectionTestUtils.getField(filterChain, "filters");
		return filters.stream().anyMatch(filter::isInstance);
	}

	@Configuration(proxyBeanMethods = false)
	static class ReactiveClientRepositoryConfiguration {

		@Bean
		ReactiveClientRegistrationRepository clientRegistrationRepository() {
			List<ClientRegistration> registrations = new ArrayList<>();
			registrations.add(getClientRegistration("first", "https://user-info-uri.com"));
			registrations.add(getClientRegistration("second", "https://other-user-info"));
			return new InMemoryReactiveClientRegistrationRepository(registrations);
		}

		private ClientRegistration getClientRegistration(String id, String userInfoUri) {
			ClientRegistration.Builder builder = ClientRegistration.withRegistrationId(id);
			builder.clientName("foo").clientId("foo")
					.clientAuthenticationMethod(
							org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
					.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).scope("read")
					.clientSecret("secret").redirectUri("https://redirect-uri.com")
					.authorizationUri("https://authorization-uri.com").tokenUri("https://token-uri.com")
					.userInfoUri(userInfoUri).userNameAttributeName("login");
			return builder.build();
		}

	}

	@Configuration(proxyBeanMethods = false)
	@Import(ReactiveClientRepositoryConfiguration.class)
	static class ReactiveOAuth2AuthorizedClientServiceConfiguration {

		@Bean
		ReactiveOAuth2AuthorizedClientService testAuthorizedClientService(
				ReactiveClientRegistrationRepository clientRegistrationRepository) {
			return new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository);
		}

	}

	@Configuration(proxyBeanMethods = false)
	@Import(ReactiveOAuth2AuthorizedClientServiceConfiguration.class)
	static class ReactiveOAuth2AuthorizedClientRepositoryConfiguration {

		@Bean
		ServerOAuth2AuthorizedClientRepository testAuthorizedClientRepository(
				ReactiveOAuth2AuthorizedClientService authorizedClientService) {
			return new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService);
		}

	}

	@Configuration(proxyBeanMethods = false)
	static class ServerHttpSecurityConfiguration {

		@Bean
		ServerHttpSecurity http() {
			TestServerHttpSecurity httpSecurity = new TestServerHttpSecurity();
			return httpSecurity;
		}

		static class TestServerHttpSecurity extends ServerHttpSecurity implements ApplicationContextAware {

			@Override
			public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
				super.setApplicationContext(applicationContext);
			}

		}

	}

}


text:
class Draggable(object):
    def dragText(self):
        return None

    def dragURL(self):
        return None

    def dragCustom(self):
        pass


text:
.class Lcom/android/server/net/NetworkPolicyManagerService$AppIdleStateChangeListener;
.super Landroid/app/usage/UsageStatsManagerInternal$AppIdleStateChangeListener;
.source "NetworkPolicyManagerService.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/net/NetworkPolicyManagerService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "AppIdleStateChangeListener"
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/net/NetworkPolicyManagerService;

# direct methods
.method private constructor <init>(Lcom/android/server/net/NetworkPolicyManagerService;)V
    .locals 0

    iput-object p1, p0, Lcom/android/server/net/NetworkPolicyManagerService$AppIdleStateChangeListener;->this$0:Lcom/android/server/net/NetworkPolicyManagerService;

    invoke-direct {p0}, Landroid/app/usage/UsageStatsManagerInternal$AppIdleStateChangeListener;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Lcom/android/server/net/NetworkPolicyManagerService;Lcom/android/server/net/NetworkPolicyManagerService$AppIdleStateChangeListener;)V
    .locals 0

    invoke-direct {p0, p1}, Lcom/android/server/net/NetworkPolicyManagerService$AppIdleStateChangeListener;-><init>(Lcom/android/server/net/NetworkPolicyManagerService;)V

    return-void
.end method

# virtual methods
.method public onAppIdleStateChanged(Ljava/lang/String;IZ)V
    .locals 4

    :try_start_0
    iget-object v2, p0, Lcom/android/server/net/NetworkPolicyManagerService$AppIdleStateChangeListener;->this$0:Lcom/android/server/net/NetworkPolicyManagerService;

    invoke-static {v2}, Lcom/android/server/net/NetworkPolicyManagerService;->-get2(Lcom/android/server/net/NetworkPolicyManagerService;)Landroid/content/Context;

    move-result-object v2

    invoke-virtual {v2}, Landroid/content/Context;->getPackageManager()Landroid/content/pm/PackageManager;

    move-result-object v2

    const/16 v3, 0x2000

    invoke-virtual {v2, p1, v3, p2}, Landroid/content/pm/PackageManager;->getPackageUidAsUser(Ljava/lang/String;II)I

    move-result v1

    iget-object v2, p0, Lcom/android/server/net/NetworkPolicyManagerService$AppIdleStateChangeListener;->this$0:Lcom/android/server/net/NetworkPolicyManagerService;

    iget-object v3, v2, Lcom/android/server/net/NetworkPolicyManagerService;->mUidRulesFirstLock:Ljava/lang/Object;

    monitor-enter v3
    :try_end_0
    .catch Landroid/content/pm/PackageManager$NameNotFoundException; {:try_start_0 .. :try_end_0} :catch_0

    :try_start_1
    iget-object v2, p0, Lcom/android/server/net/NetworkPolicyManagerService$AppIdleStateChangeListener;->this$0:Lcom/android/server/net/NetworkPolicyManagerService;

    invoke-virtual {v2, v1}, Lcom/android/server/net/NetworkPolicyManagerService;->updateRuleForAppIdleUL(I)V

    iget-object v2, p0, Lcom/android/server/net/NetworkPolicyManagerService$AppIdleStateChangeListener;->this$0:Lcom/android/server/net/NetworkPolicyManagerService;

    invoke-static {v2, v1}, Lcom/android/server/net/NetworkPolicyManagerService;->-wrap27(Lcom/android/server/net/NetworkPolicyManagerService;I)V
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    :try_start_2
    monitor-exit v3

    :goto_0
    return-void

    :catchall_0
    move-exception v2

    monitor-exit v3

    throw v2
    :try_end_2
    .catch Landroid/content/pm/PackageManager$NameNotFoundException; {:try_start_2 .. :try_end_2} :catch_0

    :catch_0
    move-exception v0

    goto :goto_0
.end method

.method public onParoleStateChanged(Z)V
    .locals 2

    iget-object v0, p0, Lcom/android/server/net/NetworkPolicyManagerService$AppIdleStateChangeListener;->this$0:Lcom/android/server/net/NetworkPolicyManagerService;

    iget-object v1, v0, Lcom/android/server/net/NetworkPolicyManagerService;->mUidRulesFirstLock:Ljava/lang/Object;

    monitor-enter v1

    :try_start_0
    iget-object v0, p0, Lcom/android/server/net/NetworkPolicyManagerService$AppIdleStateChangeListener;->this$0:Lcom/android/server/net/NetworkPolicyManagerService;

    invoke-virtual {v0}, Lcom/android/server/net/NetworkPolicyManagerService;->updateRulesForAppIdleParoleUL()V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit v1

    return-void

    :catchall_0
    move-exception v0

    monitor-exit v1

    throw v0
.end method


text:
'use strict';

module.exports = require('../src/traces/scatterpolar');


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using NUnit.Framework;
using XenAdmin.Dialogs;

namespace XenAdminTests.DialogTests
{
    public abstract class DialogTest<T>: MainWindowTester where T: XenDialogBase
    {
        protected T dialog;

        [Test]
        public void RunDialogTests()
        {
            RunBefore();

            dialog = MW<T>(NewDialog);

            RunBeforeShow();

            MW(dialog.Show);

            // Check that if we have a help button, we have help
            if (dialog.HelpButton)
                Assert.IsTrue(dialog.HasHelp(), "Help missing");

            // Any subsequent testing defined in derived class
            RunAfter();

            MW(() =>
                {
                    dialog.Close();
                    dialog.Dispose();
                });
        }

        protected abstract T NewDialog();

        protected virtual void RunBefore()
        {
        }

        protected virtual void RunBeforeShow()
        {
        }

        protected virtual void RunAfter()
        {
        }
    }
}

namespace XenAdminTests.DialogTests.state1_xml
{
    [SetUpFixture]
    public class DialogTestSetUp : MainWindowLauncher_SetUpFixture
    {
        public DialogTestSetUp()
            : base("state1.xml")
        { }
    }
}

namespace XenAdminTests.DialogTests.boston
{
    [SetUpFixture]
    public class DialogTestSetUp : MainWindowLauncher_SetUpFixture
    {
        public DialogTestSetUp()
            : base("boston-db.xml")
        { }
    }
}

namespace XenAdminTests.DialogTests.state2_xml
{
    [SetUpFixture]
    public class DialogTestSetUp : MainWindowLauncher_SetUpFixture
    {
        public DialogTestSetUp()
            : base("state2.xml")
        { }
    }
}

namespace XenAdminTests.DialogTests.cowleyPolicies_xml
{
    [SetUpFixture]
    public class DialogTestSetUp : MainWindowLauncher_SetUpFixture
    {
        public DialogTestSetUp()
            : base("cowleyPolicies.xml")
        { }
    }
}


text:
package org.concord.energy3d.gui;

import org.concord.energy3d.scene.Scene;
import org.concord.energy3d.scene.SceneManager;
import org.concord.energy3d.simulation.SolarRadiation;
import org.concord.energy3d.util.SpringUtilities;
import org.concord.energy3d.util.Util;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;

/**
 * @author Charles Xie
 */
class SimulationSettingsDialog extends JDialog {

    private static final long serialVersionUID = 1L;
    private final static DecimalFormat FORMAT2 = new DecimalFormat("##.##");
    private JTextField cellSizeTextField;

    SimulationSettingsDialog() {

        super(MainFrame.getInstance(), true);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        setTitle("Simulation Settings");

        getContentPane().setLayout(new BorderLayout());
        final JPanel panel = new JPanel(new SpringLayout());
        panel.setBorder(new EmptyBorder(15, 15, 15, 15));
        getContentPane().add(panel, BorderLayout.CENTER);

        final Scene s = Scene.getInstance();
        final JTextField mirrorNxTextField = new JTextField(s.getMirrorNx() + "", 6);
        final JTextField mirrorNyTextField = new JTextField(s.getMirrorNy() + "", 6);
        final JTextField parabolicDishNTextField = new JTextField(s.getParabolicDishN() + "", 6);
        final JTextField rackCellSizeTextField = new JTextField(FORMAT2.format(s.getRackCellSize()));
        final JLabel rackCellSizeLabelLeft = new JLabel("Rack cell size: ");
        final JLabel rackCellSizeLabelRight = new JLabel("Meters");
        final JLabel rackModelLabelRight = new JLabel("Fast but inaccurate");
        final JTextField timeStepTextField = new JTextField(FORMAT2.format(s.getTimeStep()));
        cellSizeTextField = new JTextField(FORMAT2.format(s.getSolarStep() * s.getScale()));

        final JComboBox<String> airMassComboBox = new JComboBox<>(new String[]{"None", "Kasten-Young", "Sphere Model"});
        airMassComboBox.setSelectedIndex(SolarRadiation.getInstance().getAirMassSelection() + 1);

        final JComboBox<String> rackModelComboBox = new JComboBox<>(new String[]{"Approximate", "Exact"});
        rackModelComboBox.addItemListener(e -> {
            final boolean approximate = rackModelComboBox.getSelectedIndex() == 0;
            rackCellSizeTextField.setEnabled(approximate);
            rackCellSizeLabelLeft.setEnabled(approximate);
            rackCellSizeLabelRight.setEnabled(approximate);
            rackModelLabelRight.setText(approximate ? "Fast but inaccurate" : "Slow but accurate");
        });
        rackModelComboBox.setSelectedIndex(s.isRackModelExact() ? 1 : 0);

        final JComboBox<String> calculateRoiComboBox = new JComboBox<>(new String[]{"No", "Yes"});
        calculateRoiComboBox.setSelectedIndex(s.getCalculateRoi() ? 1 : 0);

        final ActionListener okListener = e -> {
            int mirrorNx;
            int mirrorNy;
            int parabolicDishN;
            double rackCellSize;
            double cellSize;
            int timeStep;
            try {
                mirrorNx = Integer.parseInt(mirrorNxTextField.getText());
                mirrorNy = Integer.parseInt(mirrorNyTextField.getText());
                parabolicDishN = Integer.parseInt(parabolicDishNTextField.getText());
                rackCellSize = Double.parseDouble(rackCellSizeTextField.getText());
                cellSize = Double.parseDouble(cellSizeTextField.getText());
                timeStep = (int) Double.parseDouble(timeStepTextField.getText());
            } catch (final NumberFormatException err) {
                err.printStackTrace();
                JOptionPane.showMessageDialog(this, "Invalid input: " + err.getMessage(), "Invalid Input", JOptionPane.ERROR_MESSAGE);
                return;
            }
            // range check
            if (cellSize < 0.01 || cellSize > 100) {
                JOptionPane.showMessageDialog(this, "Cell size must be in 0.01-100 meters (with larger sizes for larger areas).",
                        "Range Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            // power of two check
            if (!Util.isPowerOfTwo(mirrorNx) || !Util.isPowerOfTwo(mirrorNy)) {
                JOptionPane.showMessageDialog(this, "Number of mirror grid cells in x or y direction must be power of two.",
                        "Invalid Input", JOptionPane.ERROR_MESSAGE);
                return;
            }
            // range check
            if (timeStep < 5 || timeStep > 60) {
                JOptionPane.showMessageDialog(this, "Time step must be in 5-60 seconds.", "Range Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            if (rackCellSize < 0.5 || rackCellSize > 50) {
                JOptionPane.showMessageDialog(this, "The grid cell size of a rack must be in 0.5-50 meters.", "Range Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            if (mirrorNx < 2 || mirrorNy < 2 || parabolicDishN < 2) {
                JOptionPane.showMessageDialog(this, "Number of mirror grid cells in x or y direction must be at least two.", "Range Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            s.setMirrorNx(mirrorNx);
            s.setMirrorNy(mirrorNy);
            s.setParabolicDishN(parabolicDishN);
            s.setRackModelExact(rackModelComboBox.getSelectedIndex() == 1);
            s.setRackCellSize(rackCellSize);
            s.setTimeStep(timeStep);
            s.setSolarStep(cellSize / s.getScale());
            s.setCalculateRoi(calculateRoiComboBox.getSelectedIndex() == 1);
            s.setEdited(true);
            SolarRadiation.getInstance().setAirMassSelection(airMassComboBox.getSelectedIndex() - 1);
            if (SceneManager.getInstance().getSolarHeatMap()) {
                EnergyPanel.getInstance().updateRadiationHeatMap();
            }
            SimulationSettingsDialog.this.dispose();
        };

        // set the grid size ("solar step")
        panel.add(new JLabel("Cell size: "));
        panel.add(cellSizeTextField);
        panel.add(new JLabel("Meter"));

        // set the time step
        panel.add(new JLabel("Time step: "));
        panel.add(timeStepTextField);
        timeStepTextField.setColumns(6);
        panel.add(new JLabel("Minutes"));

        // select the model for racks
        panel.add(new JLabel("Solar panel rack model:"));
        panel.add(rackModelComboBox);
        panel.add(rackModelLabelRight);

        // set number of grid points for a solar rack, used in both heat map generation and energy calculation
        panel.add(rackCellSizeLabelLeft);
        panel.add(rackCellSizeTextField);
        panel.add(rackCellSizeLabelRight);

        // set number of grid points for a mirror, used in both heat map generation and energy calculation
        panel.add(new JLabel("Heliostat mirror mesh: "));
        final JPanel p1 = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
        p1.add(mirrorNxTextField);
        p1.add(new JLabel("  \u00D7  "));
        p1.add(mirrorNyTextField);
        panel.add(p1);
        panel.add(new JLabel("Must be power of 2"));

        // set number of grid points for a parabolic dish, used in both heat map generation and energy calculation
        panel.add(new JLabel("Parabolic dish mesh: "));
        panel.add(parabolicDishNTextField);
        panel.add(new JLabel("Must be power of 2"));

        // choose air mass
        panel.add(new JLabel("Air mass: "));
        panel.add(airMassComboBox);
        panel.add(new JLabel());

        // choose to calculate ROI or not
        panel.add(new JLabel("Financial analysis: "));
        panel.add(calculateRoiComboBox);
        panel.add(new JLabel());

        SpringUtilities.makeCompactGrid(panel, 8, 3, 8, 8, 8, 8);

        final JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);

        final JButton okButton = new JButton("OK");
        okButton.addActionListener(okListener);
        okButton.setActionCommand("OK");
        buttonPanel.add(okButton);
        getRootPane().setDefaultButton(okButton);

        final JButton cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(e -> SimulationSettingsDialog.this.dispose());
        cancelButton.setActionCommand("Cancel");
        buttonPanel.add(cancelButton);

        pack();
        setLocationRelativeTo(MainFrame.getInstance());

    }

    JTextField getCellSizeField() {
        return cellSizeTextField;
    }

}


text:
package com.db4o.reflect.jdk;

import com.db4o.reflect.core.*;

/**
 * @sharpen.ignore
 */
public interface JavaReflectClass extends ConstructorAwareReflectClass {
	Class getJavaClass();
}


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

  <title>Description of edgePosition</title>
  <meta name="keywords" content="edgePosition">
  <meta name="description" content="EDGEPOSITION return position of a point on an edge">
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta name="generator" content="m2html © 2003 Guillaume Flandin">
  <meta name="robots" content="index, follow">
  <link type="text/css" rel="stylesheet" href="../../m2html.css">

Home >  imael > geom2d > edgePosition.m

edgePosition

PURPOSE

EDGEPOSITION return position of a point on an edge

SYNOPSIS

function d = edgePosition(point, edge)

DESCRIPTION

EDGEPOSITION return position of a point on an edge

   POS = edgePosition(POINT, EDGE);
   Computes position of point POINT on the edge EDGE, relative to the
   position of edge vertices.
   EDGE has the form [x1 y1 x2 y2],
   POINT has the form [x y], and is assumed to belong to edge.
   The position POS has meaning:
     POS<0:    POINT is located before the first vertex
     POS=0:    POINT is located on the first vertex
     0<POS<1:  POINT is located between the 2 vertices (on the edge)
     POS=1:    POINT is located on the second vertex
     POS<0:    POINT is located after the second vertex

   POS = edgePosition(POINT, EDGES);
   If EDGES is an array of NL edges, return NL positions, corresponding to
   each edge.

   POS = edgePosition(POINTS, EDGE);
   If POINTS is an array of NP points, return NP positions, corresponding
   to each point.

   POS = edgePosition(POINTS, EDGES);
   If POINTS is an array of NP points and edgeS is an array of NL edges,
   return an array of [NP NL] position, corresponding to each couple
   point-edge.

   See also:
   edges2d, createEdge, onEdge

   ---------

   author : David Legland
   INRA - TPV URPOI - BIA IMASTE
   created the 25/05/2004.

CROSS-REFERENCE INFORMATION

This function calls:

This function is called by:

intersectEdges	INTERSECTEDGES return all intersections points of N edges in 2D

polylineSelfIntersections	POLYLINESELFINTERSECTIONS  find self-intersections points of a polyline

<address>Generated on Fri 05-Feb-2010 11:20:41 by m2html © 2003</address>


text:
me.duyet.net

/ resume

/ git-stats

/ publications

blog.duyet.net

/ feed

/ about

/ category / Git

/ category / Nodejs

/ category / Apache Spark

/ category / javascript

/ category / BigData

ask.duyetdev.com

/

/ Ask me anything

/ Archive

demo.duyet.net

rain.duyetdev.com

sql.duyetdev.com

sqldesigner.duyetdev.com

aframe.duyet.net

arkadia.duyetdev.com

arkadia.duyetdev.com

kieu.duyet.net

node-style-guide.duyet.net

vietnamese-wordlist.duyet.net

offline.duyet.net

talk.duyet.net

/

/

/

/

/

/

static-html-server.duyetdev.com

spheres.duyetdev.com

/ uit


text:
package ru.nivanov.model;

/**
 * Created by Nikolay Ivanov on 03.10.2017.
 */
public class Vacancy {

    private final String name;
    private final String url;
    private final String author;
    private final String authorUrl;
    private final long createDate;

    /**
     * Constructor.
     * @param name ..
     * @param url ..
     * @param author ..
     * @param createDate ..
     */
    public Vacancy(String name, String url, String author, String authorUrl, long createDate) {
        this.name = name;
        this.url = url;
        this.author = author;
        this.authorUrl = authorUrl;
        this.createDate = createDate;
    }

    /**
     * Creation date getter.
     * @return ..
     */
    public long getCreateDate() {
        return createDate;
    }

    @Override
    public boolean equals(Object o) {

        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        Vacancy vacancy = (Vacancy) o;

        return getName().equals(vacancy.getName()) && getUrl().equals(vacancy.getUrl()) && getAuthor().equals(
                vacancy.getAuthor()) && getAuthorUrl().equals(vacancy.getAuthorUrl());
    }

    /**
     * Name getter.
     * @return ..
     */
    public String getName() {
        return name;
    }

    /**
     * Url getter.
     * @return ..
     */
    public String getUrl() {
        return url;
    }

    /**
     * Author getter.
     * @return ..
     */
    public String getAuthor() {
        return author;
    }

    /**
     * Author url getter.
     * @return ..
     */
    public String getAuthorUrl() {
        return authorUrl;
    }

    @Override
    public int hashCode() {

        final int constant = 31;
        int result = getName().hashCode();
        result = constant * result + getUrl().hashCode();
        result = constant * result + getAuthor().hashCode();
        result = constant * result + getAuthorUrl().hashCode();
        return result;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ann. Rep. N. Y. St. Mus. nat. Hist. 28: 54 (1876)

#### Original name
Aethalium geophilum Peck

### Remarks
null


text:
namespace Lucene
{
    Encoder::~Encoder()
    {
    }

    String Encoder::encodeText(const String& originalText)
    {
        BOOST_ASSERT(false);
        return L""; // override
    }
}


text:
using std::vector;

namespace floating_temple {
namespace toy_lang {

GetVariableFunction::GetVariableFunction() {
}

LocalObject* GetVariableFunction::Clone() const {
  return new GetVariableFunction();
}

void GetVariableFunction::Dump(DumpContext* dc) const {
  CHECK(dc != nullptr);

  dc->BeginMap();
  dc->AddString("type");
  dc->AddString("GetVariableFunction");
  dc->End();
}

void GetVariableFunction::PopulateObjectProto(
    ObjectProto* object_proto, SerializationContext* context) const {
  object_proto->mutable_get_variable_function();
}

ObjectReference* GetVariableFunction::Call(
    MethodContext* method_context,
    const vector<ObjectReference*>& parameters) const {
  CHECK(method_context != nullptr);
  CHECK_EQ(parameters.size(), 1u);

  Value value;
  if (!method_context->CallMethod(parameters[0], "get", vector<Value>(),
                                  &value)) {
    return nullptr;
  }

  return value.object_reference();
}

}  // namespace toy_lang
}  // namespace floating_temple


text:
import unittest
import sys
import time
sys.path.extend(['.', '..', 'py'])

import h2o
import h2o_cmd
import h2o_hosts
import h2o_browse as h2b
import h2o_import as h2i
import h2o_glm
import h2o_util
import h2o_rf

class Basic(unittest.TestCase):
    def tearDown(self):
        h2o.check_sandbox_for_errors()

    @classmethod
    def setUpClass(cls):
        # assume we're at 0xdata with it's hdfs namenode
        global localhost
        localhost = h2o.decide_if_localhost()
        if (localhost):
            h2o.build_cloud(1, java_heap_GB=14)
        else:
            # all hdfs info is done thru the hdfs_config michal's ec2 config sets up?
            h2o_hosts.build_cloud_with_hosts()

    @classmethod
    def tearDownClass(cls):
        h2o.tear_down_cloud()

    def test_speedrf_mnist(self):
        h2o.beta_features = True
        importFolderPath = "mnist"
        csvFilelist = [
            # ("mnist_reals_testing.csv.gz", "mnist_reals_testing.csv.gz",    600),
            # ("a.csv", "b.csv", 60),
            # ("mnist_reals_testing.csv.gz", "mnist_reals_testing.csv.gz",    600),
            ("train.csv.gz", "test.csv.gz", 600),
            ]
        trial = 0
        for (trainCsvFilename, testCsvFilename, timeoutSecs) in csvFilelist:
            trialStart = time.time()

            # PARSE test****************************************
            testKey2 = testCsvFilename + "_" + str(trial) + ".hex"
            start = time.time()
            parseResult = h2i.import_parse(bucket='smalldata', path=importFolderPath + "/" + testCsvFilename,
                                           hex_key=testKey2, timeoutSecs=timeoutSecs)
            elapsed = time.time() - start
            print "parse end on ", testCsvFilename, 'took', elapsed, 'seconds', \
                "%d pct. of timeout" % ((elapsed*100)/timeoutSecs)
            print "parse result:", parseResult['destination_key']

            print "We won't use this pruning of x on test data. See if it prunes the same as the training"
            y = 784 # last column is pixel value
            print "y:"
            x = h2o_glm.goodXFromColumnInfo(y, key=parseResult['destination_key'], timeoutSecs=300)

            # PARSE train****************************************
            trainKey2 = trainCsvFilename + "_" + str(trial) + ".hex"
            start = time.time()
            parseResult = h2i.import_parse(bucket='smalldata', path=importFolderPath + "/" + trainCsvFilename,
                                           hex_key=trainKey2, timeoutSecs=timeoutSecs)
            elapsed = time.time() - start
            print "parse end on ", trainCsvFilename, 'took', elapsed, 'seconds', \
                "%d pct. of timeout" % ((elapsed*100)/timeoutSecs)
            print "parse result:", parseResult['destination_key']

            # RF+RFView (train)****************************************
            ignore_x = h2o_glm.goodXFromColumnInfo(y, key=parseResult['destination_key'], timeoutSecs=300, forRF=True)
            ntrees = 10
            params = {
                'response': y,
                'ignored_cols_by_name': ignore_x,
                'num_trees': ntrees,
                'mtry': 28, # fix because we ignore some cols, which will change the srt(cols) calc?
                'max_depth': 15,
                'sample': 0.67,
                'destination_key': 'SpeeDRF_model',
                'bin_limit': 1024,
                'seed': 784834182943470027,
                'oobee': 1,
                }
            kwargs = params.copy()
            print "Trying rf"
            timeoutSecs = 1800
            start = time.time()
            rfv = h2o_cmd.runSpeeDRF(parseResult=parseResult,
                                timeoutSecs=timeoutSecs, pollTimeoutSecs=60, retryDelaySecs=2, **kwargs)
            elapsed = time.time() - start
            print "RF completed in", elapsed, "seconds.", \
                "%d pct. of timeout" % ((elapsed*100)/timeoutSecs)
            rfv["drf_model"] = rfv.pop("speedrf_model")
            h2o_rf.simpleCheckRFView(None, rfv, **params)
            rf_model = rfv['drf_model']
            used_trees = rf_model['N']
            data_key = rf_model['_dataKey']
            model_key = rf_model['_key']

            print "Total trees: ", used_trees
            print "On data key: ", data_key
            print "Produced model key: ", model_key

if __name__ == '__main__':
    h2o.unit_main()


text:
using FUR10N.NullContracts;
using NUnit.Framework;

namespace FUR10N.NullContractsTests
{
    [TestFixture]
    public class AttributeUsageTests : TestBase
    {
        public AttributeUsageTests() : base(MainAnalyzer.BadAttributeUsageId)
        {
        }

        [Test]
        public void ReadonlyProperty_Allowed()
        {
            var code =
@"
public class Item
{
    [NotNull]public string Id { get; }
}
";
            var d = GetDiagnostics(code);
            AssertIssues(d);
        }

        [Test]
        public void ReadonlyField_Allowed()
        {
            var code =
@"
public class Item
{
    [NotNull]public readonly string Id;
}
";
            var d = GetDiagnostics(code);
            AssertIssues(d);
        }

        [Test]
        public void ConstField_Allowed()
        {
            var code =
@"
public class Item
{
    [NotNull]
    public const string Id = """";
}
";
            var d = GetDiagnostics(code);
            AssertIssues(d);
        }

        [Test]
        public void MethodArguments_Allowed()
        {
            var code =
@"
public class Item
{
    public string GetId([NotNull]string s)
    {
        return s;
    }
}
";
            var d = GetDiagnostics(code);
            AssertIssues(d);
        }

        [Test]
        public void NotReadonlyProperty_Error()
        {
            var code =
@"
public class Item
{
    [NotNull]public string Id { get; set; }
}
";
            var d = GetDiagnostics(code);
            AssertIssues(d, MainAnalyzer.BadAttributeUsageId);
        }

        [Test]
        public void NotReadonlyField_Error()
        {
            var code =
@"
public class Item
{
    [NotNull]public string Id;
}
";
            var d = GetDiagnostics(code);
            AssertIssues(d, MainAnalyzer.BadAttributeUsageId);
        }

        [Test]
        public void Method_Success()
        {
            var code =
@"
public class Item
{
    [NotNull]public string GetId()
    {
        return """";
    }
}
";
            var d = GetDiagnostics(code);
            AssertIssues(d);
        }

        [Test]
        public void Method_ValueType_Error()
        {
            var code =
@"
public class Item
{
    [NotNull]public int GetId()
    {
        return 0;
    }
}
";
            var d = GetDiagnostics(code);
            AssertIssues(d, MainAnalyzer.BadAttributeUsageId);
        }

        [Test]
        public void Class_Error()
        {
            var code =
@"
[NotNull]public class Item
{
    public string GetId()
    {
        return """";
    }
}
";
            var d = GetDiagnostics(code);
            AssertIssues(d, MainAnalyzer.BadAttributeUsageId);
        }

        [Test]
        public void NonNullableType_Error()
        {
            var code =
@"
public class Item
{
    [NotNull]
    public readonly int Id;
}
";
            var d = GetDiagnostics(code);
            AssertIssues(d, MainAnalyzer.BadAttributeUsageId);
        }

        [Test]
        public void Struct_Error()
        {
            var code =
@"
public struct Date
{
    public int Ticks;
}

public class Item
{
    [NotNull]
    public readonly Date day;
}
";
            var d = GetDiagnostics(code);
            AssertIssues(d, MainAnalyzer.BadAttributeUsageId);
        }
    }
}


text:
layout: post
title: Errores comunes del análisis estático (parte II)
date: '2016-08-01T07:00:00.000+01:00'
dateReady: 2016-08-01
locale: es
author: Antonio Calero
comments: true
share: true
imagefeature: 2016-08-01-errores-comunes-analisis-estatico-II.png
category:
- calidad
description: Continuamos con la recopilación de errores graves que provocan rechazo y mala fama al análisis estático.

---

Si aún no has leído [los cinco primeros errores más comunes](/2016/07/20/errores-comunes-analisis-estatico-I) puedes hacerlo ahora y así ponerte en contexto.

A continuación te dejo con el resto de la recopilación:

## Error #6. Las herramientas no se complementan con otros tipos de tests

Aunque en los últimos años ha mejorado mucho hay cosas que el análisis estático no puede detectar: problemas de configuración, errores que solo se dan en tiempo de ejecución, ...

Por eso no basta solo con el análisis estático. Siempre tienes que proporcionar un buen conjunto de tests que aseguren otros aspectos de calidad (unitarios, integración, rendimiento, ...). Estos tests pueden asegurar que el código cumple con ciertos requisitos de forma diferente a como lo hace el análisis estático.

Es un error muy común pensar que solo usando análisis estático vas a poder solucionar todos tus problemas. Nada más lejos de la realidad. El análisis estático es potente, pero no tanto.

## Error #7. La configuración del IDE es la de por defecto

No puedes dejar que cada desarrollador trabaje con un IDE con configuraciones que no estén alineadas con las herramientas de análisis estático.

Hay que proporcionar las configuraciones adecuadas para cada IDE de forma que las inspecciones de código que se hagan en el IDE sean las mismas (o lo más parecidas posible) a las normativas definidas y al análisis estático. De nada sirve que la configuración del IDE indente con cuatro espacios y que luego la regla de análisis estático valide que sea con dos espacios. Tienes que revisar con mucho detalle todas las reglas existentes en el IDE y activar/desactivar las reglas que sean necesarias para alinearlas con los estándares definidos.

Cada vez que se añada una regla nueva en el análisis estático habrá que revisar que los IDEs también la incluyen. En el caso de SonarQube esto es bastante sencillo al poder utilizar el plugin "SonarLint" que incluso permite sincronizarse con el servidor de SonarQube de forma automática.

## Error #8. No hay difusión, no hay seguimiento, así que no hay mejora continua

Ya tienes todo montado y funcionando. Los desarrolladores están motivados y el ciclo de desarrollo incluye el análisis estático como un paso más. ¿Y ahora qué?

Si poco a poco vas abandonando el proceso y no difundes las mejoras, no haces seguimiento, no pides feedback a los equipos, no actualizas las herramientas, no incluyes reglas nuevas, ... el análisis estático acabará siendo ineficiente y no se producirá un ciclo de mejora continua. Dejará de aportar valor en poco tiempo.

Es fundamental comunicar los cambios, revisar el proceso frecuentemente, revisar y proponer reglas, hablar con los equipos para ver si hay más cosas que se puedan incluir en el análisis estático, comprobar y comunicar los resultados (¿hay menos errores en producción o todo sigue igual?).

## Error #9. Las quejas sobre los falsos positivos

Muy común. Una vez alguien detecta un falso positivo el análisis estático pierde todo su prestigio y "ya no vale". Hay desarrolladores que están deseando que eso ocurra para quitarle valor.

Y es que las herramientas no son perfectas (ni los humanos tampoco, a pesar de que algunos desarrolladores tengan el ego muy alto), eso es evidente, por tanto habrá casos en los que la herramienta no será lo suficientemente inteligente como para saber si ese trozo de código va a producir un error o no. Ante la duda, se marca como posible defecto y ya el desarrollador deberá tomar la decisión final.

Por ejemplo, en SonarQube es muy fácil marcar falsos positivos, así que no debería haber quejas sino todo lo contrario. Incluso si alguna regla produce demasiados falsos positivos entonces habrá que revisarla en profundidad porque es probable que haya que desactivarla o activar otras alternativas.

## Error #10. Empezar el análisis estático con demasiadas reglas

Es preferible tener pocas reglas que puedas entender e ir corrigiendo a tener muchas reglas que no sabes ni porque están ahí y que no puedas corregir.

Si no tienes tiempo suficiente para hacer un primer estudio de lo que quieres incorporar y las reglas que necesitas activar, prueba con un conjunto muy básico (aquellas que sean más graves) y empieza a sacar métricas del análisis estático. No te preocupes. Divide y vencerás. Empieza con lo mínimo y poco a poco trabaja en mejorarlo. Ese es el objetivo y ese ciclo de mejora continua es lo que más te va a ayudar.

Añade reglas poco a poco evitando las más controvertidas e inconvenientes y será la mejor forma de asegurar la calidad de tu código.

Puedes empezar incluso sin reglas. Te sorprendería ver cuanta información valiosa pueden aportar métricas como la complejidad ciclomática o el código duplicado (o repetido). Pero eso lo dejo para otro artículo.

## Bola extra. Los malvados gestores

Efectivamente. No pensarías que es todo tan fácil, ¿verdad? Recuerda que aunque [los gestores deberían programar](2016/07/27/los-gestores-deberian-programar) no lo hacen, así que no saben nada de esto ni le van a dar importancia. Tienes que conseguir ganarte a los gestores para estar de tu parte o no vas a tener una forma de poder dedicar suficiente tiempo a preocuparte por el análisis estático.

Esto es así porque no es algo a corto plazo sino más a medio o largo plazo y hay que invertir tiempo. Tienes que hacer entender a los gestores que el análisis estático tiene un gran retorno de inversión (o aliarte con alguno que piense así). Tienen que entender los requisitos, los objetivos y permitir que se dedique tiempo suficiente.

Lo que pasará si no consigues alinearte con ellos es que dedicarás mucho esfuerzo que no servirá de nada.

***

Con esto completamos el segundo "pack" de errores comunes que deberías evitar en el uso de análisis estático.

### En conclusión...

El análisis estático no es simplemente instalar una herramienta y ya está. Requiere dedicación, colaboración, difusión y una serie de tareas adicionales que si no se tienen en cuenta te llevarán al fracaso. Así que ya sabes, como con todo en esta vida, cuando te embarques en esa difícil misión de implantar análisis estático, reflexiona y planifica bien todo lo que vas a hacer, porque de eso dependerá que el análisis estático sume todas sus ventajas a tu proceso de desarrollo.

En resumen:

* No permitas que las versiones liberadas se salten los umbrales de calidad
* Ten en cuenta la opinión de los desarrolladores a la hora de definir las reglas
* Intenta utilizar el análisis estático desde el principio, y no solo cuando ya estas a punto de poner en producción el proyecto
* Alinea tus normativas de desarrollo con el análisis estático
* Utiliza reglas personalizadas para intentar cubrir los casos especiales de tu arquitectura
* No te olvides de los tests (unitarios, integración, ...), el análisis estático solo ve una parte de los posibles problemas potenciales
* Sincroniza la configuración del IDE con el análisis estático, que en todos sitios se mida lo mismo
* Difunde, difunde y difunde. Obten feedback y lleva el análisis estático a un ciclo de mejora continua (como todo lo demás)
* Los falsos positivos se pueden (y deben) gestionar, que no te frenen con ellos
* Keep It Small and Simple (KISS), hay muchas reglas que se pueden activar pero lo mejor es simplificar y empezar con pocas, que puedan resolverse
* Busca el apoyo de la gestión/dirección, sin ellos no podrás tener éxito y harás un sobreesfuerzo que no servirá de nada

Esas son algunas de las cosas que tienes que tener en cuenta pero seguro que tú conoces más, así que deja un comentario y seguimos debatiendo.

__________________________________________________

    Adaptación del artículo original de Michael Davidek


text:
package com.satalyst.powerbi;

import org.apache.commons.lang3.builder.ToStringBuilder;

/**
 * Thrown if an error executing a {@see com.satalyst.powerbi.PowerBiOperation} occurs.
 *
 * @author Aidan Morgan
 */
public class PowerBiOperationExecutionException extends Exception {
    private Integer statusCode;
    private String errorMessage;

    public PowerBiOperationExecutionException(String message, Integer statusCode, String errorMessage) {
        super(message);
        this.statusCode = statusCode;
        this.errorMessage = errorMessage;
    }

    public Integer getStatusCode() {
        return statusCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
                .append("statusCode", statusCode)
                .append("errorMessage", errorMessage)
                .toString();
    }
}


text:
<?php

namespace Surume\Runtime\Provider\Channel;

use Surume\Channel\Channel;
use Surume\Channel\ChannelBaseInterface;
use Surume\Channel\ChannelProtocolInterface;
use Surume\Channel\ChannelCompositeInterface;
use Surume\Channel\Extra\Response;
use Surume\Channel\Router\RuleHandler;
use Surume\Channel\Router\RuleMatchDestination;
use Surume\Command\CommandManagerInterface;
use Surume\Core\CoreInterface;
use Surume\Core\Service\ServiceProvider;
use Surume\Core\Service\ServiceProviderInterface;
use Surume\Promise\Promise;
use Surume\Promise\PromiseInterface;
use Surume\Runtime\Runtime;
use Surume\Runtime\RuntimeInterface;
use Error;
use Exception;

class ChannelProvider extends ServiceProvider implements ServiceProviderInterface
{
    /**
     * @var string[]
     */
    protected $requires = [
        'Surume\Command\CommandManagerInterface',
        'Surume\Config\ConfigInterface',
        'Surume\Channel\ChannelFactoryInterface',
        'Surume\Runtime\RuntimeInterface'
    ];

    /**
     * @var string[]
     */
    protected $provides = [
        'Surume\Runtime\Channel\ChannelInterface'
    ];

    /**
     * @var CommandManagerInterface
     */
    protected $commander;

    /**
     * @param CoreInterface $core
     */
    protected function register(CoreInterface $core)
    {
        $this->commander = $core->make('Surume\Command\CommandManagerInterface');

        $config  = $core->make('Surume\Config\ConfigInterface');
        $runtime = $core->make('Surume\Runtime\RuntimeInterface');
        $factory = $core->make('Surume\Channel\ChannelFactoryInterface');

        $master = $factory->create('Surume\Channel\ChannelBase', [
            $runtime->parent() !== null
                ? $config->get('channel.channels.master.class')
                : 'Surume\Channel\Model\Null\NullModel',
            array_merge(
                $config->get('channel.channels.master.config'),
                [
                    'hosts' => $runtime->parent() !== null ? $runtime->parent() : $runtime->alias()
                ]
            )
        ]);

        $slave = $factory->create('Surume\Channel\ChannelBase', [
            $config->get('channel.channels.slave.class'),
            $config->get('channel.channels.slave.config')
        ]);

        $composite = $factory->create('Surume\Channel\ChannelComposite')
            ->setBus('master', $master)
            ->setBus('slave', $slave)
        ;

        $core->instance(
            'Surume\Runtime\Channel\ChannelInterface',
            $composite
        );
    }

    /**
     * @param CoreInterface $core
     */
    protected function unregister(CoreInterface $core)
    {
        unset($this->commander);

        $core->remove(
            'Surume\Runtime\Channel\ChannelInterface'
        );
    }

    /**
     * @param CoreInterface $core
     */
    protected function boot(CoreInterface $core)
    {
        $runtime = $core->make('Surume\Runtime\RuntimeInterface');
        $channel = $core->make('Surume\Runtime\Channel\ChannelInterface');
        $console = $core->make('Surume\Runtime\Channel\ConsoleInterface');

        if ($runtime->parent() === null)
        {
            $this->applyRootRouting($runtime, $channel, $console);
        }
        else
        {
            $this->applySimpleRouting($runtime, $channel);
        }

        $runtime->on('create', [ $channel, 'start' ]);
        $runtime->on('destroy', [ $channel, 'stop' ]);
    }

    /**
     * @param RuntimeInterface $runtime
     * @param ChannelCompositeInterface $composite
     */
    private function applySimpleRouting(RuntimeInterface $runtime, ChannelCompositeInterface $composite)
    {
        $master = $composite->bus('master');
        $slave  = $composite->bus('slave');

        $router = $composite->input();
        $router->addAnchor(
            new RuleHandler(function($params) {
                return true;
            })
        );

        $router = $composite->output();
        $router->addAnchor(
            function($receiver, ChannelProtocolInterface $protocol, $flags, callable $success = null, callable $failure = null, callable $cancel = null, $timeout = 0.0) use($runtime, $slave, $master) {
                if ($runtime->manager()->existsRuntime($receiver) || $slave->isConnected($receiver))
                {
                    $slave->push($receiver, $protocol, $flags, $success, $failure, $cancel, $timeout);
                }
                else
                {
                    $master->push($runtime->parent(), $protocol, $flags, $success, $failure, $cancel, $timeout);
                }
            }
        );

        $router = $master->input();
        $router->addRule(
            new RuleMatchDestination($master->name()),
            new RuleHandler(function($params) use($composite) {
                $this->executeProtocol($composite, $params['protocol']);
            })
        );
        $router->addAnchor(
            new RuleHandler(function($params) use($slave) {
                $slave->push($slave->getConnected(), $params['protocol'], $params['flags']);
            })
        );

        $router = $slave->input();
        $router->addRule(
            new RuleMatchDestination($slave->name()),
            new RuleHandler(function($params) use($composite) {
                $this->executeProtocol($composite, $params['protocol']);
            })
        );
        $router->addAnchor(
            new RuleHandler(function($params) use($runtime, $slave, $master) {
                $master->push($runtime->parent(), $params['protocol'], $params['flags']);
            })
        );

        $router = $master->output();
        $router->addAnchor(
            function($sender, ChannelProtocolInterface $protocol, $flags, callable $success = null, callable $failure = null, callable $cancel = null, $timeout = 0.0) use($master) {
                $master->push($sender, $protocol, $flags, $success, $failure, $cancel, $timeout);
            }
        );

        $router = $slave->output();
        $router->addAnchor(
            function($sender, ChannelProtocolInterface $protocol, $flags, callable $success = null, callable $failure = null, callable $cancel = null, $timeout = 0.0) use($slave) {
                $slave->push($sender, $protocol, $flags, $success, $failure, $cancel, $timeout);
            }
        );
    }

    /**
     * @param RuntimeInterface $runtime
     * @param ChannelCompositeInterface $composite
     * @param ChannelBaseInterface $console
     */
    private function applyRootRouting(RuntimeInterface $runtime, ChannelCompositeInterface $composite, ChannelBaseInterface $console)
    {
        $master = $composite->bus('master');
        $slave  = $composite->bus('slave');

        $router = $composite->input();
        $router->addAnchor(
            new RuleHandler(function($params) {
                return true;
            })
        );

        $router = $composite->output();
        $router->addAnchor(
            function($receiver, ChannelProtocolInterface $protocol, $flags, callable $success = null, callable $failure = null, callable $cancel = null, $timeout = 0.0) use($runtime, $slave, $console) {
                if ($receiver === Runtime::RESERVED_CONSOLE_CLIENT || $protocol->getDestination() === Runtime::RESERVED_CONSOLE_CLIENT)
                {
                    $console->push(Runtime::RESERVED_CONSOLE_CLIENT, $protocol, $flags, $success, $failure, $cancel, $timeout);
                }
                else if ($runtime->manager()->existsRuntime($receiver) || $slave->isConnected($receiver))
                {
                    $slave->push($receiver, $protocol, $flags, $success, $failure, $cancel, $timeout);
                }
                else
                {
                    $slave->push($slave->getConnected(), $protocol, $flags, $success, $failure, $cancel, $timeout);
                }
            }
        );

        $router = $master->input();
        $router->addRule(
            new RuleMatchDestination($master->name()),
            new RuleHandler(function($params) use($composite) {
                $this->executeProtocol($composite, $params['protocol']);
            })
        );
        $router->addAnchor(
            new RuleHandler(function($params) use($slave) {
                $slave->push($slave->getConnected(), $params['protocol'], $params['flags']);
            })
        );

        $router = $slave->input();
        $router->addRule(
            new RuleMatchDestination($slave->name()),
            new RuleHandler(function($params) use($composite) {
                $this->executeProtocol($composite, $params['protocol']);
            })
        );
        $router->addAnchor(
            new RuleHandler(function($params) use($runtime, $slave, $console) {
                $receiver = $params['alias'];
                $protocol = $params['protocol'];
                if ($receiver === Runtime::RESERVED_CONSOLE_CLIENT || $protocol->getDestination() === Runtime::RESERVED_CONSOLE_CLIENT)
                {
                    $console->push(Runtime::RESERVED_CONSOLE_CLIENT, $protocol, $params['flags']);
                }
                else
                {
                    $slave->push($slave->getConnected(), $params['protocol'], $params['flags']);
                }
            })
        );

        $router = $master->output();
        $router->addAnchor(
            function($sender, ChannelProtocolInterface $protocol, $flags, callable $success = null, callable $failure = null, callable $cancel = null, $timeout = 0.0) use($master) {
                $master->push($sender, $protocol, $flags, $success, $failure, $cancel, $timeout);
            }
        );

        $router = $slave->output();
        $router->addAnchor(
            function($sender, ChannelProtocolInterface $protocol, $flags, callable $success = null, callable $failure = null, callable $cancel = null, $timeout = 0.0) use($slave) {
                $slave->push($sender, $protocol, $flags, $success, $failure, $cancel, $timeout);
            }
        );
    }

    /**
     * @param ChannelCompositeInterface $composite
     * @param ChannelProtocolInterface $protocol
     */
    private function executeProtocol(ChannelCompositeInterface $composite, ChannelProtocolInterface $protocol)
    {
        /**
         * If the json_decode fails, it means the received message is leftover of request response,
         * hence it should be dropped.
         */
        try
        {
            $params = json_decode($protocol->getMessage(), true);
            $command = array_shift($params);
            $params['origin'] = $protocol->getOrigin();
            $promise = $this->executeCommand($command, $params);
        }
        catch (Error $ex)
        {
            return;
        }
        catch (Exception $ex)
        {
            return;
        }

        if ($protocol->getType() === Channel::TYPE_REQ)
        {
            $promise
                ->then(
                    function($response) use($composite, $protocol, $command) {
                        return (new Response($composite, $protocol, $response))->call();
                    },
                    function($reason) use($composite, $protocol) {
                        return (new Response($composite, $protocol, $reason))->call();
                    },
                    function($reason) use($composite, $protocol) {
                        return (new Response($composite, $protocol, $reason))->call();
                    }
                );
        }
    }

    /**
     * @param string $command
     * @param mixed[] $params
     * @return PromiseInterface
     */
    private function executeCommand($command, $params = [])
    {
        try
        {
            return $this->commander->execute($command, $params);
        }
        catch (Error $ex)
        {
            return Promise::doReject($ex);
        }
        catch (Exception $ex)
        {
            return Promise::doReject($ex);
        }
    }
}


text: angular.module('app',['ui.router','ngAnimate','ngTable'])


text:
namespace gl {

using GLFunctionPointerType = void (*)();

class MockEGLInterface {
 public:
  MockEGLInterface();
  virtual ~MockEGLInterface();

  // Set the functions called from the mock EGL implementation for the purposes
  // of testing.
  static void SetEGLInterface(MockEGLInterface* egl_interface);

  // Find an entry point to the mock GL implementation.
  static GLFunctionPointerType GL_BINDING_CALL
  GetGLProcAddress(const char* name);

// Include the auto-generated parts of this class. We split this because
// it means we can easily edit the non-auto generated parts right here in
// this file instead of having to edit some template or the code generator.

// Member functions
#include "gl_mock_autogen_egl.h"

 private:
  static MockEGLInterface* interface_;

// Static mock functions that invoke the member functions of interface_.
#include "egl_bindings_autogen_mock.h"
};

}  // namespace gl

#endif  // UI_GL_EGL_MOCK_H_