text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2004 Ferdinando Ametrano

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

/*! \file interestrate.hpp
    \brief Instrument rate class
*/

#ifndef quantlib_interest_rate_hpp
#define quantlib_interest_rate_hpp

#include <ql/compounding.hpp>
#include <ql/time/daycounters/actual365fixed.hpp>

namespace QuantLib {

    //! Concrete interest rate class
    /*! This class encapsulate the interest rate compounding algebra.
        It manages day-counting conventions, compounding conventions,
        conversion between different conventions, discount/compound factor
        calculations, and implied/equivalent rate calculations.

        \test Converted rates are checked against known good results
    */
    class InterestRate {
      public:
        //! \name constructors
        //@{
        //! Default constructor returning a null interest rate.
        InterestRate();
        //! Standard constructor
        InterestRate(Rate r,
                     const DayCounter& dc,
                     Compounding comp,
                     Frequency freq);
        //@}
        //! \name conversions
        //@{
        operator Rate() const { return r_; }
        //@}
        //! \name inspectors
        //@{
        Rate rate() const { return r_; }
        const DayCounter& dayCounter() const { return dc_; }
        Compounding compounding() const { return comp_; }
        Frequency frequency() const {
            return freqMakesSense_ ? Frequency(Integer(freq_)) : NoFrequency;
        }
        //@}

        //! \name discount/compound factor calculations
        //@{
        //! discount factor implied by the rate compounded at time t.
        /*! \warning Time must be measured using InterestRate's own
                     day counter.
        */
        DiscountFactor discountFactor(Time t) const {
            return 1.0/compoundFactor(t);
        }

        //! discount factor implied by the rate compounded between two dates
        DiscountFactor discountFactor(const Date& d1,
                                      const Date& d2,
                                      const Date& refStart = Date(),
                                      const Date& refEnd = Date()) const {
            QL_REQUIRE(d2>=d1,
                       "d1 (" << d1 << ") "
                       "later than d2 (" << d2 << ")");
            Time t = dc_.yearFraction(d1, d2, refStart, refEnd);
            return discountFactor(t);
        }

        //! compound factor implied by the rate compounded at time t.
        /*! returns the compound (a.k.a capitalization) factor
            implied by the rate compounded at time t.

            \warning Time must be measured using InterestRate's own
                     day counter.
        */
        Real compoundFactor(Time t) const;

        //! compound factor implied by the rate compounded between two dates
        /*! returns the compound (a.k.a capitalization) factor
            implied by the rate compounded between two dates.
        */
        Real compoundFactor(const Date& d1,
                            const Date& d2,
                            const Date& refStart = Date(),
                            const Date& refEnd = Date()) const {
            QL_REQUIRE(d2>=d1,
                       "d1 (" << d1 << ") "
                       "later than d2 (" << d2 << ")");
            Time t = dc_.yearFraction(d1, d2, refStart, refEnd);
            return compoundFactor(t);
        }
        //@}

        //! \name implied rate calculations
        //@{

        //! implied interest rate for a given compound factor at a given time.
        /*! The resulting InterestRate has the day-counter provided as input.

            \warning Time must be measured using the day-counter provided
                     as input.
        */
        static InterestRate impliedRate(Real compound,
                                        const DayCounter& resultDC,
                                        Compounding comp,
                                        Frequency freq,
                                        Time t);

        //! implied rate for a given compound factor between two dates.
        /*! The resulting rate is calculated taking the required
            day-counting rule into account.
        */
        static InterestRate impliedRate(Real compound,
                                        const DayCounter& resultDC,
                                        Compounding comp,
                                        Frequency freq,
                                        const Date& d1,
                                        const Date& d2,
                                        const Date& refStart = Date(),
                                        const Date& refEnd = Date()) {
            QL_REQUIRE(d2>=d1,
                       "d1 (" << d1 << ") "
                       "later than d2 (" << d2 << ")");
            Time t = resultDC.yearFraction(d1, d2, refStart, refEnd);
            return impliedRate(compound, resultDC, comp, freq, t);
        }
        //@}

        //! \name equivalent rate calculations
        //@{

        //! equivalent interest rate for a compounding period t.
        /*! The resulting InterestRate shares the same implicit
            day-counting rule of the original InterestRate instance.

            \warning Time must be measured using the InterestRate's
                     own day counter.
        */
        InterestRate equivalentRate(Compounding comp,
                                    Frequency freq,
                                    Time t) const {
            return impliedRate(compoundFactor(t), dc_, comp, freq, t);
        }

        //! equivalent rate for a compounding period between two dates
        /*! The resulting rate is calculated taking the required
            day-counting rule into account.
        */
        InterestRate equivalentRate(const DayCounter& resultDC,
                                    Compounding comp,
                                    Frequency freq,
                                    Date d1,
                                    Date d2,
                                    const Date& refStart = Date(),
                                    const Date& refEnd = Date()) const {
            QL_REQUIRE(d2>=d1,
                       "d1 (" << d1 << ") "
                       "later than d2 (" << d2 << ")");
            Time t1 = dc_.yearFraction(d1, d2, refStart, refEnd);
            Time t2 = resultDC.yearFraction(d1, d2, refStart, refEnd);
            return impliedRate(compoundFactor(t1), resultDC, comp, freq, t2);
        }
        //@}
      private:
        Rate r_;
        DayCounter dc_;
        Compounding comp_;
        bool freqMakesSense_;
        Real freq_;
    };

    /*! \relates InterestRate */
    std::ostream& operator<<(std::ostream&,
                             const InterestRate&);

}

#endif


text:
from base64 import b64decode
import json
from os.path import dirname, join, exists
import unittest
from urlparse import urlparse, parse_qs
from zlib import decompress

from onelogin.saml2.authn_request import OneLogin_Saml2_Authn_Request
from onelogin.saml2.constants import OneLogin_Saml2_Constants
from onelogin.saml2.settings import OneLogin_Saml2_Settings
from onelogin.saml2.utils import OneLogin_Saml2_Utils

class OneLogin_Saml2_Authn_Request_Test(unittest.TestCase):
    def loadSettingsJSON(self, filename='settings1.json'):
        filename = join(dirname(dirname(dirname(dirname(__file__)))), 'settings', filename)
        if exists(filename):
            stream = open(filename, 'r')
            settings = json.load(stream)
            stream.close()
            return settings
        else:
            raise Exception('Settings json file does not exist')

    def setUp(self):
        self.__settings = OneLogin_Saml2_Settings(self.loadSettingsJSON())

    def testCreateRequest(self):
        """
        Tests the OneLogin_Saml2_Authn_Request Constructor.
        The creation of a deflated SAML Request
        """

        saml_settings = self.loadSettingsJSON()
        settings = OneLogin_Saml2_Settings(saml_settings)
        settings._OneLogin_Saml2_Settings__organization = {
            u'en-US': {
                u'url': u'http://sp.example.com',
                u'name': u'sp_test'
            }
        }

        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertNotIn('ProviderName="SP test"', inflated)

        saml_settings['organization'] = {}
        settings = OneLogin_Saml2_Settings(saml_settings)

        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertNotIn('ProviderName="SP test"', inflated)

    def testGetXML(self):
        """
        Tests that we can get the request XML directly without
        going through intermediate steps
        """
        saml_settings = self.loadSettingsJSON()
        saml_settings['organization'] = {
            u'en-US': {
                u'url': u'http://sp.example.com',
                u'name': u'sp_test',
                u'displayname': u'SP test',
            }
        }
        settings = OneLogin_Saml2_Settings(saml_settings)

        authn_request = OneLogin_Saml2_Authn_Request(settings)
        inflated = authn_request.get_xml()
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertIn('ProviderName="SP test"', inflated)

        saml_settings['organization'] = {}
        settings = OneLogin_Saml2_Settings(saml_settings)

        authn_request = OneLogin_Saml2_Authn_Request(settings)
        inflated = authn_request.get_xml()
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertNotIn('ProviderName="SP test"', inflated)

    def testCreateRequestAuthContext(self):
        """
        Tests the OneLogin_Saml2_Authn_Request Constructor.
        The creation of a deflated SAML Request with defined AuthContext
        """
        saml_settings = self.loadSettingsJSON()
        settings = OneLogin_Saml2_Settings(saml_settings)
        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertIn(OneLogin_Saml2_Constants.AC_PASSWORD, inflated)
        self.assertNotIn(OneLogin_Saml2_Constants.AC_X509, inflated)

        saml_settings['security']['requestedAuthnContext'] = True
        settings = OneLogin_Saml2_Settings(saml_settings)
        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertIn(OneLogin_Saml2_Constants.AC_PASSWORD_PROTECTED, inflated)
        self.assertNotIn(OneLogin_Saml2_Constants.AC_X509, inflated)

        del saml_settings['security']['requestedAuthnContext']
        settings = OneLogin_Saml2_Settings(saml_settings)
        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertIn(OneLogin_Saml2_Constants.AC_PASSWORD_PROTECTED, inflated)
        self.assertNotIn(OneLogin_Saml2_Constants.AC_X509, inflated)

        saml_settings['security']['requestedAuthnContext'] = False
        settings = OneLogin_Saml2_Settings(saml_settings)
        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertNotIn(OneLogin_Saml2_Constants.AC_PASSWORD_PROTECTED, inflated)
        self.assertNotIn(OneLogin_Saml2_Constants.AC_X509, inflated)

        saml_settings['security']['requestedAuthnContext'] = (OneLogin_Saml2_Constants.AC_PASSWORD_PROTECTED, OneLogin_Saml2_Constants.AC_X509)
        settings = OneLogin_Saml2_Settings(saml_settings)
        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertIn(OneLogin_Saml2_Constants.AC_PASSWORD_PROTECTED, inflated)
        self.assertIn(OneLogin_Saml2_Constants.AC_X509, inflated)

    def testCreateRequestAuthContextComparision(self):
        """
        Tests the OneLogin_Saml2_Authn_Request Constructor.
        The creation of a deflated SAML Request with defined AuthnContextComparison
        """
        saml_settings = self.loadSettingsJSON()
        settings = OneLogin_Saml2_Settings(saml_settings)
        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertIn(OneLogin_Saml2_Constants.AC_PASSWORD, inflated)
        self.assertNotIn(OneLogin_Saml2_Constants.AC_X509, inflated)

        saml_settings['security']['requestedAuthnContext'] = True
        settings = OneLogin_Saml2_Settings(saml_settings)
        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertIn('RequestedAuthnContext Comparison="exact"', inflated)

        saml_settings['security']['requestedAuthnContextComparison'] = 'minimun'
        settings = OneLogin_Saml2_Settings(saml_settings)
        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertIn('RequestedAuthnContext Comparison="minimun"', inflated)

    def testCreateRequestForceAuthN(self):
        """
        Tests the OneLogin_Saml2_Authn_Request Constructor.
        The creation of a deflated SAML Request with ForceAuthn="true"
        """
        saml_settings = self.loadSettingsJSON()
        settings = OneLogin_Saml2_Settings(saml_settings)
        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertNotIn('ForceAuthn="true"', inflated)

        authn_request_2 = OneLogin_Saml2_Authn_Request(settings, False, False)
        authn_request_encoded_2 = authn_request_2.get_request()
        decoded_2 = b64decode(authn_request_encoded_2)
        inflated_2 = decompress(decoded_2, -15)
        self.assertRegexpMatches(inflated_2, '^<samlp:AuthnRequest')
        self.assertNotIn('ForceAuthn="true"', inflated_2)

        authn_request_3 = OneLogin_Saml2_Authn_Request(settings, True, False)
        authn_request_encoded_3 = authn_request_3.get_request()
        decoded_3 = b64decode(authn_request_encoded_3)
        inflated_3 = decompress(decoded_3, -15)
        self.assertRegexpMatches(inflated_3, '^<samlp:AuthnRequest')
        self.assertIn('ForceAuthn="true"', inflated_3)

    def testCreateRequestIsPassive(self):
        """
        Tests the OneLogin_Saml2_Authn_Request Constructor.
        The creation of a deflated SAML Request with IsPassive="true"
        """
        saml_settings = self.loadSettingsJSON()
        settings = OneLogin_Saml2_Settings(saml_settings)
        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertNotIn('IsPassive="true"', inflated)

        authn_request_2 = OneLogin_Saml2_Authn_Request(settings, False, False)
        authn_request_encoded_2 = authn_request_2.get_request()
        decoded_2 = b64decode(authn_request_encoded_2)
        inflated_2 = decompress(decoded_2, -15)
        self.assertRegexpMatches(inflated_2, '^<samlp:AuthnRequest')
        self.assertNotIn('IsPassive="true"', inflated_2)

        authn_request_3 = OneLogin_Saml2_Authn_Request(settings, False, True)
        authn_request_encoded_3 = authn_request_3.get_request()
        decoded_3 = b64decode(authn_request_encoded_3)
        inflated_3 = decompress(decoded_3, -15)
        self.assertRegexpMatches(inflated_3, '^<samlp:AuthnRequest')
        self.assertIn('IsPassive="true"', inflated_3)

    def testCreateRequestSetNameIDPolicy(self):
        """
        Tests the OneLogin_Saml2_Authn_Request Constructor.
        The creation of a deflated SAML Request with and without NameIDPolicy
        """
        saml_settings = self.loadSettingsJSON()
        settings = OneLogin_Saml2_Settings(saml_settings)
        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertIn('<samlp:NameIDPolicy', inflated)

        authn_request_2 = OneLogin_Saml2_Authn_Request(settings, False, False, True)
        authn_request_encoded_2 = authn_request_2.get_request()
        decoded_2 = b64decode(authn_request_encoded_2)
        inflated_2 = decompress(decoded_2, -15)
        self.assertRegexpMatches(inflated_2, '^<samlp:AuthnRequest')
        self.assertIn('<samlp:NameIDPolicy', inflated_2)

        authn_request_3 = OneLogin_Saml2_Authn_Request(settings, False, False, False)
        authn_request_encoded_3 = authn_request_3.get_request()
        decoded_3 = b64decode(authn_request_encoded_3)
        inflated_3 = decompress(decoded_3, -15)
        self.assertRegexpMatches(inflated_3, '^<samlp:AuthnRequest')
        self.assertNotIn('<samlp:NameIDPolicy', inflated_3)

    def testCreateRequestSubject(self):
        """
        Tests the OneLogin_Saml2_Authn_Request Constructor.
        The creation of a deflated SAML Request with and without Subject
        """
        saml_settings = self.loadSettingsJSON()
        settings = OneLogin_Saml2_Settings(saml_settings)
        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertNotIn('<saml:Subject>', inflated)

        authn_request_2 = OneLogin_Saml2_Authn_Request(settings, name_id_value_req='testuser@example.com')
        authn_request_encoded_2 = authn_request_2.get_request()
        decoded_2 = b64decode(authn_request_encoded_2)
        inflated_2 = decompress(decoded_2, -15)
        self.assertRegexpMatches(inflated_2, '^<samlp:AuthnRequest')
        self.assertIn('Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">testuser@example.com</saml:NameID>', inflated_2)
        self.assertIn('<saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">', inflated_2)

        saml_settings['sp']['NameIDFormat'] = 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress'
        settings = OneLogin_Saml2_Settings(saml_settings)
        authn_request_3 = OneLogin_Saml2_Authn_Request(settings, name_id_value_req='testuser@example.com')
        authn_request_encoded_3 = authn_request_3.get_request()
        decoded_3 = b64decode(authn_request_encoded_3)
        inflated_3 = decompress(decoded_3, -15)
        self.assertRegexpMatches(inflated_3, '^<samlp:AuthnRequest')
        self.assertIn('Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">testuser@example.com</saml:NameID>', inflated_3)
        self.assertIn('<saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">', inflated_3)

    def testCreateDeflatedSAMLRequestURLParameter(self):
        """
        Tests the OneLogin_Saml2_Authn_Request Constructor.
        The creation of a deflated SAML Request
        """
        authn_request = OneLogin_Saml2_Authn_Request(self.__settings)
        parameters = {
            'SAMLRequest': authn_request.get_request()
        }
        auth_url = OneLogin_Saml2_Utils.redirect('http://idp.example.com/SSOService.php', parameters, True)
        self.assertRegexpMatches(auth_url, r'^http://idp\.example\.com\/SSOService\.php\?SAMLRequest=')
        exploded = urlparse(auth_url)
        exploded = parse_qs(exploded[4])
        payload = exploded['SAMLRequest'][0]
        decoded = b64decode(payload)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')

    def testCreateEncSAMLRequest(self):
        """
        Tests the OneLogin_Saml2_Authn_Request Constructor.
        The creation of a deflated SAML Request
        """
        settings = self.loadSettingsJSON()
        settings['organization'] = {
            'es': {
                'name': 'sp_prueba',
                'displayname': 'SP prueba',
                'url': 'http://sp.example.com'
            }
        }
        settings['security']['wantNameIdEncrypted'] = True
        settings = OneLogin_Saml2_Settings(settings)

        authn_request = OneLogin_Saml2_Authn_Request(settings)
        parameters = {
            'SAMLRequest': authn_request.get_request()
        }
        auth_url = OneLogin_Saml2_Utils.redirect('http://idp.example.com/SSOService.php', parameters, True)
        self.assertRegexpMatches(auth_url, r'^http://idp\.example\.com\/SSOService\.php\?SAMLRequest=')
        exploded = urlparse(auth_url)
        exploded = parse_qs(exploded[4])
        payload = exploded['SAMLRequest'][0]
        decoded = b64decode(payload)
        inflated = decompress(decoded, -15)

        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertRegexpMatches(inflated, 'AssertionConsumerServiceURL="http://stuff.com/endpoints/endpoints/acs.php"')
        self.assertRegexpMatches(inflated, '<saml:Issuer>http://stuff.com/endpoints/metadata.php</saml:Issuer>')
        self.assertRegexpMatches(inflated, 'Format="urn:oasis:names:tc:SAML:2.0:nameid-format:encrypted"')
        self.assertRegexpMatches(inflated, 'ProviderName="SP prueba"')

    def testAttributeConsumingService(self):
        """
        Tests that the attributeConsumingServiceIndex is present as an attribute
        """
        saml_settings = self.loadSettingsJSON()
        settings = OneLogin_Saml2_Settings(saml_settings)

        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)

        self.assertNotIn('AttributeConsumingServiceIndex="1"', inflated)

        saml_settings = self.loadSettingsJSON('settings4.json')
        settings = OneLogin_Saml2_Settings(saml_settings)

        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)

        self.assertRegexpMatches(inflated, 'AttributeConsumingServiceIndex="1"')

if __name__ == '__main__':
    runner = unittest.TextTestRunner()
    unittest.main(testRunner=runner)

redpajama_set_name: RedPajamaGithub


text:
// this file should only be `required` in the format-time
// when Intl.RelativeTimeFormat is not available (Safari < 14), but
// we're not currently able to do the code splitting in www, and it
// is always included. To reduce the amount of data that's loaded limit
// the number of languages loaded to just the top few that are still using
// safari <14. These seven account for most uses.
// relativetimeformat depends on locale which also needs to be polyfilled in
// safari <14
// The plural rules is required for safari 12.
import 'regenerator-runtime/runtime'; // Needed for async/await
import {shouldPolyfill as shouldPolyfillLocale} from '@formatjs/intl-locale/should-polyfill';
import {shouldPolyfill as shouldPolyfillRelativeTimeFormat} from '@formatjs/intl-relativetimeformat/should-polyfill';
import {shouldPolyfill as shouldPolyfillPluralRules} from '@formatjs/intl-pluralrules/should-polyfill';
/**
 * polyfill all the parts needed from intl
 * @param  {string} locale currently selected locale
 * @return {Promise}       returns a promise that resolves when everything is loaded
 */
const intlPolyfill = async function (locale) {
    if (!(shouldPolyfillLocale() ||
        shouldPolyfillPluralRules(locale) ||
        shouldPolyfillRelativeTimeFormat(locale))) {
        return;
    }

    if (shouldPolyfillRelativeTimeFormat(locale)) {
        await import('@formatjs/intl-relativetimeformat/polyfill');
    }

    if (shouldPolyfillPluralRules(locale)) {
        await import('@formatjs/intl-pluralrules/polyfill');
    }

    if (shouldPolyfillLocale(locale)) {
        await import('@formatjs/intl-locale/polyfill');
    }

    switch (locale.toLowerCase().split('-')[0]) {
    case 'af':
        await import('@formatjs/intl-relativetimeformat/locale-data/af');
        await import('@formatjs/intl-pluralrules/locale-data/af');
        break;
    case 'ar':
        await import('@formatjs/intl-relativetimeformat/locale-data/ar');
        await import('@formatjs/intl-pluralrules/locale-data/ar');
        break;
    case 'am':
        await import('@formatjs/intl-relativetimeformat/locale-data/am');
        await import('@formatjs/intl-pluralrules/locale-data/am');
        break;
    case 'an':
        await import('@formatjs/intl-relativetimeformat/locale-data/en');
        await import('@formatjs/intl-pluralrules/locale-data/an');
        break;
    case 'az':
        await import('@formatjs/intl-relativetimeformat/locale-data/az');
        await import('@formatjs/intl-pluralrules/locale-data/az');
        break;
    case 'id':
        await import('@formatjs/intl-relativetimeformat/locale-data/id');
        await import('@formatjs/intl-pluralrules/locale-data/id');
        break;
    case 'bn':
        await import('@formatjs/intl-relativetimeformat/locale-data/bn');
        await import('@formatjs/intl-pluralrules/locale-data/bn');
        break;
    case 'be':
        await import('@formatjs/intl-relativetimeformat/locale-data/be');
        await import('@formatjs/intl-pluralrules/locale-data/be');
        break;
    case 'bg':
        await import('@formatjs/intl-relativetimeformat/locale-data/bg');
        await import('@formatjs/intl-pluralrules/locale-data/bg');
        break;
    case 'ca':
        await import('@formatjs/intl-relativetimeformat/locale-data/ca');
        await import('@formatjs/intl-pluralrules/locale-data/ca');
        break;
    case 'cs':
        await import('@formatjs/intl-relativetimeformat/locale-data/cs');
        await import('@formatjs/intl-pluralrules/locale-data/cs');
        break;
    case 'cy':
        await import('@formatjs/intl-relativetimeformat/locale-data/cy');
        await import('@formatjs/intl-pluralrules/locale-data/cy');
        break;
    case 'da':
        await import('@formatjs/intl-relativetimeformat/locale-data/da');
        await import('@formatjs/intl-pluralrules/locale-data/da');
        break;
    case 'de':
        await import('@formatjs/intl-relativetimeformat/locale-data/de');
        await import('@formatjs/intl-pluralrules/locale-data/de');
        break;
    case 'et':
        await import('@formatjs/intl-relativetimeformat/locale-data/et');
        await import('@formatjs/intl-pluralrules/locale-data/et');
        break;
    case 'el':
        await import('@formatjs/intl-relativetimeformat/locale-data/el');
        await import('@formatjs/intl-pluralrules/locale-data/el');
        break;
    case 'en':
        await import('@formatjs/intl-relativetimeformat/locale-data/en');
        await import('@formatjs/intl-pluralrules/locale-data/en');
        break;
    case 'es':
    case 'rap':
    case 'qu':
        await import('@formatjs/intl-relativetimeformat/locale-data/es');
        await import('@formatjs/intl-pluralrules/locale-data/es');
        break;
    case 'eu':
        await import('@formatjs/intl-relativetimeformat/locale-data/eu');
        await import('@formatjs/intl-pluralrules/locale-data/eu');
        break;
    case 'fa':
        await import('@formatjs/intl-relativetimeformat/locale-data/fa');
        await import('@formatjs/intl-pluralrules/locale-data/fa');
        break;
    case 'fr':
    case 'ht':
        await import('@formatjs/intl-relativetimeformat/locale-data/fr');
        await import('@formatjs/intl-pluralrules/locale-data/fr');
        break;
    case 'fy':
        await import('@formatjs/intl-relativetimeformat/locale-data/fy');
        await import('@formatjs/intl-pluralrules/locale-data/fy');
        break;
    case 'ga':
        await import('@formatjs/intl-relativetimeformat/locale-data/ga');
        await import('@formatjs/intl-pluralrules/locale-data/ga');
        break;
    case 'gd':
        await import('@formatjs/intl-relativetimeformat/locale-data/gd');
        await import('@formatjs/intl-pluralrules/locale-data/gd');
        break;
    case 'gl':
        await import('@formatjs/intl-relativetimeformat/locale-data/gl');
        await import('@formatjs/intl-pluralrules/locale-data/gl');
        break;
    case 'ko':
        await import('@formatjs/intl-relativetimeformat/locale-data/ko');
        await import('@formatjs/intl-pluralrules/locale-data/ko');
        break;
    case 'hy':
        await import('@formatjs/intl-relativetimeformat/locale-data/hy');
        await import('@formatjs/intl-pluralrules/locale-data/hy');
        break;
    case 'he':
        await import('@formatjs/intl-relativetimeformat/locale-data/he');
        await import('@formatjs/intl-pluralrules/locale-data/he');
        break;
    case 'hr':
        await import('@formatjs/intl-relativetimeformat/locale-data/hr');
        await import('@formatjs/intl-pluralrules/locale-data/hr');
        break;
    case 'xh':
        await import('@formatjs/intl-relativetimeformat/locale-data/xh');
        await import('@formatjs/intl-pluralrules/locale-data/xh');
        break;
    case 'zu':
        await import('@formatjs/intl-relativetimeformat/locale-data/zu');
        await import('@formatjs/intl-pluralrules/locale-data/zu');
        break;
    case 'is':
        await import('@formatjs/intl-relativetimeformat/locale-data/is');
        await import('@formatjs/intl-pluralrules/locale-data/is');
        break;
    case 'it':
        await import('@formatjs/intl-relativetimeformat/locale-data/it');
        await import('@formatjs/intl-pluralrules/locale-data/it');
        break;
    case 'ka':
        await import('@formatjs/intl-relativetimeformat/locale-data/ka');
        await import('@formatjs/intl-pluralrules/locale-data/ka');
        break;
    case 'kk':
        await import('@formatjs/intl-relativetimeformat/locale-data/kk');
        await import('@formatjs/intl-pluralrules/locale-data/kk');
        break;
    case 'sw':
        await import('@formatjs/intl-relativetimeformat/locale-data/sw');
        await import('@formatjs/intl-pluralrules/locale-data/sw');
        break;
    case 'ku':
        await import('@formatjs/intl-relativetimeformat/locale-data/ku');
        await import('@formatjs/intl-pluralrules/locale-data/ku');
        break;
    case 'ckb':
        await import('@formatjs/intl-relativetimeformat/locale-data/ckb');
        await import('@formatjs/intl-pluralrules/locale-data/ckb');
        break;
    case 'lv':
        await import('@formatjs/intl-relativetimeformat/locale-data/lv');
        await import('@formatjs/intl-pluralrules/locale-data/lv');
        break;
    case 'lt':
        await import('@formatjs/intl-relativetimeformat/locale-data/lt');
        await import('@formatjs/intl-pluralrules/locale-data/lt');
        break;
    case 'hu':
        await import('@formatjs/intl-relativetimeformat/locale-data/hu');
        await import('@formatjs/intl-pluralrules/locale-data/hu');
        break;
    case 'mi':
        await import('@formatjs/intl-relativetimeformat/locale-data/mi');
        await import('@formatjs/intl-pluralrules/locale-data/en');
        break;
    case 'mn':
        await import('@formatjs/intl-relativetimeformat/locale-data/mn');
        await import('@formatjs/intl-pluralrules/locale-data/mn');
        break;
    case 'nl':
        await import('@formatjs/intl-relativetimeformat/locale-data/nl');
        await import('@formatjs/intl-pluralrules/locale-data/nl');
        break;
    case 'ja':
        await import('@formatjs/intl-relativetimeformat/locale-data/ja');
        await import('@formatjs/intl-pluralrules/locale-data/ja');
        break;
    case 'nb':
        await import('@formatjs/intl-relativetimeformat/locale-data/nb');
        await import('@formatjs/intl-pluralrules/locale-data/nb');
        break;
    case 'nn':
        await import('@formatjs/intl-relativetimeformat/locale-data/nn');
        await import('@formatjs/intl-pluralrules/locale-data/nn');
        break;
    case 'or':
        await import('@formatjs/intl-relativetimeformat/locale-data/or');
        await import('@formatjs/intl-pluralrules/locale-data/or');
        break;
    case 'uz':
        await import('@formatjs/intl-relativetimeformat/locale-data/uz');
        await import('@formatjs/intl-pluralrules/locale-data/uz');
        break;
    case 'th':
        await import('@formatjs/intl-relativetimeformat/locale-data/th');
        await import('@formatjs/intl-pluralrules/locale-data/th');
        break;
    case 'km':
        await import('@formatjs/intl-relativetimeformat/locale-data/km');
        await import('@formatjs/intl-pluralrules/locale-data/km');
        break;
    case 'pl':
        await import('@formatjs/intl-relativetimeformat/locale-data/pl');
        await import('@formatjs/intl-pluralrules/locale-data/pl');
        break;
    case 'pt':
        await import('@formatjs/intl-relativetimeformat/locale-data/pt');
        await import('@formatjs/intl-pluralrules/locale-data/pt');
        break;
    case 'ro':
        await import('@formatjs/intl-relativetimeformat/locale-data/ro');
        await import('@formatjs/intl-pluralrules/locale-data/ro');
        break;
    case 'ru':
        await import('@formatjs/intl-relativetimeformat/locale-data/ru');
        await import('@formatjs/intl-pluralrules/locale-data/ru');
        break;
    case 'nso':
        await import('@formatjs/intl-relativetimeformat/locale-data/en');
        await import('@formatjs/intl-pluralrules/locale-data/nso');
        break;
    case 'tn':
        await import('@formatjs/intl-relativetimeformat/locale-data/en');
        await import('@formatjs/intl-pluralrules/locale-data/tn');
        break;
    case 'sk':
        await import('@formatjs/intl-relativetimeformat/locale-data/sk');
        await import('@formatjs/intl-pluralrules/locale-data/sk');
        break;
    case 'sl':
        await import('@formatjs/intl-relativetimeformat/locale-data/sl');
        await import('@formatjs/intl-pluralrules/locale-data/sl');
        break;
    case 'sr':
        await import('@formatjs/intl-relativetimeformat/locale-data/sr');
        await import('@formatjs/intl-pluralrules/locale-data/sr');
        break;
    case 'fi':
        await import('@formatjs/intl-relativetimeformat/locale-data/fi');
        await import('@formatjs/intl-pluralrules/locale-data/fi');
        break;
    case 'sv':
        await import('@formatjs/intl-relativetimeformat/locale-data/sv');
        await import('@formatjs/intl-pluralrules/locale-data/sv');
        break;
    case 'vi':
        await import('@formatjs/intl-relativetimeformat/locale-data/vi');
        await import('@formatjs/intl-pluralrules/locale-data/vi');
        break;
    case 'tr':
        await import('@formatjs/intl-relativetimeformat/locale-data/tr');
        await import('@formatjs/intl-pluralrules/locale-data/tr');
        break;
    case 'uk':
        await import('@formatjs/intl-relativetimeformat/locale-data/uk');
        await import('@formatjs/intl-pluralrules/locale-data/uk');
        break;
    case 'zh':
        await import('@formatjs/intl-relativetimeformat/locale-data/zh');
        await import('@formatjs/intl-pluralrules/locale-data/zh');
        break;
    default:
        await import('@formatjs/intl-relativetimeformat/locale-data/en');
        await import('@formatjs/intl-pluralrules/locale-data/en');
        break;
    }
};

export default intlPolyfill;


text:
//========= Copyright 2016-2017, HTC Corporation. All rights reserved. ===========

using HTC.UnityPlugin.Utility;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using UnityEngine;
using UnityEngine.EventSystems;

namespace HTC.UnityPlugin.Pointer3D
{
    public enum RaycastMode
    {
        DefaultRaycast,
        Projection,
        Projectile,
    }

    // Contains and handles Pointer3DEventDatas, derived class should implement their own Pointer3DEventData
    // and add into buttonEventDataList, Pointer3DInputModule then will send eventData to the raycast target.
    public class Pointer3DRaycaster : BaseFallbackCamRaycaster
    {
        public const float MIN_SEGMENT_DISTANCE = 0.01f;

        private Pointer3DEventData hoverEventData;
        private ReadOnlyCollection<Pointer3DEventData> buttonEventDataListReadOnly;
        private ReadOnlyCollection<RaycastResult> sortedRaycastResultsReadOnly;
        private ReadOnlyCollection<Vector3> breakPointsReadOnly;

        protected readonly List<Pointer3DEventData> buttonEventDataList = new List<Pointer3DEventData>();
        protected readonly List<RaycastResult> sortedRaycastResults = new List<RaycastResult>();
        protected readonly List<Vector3> breakPoints = new List<Vector3>();

        public float dragThreshold = 0.02f;
        public float clickInterval = 0.3f;

        public bool showDebugRay = true;

        public Pointer3DEventData HoverEventData
        {
            get { return hoverEventData ?? (hoverEventData = new Pointer3DEventData(this, EventSystem.current)); }
        }

        public ReadOnlyCollection<Pointer3DEventData> ButtonEventDataList
        {
            get { return buttonEventDataListReadOnly ?? (buttonEventDataListReadOnly = buttonEventDataList.AsReadOnly()); }
        }

        public ReadOnlyCollection<RaycastResult> SortedRaycastResults
        {
            get { return sortedRaycastResultsReadOnly ?? (sortedRaycastResultsReadOnly = sortedRaycastResults.AsReadOnly()); }
        }

        public ReadOnlyCollection<Vector3> BreakPoints
        {
            get { return breakPointsReadOnly ?? (breakPointsReadOnly = breakPoints.AsReadOnly()); }
        }

        public virtual Vector2 GetScrollDelta()
        {
            return Vector2.zero;
        }
#if UNITY_EDITOR
        protected override void OnValidate()
        {
            base.OnValidate();

            // auto create RaySegmentGenerator if raycast mode is set when using previous version
            // and reset to DefaultRaycast since raycastMode is obsoleted
            if (m_raycastMode != RaycastMode.DefaultRaycast)
            {
                if (Application.isPlaying)
                {
                    SetLagacyRaycastMode(m_raycastMode);
                    m_raycastMode = RaycastMode.DefaultRaycast;
                }
                else
                {
                    // force saving changes of raycastMode
                    // use delayCall because sometimes scene is not loaded and can't be marked dirty at this time
                    UnityEditor.EditorApplication.delayCall += new UnityEditor.EditorApplication.CallbackFunction(() =>
                    {
                        Debug.LogWarning("The RaycastMode." + m_raycastMode + " setting has been replaced by adding " + (m_raycastMode == RaycastMode.Projection ? "ProjectionGenerator" : "ProjectileGenerator")
                            + " component. Please save the scene to preserve this changes.");
                        SetLagacyRaycastMode(m_raycastMode);
                        m_raycastMode = RaycastMode.DefaultRaycast;
                        UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(gameObject.scene);
                        UnityEditor.EditorUtility.SetDirty(this);
                    });
                }
            }
        }
#endif
        protected override void Start()
        {
            base.Start();

            if (m_raycastMode != RaycastMode.DefaultRaycast)
            {
                SetLagacyRaycastMode(m_raycastMode);
                m_raycastMode = RaycastMode.DefaultRaycast;
            }

            Pointer3DInputModule.AddRaycaster(this);
        }

        // override OnEnable & OnDisable on purpose so that this BaseRaycaster won't be registered into RaycasterManager
        protected override void OnEnable()
        {
            //base.OnEnable();
        }

        protected override void OnDisable()
        {
            //base.OnDisable();
        }

        protected override void OnDestroy()
        {
            base.OnDestroy();
            Pointer3DInputModule.RemoveRaycasters(this);
        }

        public virtual void CleanUpRaycast()
        {
            sortedRaycastResults.Clear();
            breakPoints.Clear();
        }

        // invoke by Pointer3DInputModule
        public virtual void Raycast()
        {
            sortedRaycastResults.Clear();
            breakPoints.Clear();

            var zScale = transform.lossyScale.z;
            var amountDistance = (FarDistance - NearDistance) * zScale;
            var origin = transform.TransformPoint(0f, 0f, NearDistance);

            breakPoints.Add(origin);

            bool hasNext = true;
            Vector3 direction;
            float distance;
            Ray ray;
            RaycastResult firstHit = default(RaycastResult);

            var generator = CurrentSegmentGenerator();
            if (ReferenceEquals(generator, null))
            {
                // process default raycast

                direction = transform.forward;
                distance = amountDistance;
                ray = new Ray(origin, direction);

                // move event camera in place
                eventCamera.farClipPlane = eventCamera.nearClipPlane + distance;
                eventCamera.transform.position = ray.origin - (ray.direction * eventCamera.nearClipPlane);
                eventCamera.transform.rotation = Quaternion.LookRotation(ray.direction, transform.up);

                ForeachRaycastMethods(ray, distance, sortedRaycastResults);

                firstHit = FirstRaycastResult();
                breakPoints.Add(firstHit.isValid ? firstHit.worldPosition : ray.GetPoint(distance));
#if UNITY_EDITOR
                if (showDebugRay)
                {
                    Debug.DrawLine(breakPoints[0], breakPoints[1], firstHit.isValid ? Color.green : Color.red);
                }
#endif
            }
            else
            {
                generator.ResetSegments();

                do
                {
                    hasNext = generator.NextSegment(out direction, out distance);

                    if (distance < MIN_SEGMENT_DISTANCE)
                    {
                        Debug.LogWarning("RaySegment.distance cannot smaller than " + MIN_SEGMENT_DISTANCE + "! distance=" + distance.ToString("0.000"));
                        break;
                    }

                    distance *= zScale;

                    if (distance < amountDistance)
                    {
                        amountDistance -= distance;
                    }
                    else
                    {
                        distance = amountDistance;
                        amountDistance = 0f;
                    }

                    ray = new Ray(origin, direction);

                    // move event camera in place
                    eventCamera.farClipPlane = eventCamera.nearClipPlane + distance;
                    eventCamera.transform.position = ray.origin - (ray.direction * eventCamera.nearClipPlane);
                    eventCamera.transform.rotation = Quaternion.LookRotation(ray.direction, transform.up);

                    ForeachRaycastMethods(ray, distance, sortedRaycastResults);

                    firstHit = FirstRaycastResult();
                    // end loop if raycast hit
                    if (firstHit.isValid)
                    {
                        breakPoints.Add(firstHit.worldPosition);
#if UNITY_EDITOR
                        if (showDebugRay)
                        {
                            Debug.DrawLine(breakPoints[breakPoints.Count - 2], breakPoints[breakPoints.Count - 1], Color.green);
                        }
#endif
                        break;
                    }
                    // otherwise, shift to next iteration
                    origin = ray.GetPoint(distance);
                    breakPoints.Add(origin);
#if UNITY_EDITOR
                    if (showDebugRay)
                    {
                        Debug.DrawLine(breakPoints[breakPoints.Count - 2], breakPoints[breakPoints.Count - 1], Color.red);
                    }
#endif
                }
                while (hasNext && amountDistance > 0f);
            }
        }
        // called by StandaloneInputModule, not supported
        public override void Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList) { }

        public RaycastResult FirstRaycastResult()
        {
            for (int i = 0, imax = sortedRaycastResults.Count; i < imax; ++i)
            {
                if (!sortedRaycastResults[i].isValid) { continue; }
                return sortedRaycastResults[i];
            }
            return default(RaycastResult);
        }

        #region managing segment generators
        private IndexedSet<IRaySegmentGenerator> generators = new IndexedSet<IRaySegmentGenerator>();

        public void AddGenerator(IRaySegmentGenerator generator)
        {
            generators.AddUnique(generator);
        }

        public void RemoveGenerator(IRaySegmentGenerator generator)
        {
            generators.Remove(generator);
        }

        // returns first enabled generator in generators, doesn't gaurantee any orders
        public IRaySegmentGenerator CurrentSegmentGenerator()
        {
            for (int i = 0, imax = generators.Count; i < imax; ++i)
            {
                if (generators[i].enabled) { return generators[i]; }
            }
            return null;
        }

        // enable or create TGenerator, disable others
        public TGenerator ForceEnableSegmentGenerator<TGenerator>() where TGenerator : MonoBehaviour, IRaySegmentGenerator
        {
            var gen = default(TGenerator);
            var genFound = false;

            var gens = ListPool<IRaySegmentGenerator>.Get();
            GetComponents(gens);
            for (int i = 0, imax = gens.Count; i < imax; ++i)
            {
                if (genFound || !(gens[i] is TGenerator))
                {
                    gens[i].enabled = false;
                }
                else
                {
                    gens[i].enabled = true;
                    gen = gens[i] as TGenerator;
                    genFound = true;
                }
            }
            ListPool<IRaySegmentGenerator>.Release(gens);

            if (!genFound)
            {
                gen = gameObject.AddComponent<TGenerator>();
            }

            return gen;
        }

        public void ForceDisableSegmentGenerators()
        {
            var gens = ListPool<IRaySegmentGenerator>.Get();
            GetComponents(gens);
            for (int i = 0, imax = gens.Count; i < imax; ++i)
            {
                gens[i].enabled = false;
            }
            ListPool<IRaySegmentGenerator>.Release(gens);
        }
        #endregion

        #region obsolete interfaces
        [HideInInspector]
        [SerializeField]
        private RaycastMode m_raycastMode = RaycastMode.DefaultRaycast;
        [HideInInspector]
        [SerializeField]
        private float m_velocity = 2f;
        [HideInInspector]
        [SerializeField]
        private Vector3 m_gravity = Vector3.down;

        [Obsolete("Please use component ProjectionGenerator / ProjectileGenerator")]
        public RaycastMode raycastMode
        {
            get { return m_raycastMode; }
            set
            {
                m_raycastMode = value;
                SetLagacyRaycastMode(value);
            }
        }

        [Obsolete("Please use ProjectionGenerator.velocity / ProjectileGenerator.velocity")]
        public float velocity
        {
            get { return m_velocity; }
            set
            {
                m_velocity = value;
                var gen = CurrentSegmentGenerator();
                if (gen != null)
                {
                    if (gen is ProjectionGenerator) { ((ProjectionGenerator)gen).velocity = value; }
                    else if (gen is ProjectileGenerator) { ((ProjectileGenerator)gen).velocity = value; }
                }
            }
        }

        [Obsolete("Please use ProjectionGenerator.gravity / ProjectileGenerator.gravity")]
        public Vector3 gravity
        {
            get { return m_gravity; }
            set
            {
                m_gravity = value;
                var gen = CurrentSegmentGenerator();
                if (gen != null)
                {
                    if (gen is ProjectionGenerator) { ((ProjectionGenerator)gen).gravity = value; }
                    else if (gen is ProjectileGenerator) { ((ProjectileGenerator)gen).gravity = value; }
                }
            }
        }

        [Obsolete("Please use component ProjectionGenerator / ProjectileGenerator")]
        protected virtual void InitSegmentGenerator() { }

        // for backward compatible
        private void SetLagacyRaycastMode(RaycastMode mode)
        {
            switch (mode)
            {
                case RaycastMode.Projection:
                    {
                        var gen = ForceEnableSegmentGenerator<ProjectionGenerator>();
                        gen.velocity = m_velocity;
                        gen.gravity = m_gravity;
                        break;
                    }
                case RaycastMode.Projectile:
                    {
                        var gen = ForceEnableSegmentGenerator<ProjectileGenerator>();
                        gen.velocity = m_velocity;
                        gen.gravity = m_gravity;
                        break;
                    }
                default:
                    {
                        ForceDisableSegmentGenerators();
                        break;
                    }
            }
        }
        #endregion
    }
}


text:
package color

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestText(t *testing.T) {
	Println("*** colored text ***")
	Println(Black("black"))
	Println(Red("red"))
	Println(Green("green"))
	Println(Yellow("yellow"))
	Println(Blue("blue"))
	Println(Magenta("magenta"))
	Println(Cyan("cyan"))
	Println(White("white"))
	Println(Grey("grey"))
}

func TestBackground(t *testing.T) {
	Println("*** colored background ***")
	Println(BlackBg("black background", Wht))
	Println(RedBg("red background"))
	Println(GreenBg("green background"))
	Println(YellowBg("yellow background"))
	Println(BlueBg("blue background"))
	Println(MagentaBg("magenta background"))
	Println(CyanBg("cyan background"))
	Println(WhiteBg("white background"))
}

func TestEmphasis(t *testing.T) {
	Println("*** emphasis ***")
	Println(Reset("reset"))
	Println(Bold("bold"))
	Println(Dim("dim"))
	Println(Italic("italic"))
	Println(Underline("underline"))
	Println(Inverse("inverse"))
	Println(Hidden("hidden"))
	Println(Strikeout("strikeout"))
}

func TestMixMatch(t *testing.T) {
	Println("*** mix and match ***")
	Println(Green("bold green with white background", B, WhtBg))
	Println(Red("underline red", U))
	Println(Yellow("dim yellow", D))
	Println(Cyan("inverse cyan", In))
	Println(Blue("bold underline dim blue", B, U, D))
}

func TestEnableDisable(t *testing.T) {
	Disable()
	assert.Equal(t, "red", Red("red"))
	Enable()
	assert.NotEqual(t, "green", Green("green"))
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.util;

import com.google.common.collect.Iterables;
import org.testng.annotations.Test;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertTrue;

public class TestDisjointSet
{
    @Test
    public void testInitial()
    {
        DisjointSet<Integer> disjoint = new DisjointSet<>();

        // assert that every node is considered its own group
        for (int i = 0; i < 100; i++) {
            assertEquals(disjoint.find(i).intValue(), i);
        }
        assertEquals(disjoint.getEquivalentClasses().size(), 100);
    }

    @Test
    public void testMergeAllSequentially()
    {
        DisjointSet<Integer> disjoint = new DisjointSet<>();

        // insert pair (i, i+1); assert all inserts are considered new
        for (int i = 0; i < 100; i++) {
            assertTrue(disjoint.findAndUnion(i, i + 1));
            if (i != 0) {
                assertEquals(disjoint.find(i - 1), disjoint.find(i));
            }
            if (i != 99) {
                assertNotEquals(disjoint.find(i + 1), disjoint.find(i + 2));
            }
        }
        // assert every pair (i, j) is in the same set
        for (int i = 0; i <= 100; i++) {
            for (int j = 0; j <= 100; j++) {
                assertEquals(disjoint.find(i), disjoint.find(j));
                assertFalse(disjoint.findAndUnion(i, j));
            }
        }
        Collection<Set<Integer>> equivalentClasses = disjoint.getEquivalentClasses();
        assertEquals(equivalentClasses.size(), 1);
        assertEquals(Iterables.getOnlyElement(equivalentClasses).size(), 101);
    }

    @Test
    public void testMergeAllBackwardsSequentially()
    {
        DisjointSet<Integer> disjoint = new DisjointSet<>();

        // insert pair (i, i+1); assert all inserts are considered new
        for (int i = 100; i > 0; i--) {
            assertTrue(disjoint.findAndUnion(i, i - 1));
            if (i != 100) {
                assertEquals(disjoint.find(i + 1), disjoint.find(i));
            }
            if (i != 1) {
                assertNotEquals(disjoint.find(i - 1), disjoint.find(i - 2));
            }
        }
        // assert every pair (i, j) is in the same set
        for (int i = 0; i <= 100; i++) {
            for (int j = 0; j <= 100; j++) {
                assertEquals(disjoint.find(i), disjoint.find(j));
                assertFalse(disjoint.findAndUnion(i, j));
            }
        }
        Collection<Set<Integer>> equivalentClasses = disjoint.getEquivalentClasses();
        assertEquals(equivalentClasses.size(), 1);
        assertEquals(Iterables.getOnlyElement(equivalentClasses).size(), 101);
    }

    @Test
    public void testMergeFourGroups()
    {
        DisjointSet<Integer> disjoint = new DisjointSet<>();

        // insert pair (i, i+1); assert all inserts are considered new
        List<Integer> inputs = IntStream.range(0, 96).boxed().collect(Collectors.toList());
        Collections.shuffle(inputs);
        for (int i : inputs) {
            assertTrue(disjoint.findAndUnion(i, i + 4));
        }
        // assert every pair (i, j) is in the same set
        for (int i = 0; i < 100; i++) {
            for (int j = 0; j < 100; j++) {
                if ((i - j) % 4 == 0) {
                    assertEquals(disjoint.find(i), disjoint.find(j));
                    assertFalse(disjoint.findAndUnion(i, j));
                }
                else {
                    assertNotEquals(disjoint.find(i), disjoint.find(j));
                }
            }
        }
        Collection<Set<Integer>> equivalentClasses = disjoint.getEquivalentClasses();
        assertEquals(equivalentClasses.size(), 4);
        equivalentClasses.stream()
                .forEach(equivalentClass -> assertEquals(equivalentClass.size(), 25));
    }

    @Test
    public void testMergeRandomly()
    {
        DisjointSet<Double> disjoint = new DisjointSet<>();

        Random rand = new Random();
        // Don't use List here. That will box the primitive early.
        // Boxing need to happen right before calls to DisjointSet to test that correct equality check is used for comparisons.
        double[] numbers = new double[100];
        for (int i = 0; i < 100; i++) {
            numbers[i] = rand.nextDouble();
            disjoint.find(numbers[i]);
        }
        int groupCount = 100;
        while (groupCount > 1) {
            // this loop roughly runs 180-400 times
            boolean newEquivalence = disjoint.findAndUnion(numbers[rand.nextInt(100)], numbers[rand.nextInt(100)]);
            if (newEquivalence) {
                groupCount--;
            }
            assertEquals(disjoint.getEquivalentClasses().size(), groupCount);
        }
    }
}


text:
#include "qtpool.h"

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <pthread.h>
#include <assert.h>

#include "qterror.h"

/*
 * This procedure repeatedly retrives a function from the function queue
 * and executes it. This runs until the calling thread is cancelled. The
 * argument is a pointer to an initialized qtpool object. This procedure
 * does not return unless the value of arg NULL.
 */
static void*
get_and_run(void* arg)
{
	struct function_queue_element fqe;
	struct qtpool* tq = NULL;

	if(arg == NULL)
		return NULL;

	tq = arg;

	do {
		pthread_testcancel();

		if(fqpop(tq->fq, &fqe, 1) == QTSUCCESS)
			fqe.func(fqe.arg);

	} while(1);
}

/*
 * This procedure initializes the qtpool object tq using the startup
 * information from tqsi. The procedure returns a qterror code to
 * indicate its status. The value of tq must not be NULL. The value of
 * tqsi must not be NULL.
 */
enum qterror
qtinit(struct qtpool* tq, struct qtpool_startup_info* tqsi)
{
	assert(tq != NULL);
	assert(tqsi != NULL);

	tq->fq = tqsi->fq;
	tq->max_threads = tqsi->max_threads;
	tq->threads = malloc(tq->max_threads * sizeof(pthread_t));

	if(tq->threads == NULL)
		return QTEMALLOC;

	tq->start_errors.errors = calloc(tq->max_threads, sizeof(int));

	if(tq->start_errors.errors == NULL){
		free(tq->threads);
		return QTEMALLOC;
	}

	return QTSUCCESS;
}

/*
 * This procedure destroys the given qtpool object. An attempt to use
 * the object after destroying it results in undefined behavior. The
 * object can be reinitialized by qtinit(). This procedure always
 * succeeds. The value of tq must not be NULL.
 */
enum qterror
qtdestroy(struct qtpool* tq)
{
	assert(tq != NULL);
	free(tq->start_errors.errors);
	free(tq->threads);
	return QTSUCCESS;
}

/*
 * This procedure starts the threads for the given pool. The number of
 * threads which start successfully is stored in the integer pointed to
 * by started if the value of started is not NULL. This procedure
 * returns an error code indicating its status. The value of tq must not
 * be NULL.
 */
enum qterror
qtstart(struct qtpool* tq, int* started)
{
	enum qterror ret = QTSUCCESS;
	unsigned int i = 0;

	assert(tq != NULL);

	if(started != NULL)
		*started = 0;

	for(i = 0; i < tq->max_threads; ++i) {
		if(pthread_create(&tq->threads[i], NULL, get_and_run,
					tq) != 0) {
			if(tq->start_errors.errors != NULL)
				tq->start_errors.errors[i] = errno;

			ret = QTEPTCREATE;
		} else {
			if(started != NULL)
				++*started;
		}
	}

	return ret;
}

/*
 * This procedure stops the threads in a given pool. The threads are
 * stopped by canceling them. If the value of join is not zero, the
 * threads are joined and the procedure blocks until all the threads
 * have terminated. Otherwise, the threads are detached and the
 * procedure does not block. This procedure always succeeds. The value
 * of tq must not be NULL.
 */
enum qterror
qtstop(struct qtpool* tq, int join)
{
	unsigned int i = 0;

	assert(tq != NULL);

	for(i = 0; i < tq->max_threads; ++i) {
		int pc = pthread_cancel(tq->threads[i]);

		if(join) {
			if(pc == 0)
				(void) pthread_join(tq->threads[i], NULL);
			else
				(void) pthread_detach(tq->threads[i]);
		}
	}

	return QTSUCCESS;
}

/*
 * This procedure retrieves an errno value corresponding to the status
 * of the status of the creation of the thread of the given index n.
 * The value is then stored at the address pointed to by out. This
 * procedure returns an error code indicating its status. The value of
 * tq must not be NULL. The value of out must not be NULL.
 */
enum qterror
qtstart_get_e(struct qtpool* tq, size_t n, int* out)
{
	assert(tq != NULL);
	assert(out != NULL);

	if(n >= tq->max_threads)
		return QTEINVALID;

	*out = tq->start_errors.errors[n];
	return QTSUCCESS;
}


text:
package com.arialyy.aria.core.common;

import android.os.Parcel;
import android.os.Parcelable;
import com.arialyy.aria.orm.annotation.Unique;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by AriaL on 2017/6/3.
 */
public abstract class AbsGroupEntity extends AbsEntity implements Parcelable {
  /**
   * 组合任务等hash为: 为子任务地址相加的url的Md5
   * ftpdir为:ftpdir下载地址
   */
  @Unique protected String groupHash;

  /**
   * 任务组别名
   */
  private String alias;

  /**
   * 任务组下载文件的文件夹地址
   */
  @Unique private String dirPath;

  /**
   * 子任务url地址
   */
  private List<String> urls = new ArrayList<>();

  public String getDirPath() {
    return dirPath;
  }

  public void setDirPath(String dirPath) {
    this.dirPath = dirPath;
  }

  public List<String> getUrls() {
    return urls;
  }

  public void setUrls(List<String> urls) {
    this.urls = urls;
  }

  /**
   * 组合任务等hash为: 为子任务地址相加的url的Md5
   * ftpdir为:ftpdir下载地址
   */
  public String getGroupHash() {
    return groupHash;
  }

  public String getAlias() {
    return alias;
  }

  @Override public String getKey() {
    return groupHash;
  }

  public void setAlias(String alias) {
    this.alias = alias;
  }

  public AbsGroupEntity() {
  }

  @Override public int describeContents() {
    return 0;
  }

  @Override public void writeToParcel(Parcel dest, int flags) {
    super.writeToParcel(dest, flags);
    dest.writeString(this.groupHash);
    dest.writeString(this.alias);
  }

  protected AbsGroupEntity(Parcel in) {
    super(in);
    this.groupHash = in.readString();
    this.alias = in.readString();
  }
}


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 msm.login.presenter;

import java.net.SocketException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import msm.base.BasePresenter;
import msm.communication.IP;
import msm.communication.Server;
import msm.login.view.LoginFrame;
import msm.login.view.LoginView;

/**
 *
 * @author mgalvao3
 */
public class LoginPresenter extends BasePresenter {

    private final LoginView mView;

    public LoginPresenter(LoginView view) {
        mView = view;
    }

    public void listIpAddresses() {
        ArrayList<String> ips;
        try {
            ips = (ArrayList<String>) Server.getNetworkInterfacesAddresses();
            mView.populateIPs(ips);
        } catch (SocketException ex) {
            Logger.getLogger(LoginFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void onEnterClicked(String userIp) {
        if(IP.isValid(userIp)) {
            mView.loginSuccessfull(userIp);
        } else {
            mView.showIpError();
        }
    }

    public void setUpWindow() {
        listIpAddresses();
        mView.setBackgroundColor("#ecf6f9");
        mView.setAvatarIcon("images/avatar_login.png");
    }

}


text:
using Eigen::Matrix3Xd;
using Eigen::VectorXd;

int main(int argc, char* argv[]) {
  RigidBodyTree tree;

  for (int i = 0; i < 10; ++i) {
    drake::parsers::urdf::AddModelInstanceFromUrdfFile(
        drake::GetDrakePath() + "/systems/plants/test/PointMass.urdf",
            DrakeJoint::ROLLPITCHYAW, &tree);
  }

  drake::parsers::urdf::AddModelInstanceFromUrdfFile(
      drake::GetDrakePath() + "/systems/plants/test/FallingBrick.urdf",
          DrakeJoint::FIXED, &tree);

  VectorXd q = VectorXd::Random(tree.number_of_positions());
  VectorXd v = VectorXd::Random(tree.number_of_velocities());
  auto kinsol = tree.doKinematics(q, v);

  VectorXd phi;
  Matrix3Xd normal, xA, xB;
  std::vector<int> bodyA_idx, bodyB_idx;
  tree.collisionDetect(kinsol, phi, normal, xA, xB, bodyA_idx, bodyB_idx,
                       false);
}


text:
layout: archive
lang: en
ref: java_porthandler
read_time: true
share: true
author_profile: false
permalink: /docs/en/software/dynamixel/dynamixel_sdk/api_reference/java/java_porthandler/
sidebar:
  title: DynamixelSDK
  nav: "dynamixel_sdk"
---

### [Java PortHandler](#java-porthandler)

- Description

   PortHandler dependent functions for serial communication.

- Members

   None

- Methods

| Methods                                     | Description                                                |
|:--------------------------------------------|:-----------------------------------------------------------|
| **[portHandle](#porthandler)**              | Initializes parameters for serial port control             |
| **[openPort](#openport)**                   | Opens a serial port                                        |
| **[closePort](#closeport)**                 | Closes a serial port                                       |
| **[clearPort](#clearport)**                 | Refreshes a serial port                                    |
| **[setPortName](#setportname)**             | Sets a device name                                         |
| **[getPortName](#getportname)**             | Gets a device name                                         |
| **[setBaudrate](#setbaudrate)**             | Sets a baudrate                                            |
| **[getBaudrate](#getbaudrate)**             | Gets a baudrate                                            |
| **[getBytesAvailable](#getbytesavailable)** | Checks how many bytes can be read in port buffer           |
| **[readPort](#readport)**                   | Reads bytes from port buffer                               |
| **[writePort](#writeport)**                 | Writes bytes to port buffer                                |
| **[setPacketTimeout](#setpackettimeout)**   | Sets timeout                                               |
| **[isPacketTimeout](#ispackettimeout)**     | Checks whether communication has been succeeded in timeout |

- Enumerator

   None

#### Method References

##### portHandler
- Syntax
``` java
int portHandler(String port_name)
```
- Parameters

| Parameters | Description |
|:-----------|:------------|
| port_name  | Port name   |

- Detailed Description

   The function initializes the parameters for port control. At first, this checks if the port with same device name is set already in the `portData` pointer struct. If it exists, the function returns the port number as what it has. If not, the function finds any free port, resize `portData` struct and start to initialize struct members.

##### openPort
- Syntax
``` java
Boolean openPort(int port_num)
```
- Parameters

| Parameters | Description |
|:-----------|:------------|
| port_num   | Port number |

- Detailed Description

   This function opens the port by `setBaudRate` function using default baudrate(1M). If the baudrate is needed to be changed to another baudrate value, `setBaudRate` function should be called again after calling `openPort` function. When the port succeeds to be opened, this function will return true, and if not, then false.

##### closePort
- Syntax
``` java
void closePort(int port_num)
```
- Parameters

| Parameters | Description |
|:-----------|:------------|
| port_num   | Port number |

- Detailed Description

  This function closes the port by closing the file descriptor.

##### clearPort
- Syntax
``` java
void clearPort(int port_num)
```
- Parameters

| Parameters | Description |
|:-----------|:------------|
| port_num   | Port number |

- Detailed Description

  This function clears the port by flushing the file descriptor.

##### setPortName
- Syntax
``` java
void setPortName(int port_num, String port_name)
```
- Parameters

| Parameters | Description |
|:-----------|:------------|
| port_num   | Port number |
| port_name  | Port name   |

- Detailed Description

  This function sets the device name as port_name.

##### getPortName
- Syntax
``` java
String getPortName(int port_num)
```
- Parameters

| Parameters | Description |
|:-----------|:------------|
| port_num   | Port number |

- Detailed Description

  This function returns the device name which the port is using.

##### setBaudrate
- Syntax

``` java
Boolean setBaudrate(int port_num, const int baudrate)
```

- Parameters

| Parameters | Description     |
|:-----------|:----------------|
| port_num   | Port number     |
| baudrate   | Target baudrate |

- Description

  This function converts `baudrate` to baudrate type value at first. Secondly, it closes the port with `closePort` function, and opens the port with `setupPort` function again. If the value of `baudrate` is not in the compatible baudrate list, the `setCustomBaudrate` function suggests the baudrate value which is closest of available baudrate value. Finally, it returns false.

##### getBaudrate
- Syntax

``` java
int getBaudrate(int port_num)
```

- Parameters

| Parameters | Description |
|:-----------|:------------|
| port_num   | Port number |

- Description

  This function returns the baudrate value previously set.

##### getBytesAvailable
- Syntax

``` java
int getBytesAvailable(int port_num)
```

- Parameters

| Parameters | Description |
|:-----------|:------------|
| port_num   | Port number |

- Description

  This function checks how much the data can be read, and returns its length.

##### readPort
- Syntax

``` java
int readPort(int port_num, byte[] packet, int length)
```

- Parameters

| Parameters | Description                              |
|:-----------|:-----------------------------------------|
| port_num   | Port number                              |
| packet     | The number of data bytes read previously |
| length     | Byte length for read                     |

- Description

  This function gets length byte data from port buffer and returns a number of read data bytes. On end-of-file, 0 is returned, on error it returns -1.

##### writePort
- Syntax

``` java
int writePort(int port_num, byte[] packet, int length)
```

- Parameters

| Parameters | Description                       |
|:-----------|:----------------------------------|
| port_num   | Port number                       |
| packet     | The number of data bytes to write |
| length     | Byte length for write             |

- Description

  This function transmits length byte, and returns how much the data was written. On error, it returns -1.

##### setPacketTimeout
- Syntax

``` java
void setPacketTimeout (int port_num, uint16_t packet_length)
```

- Parameters

| Parameters    | Description                  |
|:--------------|:-----------------------------|
| port_num      | Port number                  |
| Packet_length | Target byte length for write |

- Description

  This function sets the start time when it transmits the packet, and set the timeout of packet transmission to be ready for deciding communication result.

##### setPacketTimeoutMSec
- Syntax

``` java
void setPacketTimeoutMSec (int port_num, double msec)
```

- Parameters

| Parameters | Description |
|:-----------|:------------|
| port_num   | Port number |
| msec       | Miliseconds |

- Description

  This function sets the start time with `msec` milisecond value when it transmits the packet, and set the timeout of packet transmission to be ready for deciding communication result.

##### isPacketTimeout
- Syntax

``` java
Boolean isPacketTimeout(int port_num)
```

- Parameters

| Parameters | Description |
|:-----------|:------------|
| port_num   | Port number |

- Description

  This function decides the timeover of packet communication. If the time limit is over, it returns false.


text:
class CircularDependencyException extends Error {
    /**
     * Constructor.
     *
     * @param {string} required
     */
    constructor(required) {
        super('Circular reference with ' + required);

        /**
         * @type {string}
         */
        this.requiring = undefined;

        /**
         * @type {string}
         */
        this.required = required;
    }
}

module.exports = CircularDependencyException;


text:
package com.capitalone.dashboard.datafactory.rally;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.capitalone.dashboard.collector.FeatureSettings;
import com.capitalone.dashboard.model.Feature;
import com.capitalone.dashboard.model.Iteration;
import com.capitalone.dashboard.model.Scope;
import com.capitalone.dashboard.model.ScopeOwnerCollectorItem;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.rallydev.rest.RallyRestApi;
import com.rallydev.rest.request.QueryRequest;
import com.rallydev.rest.response.QueryResponse;
import com.rallydev.rest.util.Fetch;
import com.rallydev.rest.util.QueryFilter;
public class RallyDataFactoryImpl implements RallyDataFactory {
	private FeatureSettings featureSettings;
	@Autowired
	public RallyDataFactoryImpl(FeatureSettings featureSettings){
		this.featureSettings=featureSettings;
	}
public RallyRestApi getRallyClient() throws URISyntaxException
{
	URI url = new URI(featureSettings.getRallyBaseUri());
	String key = featureSettings.getRallyApiKey();
	return new RallyRestApi(url,key);
	}
public List<Scope> getProjects() throws URISyntaxException, IOException
{
	List<Scope> projects = new ArrayList<>();
	RallyRestApi restApi=getRallyClient();
	QueryRequest request = new QueryRequest("Projects");
	   request.setFetch(new Fetch("Name","ObjectID","CreationDate","State"));
	   request.setScopedDown(true);
	//  request.setQueryFilter(new QueryFilter("State","=","Planning"));
	   QueryResponse response = restApi.query(request);
	   if(response.getResults()!=null){
	   for(JsonElement result : response.getResults()){
		   JsonObject project = result.getAsJsonObject();
		   if(project.get("Name").getAsString().contains(featureSettings.getApplicationName())){
		  Scope scope = new Scope();
		  scope.setpId(project.get("ObjectID").getAsString());
		  scope.setName(project.get("Name").getAsString());
		  scope.setBeginDate(project.get("CreationDate").getAsString());
		  scope.setAssetState("Active");
          projects.add(scope);
	   }
	   }
	   }
	   restApi.close();
	   return projects;
}
public List<ScopeOwnerCollectorItem> getUsers() throws URISyntaxException, IOException
{
List<ScopeOwnerCollectorItem> users = new ArrayList<>();
RallyRestApi restApi=getRallyClient();
QueryRequest request = new QueryRequest("Projects");
   request.setFetch(new Fetch("Name","ObjectID","CreationDate","State"));
   request.setScopedDown(true);
//  request.setQueryFilter(new QueryFilter("State","=","Planning"));
   QueryResponse response = restApi.query(request);
   if(response.getResults()!=null){
   for(JsonElement result : response.getResults()){
	   JsonObject project = result.getAsJsonObject();
	   if(project.get("Name").getAsString().contains(featureSettings.getApplicationName())){
	   ScopeOwnerCollectorItem user = new ScopeOwnerCollectorItem();
	  user.setTeamId((project.get("ObjectID").getAsString()));
	  user.setName(project.get("Name").getAsString());
	  user.setAssetState("Active");
      users.add(user);
   }
   }
   }
   return users;
}
@SuppressWarnings("unchecked")
public List<Feature> getStories(String agileType,String storyType) throws URISyntaxException, IOException{
	List<Feature> stories = new ArrayList<>();
	RallyRestApi restApi=getRallyClient();
	String projectRef = "/project/";
	Iteration it = getCurrentIteration();
	List<ScopeOwnerCollectorItem> users= getUsers();
	for(ScopeOwnerCollectorItem user:users){
		String objectID=user.getTeamId();
		QueryRequest request=null;
		if(storyType.equals("story")){
	 request = new QueryRequest("HierarchicalRequirement");
		}
		else if(storyType.equals("defect")){
	 request = new QueryRequest("Defects");

		}
	   request.setFetch(new Fetch("Name","ObjectID","FormattedID","PlanEstimate","TaskStatus","LastUpdateDate","ScheduleState","Owner","Project","Iteration","Parent"));
	   request.setScopedDown(true);
	   request.setProject(projectRef+objectID);
	   if(agileType.equals("scrum")){
	  request.setQueryFilter(new QueryFilter("Iteration.Name","=",it.getName()));
	   }
	   else if(agileType.equals("kanban")){
			  request.setQueryFilter(new QueryFilter("Iteration.Name","=",null).and(new QueryFilter("ScheduleState","!=","Backlog")));
	   }
	   QueryResponse response = restApi.query(request);
	   if(response.getResults()!=null){
	   for(JsonElement result : response.getResults()){
		   Feature feature = new Feature();
		   JsonObject project = result.getAsJsonObject();
		 feature.setsId(project.get("ObjectID").getAsString());
		 feature.setsName(project.get("Name").getAsString());
		 feature.setsNumber(project.get("FormattedID").getAsString());
		 feature.setsStatus(project.get("ScheduleState").getAsString());
		 feature.setIsDeleted("False");
		 //feature.setsState(project.get("TaskStatus").getAsString());
		 if(!project.get("PlanEstimate").isJsonNull()){
		 feature.setsEstimate(project.get("PlanEstimate").getAsString());
	   }
		 feature.setChangeDate(project.get("LastUpdateDate").getAsString());
		 feature.setsProjectName(project.getAsJsonObject("Project").get("_refObjectName").getAsString());
		 feature.setsProjectID(project.getAsJsonObject("Project").get("ObjectID").getAsString());
    	 try{
		 if(!project.get("Parent").isJsonNull()){
			 feature.setsEpicID(project.getAsJsonObject("Parent").get("ObjectID").getAsString());
			feature.setsEpicName(project.getAsJsonObject("Parent").get("_refObjectName").getAsString());

          }
    	 }
    	 catch(Exception e){
    		 feature.setsEpicID("");
    	 }
         if(!project.get("Iteration").isJsonNull()){
	     feature.setsSprintID(it.getID());
	      feature.setsSprintName(it.getName());
	      feature.setsSprintBeginDate(it.getBeginDate());
			feature.setsSprintEndDate(it.getEndDate());
			feature.setsSprintAssetState("Active");
        }
         else {
				// Issue #678 - leave sprint blank. Not having a sprint does not imply kanban
				// as a story on a scrum board without a sprint is really on the backlog
				// Instead the feature service is responsible for deducing if a sprint is part of
				// kanban - see service for more details
				feature.setsSprintID("");
				feature.setsSprintName("");
				feature.setsSprintBeginDate("");
				feature.setsSprintEndDate("");
				//feature.setsSprintAssetState(getJSONString(dataMainObj, "Timebox.AssetState"));
			}
         feature.setsTeamID(project.getAsJsonObject("Project").get("ObjectID").getAsString());

			// sTeamName
         //List<String> ownerID= new ArrayList<>();
			feature.setsTeamName(project.getAsJsonObject("Project").get("_refObjectName").getAsString());
			//ownerID.add(project.getAsJsonObject("Owner").get("ObjectID").getAsString());
		//	feature.setsOwnersID(ownerID);
	   stories.add(feature);
	   }
	   }
	}
	   return stories;

}

public Iteration getCurrentIteration() throws IOException, URISyntaxException{
	RallyRestApi restApi=getRallyClient();
	Iteration it = new Iteration();
	String projectRef="/project/"+featureSettings.getProjectObjectId();
	String now = LocalDateTime.now().toString();
	QueryRequest request = new QueryRequest("Iteration");
	 request.setFetch(new Fetch("Name","ObjectID","StartDate","EndDate"));
	 request.setProject(projectRef);
	 request.setQueryFilter(new QueryFilter("StartDate","<=",now).and(new QueryFilter("EndDate",">=",now)));
	 request.setScopedDown(true);
	   QueryResponse response = restApi.query(request);
	   if(response.getResults()!=null){
		   for(JsonElement result : response.getResults()){
			   JsonObject iteration = result.getAsJsonObject();
		   it.setID(iteration.get("ObjectID").getAsString());
		   it.setName(iteration.get("Name").getAsString());
		   it.setStartDate(iteration.get("StartDate").getAsString());
		   it.setEndDate(iteration.get("EndDate").getAsString());
		   }
}
return it;
}
}


text:
Request info hook for [Sails JS](http://sailsjs.org)

### Installation

run `npm install sails-hook-request-info` in your sails appliaction

### Log format

| Field | Format | Extract from the example above
|:------------- |:---------------:| -------------:|
| 1 | Request user-agent | Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) |
| 2 | Request referer | referer:http://localhost:8002/ |
| 3 | Request x-forwarded-for | ::1 |
| 4 | Request method | GET |
| 5 | Request url | /api/v1/userAutoshow/getUserCount |
| 6 | Http version | HTTP/1.1 |
| 7 | Response status code | 200 |
| 8 | Response size | response size : 621B |
| 9 | Response time | time 321ms |

### Example

after installation complete, you will see request info in your terminal

like this :

#### Response status code is 2xx

```info: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36" "referer:http://localhost:8002/" "::1 GET /api/v1/userAutoshow/getUserCount HTTP/1.1 200" response size : 621B need time 321ms```

#### Response status code is 4xx or 5xx

```error: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36" "referer:" "::1 GET /sdfdsf HTTP/1.1 404" response size : 6.68kB need time 71ms.```

#### Request is caching in client's browser (response size is -1)

```info: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36" "referer:http://localhost:8002/" "::1 GET /api/v1/userAutoshow/getUserCount HTTP/1.1 304" response size : -1 need time 368ms.```


text:
/**
 * Exceptions of the system.
 */
package org.codeforamerica.open311.facade.exceptions;


text:
using namespace PinnedDownGameplay::Events;

const HashedString ClientConnectedEvent::ClientConnectedEventType = HashedString("ClientConnected");


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Meddn Soc. Fauna Flora fenn. 18: 62 (1891)

#### Original name
Agaricus serotinus Pers., 1793

### Remarks
null


text:
{% extends 'civic_calendar/_base.html' %}

{% block content %}

What you're looking for was not found.

{{ reason }}

{% endblock content %}


text:
<Dialog Name="CostAllocation" HelpFile="CostAllocation.html">
	<DialogComponent type="DialogFile">
		<Name>sourceHeader</Name>
		<Description>Enter the name of the input source file here</Description>
		<LabelText>Input Source Raster File:</LabelText>
		<DialogMode>Open File</DialogMode>
		<Filter>Raster Files (*.dep), DEP</Filter>
		<IsVisible>True</IsVisible>
		<MakeOptional>False</MakeOptional>
		<ShowButton>True</ShowButton>
	</DialogComponent>
        <DialogComponent type="DialogFile">
		<Name>backlinkHeader</Name>
		<Description>Enter the name of the back-link image here</Description>
		<LabelText>Input Back-Link Raster File:</LabelText>
		<DialogMode>Open File</DialogMode>
		<Filter>Raster Files (*.dep), DEP</Filter>
		<IsVisible>True</IsVisible>
		<MakeOptional>False</MakeOptional>
		<ShowButton>True</ShowButton>
	</DialogComponent>
        <DialogComponent type="DialogFile">
		<Name>outputFile</Name>
		<Description>Enter the name of the output file here</Description>
		<LabelText>Output Cost-Alocation Raster File:</LabelText>
		<DialogMode>Save File</DialogMode>
		<Filter>Raster Files (*.dep), DEP</Filter>
		<IsVisible>True</IsVisible>
		<MakeOptional>False</MakeOptional>
		<ShowButton>True</ShowButton>
	</DialogComponent>
</Dialog>


text:
package conn

import (
	"net"

	"golang.org/x/net/ipv4"
)

// Creates listener on all interfaces and then filters packets not received by interfaceName
func NewUDP4FilterListener(interfaceName, laddr string) (c *serveIfConn, e error) {
	iface, err := net.InterfaceByName(interfaceName)
	if err != nil {
		return nil, err
	}
	l, err := net.ListenPacket("udp4", laddr)
	if err != nil {
		return nil, err
	}
	defer func() {
		if e != nil {
			l.Close()
		}
	}()
	p := ipv4.NewPacketConn(l)
	if err := p.SetControlMessage(ipv4.FlagInterface, true); err != nil {
		return nil, err
	}
	return &serveIfConn{ifIndex: iface.Index, conn: p}, nil
}

type serveIfConn struct {
	ifIndex int
	conn    *ipv4.PacketConn
	cm      *ipv4.ControlMessage
}

func (s *serveIfConn) ReadFrom(b []byte) (n int, addr net.Addr, err error) {
	for { // Filter all other interfaces
		n, s.cm, addr, err = s.conn.ReadFrom(b)
		if err != nil || s.cm == nil || s.cm.IfIndex == s.ifIndex {
			break
		}
	}
	return
}

func (s *serveIfConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {

	// ipv4 docs state that Src is "specify only", however testing by tfheen
	// shows that Src IS populated.  Therefore, to reuse the control message,
	// we set Src to nil to avoid the error "write udp4: invalid argument"
	s.cm.Src = nil
	return s.conn.WriteTo(b, s.cm, addr)
}

func (s *serveIfConn) Close() error { return s.conn.Close() }

// Function only exists to support deprecated dhcp4/ServeIf DO NOT USE
func NewServeIf(ifIndex int, p *ipv4.PacketConn) *serveIfConn {
	return &serveIfConn{ifIndex: ifIndex, conn: p}
}


text:
angular.module('myList',[])
  .controller('ListController',function($http){
    var list = this;

    list.data = [];

    list.getData = function(){
        $http({
          method: 'GET',
          url: 'http://api-nivesh2.c9users.io/api/v1/fetch'
        }).then(function successCallback(response){
          list.data = response.data.data;
        }, function errorCallback(response){
          console.log(response);
        });
    };

    list.addData = function() {
        console.log('add function called');
        if(list.key!==undefined){
          var _data = JSON.stringify({"key":list.key, "value":list.value});
          console.log(_data);
          // Simple GET request example:
          $http({
            method: 'POST',
            url: 'http://api-nivesh2.c9users.io/api/v1/insert',
            data: _data
          }).then(function successCallback(response) {
              console.log(response);

              var _index=-1;
              list.data.forEach(function(item,index,array){
                if(item.key === list.key){
                  item.value = list.value;
                  _index = 0;
                }
              });

              if(_index===-1){
                list.data.push({'key':list.key,'value':list.value});
              }

              list.key='';
              list.value='';

            }, function errorCallback(response) {
              console.log(response);
            });
        }
    };

    list.delete = function(key){
      console.log('deleting '+key);
      $http({
        method: 'GET',
        url: "http://api-nivesh2.c9users.io/api/v1/delete?key="+key
      }).then(function successCallback(response){
        console.log(response);
      }, function errorCallback(response){
        console.log(response);
      });

      setTimeout(()=>{
        list.data =  list.data.filter((item)=>{
            return item.key !== key;
          });
      },0);
    };

  });


text:
package org.codingmatters.tests.compile;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;

import java.io.File;
import java.io.FileWriter;

import static org.codingmatters.tests.reflect.ReflectMatchers.*;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;

/**
 * Created by nelt on 9/6/16.
 */
public class CompiledCodeTest {

    @Rule
    public TemporaryFolder dir = new TemporaryFolder();
    @Rule
    public TemporaryFolder dir2 = new TemporaryFolder();
    @Rule
    public ExpectedException exception = ExpectedException.none();

    private CompiledCode compiled;

    @Before
    public void setUp() throws Exception {
        File helloWorld = new File(this.dir.newFolder("org", "codingmatters"), "HelloWorld.java");

        try(FileWriter writer = new FileWriter(helloWorld)) {
            writer.write(
                    "package org.codingmatters;\n" +
                    "\n" +
                    "public class HelloWorld {\n" +
                    "    public HelloWorld() {}\n" +
                    "\n" +
                    "    public String sayHello() {return \"Hello, World\";}\n" +
                    "\n" +
                    "    public static void main(String[] args) {\n" +
                    "        System.out.println(new HelloWorld().sayHello());\n" +
                    "    }\n" +
                    "}"
            );
            writer.flush();
        }

        this.compiled = CompiledCode.builder().source(this.dir.getRoot()).compile();
    }

    @Test
    public void compilationFails() throws Exception {
        exception.expect(AssertionError.class);
        exception.expectMessage(is(
                this.dir.getRoot().getAbsolutePath() + "/org/codingmatters/BrokenHello.java:3: error: reached end of file while parsing\n" +
                "public class BrokenHello {\n" +
                "                          ^\n" +
                "\n" +
                "source files with error :\n" +
                this.dir.getRoot().getAbsolutePath() + "/org/codingmatters/BrokenHello.java : \n" +
                "001   package org.codingmatters;\n" +
                "002   \n" +
                "003   public class BrokenHello {\n"
        ));

        File helloWorld = new File(this.dir.getRoot(), "org/codingmatters/BrokenHello.java");

        try(FileWriter writer = new FileWriter(helloWorld)) {
            writer.write(
                    "package org.codingmatters;\n" +
                    "\n" +
                    "public class BrokenHello {\n"
            );
            writer.flush();
        }

        this.compiled = CompiledCode.builder().source(this.dir.getRoot()).compile();
    }

    @Test
    public void getCompiledClass() throws Exception {
        assertThat(compiled.getClass("org.codingmatters.HelloWorld"), is(anInstance().class_()));
        assertThat(compiled.getClass("org.codingmatters.NoSuchClass"), is(not(anInstance().class_())));
    }

    @Test
    public void classMatcher_methodNameMatches() throws Exception {
        assertThat(
                compiled.getClass("org.codingmatters.HelloWorld"),
                is(anInstance().class_()
                        .with(aPublic().method().named("sayHello").returning(String.class))
                        .with(aStatic().public_().method().named("main").withParameters(String[].class).returningVoid())
                )
        );
    }

    @Test
    public void addCompileTarget() throws Exception {
        File newClass = new File(this.dir2.newFolder("org", "codingmatters"), "NewClass.java");

        try(FileWriter writer = new FileWriter(newClass)) {
            writer.write(
                    "package org.codingmatters;\n" +
                            "\n" +
                            "public class NewClass {\n" +
                            "}"
            );
            writer.flush();
        }

        CompiledCode extented = this.compiled.withCompiled(this.dir2.getRoot());

        assertThat(extented.getClass("org.codingmatters.HelloWorld"), is(anInstance().class_()));
        assertThat(extented.getClass("org.codingmatters.NewClass"), is(anInstance().class_()));

        assertThat(compiled.getClass("org.codingmatters.NewClass"), is(not(anInstance().class_())));
    }

    @Test
    public void invokeWithNullArgument_nullMustBeEnclosedInAnArray() throws Exception {
        StringBuilder o = new StringBuilder();
        this.compiled.on(o).invoke("append", String.class).with(new Object [] {null});

        this.exception.expect(AssertionError.class);
        this.exception.expectMessage("(if you meant to invoke method with one null argument, call with new Object[] {null})");
        this.compiled.on(o).invoke("append", String.class).with(null);
    }
}


text:
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<pre id="info">

</pre>
<input value="获取信息" type="button" id="btn" />
<script>
    var btn = document.getElementById('btn');
    var info = document.getElementById('info');
    btn.addEventListener('click',function(){
        var xmlHttp = null;

        if(window.XMLHttpRequest) {
            xmlHttp = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlHttp.open("GET", './data.json', true);

        // 监听readystate,关于readystate参照https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/readyState
        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4) {
                info.innerHTML = "数据正在加载...";
                // 当http状态返回200时候,http状态列表 http://www.daqianduan.com/4280.html
                if (xmlHttp.status == 200) {
                    var data = xmlHttp.responseText;
                    data = JSON.parse(data);
                    var str = "";
                    for(var key in data){
                        str = str+key+":"+data[key]+"\r\n";
                    }

                    info.innerHTML = str;
                }
            }
        }
        xmlHttp.send();

    },false);
</script>
</body>
</html>