text:
spendb.factory('flash', ['$rootScope', '$timeout', function($rootScope, $timeout) {
  // Message flashing.
  var currentMessage = null;

  return {
    setMessage: function(message, type) {
      currentMessage = [message, type];
      $timeout(function() {
        currentMessage = null;
      }, 4000);
    },
    getMessage: function() {
      if (currentMessage) {
        return currentMessage[0];
      }
    },
    getType: function() {
      if (currentMessage) {
        return currentMessage[1];
      }
    }
  };
}]);

spendb.factory('validation', ['flash', 'config', function(flash, config) {
  // handle server-side form validation errors.
  return {
    handle: function(form) {
      return function(res) {
        if (res.status == 400 || !form) {
            var errors = [];
            for (var field in res.data.errors) {
                form[field].$setValidity('value', false);
                form[field].$message = res.data.errors[field];
                errors.push(field);
            }
            if (angular.isDefined(form._errors)) {
                angular.forEach(form._errors, function(field) {
                    if (errors.indexOf(field) == -1) {
                        form[field].$setValidity('value', true);
                    }
                });
            }
            form._errors = errors;
        } else {
          flash.setMessage(res.data.message || res.data.title || 'Server error', 'danger');
        }
      }
    },
    clear: function(form) {
      if (angular.isDefined(form._errors)) {
        for (var i in form._errors) {
          var field = form._errors[i];
          form[field].$setValidity('value', true);
          form[field].$message = undefined;
        }
      };
      form._errors = undefined;
      form.$setPristine();
      form.$setValidity();
    }
  };
}]);

spendb.factory('data', ['$http', 'config', function($http, config) {
  /* This is used to cache reference data once it has been retrieved from the
  server. Reference data includes the canonical lists of country names,
  currencies, etc. */
  var referenceData = $http.get(config.apiBaseUrl + '/api/3/reference');

  var getData = function(cb) {
    referenceData.then(function(res) {
      cb(res.data);
    });
  };

  return {get: getData}
}]);

spendb.factory('session', ['$http', 'config', function($http, config) {
  var sessionDfd = null;

  var logout = function(cb) {
    $http.post(config.apiBaseUrl + '/api/3/sessions/logout').then(function() {
      sessionDfd = null;
      get(cb);
    });
  };

  var flush = function() {
    sessionDfd = null;
  };

  var get = function(cb) {
    if (sessionDfd === null) {
      var data = {'_': new Date()}
      sessionDfd = $http.get(config.apiBaseUrl + '/api/3/sessions', {params: data});
    }
    sessionDfd.then(function(res) {
      cb(res.data);
    });
  };

  return {
    get: get,
    flush: flush,
    logout: logout
  }
}]);


text:
namespace Checkout
{
    public class ApiUrls
    {
        private static string _cardTokensApiUri;
        private static string _paymentTokensApiUri;
        private static string _updatePaymentTokensApiUri;
        private static string _cardChargesApiUri;
        private static string _cardTokenChargesApiUri;
        private static string _defaultCardChargesApiUri;
        private static string _chargeRefundsApiUri;
        private static string _chargeVoidApiUri;
        private static string _captureChargesApiUri;
        private static string _updateChargesApiUri;
        private static string _localPaymentChargesApiUri;

        private static string _chargesApiUri;
        private static string _chargeApiUri;
        private static string _chargeHistoryApiUri;

        private static string _customersApiUri;
        private static string _customerApiUri;

        private static string _cardsApiUri;
        private static string _cardApiUri;

        private static string _reportingTransactionsUri;
        private static string _reportingChargebacksUri;

        private static string _binLookupUri;
        private static string _localPaymentIssuerIdLookup;

        private static string _recurringPaymentPlanCreateApiUri;
        private static string _recurringPaymentPlanApiUri;
        private static string _recurringPaymentPlanSearchApiUri;
        private static string _recurringCustomerPaymentPlanSearchApiUri;
        private static string _recurringCustomerPaymentPlanApiUri;
        private static string _visaCheckout;

        private static string _drinkCreateUri;
        private static string _drinkRemoveUri;
        private static string _drinkUpdateUri;
        private static string _drinkGetUri;
        private static string _drinkAll;
        public static void ResetApiUrls()
        {
            _cardTokensApiUri = null;
            _paymentTokensApiUri = null;
            _updatePaymentTokensApiUri = null;
            _cardChargesApiUri = null;
            _cardTokenChargesApiUri = null;
            _defaultCardChargesApiUri = null;
            _chargeRefundsApiUri = null;
            _chargeVoidApiUri = null;
            _captureChargesApiUri = null;
            _updateChargesApiUri = null;
            _chargesApiUri = null;
            _chargeApiUri = null;
            _chargeHistoryApiUri = null;
            _customersApiUri = null;
            _customerApiUri = null;
            _cardsApiUri = null;
            _cardApiUri = null;
            _reportingTransactionsUri = null;
            _reportingChargebacksUri = null;
            _binLookupUri = null;
            _visaCheckout = null;
            _localPaymentIssuerIdLookup = null;

            _recurringPaymentPlanApiUri = null;
            _recurringPaymentPlanCreateApiUri = null;
            _recurringPaymentPlanSearchApiUri = null;
            _recurringCustomerPaymentPlanSearchApiUri = null;
            _recurringCustomerPaymentPlanApiUri = null;
            _localPaymentChargesApiUri = null;

            _drinkCreateUri = null;
            _drinkRemoveUri = null;
            _drinkUpdateUri = null;
            _drinkGetUri = null;
            _drinkAll = null;
        }

        public static string Charges
            => _chargesApiUri ?? (_chargesApiUri = string.Concat(AppSettings.BaseApiUri, "/charges"));

        public static string Charge
            => _chargeApiUri ?? (_chargeApiUri = string.Concat(AppSettings.BaseApiUri, "/charges/{0}"));

        public static string ChargeHistory
            =>
                _chargeHistoryApiUri ??
                (_chargeHistoryApiUri = string.Concat(AppSettings.BaseApiUri, "/charges/{0}/history"));

        public static string CaptureCharge
            =>
                _captureChargesApiUri ??
                (_captureChargesApiUri = string.Concat(AppSettings.BaseApiUri, "/charges/{0}/capture"));

        public static string RefundCharge
            =>
                _chargeRefundsApiUri ??
                (_chargeRefundsApiUri = string.Concat(AppSettings.BaseApiUri, "/charges/{0}/refund"));

        public static string VoidCharge
            => _chargeVoidApiUri ?? (_chargeVoidApiUri = string.Concat(AppSettings.BaseApiUri, "/charges/{0}/void"));

        public static string DefaultCardCharge
            =>
                _defaultCardChargesApiUri ??
                (_defaultCardChargesApiUri = string.Concat(AppSettings.BaseApiUri, "/charges/customer"));

        public static string LocalPaymentCharge
            =>
                _localPaymentChargesApiUri ??
                (_localPaymentChargesApiUri = string.Concat(AppSettings.BaseApiUri, "/charges/localpayment"));

        public static string CardTokenCharge
            =>
                _cardTokenChargesApiUri ??
                (_cardTokenChargesApiUri = string.Concat(AppSettings.BaseApiUri, "/charges/token"));

        public static string CardCharge
            => _cardChargesApiUri ?? (_cardChargesApiUri = string.Concat(AppSettings.BaseApiUri, "/charges/card"));

        public static string CardToken
            => _cardTokensApiUri ?? (_cardTokensApiUri = string.Concat(AppSettings.BaseApiUri, "/tokens/card"));

        public static string PaymentToken
            => _paymentTokensApiUri ?? (_paymentTokensApiUri = string.Concat(AppSettings.BaseApiUri, "/tokens/payment"))
            ;

        public static string UpdatePaymentToken
            =>
                _updatePaymentTokensApiUri ??
                (_paymentTokensApiUri = string.Concat(AppSettings.BaseApiUri, "/tokens/payment/{0}"));

        public static string VisaCheckout
            => _visaCheckout ?? (_visaCheckout = string.Concat(AppSettings.BaseApiUri, "/tokens/card/visa-checkout"));

        public static string Customers
            => _customersApiUri ?? (_customersApiUri = string.Concat(AppSettings.BaseApiUri, "/customers"));

        public static string Customer
            => _customerApiUri ?? (_customerApiUri = string.Concat(AppSettings.BaseApiUri, "/customers/{0}"));

        public static string Cards
            => _cardsApiUri ?? (_cardsApiUri = string.Concat(AppSettings.BaseApiUri, "/customers/{0}/cards"));

        public static string Card
            => _cardApiUri ?? (_cardApiUri = string.Concat(AppSettings.BaseApiUri, "/customers/{0}/cards/{1}"));

        public static string ReportingTransactions
            =>
                _reportingTransactionsUri ??
                (_reportingTransactionsUri = string.Concat(AppSettings.BaseApiUri, "/reporting/transactions"));

        public static string ReportingChargebacks
            =>
                _reportingChargebacksUri ??
                (_reportingChargebacksUri = string.Concat(AppSettings.BaseApiUri, "/reporting/chargebacks"));

        public static string BinLookup
            => _binLookupUri ?? (_binLookupUri = string.Concat(AppSettings.BaseApiUri, "/lookups/bins/{0}"));

        public static string LocalPaymentIssuerIdLookup
            => _localPaymentIssuerIdLookup ?? (_localPaymentIssuerIdLookup = string.Concat(AppSettings.BaseApiUri, "/lookups/localpayments/{0}/tags/issuerid"));

        public static string RecurringPaymentPlans
            =>
                _recurringPaymentPlanCreateApiUri ??
                (_recurringPaymentPlanCreateApiUri = string.Concat(AppSettings.BaseApiUri, "/recurringPayments/plans"));

        public static string RecurringPaymentPlan
            =>
                _recurringPaymentPlanApiUri ??
                (_recurringPaymentPlanApiUri = string.Concat(AppSettings.BaseApiUri, "/recurringPayments/plans/{0}"));

        public static string RecurringPaymentPlanSearch
            =>
                _recurringPaymentPlanSearchApiUri ??
                (_recurringPaymentPlanSearchApiUri =
                    string.Concat(AppSettings.BaseApiUri, "/recurringPayments/plans/search"));

        public static string RecurringCustomerPaymentPlanSearch
            =>
                _recurringCustomerPaymentPlanSearchApiUri ??
                (_recurringCustomerPaymentPlanSearchApiUri =
                    string.Concat(AppSettings.BaseApiUri, "/recurringPayments/customers/search"));

        public static string RecurringCustomerPaymentPlan
            =>
                _recurringCustomerPaymentPlanApiUri ??
                (_recurringCustomerPaymentPlanApiUri =
                    string.Concat(AppSettings.BaseApiUri, "/recurringPayments/customers/{0}"));

        public static string DrinksCreateUrl
          =>
              _drinkCreateUri ??
              (_drinkCreateUri =
                  string.Concat(AppSettings.BaseApiUri, "api/PostDrink/{0}/{1}"));

    public static string DrinkDeleteUrl
        =>
            _drinkRemoveUri ??
            (_drinkRemoveUri =
                string.Concat(AppSettings.BaseApiUri, "api/DeleteADrink/{0}"));

        public static string DrinkUpdateUrl
       =>
           _drinkUpdateUri ??
           (_drinkUpdateUri =
               string.Concat(AppSettings.BaseApiUri, "api/PutDrink/{0}/{1}"));

        public static string DrinkGetUrl
    =>
        _drinkGetUri ??
        (_drinkGetUri =
            string.Concat(AppSettings.BaseApiUri, "api/GetDrink/{0}"));

        public static string DrinkAllUrl
  =>
      _drinkAll ??
      (_drinkAll =
          string.Concat(AppSettings.BaseApiUri, "api/GetDrinks"));

    }
}

redpajama_set_name: RedPajamaGithub


text:
![](https://travis-ci.org/a-warner/ghost_dog.png)

Making method_missing easier to deal with since 2013...

## Installation

Add this line to your application's Gemfile:

    gem 'ghost_dog'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install ghost_dog

## Motivation

I've written similar looking `method_missing` and `respond_to?` code frequently enough
that I finally decided it was time for an abstraction.  This might not be the best
abstraction, but it was the simplest way of thinking about it for me.  Feel free to fork
the project and add your own interfaces for it.

Ghost Dog is built around the simple type `Responder`, which implements `matches?` and `call`.  `matches?` is used
to determine whether a `Responder` can be used for a missing method (and therefore used in both `respond_to?`
and `method_missing`) and `call` is used to actually respond to a method invocation.  Most of the time you shouldn't
be dealing directly with the `Responder` class; instead, you'll define methods either via the shorthand or with
the DSL.

In order to define a `ghost_method`, you need to implement a Matcher, which can either be a simple regex with
capture groups or a proc. When using a regex, any capture groups will be passed to your responding block. When using
a proc, anything returned by the proc will be passed to your responding block.  The matcher block should return
something truthy if the method is available, otherwise it should return something falsy.  See below for additional
examples.

## Usage

Check out the specs for full usage information.  Here are some quick examples:

Simple syntax:

```ruby
class Minimal
  include GhostDog

  ghost_method /^tell_me_(.+)$/ do |what_to_tell|
    what_to_tell.gsub('_', ' ')
  end
end
```

```sh
>> Minimal.new.tell_me_hello_world # "hello world"
```

More complex example, using the DSL version:

```ruby
class ComplexExample
  include GhostDog

  def names
    ['ishmael', 'dave']
  end

  ghost_method do
    match_with do |method_name|
      if match = method_name.match(/^call_me_(#{names.join('|')})$/)
        match.to_a.drop(1)
      end
    end

    respond_with do |name|
      "what's going on #{name}?"
    end
  end
end
```

```sh
>> ComplexExample.new.call_me_ishmael # "what's going on ishmael?"
>> ComplexExample.new.call_me_samuel # NoMethodError
```

Implementing a (fairly) complex example (using `detect_by` instead of `find_by`) as a duplicate of ActiveRecord's dynamic finders:

```ruby
class MyModel < ActiveRecord::Base
  class << self
    include GhostDog

    ghost_method do
      create_method false

      match_with do |method_name|
        cols = column_names.join('|')
        if match = method_name.match(/\Adetect_by_(#{cols})((?:_and_(?:#{cols}))*)\z/)
          [[match[1]] + match[2].split('_and_').select(&:present?)]
        end
      end

      respond_with do |*args|
        columns_to_find_by = args.shift
        unless args.length == columns_to_find_by.length
          raise ArgumentError, "Wrong number of arguments (#{args.length} for #{columns_to_find_by.length})"
        end

        where(Hash[columns_to_find_by.zip(args)]).first
      end
    end
  end
end
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
require 'plutolib/active_hash_methods'
class Doogle::Status < ActiveHash::Base
  self.data = [
    {:id => 1, :name => 'Unfinished / Draft', :cmethod => 'draft'},
    {:id => 2, :name => 'Complete', :cmethod => 'published'},
    {:id => 3, :name => 'Deleted'}
  ]
  include Plutolib::ActiveHashMethods
end


text:
<?php

namespace Oro\Bundle\ConfigBundle\Tests\Unit\Config;

use Symfony\Component\EventDispatcher\EventDispatcher;

use Oro\Bundle\ConfigBundle\Config\ConfigDefinitionImmutableBag;
use Oro\Bundle\ConfigBundle\Config\ConfigManager;
use Oro\Bundle\ConfigBundle\Config\GlobalScopeManager;
use Oro\Bundle\ConfigBundle\Event\ConfigSettingsUpdateEvent;
use Oro\Bundle\ConfigBundle\Event\ConfigUpdateEvent;
use Oro\Bundle\ConfigBundle\Event\ConfigGetEvent;

class ConfigManagerTest extends \PHPUnit_Framework_TestCase
{
    /** @var ConfigManager */
    protected $manager;

    /** @var ConfigDefinitionImmutableBag */
    protected $bag;

    /** @var EventDispatcher|\PHPUnit_Framework_MockObject_MockObject */
    protected $dispatcher;

    /** @var GlobalScopeManager|\PHPUnit_Framework_MockObject_MockObject */
    protected $globalScopeManager;

    /** @var GlobalScopeManager|\PHPUnit_Framework_MockObject_MockObject */
    protected $userScopeManager;

    /**
     * @var array
     */
    protected $settings = array(
        'oro_user' => array(
            'greeting' => array(
                'value' => true,
                'type'  => 'boolean',
            ),
            'level'    => array(
                'value' => 20,
                'type'  => 'scalar',
            )
        ),
        'oro_test' => array(
            'anysetting'  => array(
                'value' => 'anyvalue',
                'type'  => 'scalar',
            ),
            'emptystring' => array(
                'value' => '',
                'type'  => 'scalar',
            ),
        ),
    );

    public function setUp()
    {
        $this->bag        = new ConfigDefinitionImmutableBag($this->settings);
        $this->dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcher')
            ->disableOriginalConstructor()
            ->getMock();

        $this->manager = new ConfigManager(
            'user',
            $this->bag,
            $this->dispatcher
        );

        $this->globalScopeManager = $this->getMockBuilder('Oro\Bundle\ConfigBundle\Config\GlobalScopeManager')
            ->disableOriginalConstructor()
            ->getMock();
        $this->userScopeManager   = $this->getMockBuilder('Oro\Bundle\ConfigBundle\Config\GlobalScopeManager')
            ->disableOriginalConstructor()
            ->getMock();

        $this->manager->addManager('user', $this->userScopeManager);
        $this->manager->addManager('global', $this->globalScopeManager);
    }

    /**
     * @dataProvider scopeIdentifierDataProvider
     *
     * @param int|null|object $scopeIdentifier
     */
    public function testSet($scopeIdentifier)
    {
        $name  = 'testName';
        $value = 'testValue';
        $this->userScopeManager->expects($this->once())
            ->method('set')
            ->with($name, $value, $scopeIdentifier);

        $this->manager->set($name, $value, $scopeIdentifier);
    }

    /**
     * @dataProvider scopeIdentifierDataProvider
     *
     * @param int|null|object $scopeIdentifier
     */
    public function testReset($scopeIdentifier)
    {
        $name = 'testName.testValue';
        $this->userScopeManager->expects($this->once())
            ->method('reset')
            ->with($name, $scopeIdentifier);

        $this->manager->reset($name, $scopeIdentifier);
    }

    /**
     * @dataProvider scopeIdentifierDataProvider
     *
     * @param int|null|object $scopeIdentifier
     * @param int $idValue
     */
    public function testFlush($scopeIdentifier, $idValue)
    {
        $greetingKey = 'oro_user.greeting';
        $changes = [
            $greetingKey => [
                'value'                  => 'updated value',
                'use_parent_scope_value' => false
            ]
        ];

        $this->userScopeManager->expects($this->once())
            ->method('getSettingValue')
            ->with($greetingKey, false)
            ->willReturn('old value');

        $beforeEvent = new ConfigSettingsUpdateEvent($this->manager, $changes);
        $afterEvent  = new ConfigUpdateEvent(
            [
                $greetingKey => ['old' => 'old value', 'new' => 'updated value']
            ],
            'user'
        );

        $loadEvent = new ConfigGetEvent($this->manager, $greetingKey, 'old value', false, $idValue);

        $this->userScopeManager->expects($this->once())
            ->method('getChanges')
            ->willReturn($changes);
        $this->userScopeManager->expects($this->any())
            ->method('resolveIdentifier')
            ->willReturn($idValue);

        $this->userScopeManager->expects($this->once())
            ->method('save')
            ->with($changes)
            ->willReturn(
                [
                    [$greetingKey => 'updated value'],
                    []
                ]
            );

        $this->dispatcher->expects($this->exactly(4))
            ->method('dispatch')
            ->withConsecutive(
                [ConfigGetEvent::NAME, $loadEvent],
                [ConfigGetEvent::NAME . '.' . $greetingKey, $loadEvent],
                [ConfigSettingsUpdateEvent::BEFORE_SAVE, $beforeEvent],
                [ConfigUpdateEvent::EVENT_NAME, $afterEvent]
            );

        $this->manager->flush($scopeIdentifier);
    }

    /**
     * @dataProvider scopeIdentifierDataProvider
     *
     * @param int|null|object $scopeIdentifier
     * @param int $idValue
     */
    public function testSave($scopeIdentifier, $idValue)
    {

        $greetingKey = 'oro_user.greeting';
        $levelKey = 'oro_user.level';

        $data           = [
            'oro_user___greeting' => [
                'value'                  => 'updated value',
                'use_parent_scope_value' => false
            ],
            'oro_user___unknown'  => [
                'value'                  => 'some value',
                'use_parent_scope_value' => false
            ],
            'oro_user___level'    => [
                'use_parent_scope_value' => true
            ]
        ];
        $normalizedData = [
            $greetingKey => [
                'value'                  => 'updated value',
                'use_parent_scope_value' => false
            ],
            $levelKey    => [
                'use_parent_scope_value' => true
            ]
        ];

        $this->userScopeManager->expects($this->any())
            ->method('resolveIdentifier')
            ->willReturn($idValue);
        $this->userScopeManager->expects($this->exactly(2))
            ->method('getSettingValue')
            ->willReturnMap(
                [
                    [$greetingKey, false, $scopeIdentifier, 'old value'],
                    [$levelKey, false, $scopeIdentifier, 2000]
                ]
            );

        $beforeEvent = new ConfigSettingsUpdateEvent($this->manager, $normalizedData);
        $afterEvent  = new ConfigUpdateEvent(
            [
                $greetingKey => ['old' => 'old value', 'new' => 'updated value'],
                $levelKey    => ['old' => 2000, 'new' => 20]
            ],
            'user'
        );

        $greetingOldValueLoadEvent = new ConfigGetEvent($this->manager, $greetingKey, 'old value', false, $idValue);
        $levelOldValueLoadEvent = new ConfigGetEvent($this->manager, $levelKey, '2000', false, $idValue);
        $levelNullValueLoadEvent = new ConfigGetEvent($this->manager, $levelKey, null, false, $idValue);

        $this->userScopeManager->expects($this->once())
            ->method('save')
            ->with($normalizedData)
            ->willReturn(
                [
                    [$greetingKey => 'updated value'],
                    [$levelKey]
                ]
            );

        $this->dispatcher->expects($this->exactly(8))
            ->method('dispatch')
            ->withConsecutive(
                [ConfigGetEvent::NAME, $greetingOldValueLoadEvent],
                [ConfigGetEvent::NAME . '.' . $greetingKey, $greetingOldValueLoadEvent],
                [ConfigGetEvent::NAME, $levelOldValueLoadEvent],
                [ConfigGetEvent::NAME . '.' . $levelKey, $levelOldValueLoadEvent],
                [ConfigSettingsUpdateEvent::BEFORE_SAVE, $beforeEvent],
                [ConfigGetEvent::NAME, $levelNullValueLoadEvent],
                [ConfigGetEvent::NAME  . '.' . $levelKey, $levelNullValueLoadEvent],
                [ConfigUpdateEvent::EVENT_NAME, $afterEvent]
            );

        $this->manager->save($data, $scopeIdentifier);
    }

    /**
     * @dataProvider scopeIdentifierDataProvider
     *
     * @param int|null|object $scopeIdentifier
     */
    public function testCalculateChangeSet($scopeIdentifier)
    {
        $data = [];
        $this->userScopeManager->expects($this->once())
            ->method('calculateChangeSet')
            ->with($data, $scopeIdentifier);

        $this->manager->calculateChangeSet($data, $scopeIdentifier);
    }

    public function testReload()
    {
        $this->userScopeManager->expects($this->once())
            ->method('reload');

        $this->manager->reload();
    }

    /**
     * @dataProvider getFromParentParamProvider
     * @param string $parameterName
     * @param bool $full
     * @param mixed $expectedResult
     */
    public function testGetFromParentScope($parameterName, $full, $expectedResult)
    {
        $this->userScopeManager->expects($this->once())
            ->method('getSettingValue')
            ->with($parameterName, $full)
            ->willReturn(null);

        $this->globalScopeManager->expects($this->once())
            ->method('getSettingValue')
            ->with($parameterName, $full)
            ->willReturnCallback(function ($name, $full) {
                if ($name === 'oro_test.someArrayValue') {
                    $value = ['foo' => 'bar'];
                    if ($full) {
                        $value = [
                            'scope'                  => 'global',
                            'value'                  => ['foo' => 'bar'],
                            'use_parent_scope_value' => false
                        ];
                    }
                } else {
                    $value = 1;
                    if ($full) {
                        $value = ['scope' => 'global', 'value' => 1, 'use_parent_scope_value' => true];
                    }
                }

                return $value;
            });

        $this->assertEquals(
            $expectedResult,
            $this->manager->get($parameterName, false, $full)
        );
    }

    /**
     * @return array
     */
    public function getFromParentParamProvider()
    {
        return [
            [
                'parameterName'  => 'oro_test.someValue',
                'full'           => false,
                'expectedResult' => 1,
            ],
            [
                'parameterName'  => 'oro_test.someValue',
                'full'           => true,
                'expectedResult' => ['scope' => 'global', 'value' => 1, 'use_parent_scope_value' => true],
            ],
            [
                'parameterName'  => 'oro_test.someArrayValue',
                'full'           => true,
                'expectedResult' => [
                    'scope'                  => 'global',
                    'value'                  => ['foo' => 'bar'],
                    'use_parent_scope_value' => true
                ]
            ],
            [
                'parameterName'  => 'oro_test.someArrayValue',
                'full'           => false,
                'expectedResult' => ['foo' => 'bar']
            ]
        ];
    }

    /**
     * @dataProvider scopeIdentifierDataProvider
     *
     * @param int|null|object $scopeIdentifier
     */
    public function testGet($scopeIdentifier)
    {
        $parameterName = 'oro_test.someValue';

        $this->userScopeManager->expects($this->once())
            ->method('getSettingValue')
            ->with($parameterName, false, $scopeIdentifier)
            ->willReturn(2);

        $this->globalScopeManager->expects($this->never())
            ->method('getSettingValue');

        $this->assertEquals(2, $this->manager->get($parameterName, false, false, $scopeIdentifier));
    }

    /**
     * @dataProvider scopeIdentifierDataProvider
     *
     * @param int|null|object $scopeIdentifier
     */
    public function testGetDefaultSettings($scopeIdentifier)
    {
        $parameterName = 'oro_test.anysetting';

        $this->userScopeManager->expects($this->once())
            ->method('getSettingValue')
            ->with($parameterName, false, $scopeIdentifier)
            ->willReturn(null);

        $this->globalScopeManager->expects($this->once())
            ->method('getSettingValue')
            ->with($parameterName, false, $scopeIdentifier)
            ->willReturn(null);

        $this->assertEquals(
            'anyvalue',
            $this->manager->get($parameterName, false, false, $scopeIdentifier)
        );
    }

    public function testGetEmptyValueSettings()
    {
        $parameterName = 'oro_test.emptystring';

        $this->userScopeManager->expects($this->once())
            ->method('getSettingValue')
            ->with($parameterName, false)
            ->willReturn('');

        $this->globalScopeManager->expects($this->never())
            ->method('getSettingValue');

        $this->assertEquals('', $this->manager->get($parameterName));
    }

    public function testGetSettingsDefaultsMethodReturnNullForMissing()
    {
        $this->assertEquals(null, $this->manager->getSettingsDefaults('oro_test.null', true));
    }

    public function testGetSettingsDefaultsMethodReturnPlain()
    {
        $this->assertEquals('anyvalue', $this->manager->getSettingsDefaults('oro_test.anysetting'));
    }

    public function testGetSettingsDefaultsMethodReturnFull()
    {
        $this->assertEquals(
            [
                'value' => 'anyvalue',
                'type' => 'scalar',
            ],
            $this->manager->getSettingsDefaults('oro_test.anysetting', true)
        );
    }

    /**
     * @dataProvider scopeIdentifierDataProvider
     *
     * @param int|null|object $scopeIdentifier
     */
    public function testGetMergedWithParentValue($scopeIdentifier)
    {
        $parameterName = 'oro_test.anysetting';

        $this->globalScopeManager->expects($this->once())
            ->method('getSettingValue')
            ->with($parameterName, false, $scopeIdentifier)
            ->willReturn(['a' => 1, 'b' => 1, 'c' => 1]);

        $this->userScopeManager->expects($this->once())
            ->method('getSettingValue')
            ->with($parameterName, false, $scopeIdentifier)
            ->willReturn(['a' => null, 'b' => 2]);

        $this->assertEquals(
            [
                'a' => null,
                'b' => 2,
                'c' => 1,
            ],
            $this->manager->getMergedWithParentValue([], $parameterName, false, $scopeIdentifier)
        );
    }

    public function testGetValues()
    {
        $parameterName = 'oro_test.someValue';
        $entity1 = new \stdClass();
        $entity1->id = 1;
        $entity2 = new \stdClass();
        $entity2->id = 2;
        $entities = [$entity1, $entity2];

        $this->userScopeManager->expects($this->any())
            ->method('resolveIdentifier')
            ->willReturnMap(
                [
                    [$entity1, 33],
                    [$entity2, 55]
                ]
            );

        $this->userScopeManager->expects($this->exactly(2))
            ->method('getSettingValue')
            ->withConsecutive(
                [$parameterName, false, $entity1],
                [$parameterName, false, $entity2]
            )
            ->willReturnMap(
                [
                    [$parameterName, false, $entity1, 'val1'],
                    [$parameterName, false, $entity2, 'val2']
                ]
            );

        $this->globalScopeManager->expects($this->never())
            ->method('getSettingValue');

        $this->assertEquals([33 => 'val1', 55 => 'val2'], $this->manager->getValues($parameterName, $entities));
    }

    /**
     * @return array
     */
    public function scopeIdentifierDataProvider()
    {
        return [
            [null, 1],
            [2, 2],
            [new \stdClass(), 123]
        ];
    }
}


text:
/**
 * Pipedrive API v1
 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
 *
 * The version of the OpenAPI document: 1.0.0
 *
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 *
 */

import ApiClient from '../ApiClient';

/**
 * The GetPersonDetailsResponseAllOfAdditionalData model module.
 * @module model/GetPersonDetailsResponseAllOfAdditionalData
 * @version 1.0.0
 */
class GetPersonDetailsResponseAllOfAdditionalData {
    /**
     * Constructs a new GetPersonDetailsResponseAllOfAdditionalData.
     * @alias module:model/GetPersonDetailsResponseAllOfAdditionalData
     */
    constructor() {

        GetPersonDetailsResponseAllOfAdditionalData.initialize(this);
    }

    /**
     * Initializes the fields of this object.
     * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
     * Only for internal use.
     */
    static initialize(obj) {
    }

    /**
     * Constructs a GetPersonDetailsResponseAllOfAdditionalData from a plain JavaScript object, optionally creating a new instance.
     * Copies all relevant properties from data to obj if supplied or a new instance if not.
     * @param {Object} data The plain JavaScript object bearing properties of interest.
     * @param {module:model/GetPersonDetailsResponseAllOfAdditionalData} obj Optional instance to populate.
     * @return {module:model/GetPersonDetailsResponseAllOfAdditionalData} The populated GetPersonDetailsResponseAllOfAdditionalData instance.
     */
    static constructFromObject(data, obj) {
        if (data) {
            obj = obj || new GetPersonDetailsResponseAllOfAdditionalData();

            if (data.hasOwnProperty('dropbox_email')) {
                obj['dropbox_email'] = ApiClient.convertToType(data['dropbox_email'], 'String');

                delete data['dropbox_email'];
            }

            if (Object.keys(data).length > 0) {
                Object.assign(obj, data);
            }

        }
        return obj;
    }

}

/**
 * Dropbox email for the person
 * @member {String} dropbox_email
 */
GetPersonDetailsResponseAllOfAdditionalData.prototype['dropbox_email'] = undefined;

export default GetPersonDetailsResponseAllOfAdditionalData;


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview A widget that exposes UI for interacting with a list of braille
 * displays.
 */

goog.provide('BluetoothBrailleDisplayUI');

goog.require('BluetoothBrailleDisplayListener');
goog.require('BluetoothBrailleDisplayManager');
goog.require('Msgs');

/**
 * A widget used for interacting with bluetooth braille displays.
 * @implements {BluetoothBrailleDisplayListener}
 */
BluetoothBrailleDisplayUI = class {
  constructor() {
    /** @private {!BluetoothBrailleDisplayManager} */
    this.manager_ = new BluetoothBrailleDisplayManager();

    this.manager_.addListener(this);

    /** @private {Element} */
    this.root_;

    /** @private {Element} */
    this.displaySelect_;

    /** @private {Element} */
    this.controls_;

    /** @private {string|undefined} */
    this.selectedAndConnectedDisplayAddress_;
  }

  /**
   * Attaches this widget to |element|.
   * @param {!Element} element
   */
  attach(element) {
    this.manager_.start();
    const container = document.createElement('div');
    element.appendChild(container);
    this.root_ = container;

    const title = document.createElement('h2');
    title.textContent = Msgs.getMsg('options_bluetooth_braille_display_title');
    container.appendChild(title);
    const controls = document.createElement('div');
    container.appendChild(controls);
    this.controls_ = controls;
    controls.className = 'option';

    const selectLabel = document.createElement('span');
    controls.appendChild(selectLabel);
    selectLabel.id = 'bluetoothBrailleSelectLabel';
    selectLabel.textContent =
        Msgs.getMsg('options_bluetooth_braille_display_select_label');

    const displaySelect = document.createElement('select');
    this.displaySelect_ = displaySelect;
    controls.appendChild(displaySelect);
    displaySelect.setAttribute(
        'aria-labelledby', 'bluetoothBrailleSelectLabel');
    displaySelect.addEventListener('change', (evt) => {
      this.updateControls_();
    });

    const connectOrDisconnect = document.createElement('button');
    controls.appendChild(connectOrDisconnect);
    connectOrDisconnect.id = 'connectOrDisconnect';
    connectOrDisconnect.disabled = true;
    connectOrDisconnect.textContent =
        Msgs.getMsg('options_bluetooth_braille_display_connect');

    const forget = document.createElement('button');
    controls.appendChild(forget);
    forget.id = 'forget';
    forget.textContent =
        Msgs.getMsg('options_bluetooth_braille_display_forget');
    forget.disabled = true;
  }

  /**
   * Detaches the rendered widget.
   */
  detach() {
    this.manager_.stop();

    if (this.root_) {
      this.root_.remove();
      this.root_ = null;
    }
  }

  /** @override */
  onDisplayListChanged(displays) {
    if (!this.displaySelect_) {
      throw 'Expected attach to have been called.';
    }

    // Remove any displays that were removed.
    for (let i = 0; i < this.displaySelect_.children.length; i++) {
      const domDisplay = this.displaySelect_.children[i];
      if (!displays.find((display) => domDisplay.id == display.address)) {
        domDisplay.remove();
      }
    }

    displays.forEach((display) => {
      // Check if the element already exists.
      let displayContainer =
          this.displaySelect_.querySelector('#' + CSS.escape(display.address));

      // If the display already exists, no further processing is needed.
      if (displayContainer) {
        return;
      }

      displayContainer = document.createElement('option');
      this.displaySelect_.appendChild(displayContainer);
      displayContainer.id = display.address;
      const name = document.createElement('span');
      displayContainer.appendChild(name);
      name.textContent = display.name;
    });
    this.updateControls_();
  }

  /** @override */
  onPincodeRequested(display) {
    this.controls_.hidden = true;
    let form = document.createElement('form');
    this.controls_.parentElement.insertBefore(form, this.controls_);

    // Create the text field and its label.
    const label = document.createElement('label');
    form.appendChild(label);
    label.id = 'pincodeLabel';
    label.textContent =
        Msgs.getMsg('options_bluetooth_braille_display_pincode_label');
    label.for = 'pincode';
    const pincodeField = document.createElement('input');
    pincodeField.id = 'pincode';
    pincodeField.type = 'text';
    pincodeField.setAttribute('aria-labelledby', 'pincodeLabel');
    form.appendChild(pincodeField);

    let timeoutId = -1;
    form.addEventListener('submit', (evt) => {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }

      if (pincodeField.value) {
        this.manager_.finishPairing(display, pincodeField.value);
      }

      this.controls_.hidden = false;
      form.remove();
      form = null;
      evt.preventDefault();
      evt.stopPropagation();
      this.displaySelect_.focus();
    });

    // Also, schedule a 60 second timeout for pincode entry.
    timeoutId = setTimeout(() => {
      form.remove();
      this.controls_.hidden = false;
      this.displaySelect_.focus();
    }, 60000);

    document.body.blur();
    pincodeField.focus();
  }

  /**
   * @private
   */
  updateControls_() {
    // Only update controls if there is a selected display.
    const sel = this.displaySelect_.options[this.displaySelect_.selectedIndex];
    if (!sel) {
      this.selectedAndConnectedDisplayAddress_ = undefined;
      return;
    }

    chrome.bluetooth.getDevice(sel.id, (display) => {
      // Record metrics if the display is connected for the first time either
      // via a click of the Connect button or re-connection by selection via the
      // select.
      if (display.connected) {
        if (this.selectedAndConnectedDisplayAddress_ != sel.id) {
          this.selectedAndConnectedDisplayAddress_ = sel.id;
          chrome.metricsPrivate.recordUserAction(
              BluetoothBrailleDisplayUI.CONNECTED_METRIC_NAME_);
        }
      } else {
        // The display is no longer connected.
        if (this.selectedAndConnectedDisplayAddress_ == sel.id) {
          this.selectedAndConnectedDisplayAddress_ = undefined;
        }
      }

      const connectOrDisconnect =
          this.controls_.querySelector('#connectOrDisconnect');
      connectOrDisconnect.disabled = display.connecting;
      this.displaySelect_.disabled = display.connecting;
      connectOrDisconnect.textContent = Msgs.getMsg(
          display.connecting ?
              'options_bluetooth_braille_display_connecting' :
              (display.connected ?
                   'options_bluetooth_braille_display_disconnect' :
                   'options_bluetooth_braille_display_connect'));
      connectOrDisconnect.onclick = function(savedDisplay, evt) {
        if (savedDisplay.connected) {
          this.manager_.disconnect(savedDisplay);
        } else {
          this.manager_.connect(savedDisplay);
        }
      }.bind(this, display);

      const forget = this.controls_.querySelector('#forget');
      forget.disabled = !display.paired || display.connecting;
      forget.onclick = function(savedDisplay) {
        this.manager_.forget(savedDisplay);
      }.bind(this, display);
    });
  }
};

/** @private {string} */
BluetoothBrailleDisplayUI.CONNECTED_METRIC_NAME_ =
    'Accessibility.ChromeVox.BluetoothBrailleDisplayConnectedButtonClick';


text:
static void * JXHTTPOperationQueueContext = &JXHTTPOperationQueueContext;
static NSInteger JXHTTPOperationQueueDefaultMaxOps = 4;

@interface JXHTTPOperationQueue ()
@property (strong) NSMutableDictionary *bytesDownloadedPerOperation;
@property (strong) NSMutableDictionary *bytesUploadedPerOperation;
@property (strong) NSMutableDictionary *expectedDownloadBytesPerOperation;
@property (strong) NSMutableDictionary *expectedUploadBytesPerOperation;
@property (strong) NSDate *startDate;
@property (strong) NSDate *finishDate;
@property (strong) NSString *uniqueString;
@property (strong) NSNumber *downloadProgress;
@property (strong) NSNumber *uploadProgress;
@property (strong) NSNumber *bytesDownloaded;
@property (strong) NSNumber *bytesUploaded;
@property (strong) NSNumber *expectedDownloadBytes;
@property (strong) NSNumber *expectedUploadBytes;
@property (strong) NSMutableSet *observedOperationSet;
#if OS_OBJECT_USE_OBJC
@property (strong) dispatch_queue_t observationQueue;
@property (strong) dispatch_queue_t progressQueue;
@property (strong) dispatch_queue_t blockQueue;
#else
@property (assign) dispatch_queue_t observationQueue;
@property (assign) dispatch_queue_t progressQueue;
@property (assign) dispatch_queue_t blockQueue;
#endif
@end

@implementation JXHTTPOperationQueue

#pragma mark - Initialization

- (void)dealloc
{
    [self removeObserver:self forKeyPath:@"operations" context:JXHTTPOperationQueueContext];

    #if !OS_OBJECT_USE_OBJC
    dispatch_release(_observationQueue);
    dispatch_release(_progressQueue);
    dispatch_release(_blockQueue);
    _observationQueue = NULL;
    _progressQueue = NULL;
    _blockQueue = NULL;
    #endif
}

- (instancetype)init
{
    if (self = [super init]) {
        self.maxConcurrentOperationCount = JXHTTPOperationQueueDefaultMaxOps;
        self.uniqueString = [[NSProcessInfo processInfo] globallyUniqueString];
        self.observedOperationSet = [[NSMutableSet alloc] init];
        self.performsBlocksOnMainQueue = NO;
        self.delegate = nil;
        self.startDate = nil;
        self.finishDate = nil;

        self.willStartBlock = nil;
        self.willFinishBlock = nil;
        self.didStartBlock = nil;
        self.didUploadBlock = nil;
        self.didDownloadBlock = nil;
        self.didMakeProgressBlock = nil;
        self.didFinishBlock = nil;

        NSString *prefix = [[NSString alloc] initWithFormat:@"%@.%p.", NSStringFromClass([self class]), self];
        self.observationQueue = dispatch_queue_create([[prefix stringByAppendingString:@"observation"] UTF8String], DISPATCH_QUEUE_SERIAL);
        self.progressQueue = dispatch_queue_create([[prefix stringByAppendingString:@"progress"] UTF8String], DISPATCH_QUEUE_CONCURRENT);
        self.blockQueue = dispatch_queue_create([[prefix stringByAppendingString:@"blocks"] UTF8String], DISPATCH_QUEUE_SERIAL);

        [self addObserver:self
               forKeyPath:@"operations"
                  options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
                  context:JXHTTPOperationQueueContext];
    }
    return self;
}

+ (instancetype)sharedQueue
{
    static id sharedQueue = nil;
    static dispatch_once_t predicate;

    dispatch_once(&predicate, ^{
        sharedQueue = [[self alloc] init];
    });

    return sharedQueue;
}

#pragma mark - Accessors

- (NSTimeInterval)elapsedSeconds
{
    if (self.startDate) {
        NSDate *endDate = self.finishDate ? self.finishDate : [[NSDate alloc] init];
        return [endDate timeIntervalSinceDate:self.startDate];
    } else {
        return 0.0;
    }
}

#pragma mark - Private Methods

- (void)performDelegateMethod:(SEL)selector
{
    if ([self.delegate respondsToSelector:selector])
        [self.delegate performSelector:selector onThread:[NSThread currentThread] withObject:self waitUntilDone:YES];

    JXHTTPQueueBlock block = [self blockForSelector:selector];

    if (!block)
        return;

    dispatch_async(self.performsBlocksOnMainQueue ? dispatch_get_main_queue() : self.blockQueue, ^{
        block(self);
    });
}

- (JXHTTPQueueBlock)blockForSelector:(SEL)selector
{
    if (selector == @selector(httpOperationQueueWillStart:))
        return self.willStartBlock;
    if (selector == @selector(httpOperationQueueWillFinish:))
        return self.willFinishBlock;
    if (selector == @selector(httpOperationQueueDidStart:))
        return self.didStartBlock;
    if (selector == @selector(httpOperationQueueDidUpload:))
        return self.didUploadBlock;
    if (selector == @selector(httpOperationQueueDidDownload:))
        return self.didDownloadBlock;
    if (selector == @selector(httpOperationQueueDidMakeProgress:))
        return self.didMakeProgressBlock;
    if (selector == @selector(httpOperationQueueDidFinish:))
        return self.didFinishBlock;
    return nil;
}

#pragma mark - <NSKeyValueObserving>

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (context != JXHTTPOperationQueueContext) {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        return;
    }

    __weak __typeof(self) weakSelf = self;

    if (object == self && [keyPath isEqualToString:@"operations"]) {
        if (![[change objectForKey:NSKeyValueChangeKindKey] intValue] == NSKeyValueChangeSetting)
            return;

        NSDate *now = [[NSDate alloc] init];

        NSArray *newOperationsArray = [change objectForKey:NSKeyValueChangeNewKey];
        NSArray *oldOperationsArray = [change objectForKey:NSKeyValueChangeOldKey];

        NSMutableArray *insertedArray = [[NSMutableArray alloc] initWithArray:newOperationsArray];
        NSMutableArray *removedArray = [[NSMutableArray alloc] initWithArray:oldOperationsArray];

        [insertedArray removeObjectsInArray:oldOperationsArray];
        [removedArray removeObjectsInArray:newOperationsArray];

        NSUInteger newCount = [newOperationsArray count];
        NSUInteger oldCount = [oldOperationsArray count];

        BOOL starting = oldCount < 1 && newCount > 0;
        BOOL finishing = oldCount > 0 && newCount < 1;

        if (starting) {
            dispatch_barrier_async(self.progressQueue, ^{
                weakSelf.bytesDownloadedPerOperation = [[NSMutableDictionary alloc] init];
                weakSelf.bytesUploadedPerOperation = [[NSMutableDictionary alloc] init];
                weakSelf.expectedDownloadBytesPerOperation = [[NSMutableDictionary alloc] init];
                weakSelf.expectedUploadBytesPerOperation = [[NSMutableDictionary alloc] init];
                weakSelf.downloadProgress = @0.0f;
                weakSelf.uploadProgress = @0.0f;
                weakSelf.bytesDownloaded = @0LL;
                weakSelf.bytesUploaded = @0LL;
                weakSelf.expectedDownloadBytes = @0LL;
                weakSelf.expectedUploadBytes = @0LL;
                weakSelf.finishDate = nil;
                weakSelf.startDate = now;
                [weakSelf performDelegateMethod:@selector(httpOperationQueueWillStart:)];
            });
        } else if (finishing) {
            dispatch_barrier_async(self.progressQueue, ^{
                [weakSelf performDelegateMethod:@selector(httpOperationQueueWillFinish:)];
            });
        }

        for (JXHTTPOperation *operation in insertedArray) {
            if (![operation isKindOfClass:[JXHTTPOperation class]])
                continue;

            NSNumber *expectedUp = @(operation.requestBody.httpContentLength);
            NSString *uniqueString = [operation.uniqueString copy];

            dispatch_barrier_async(self.progressQueue, ^{
                [weakSelf.expectedUploadBytesPerOperation setObject:expectedUp forKey:uniqueString];
            });

            dispatch_sync(self.observationQueue, ^{
                if (![self.observedOperationSet containsObject:operation]) {
                    [operation addObserver:self forKeyPath:@"bytesDownloaded" options:0 context:JXHTTPOperationQueueContext];
                    [operation addObserver:self forKeyPath:@"bytesUploaded" options:0 context:JXHTTPOperationQueueContext];
                    [operation addObserver:self forKeyPath:@"response" options:0 context:JXHTTPOperationQueueContext];

                    [self.observedOperationSet addObject:operation];
                }
            });
        }

        for (JXHTTPOperation *operation in removedArray) {
            if (![operation isKindOfClass:[JXHTTPOperation class]])
                continue;

            dispatch_sync(self.observationQueue, ^{
                if ([self.observedOperationSet containsObject:operation]) {
                    [operation removeObserver:self forKeyPath:@"bytesDownloaded" context:JXHTTPOperationQueueContext];
                    [operation removeObserver:self forKeyPath:@"bytesUploaded" context:JXHTTPOperationQueueContext];
                    [operation removeObserver:self forKeyPath:@"response" context:JXHTTPOperationQueueContext];

                    [self.observedOperationSet removeObject:operation];
                }
            });

            if ([operation isCancelled]) {
                NSString *uniqueString = [operation.uniqueString copy];

                dispatch_barrier_async(self.progressQueue, ^{
                    [weakSelf.bytesDownloadedPerOperation removeObjectForKey:uniqueString];
                    [weakSelf.bytesUploadedPerOperation removeObjectForKey:uniqueString];
                });
            }
        }

        if (starting) {
            dispatch_barrier_async(self.progressQueue, ^{
                [weakSelf performDelegateMethod:@selector(httpOperationQueueDidStart:)];
            });
        } else if (finishing) {
            dispatch_barrier_async(self.progressQueue, ^{
                weakSelf.finishDate = now;
                [weakSelf performDelegateMethod:@selector(httpOperationQueueDidFinish:)];
            });
        }

        return;
    }

    if ([keyPath isEqualToString:@"response"]) {
        JXHTTPOperation *operation = object;
        long long expectedDown = [operation.response expectedContentLength];
        NSString *uniqueString = [operation.uniqueString copy];

        if (expectedDown && expectedDown != NSURLResponseUnknownLength) {
            dispatch_barrier_async(self.progressQueue, ^{
                [weakSelf.expectedDownloadBytesPerOperation setObject:@(expectedDown) forKey:uniqueString];
            });
        }

        return;
    }

    if ([keyPath isEqualToString:@"bytesDownloaded"]) {
        JXHTTPOperation *operation = (JXHTTPOperation *)object;
        long long bytesDownloaded = operation.bytesDownloaded;
        NSString *uniqueString = [operation.uniqueString copy];

        dispatch_barrier_async(self.progressQueue, ^{
            [weakSelf.bytesDownloadedPerOperation setObject:@(bytesDownloaded) forKey:uniqueString];
        });

        dispatch_sync(self.progressQueue, ^{
            long long bytesDownloaded = 0LL;
            long long expectedDownloadBytes = 0LL;

            for (NSString *opString in [self.bytesDownloadedPerOperation allKeys]) {
                bytesDownloaded += [[self.bytesDownloadedPerOperation objectForKey:opString] longLongValue];
            }

            for (NSString *opString in [self.expectedDownloadBytesPerOperation allKeys]) {
                expectedDownloadBytes += [[self.expectedDownloadBytesPerOperation objectForKey:opString] longLongValue];
            }

            dispatch_barrier_async(self.progressQueue, ^{
                weakSelf.bytesDownloaded = @(bytesDownloaded);
                weakSelf.expectedDownloadBytes = @(expectedDownloadBytes);
                weakSelf.downloadProgress = expectedDownloadBytes ? @(bytesDownloaded / (float)expectedDownloadBytes) : @0.0f;
                [weakSelf performDelegateMethod:@selector(httpOperationQueueDidUpload:)];
                [weakSelf performDelegateMethod:@selector(httpOperationQueueDidMakeProgress:)];
            });
        });

        return;
    }

    if ([keyPath isEqualToString:@"bytesUploaded"]) {
        JXHTTPOperation *operation = (JXHTTPOperation *)object;

        long long bytesUploaded = operation.bytesUploaded;
        NSString *uniqueString = [operation.uniqueString copy];

        dispatch_barrier_async(self.progressQueue, ^{
            [weakSelf.bytesUploadedPerOperation setObject:@(bytesUploaded) forKey:uniqueString];
        });

        dispatch_sync(self.progressQueue, ^{
            long long bytesUploaded = 0LL;
            long long expectedUploadBytes = 0LL;

            for (NSString *opString in [self.bytesUploadedPerOperation allKeys]) {
                bytesUploaded += [[self.bytesUploadedPerOperation objectForKey:opString] longLongValue];
            }

            for (NSString *opString in [self.expectedUploadBytesPerOperation allKeys]) {
                expectedUploadBytes += [[self.expectedUploadBytesPerOperation objectForKey:opString] longLongValue];
            }

            dispatch_barrier_async(self.progressQueue, ^{
                weakSelf.bytesUploaded = @(bytesUploaded);
                weakSelf.expectedUploadBytes = @(expectedUploadBytes);
                weakSelf.uploadProgress = expectedUploadBytes ? @(bytesUploaded / (float)expectedUploadBytes) : @0.0f;
                [weakSelf performDelegateMethod:@selector(httpOperationQueueDidDownload:)];
                [weakSelf performDelegateMethod:@selector(httpOperationQueueDidMakeProgress:)];
            });
        });

        return;
    }
}

@end


text:
<?php

use common\models\facility\Room;
use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model common\models\facility\Price */
/* @var $returnUrl string */
/* @var $objectModel Room */

$objectModel = Room::findOne($model->room_id);
$facilityModel = $objectModel->facility;
$updateUrl = ['room/update', 'id' => $model->room_id, 'relation_id' => $facilityModel->id];
$modelClass = Yii::t('back', 'Price');
$this->title = Yii::t('back', 'Create {modelClass}', compact('modelClass'));
$this->params['breadcrumbs'][] = ['label' => Yii::t('back', 'Facilities'), 'url' => ['facility/index']];
$this->params['breadcrumbs'][] = ['label' => $facilityModel->title, 'url' => ['facility/update', 'id' => $facilityModel->id]];
$this->params['breadcrumbs'][] = ['label' => $objectModel->title, 'url' => $updateUrl];
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?= $this->render('_form', compact('model', 'returnUrl')) ?>


text:
package net.jueb.util4j.test;

import java.io.IOException;
import java.util.BitSet;

public class BitMapDemo {
	private BitSet bits;

//	public void perform(String largeFileName, int total, String destLargeFileName, Castor<Integer> castor,
//			int readerBufferSize, int writerBufferSize, boolean asc) throws IOException {
//
//		System.out.println("BitmapSort Started.");
//		long start = System.currentTimeMillis();
//		bits = new BitSet(total);
//		InputPart<Integer> largeIn = PartFactory.createCharBufferedInputPart(largeFileName, readerBufferSize);
//		OutputPart<Integer> largeOut = PartFactory.createCharBufferedOutputPart(destLargeFileName, writerBufferSize);
//		largeOut.delete();
//
//		Integer data;
//		int off = 0;
//		try {
//			while (true) {
//				data = largeIn.read();
//				if (data == null)
//					break;
//				int v = data;
//				set(v);
//				off++;
//			}
//			largeIn.close();
//			int size = bits.size();
//			System.out.println(String.format("lines : %d ,bits : %d", off, size));
//
//			if (asc) {
//				for (int i = 0; i < size; i++) {
//					if (get(i)) {
//						largeOut.write(i);
//					}
//				}
//			} else {
//				for (int i = size - 1; i >= 0; i--) {
//					if (get(i)) {
//						largeOut.write(i);
//					}
//				}
//			}
//
//			largeOut.close();
//			long stop = System.currentTimeMillis();
//			long elapsed = stop - start;
//			System.out.println(String.format("BitmapSort Completed.elapsed : %dms", elapsed));
//		} finally {
//			largeIn.close();
//			largeOut.close();
//		}
//	}

	private void set(int i) {
		bits.set(i);
	}

	private boolean get(int v) {
		return bits.get(v);
	}
}


text:
@interface YFNavController : UINavigationController

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Reviewed: no -->
<section
    xmlns="http://docbook.org/ns/docbook" version="5.0"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    xml:id="zend.di.configuration">
    <info><title>Configurazione Zend\Di</title></info>

    <para>
        La maggior parte della configurazione, sia per il
        setup delle Definitions come per l'impostazione dell'Instance
        Manager può essere raggiunto da un file di configurazione.
        Questo file produrrà un array (tipicamente) con una particolare
        struttura iterabile.
    </para>

    <para>
        Le tue parole chiave sono 'definition' ed 'istanza', ognuna
        specifica valori per rispettivamente: impostazioni di definizione
        e impostazioni per l'instanza manager.
    </para>

    <para>
        La sezione di definizione si aspetta le seguenti informazioni
        espresse come un array PHP:
    </para>

    <programlisting language="php"><![CDATA[
$config = array(
    'definition' => array(
        'compiler' => array(/* @todo compiler information */),
        'runtime'  => array(/* @todo runtime information */),
        'class' => array(
            'instantiator' => '', // the name of the instantiator, by default this is __construct
            'supertypes    => array(), // an array of supertypes the class implements
            'methods'      => array(
                'setSomeParameter' => array( // a method name
                    'parameterName' => array(
                        'name',       // string parameter name
                        'type',       // type or null
                        'is-required' // bool
                    )
                )

            )
        )
    )
);
]]></programlisting>

</section>


text:
@interface XXMoreInputView : UIView

@end


text:
package gov.samhsa.acs.contexthandler;

import static org.junit.Assert.*;
import gov.samhsa.acs.common.dto.XacmlResponse;
import gov.samhsa.acs.contexthandler.PolicyDecisionPoint;
import gov.samhsa.acs.contexthandler.PolicyDecisionPointImpl;
import gov.samhsa.acs.contexthandler.PolicyDecisionPointImplData;
import gov.samhsa.acs.contexthandler.RequestGenerator;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

import org.herasaf.xacml.core.api.PDP;
import org.herasaf.xacml.core.context.RequestMarshaller;
import org.herasaf.xacml.core.context.impl.RequestType;
import org.herasaf.xacml.core.policy.Evaluatable;
import org.herasaf.xacml.core.policy.PolicyMarshaller;
import org.herasaf.xacml.core.simplePDP.SimplePDPFactory;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PolicyDecisionPointDemoIT {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(PolicyDecisionPointDemoIT.class);
	private final String policyFile = "src/test/resources/samplePolicy.xml";
	private final String requestFile = "src/test/resources/samplePolicyRequest.xml";
	private PDP simplePDP;
	private Evaluatable policy;
	private List<Evaluatable> policies;
	private RequestType request;
	private PolicyDecisionPoint pdp;
	@Mock
	private PolicyDecisionPointImplData dataMock;
	@Mock
	private RequestGenerator requestGeneratorMock;

	@Before
	public void setUp() throws Exception {
		simplePDP = SimplePDPFactory.getSimplePDP();
		pdp = new PolicyDecisionPointImpl(dataMock,requestGeneratorMock);

		try {
			InputStream is = new FileInputStream(policyFile);
			policy = PolicyMarshaller.unmarshal(is);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
		InputStream requestis = null;
		try {
			requestis = new FileInputStream(requestFile);
			request = RequestMarshaller.unmarshal(requestis);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
		policies = new LinkedList<Evaluatable>();
		policies.add(policy);
	}

	public void printPolicy(){
		try {
			InputStream in=new FileInputStream(policyFile);;
			String readLine;
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			System.out.println("");
			System.out.println("");
			System.out.println("****************************************");
			System.out.println("**Policy file being evaluated against**");
			System.out.println("****************************************");
			System.out.println("");
			while (((readLine = br.readLine()) != null)) {
				System.out.println(readLine);
			}
		} catch (IOException e) {
			LOGGER.warn("Error happens when printing policy file:", e);
		}
	}

	public void printRequest(){
		try {
			InputStream in=new FileInputStream(requestFile);;
			String readLine;
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			System.out.println("");
			System.out.println("");
			System.out.println("**************************************");
			System.out.println("**Request being sent to XACML engine**");
			System.out.println("**************************************");
			System.out.println("");
			while (((readLine = br.readLine()) != null)) {
				System.out.println(readLine);
			}
		} catch (IOException e) {
			LOGGER.warn("Error happens when printing request file:", e);
		}
	}

	@Test
	public void test() {
		XacmlResponse response = pdp.evaluateRequest(simplePDP,request,policies);
		printPolicy();
		printRequest();
		System.out.println("");
		System.out.println("");
		System.out.println("************");
		System.out.println("**Decision**");
		System.out.println("************");
		System.out.println("");
		System.out.println("Decision: " + response.getPdpDecision());
		for (String obligation : response.getPdpObligation())
			System.out.println("With Obligation: " + obligation);
	}

}


text:
#ifndef H_BLE_LL_CONN_PRIV_
#define H_BLE_LL_CONN_PRIV_

#include "controller/ble_ll_conn.h"
#include "controller/ble_ll_hci.h"

#ifdef __cplusplus
extern "C" {
#endif

/*
 * Definitions for min/max RX/TX time/bytes values allowed for connections.
 * Source: Core 5.0 specification, Vol 6, Part B, section 4.5.10
 */
#define BLE_LL_CONN_SUPP_TIME_MIN           (328)   /* usecs */
#define BLE_LL_CONN_SUPP_TIME_MAX           (17040) /* usecs */
#define BLE_LL_CONN_SUPP_TIME_MIN_UNCODED   (328)   /* usecs */
#define BLE_LL_CONN_SUPP_TIME_MAX_UNCODED   (2120)  /* usecs */
#define BLE_LL_CONN_SUPP_TIME_MIN_CODED     (2704)  /* usecs */
#define BLE_LL_CONN_SUPP_TIME_MAX_CODED     (17040) /* usecs */
#define BLE_LL_CONN_SUPP_BYTES_MIN          (27)    /* bytes */
#define BLE_LL_CONN_SUPP_BYTES_MAX          (251)   /* bytes */

/* Connection event timing */
#define BLE_LL_CONN_INITIAL_OFFSET          (1250)
#define BLE_LL_CONN_ITVL_USECS              (1250)
#define BLE_LL_CONN_TX_WIN_USECS            (1250)
#define BLE_LL_CONN_TX_OFF_USECS            (1250)
#define BLE_LL_CONN_CE_USECS                (625)
#define BLE_LL_CONN_TX_WIN_MIN              (1)         /* in tx win units */
#define BLE_LL_CONN_PERIPH_LATENCY_MAX       (499)

/* Connection handle range */
#define BLE_LL_CONN_MAX_CONN_HANDLE         (0x0EFF)

/* Offset (in bytes) of advertising address in connect request */
#define BLE_LL_CONN_REQ_ADVA_OFF    (BLE_LL_PDU_HDR_LEN + BLE_DEV_ADDR_LEN)

/* Default authenticated payload timeout (30 seconds; in 10 msecs increments) */
#define BLE_LL_CONN_DEF_AUTH_PYLD_TMO       (3000)
#define BLE_LL_CONN_AUTH_PYLD_OS_TMO(x)     ble_npl_time_ms_to_ticks32((x) * 10)

#if MYNEWT_VAL(BLE_LL_CONN_STRICT_SCHED)
#define BLE_LL_CONN_CSS_NO_SLOT             (UINT16_MAX)
#endif

/* Global Link Layer connection parameters */
struct ble_ll_conn_global_params
{
#if MYNEWT_VAL(BLE_LL_ROLE_CENTRAL) || MYNEWT_VAL(BLE_LL_ROLE_PERIPHERAL)
    uint8_t supp_max_tx_octets;
    uint8_t supp_max_rx_octets;
    uint8_t conn_init_max_tx_octets;
    uint8_t sugg_tx_octets;
    uint16_t sugg_tx_time;
    uint16_t conn_init_max_tx_time;
    uint16_t conn_init_max_tx_time_uncoded;
    uint16_t conn_init_max_tx_time_coded;
    uint16_t supp_max_tx_time;
    uint16_t supp_max_rx_time;
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LL_ENHANCED_CONN_UPDATE)
    uint16_t acc_subrate_min;
    uint16_t acc_subrate_max;
    uint16_t acc_max_latency;
    uint16_t acc_cont_num;
    uint16_t acc_supervision_tmo;
#endif
#endif
};
extern struct ble_ll_conn_global_params g_ble_ll_conn_params;

#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LL_PERIODIC_ADV_SYNC_TRANSFER)
struct ble_ll_conn_sync_transfer_params
{
    uint32_t sync_timeout_us;
    uint16_t max_skip;
    uint8_t  mode;
};
extern struct ble_ll_conn_sync_transfer_params g_ble_ll_conn_sync_transfer_params;
#endif

/* Some data structures used by other LL routines */
SLIST_HEAD(ble_ll_conn_active_list, ble_ll_conn_sm);
STAILQ_HEAD(ble_ll_conn_free_list, ble_ll_conn_sm);
extern struct ble_ll_conn_active_list g_ble_ll_conn_active_list;
extern struct ble_ll_conn_free_list g_ble_ll_conn_free_list;

#if MYNEWT_VAL(BLE_LL_CONN_STRICT_SCHED)
SLIST_HEAD(ble_ll_conn_css_list, ble_ll_conn_sm);
extern struct ble_ll_conn_css_list g_ble_ll_conn_css_list;
#endif

struct ble_ll_conn_create_scan {
    uint8_t filter_policy;
    uint8_t own_addr_type;
    uint8_t peer_addr_type;
    uint8_t peer_addr[BLE_DEV_ADDR_LEN];
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LL_EXT_ADV)
    uint8_t init_phy_mask;
#endif
    struct {
        uint16_t itvl;
        uint16_t window;
    } scan_params[2];
};

struct ble_ll_conn_create_params {
    uint32_t conn_itvl;
    uint32_t conn_itvl_ticks;
    uint8_t conn_itvl_usecs;
    uint16_t conn_latency;
    uint16_t supervision_timeout;
    uint16_t min_ce_len;
    uint16_t max_ce_len;
};

struct ble_ll_conn_create_sm {
    struct ble_ll_conn_sm *connsm;
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LL_EXT_ADV)
    struct ble_ll_conn_create_params params[3];
#endif
};

extern struct ble_ll_conn_create_sm g_ble_ll_conn_create_sm;
extern struct ble_ll_conn_sm *g_ble_ll_conn_css_ref;

/* Generic interface */
struct ble_ll_len_req;
struct ble_mbuf_hdr;
struct ble_ll_adv_sm;

struct hci_create_conn
{
    uint16_t scan_itvl;
    uint16_t scan_window;
    uint8_t filter_policy;
    uint8_t peer_addr_type;
    uint8_t peer_addr[BLE_DEV_ADDR_LEN];
    uint8_t own_addr_type;
    uint16_t conn_itvl_min;
    uint16_t conn_itvl_max;
    uint16_t conn_latency;
    uint16_t supervision_timeout;
    uint16_t min_ce_len;
    uint16_t max_ce_len;
};

void ble_ll_conn_sm_new(struct ble_ll_conn_sm *connsm);
void ble_ll_conn_end(struct ble_ll_conn_sm *connsm, uint8_t ble_err);
void ble_ll_conn_enqueue_pkt(struct ble_ll_conn_sm *connsm, struct os_mbuf *om,
                             uint8_t hdr_byte, uint16_t length);
struct ble_ll_conn_sm *ble_ll_conn_sm_get(void);
void ble_ll_conn_central_init(struct ble_ll_conn_sm *connsm,
                              struct ble_ll_conn_create_scan *cc_scan,
                              struct ble_ll_conn_create_params *cc_params);

struct ble_ll_conn_sm *ble_ll_conn_find_by_handle(uint16_t handle);
void ble_ll_conn_update_eff_data_len(struct ble_ll_conn_sm *connsm);

/* Advertising interface */
int ble_ll_conn_periph_start(uint8_t *rxbuf, uint8_t pat,
                             struct ble_mbuf_hdr *rxhdr, bool force_csa2);

/* Link Layer interface */
void ble_ll_conn_module_init(void);
void ble_ll_conn_set_global_chanmap(uint8_t num_used_chans, const uint8_t *chanmap);
void ble_ll_conn_module_reset(void);
void ble_ll_conn_tx_pkt_in(struct os_mbuf *om, uint16_t handle, uint16_t len);
int ble_ll_conn_rx_isr_start(struct ble_mbuf_hdr *rxhdr, uint32_t aa);
int ble_ll_conn_rx_isr_end(uint8_t *rxbuf, struct ble_mbuf_hdr *rxhdr);
void ble_ll_conn_rx_data_pdu(struct os_mbuf *rxpdu, struct ble_mbuf_hdr *hdr);
void ble_ll_conn_wfr_timer_exp(void);
int ble_ll_conn_is_lru(struct ble_ll_conn_sm *s1, struct ble_ll_conn_sm *s2);
uint32_t ble_ll_conn_get_ce_end_time(void);
void ble_ll_conn_event_halt(void);
/* HCI */
void ble_ll_disconn_comp_event_send(struct ble_ll_conn_sm *connsm,
                                    uint8_t reason);
void ble_ll_auth_pyld_tmo_event_send(struct ble_ll_conn_sm *connsm);
int ble_ll_conn_hci_disconnect_cmd(const struct ble_hci_lc_disconnect_cp *cmd);
int ble_ll_conn_hci_rd_rem_ver_cmd(const uint8_t *cmdbuf, uint8_t len);
int ble_ll_conn_hci_create(const uint8_t *cmdbuf, uint8_t len);
int ble_ll_conn_hci_update(const uint8_t *cmdbuf, uint8_t len);
int ble_ll_conn_hci_set_chan_class(const uint8_t *cmdbuf, uint8_t len);
int ble_ll_conn_hci_param_rr(const uint8_t *cmdbuf, uint8_t len,
                             uint8_t *rspbuf, uint8_t *rsplen);
int ble_ll_conn_hci_param_nrr(const uint8_t *cmdbuf, uint8_t len,
                             uint8_t *rspbuf, uint8_t *rsplen);
int ble_ll_conn_create_cancel(ble_ll_hci_post_cmd_complete_cb *post_cmd_cb);
void ble_ll_conn_num_comp_pkts_event_send(struct ble_ll_conn_sm *connsm);
void ble_ll_conn_comp_event_send(struct ble_ll_conn_sm *connsm, uint8_t status,
                                 uint8_t *evbuf, struct ble_ll_adv_sm *advsm);
void ble_ll_conn_timeout(struct ble_ll_conn_sm *connsm, uint8_t ble_err);
int ble_ll_conn_hci_chk_conn_params(uint16_t itvl_min, uint16_t itvl_max,
                                    uint16_t latency, uint16_t spvn_tmo);
int ble_ll_conn_hci_read_rem_features(const uint8_t *cmdbuf, uint8_t len);
int ble_ll_conn_hci_rd_rssi(const uint8_t *cmdbuf, uint8_t len, uint8_t *rspbuf,
                            uint8_t *rsplen);
int ble_ll_conn_hci_rd_chan_map(const uint8_t *cmdbuf, uint8_t len,
                                uint8_t *rspbuf, uint8_t *rsplen);
int ble_ll_conn_hci_set_data_len(const uint8_t *cmdbuf, uint8_t len,
                                 uint8_t *rspbuf, uint8_t *rsplen);
int ble_ll_conn_hci_le_start_encrypt(const uint8_t *cmdbuf, uint8_t len);
int ble_ll_conn_hci_le_ltk_reply(const uint8_t *cmdbuf, uint8_t len,
                                 uint8_t *rspbuf, uint8_t *rsplen);
int ble_ll_conn_hci_le_ltk_neg_reply(const uint8_t *cmdbuf, uint8_t len,
                                     uint8_t *rspbuf, uint8_t *rsplen);
int ble_ll_conn_hci_wr_auth_pyld_tmo(const uint8_t *cmdbuf, uint8_t len,
                                     uint8_t *rspbuf, uint8_t *rsplen);
int ble_ll_conn_hci_rd_auth_pyld_tmo(const uint8_t *cmdbuf, uint8_t len,
                                     uint8_t *rspbuf, uint8_t *rsplen);
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LL_SCA_UPDATE)
int ble_ll_conn_req_peer_sca(const uint8_t *cmdbuf, uint8_t len,
                             uint8_t *rspbuf, uint8_t *rsplen);
#endif
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LL_ENHANCED_CONN_UPDATE)
int ble_ll_conn_hci_set_default_subrate(const uint8_t *cmdbuf, uint8_t len,
                                        uint8_t *rspbuf, uint8_t *rsplen);
int ble_ll_conn_hci_subrate_req(const uint8_t *cmdbuf, uint8_t len,
                                uint8_t *rspbuf, uint8_t *rsplen);
#endif

#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LE_PING)
void ble_ll_conn_auth_pyld_timer_start(struct ble_ll_conn_sm *connsm);
void ble_ll_conn_auth_pyld_timer_cb(struct ble_npl_event *ev);
#else
#define ble_ll_conn_auth_pyld_timer_start(x)
#endif

#if MYNEWT_VAL(BLE_LL_CFG_FEAT_CTRL_TO_HOST_FLOW_CONTROL)
void ble_ll_conn_cth_flow_set_buffers(uint16_t num_buffers);
bool ble_ll_conn_cth_flow_enable(bool enabled);
void ble_ll_conn_cth_flow_process_cmd(const uint8_t *cmdbuf);
#endif

#if MYNEWT_VAL(BLE_LL_CFG_FEAT_DATA_LEN_EXT)
int ble_ll_conn_set_data_len(struct ble_ll_conn_sm *connsm,
                             uint16_t tx_octets, uint16_t tx_time,
                             uint16_t rx_octets, uint16_t rx_time);
#endif

void ble_ll_conn_itvl_to_ticks(uint32_t itvl,
                               uint32_t *itvl_ticks, uint8_t *itvl_usecs);

int ble_ll_hci_cmd_rx(uint8_t *cmd, void *arg);
int ble_ll_hci_acl_rx(struct os_mbuf *om, void *arg);

int ble_ll_conn_hci_le_rd_phy(const uint8_t *cmdbuf, uint8_t len,
                              uint8_t *rsp, uint8_t *rsplen);
int ble_ll_conn_hci_le_set_phy(const uint8_t *cmdbuf, uint8_t len);
int ble_ll_conn_phy_update_if_needed(struct ble_ll_conn_sm *connsm);
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LL_EXT_ADV)
int ble_ll_conn_hci_ext_create(const uint8_t *cmdbuf, uint8_t len);
#endif

#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LL_PERIODIC_ADV_SYNC_TRANSFER)
int ble_ll_set_sync_transfer_params(const uint8_t *cmdbuf, uint8_t len,
                                    uint8_t *rspbuf, uint8_t *rsplen);
int ble_ll_set_default_sync_transfer_params(const uint8_t *cmdbuf, uint8_t len);
#endif

#if MYNEWT_VAL(BLE_LL_CONN_STRICT_SCHED)
void ble_ll_conn_css_set_next_slot(uint16_t slot_idx);
uint16_t ble_ll_conn_css_get_next_slot(void);
int ble_ll_conn_css_is_slot_busy(uint16_t slot_idx);
int ble_ll_conn_css_move(struct ble_ll_conn_sm *connsm, uint16_t slot_idx);

#endif

#ifdef __cplusplus
}
#endif

#endif /* H_BLE_LL_CONN_PRIV_ */


text:
@interface HMMapViewController ()

@property (strong, nonatomic) CLLocationManager *locationManager;

@property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
@property (strong, nonatomic) NSManagedObjectContext* managedObjectContext;

@property (strong, nonatomic) NSMutableArray* mapPointArray;

@property (assign, nonatomic) NSInteger ratingOfPoints;
@property (assign, nonatomic) BOOL pointHasComments;

@property (strong, nonatomic) NSArray *placeArray;

@property (weak, nonatomic) MKAnnotationView *userLocationPin;

@end

static NSString* kSettingsComments = @"comments";
static NSString* kSettingsRating = @"rating";

@implementation HMMapViewController

static NSMutableArray* nameCountries;
static bool isMainRoute;

- (NSManagedObjectContext*) managedObjectContext {

    if (!_managedObjectContext) {
        _managedObjectContext = [[HMCoreDataManager sharedManager] managedObjectContext];
    }
    return _managedObjectContext;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.locationManager = [[CLLocationManager alloc] init];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(showPlace:)
                                                 name:showPlaceNotificationCenter object:nil];
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    self.ratingOfPoints = [userDefaults integerForKey:kSettingsRating];
    self.pointHasComments = [userDefaults boolForKey:kSettingsComments];

    // Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7.
    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [self.locationManager requestWhenInUseAuthorization];
    }
    UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

    UIButton *yourCurrentLocation = [UIButton buttonWithType:UIButtonTypeCustom];
    [yourCurrentLocation setBackgroundImage:[UIImage imageNamed:@"compass"]
                                   forState:UIControlStateNormal];
    [yourCurrentLocation addTarget:self action:@selector(showYourCurrentLocation:) forControlEvents:UIControlEventTouchUpInside];
    yourCurrentLocation.frame = CGRectMake(0, 0, 30, 30);
    yourCurrentLocation.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;
    UIView *viewForShowCurrentLocation = [[UIView alloc] initWithFrame:CGRectMake(0, 30, 30, 30)];
    [viewForShowCurrentLocation addSubview:yourCurrentLocation];
    UIBarButtonItem *buttonForShowCurrentLocation = [[UIBarButtonItem alloc] initWithCustomView:viewForShowCurrentLocation];

    UIButton *moveToSettingsController = [UIButton buttonWithType:UIButtonTypeCustom];
    [moveToSettingsController setBackgroundImage:[UIImage imageNamed:@"tools"]
                                        forState:UIControlStateNormal];
    [moveToSettingsController addTarget:self action:@selector(moveToToolsController:) forControlEvents:UIControlEventTouchUpInside];
    moveToSettingsController.frame = CGRectMake(0, 0, 30, 30);
    moveToSettingsController.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;
    UIView *viewForMoveToSettingsController = [[UIView alloc] initWithFrame:CGRectMake(0, 30, 30, 30)];
    [viewForMoveToSettingsController addSubview:moveToSettingsController];
    UIBarButtonItem *buttonForMoveToSettingsController = [[UIBarButtonItem alloc] initWithCustomView:viewForMoveToSettingsController];

    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [searchButton setBackgroundImage:[UIImage imageNamed:@"Lupa"]
                            forState:UIControlStateNormal];
    [searchButton addTarget:self action:@selector(buttonSearch:) forControlEvents:UIControlEventTouchUpInside];
    searchButton.frame = CGRectMake(0, 0, 30, 30);
    searchButton.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;
    UIView *viewForSearchButton = [[UIView alloc] initWithFrame:CGRectMake(0, 30, 30, 30)];
    [viewForSearchButton addSubview:searchButton];
    UIBarButtonItem *buttonSearchButton = [[UIBarButtonItem alloc] initWithCustomView:viewForSearchButton];

    UIButton *moveToFilterController = [UIButton buttonWithType:UIButtonTypeCustom];
    [moveToFilterController setBackgroundImage:[UIImage imageNamed:@"filter"]
                                      forState:UIControlStateNormal];
    [moveToFilterController addTarget:self action:@selector(moveToFilterController:) forControlEvents:UIControlEventTouchUpInside];
    moveToFilterController.frame = CGRectMake(0, 0, 30, 30);
    moveToFilterController.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;
    UIView *viewForMoveToFilterController = [[UIView alloc] initWithFrame:CGRectMake(0, 30, 30, 30)];
    [viewForMoveToFilterController addSubview:moveToFilterController];
    UIBarButtonItem *buttonForMoveToFilterController = [[UIBarButtonItem alloc] initWithCustomView:viewForMoveToFilterController];

    NSArray *buttons = @[ buttonForShowCurrentLocation ,flexibleItem , buttonSearchButton , flexibleItem , buttonForMoveToFilterController , flexibleItem, buttonForMoveToSettingsController ];

    [self.downToolBar setItems:buttons animated:NO];

    self.mapView.showsUserLocation = YES;

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receiveChangeMapTypeNotification:)
                                                 name:@"ChangeMapTypeNotification"
                                               object:nil];

    [self loadSettings];

    self.locationManager.delegate = self;

    [self startHeadingEvents];

    [self.locationManager startUpdatingHeading];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    self.ratingOfPoints = [userDefaults integerForKey:kSettingsRating];
    self.pointHasComments = [userDefaults boolForKey:kSettingsComments];
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self printPointWithContinent];

    NSLog(@" Points in map array %lu",(unsigned long)[self.mapPointArray count]);
    NSLog(@" point has comments %@",self.pointHasComments ? @"Yes" : @"No");

    [[self navigationController] setNavigationBarHidden:YES animated:YES];
}

#pragma mark - buttons on Tool Bar

- (void)showYourCurrentLocation:(UIBarButtonItem *)sender {
    MKMapRect zoomRect = MKMapRectNull;
    CLLocationCoordinate2D location = self.mapView.userLocation.coordinate;
    MKMapPoint center = MKMapPointForCoordinate(location);
    static double delta = 40000;
    MKMapRect rect = MKMapRectMake(center.x - delta, center.y - delta, delta * 2, delta * 2);
    zoomRect = MKMapRectUnion(zoomRect, rect);
    zoomRect = [self.mapView mapRectThatFits:zoomRect];

    [self.mapView setVisibleMapRect:zoomRect
                        edgePadding:UIEdgeInsetsMake(50, 50, 50, 50)
                           animated:YES];
}

- (void)moveToToolsController:(UIBarButtonItem *)sender {

    [self performSegueWithIdentifier:@"showSettingsViewController" sender:sender];

}

- (void)moveToFilterController:(UIBarButtonItem *)sender {

    [self performSegueWithIdentifier:@"showFilterViewController" sender:sender];

}

- (void)buttonSearch:(UIBarButtonItem *)sender {

    [self performSegueWithIdentifier:@"showSearchViewController" sender:sender];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Segues

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"showSettingsViewController"]) {

        // sending smth to destinationViewController

    } else if ([[segue identifier] isEqualToString:@"Comments"]) {
        Place  *place = [self.placeArray objectAtIndex:0];
        HMCommentsTableViewController *createViewController = segue.destinationViewController;
        createViewController.create = place;
    }
}

#pragma mark - Notifications

- (void) receiveChangeMapTypeNotification:(NSNotification *) notification {
    if ([[notification name] isEqualToString:@"ChangeMapTypeNotification"])  {

        [self loadSettings];

    }
}

#pragma mark - Deallocation

- (void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Annotation View

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <HMAnnotationView>)annotation {

    static NSString* identifier = @"Annotation";
    MKPinAnnotationView* pin = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
    if ([annotation isKindOfClass:[MKUserLocation class]]) {

        NSString *identifier = @"UserAnnotation";

        MKAnnotationView *pin = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
        if (!pin) {

            pin = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];

        pin.canShowCallout = YES;
        pin.image = [UIImage imageNamed:@"UserArrow"];
    } else {
        pin.annotation = annotation;
    }

    self.userLocationPin = pin;
    return pin;
}
    if (!pin) {
        pin = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
    }

    switch (((HMMapAnnotation *)annotation).ratingForColor) {

        case badRating:
        {
            pin.pinTintColor = [UIColor redColor];
            break;
        }
        case senseLess:
        {
            pin.pinTintColor = [UIColor whiteColor];
            break;
        }
        case veryGoodRating:
        {
            pin.pinTintColor = [UIColor greenColor];
            break;
        }
    }
    pin.animatesDrop = NO;
    pin.canShowCallout = YES;

    UIButton* descriptionButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    [descriptionButton addTarget:self
                          action:@selector(actionDescription:)
                forControlEvents:UIControlEventTouchUpInside];
    pin.rightCalloutAccessoryView = descriptionButton;

    UIButton* directionButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
    [directionButton addTarget:self
                        action:@selector(actionDirection:)
              forControlEvents:UIControlEventTouchUpInside];
    pin.leftCalloutAccessoryView = directionButton;

    return pin;
}

#pragma mark - MKMapViewDelegate -

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id <MKOverlay>)overlay {

    if ([overlay isKindOfClass:[MKPolyline class]]) {

        MKPolylineRenderer* renderer = [[MKPolylineRenderer alloc] initWithOverlay:overlay];

        if (!isMainRoute) {
            renderer.lineWidth = 2.5f;
            renderer.strokeColor = [UIColor colorWithRed:0.f green:0.1f blue:1.f alpha:0.9f];
            return renderer;
        } else {
            renderer.lineWidth = 1.5f;
            renderer.strokeColor = [UIColor colorWithRed:0.f green:0.5f blue:1.f alpha:0.6f];
            return renderer;
        }
    }
    else if ([overlay isKindOfClass:[MKPolygon class]]) {
        MKPolygonRenderer *polygonView = [[MKPolygonRenderer alloc] initWithOverlay:overlay];
        polygonView.lineWidth = 2.f;
        polygonView.strokeColor = [UIColor magentaColor];

        return polygonView;
    }
    return nil;
}

#pragma mark - Alert -

- (UIAlertController *)createAlertControllerWithTitle:(NSString *)title
                                              message:(NSString *)message {

    UIAlertController * alert =   [UIAlertController
                                   alertControllerWithTitle:title
                                   message:message
                                   preferredStyle:UIAlertControllerStyleAlert];
        return alert;
}

- (void)actionWithTitle:(NSString *)title
             alertTitle:(NSString *)alertTitle
           alertMessage:(NSString *)alertMessage {

    UIAlertController * alert = [self createAlertControllerWithTitle:alertTitle
                                                             message:alertMessage];
    UIAlertAction* alertAction = [UIAlertAction
                                  actionWithTitle:title
                                  style:UIAlertActionStyleCancel
                                  handler:^(UIAlertAction * action) {
                                  }];
    [alert addAction:alertAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void) createRouteForAnotationCoordinate:(CLLocationCoordinate2D)endCoordinate
                           startCoordinate:(CLLocationCoordinate2D)startCoordinate {
    MKDirections* directions;

    MKDirectionsRequest* request = [[MKDirectionsRequest alloc] init];
    MKPlacemark* startPlacemark = [[MKPlacemark alloc] initWithCoordinate:startCoordinate
                                                        addressDictionary:nil];
    MKMapItem* startDestination = [[MKMapItem alloc] initWithPlacemark:startPlacemark];
    request.source = startDestination;
    MKPlacemark* endPlacemark = [[MKPlacemark alloc] initWithCoordinate:endCoordinate
                                                      addressDictionary:nil];
    MKMapItem* endDestination = [[MKMapItem alloc] initWithPlacemark:endPlacemark];

    request.destination = endDestination;
    request.transportType = MKDirectionsTransportTypeAutomobile;
    request.requestsAlternateRoutes = isMainRoute;
    BOOL temp = isMainRoute;
    directions = [[MKDirections alloc] initWithRequest:request];
    [directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
    if (error) {
        NSLog(@"%@", error);
        } else if ([response.routes count] == 0) {
            NSLog(@"routes = 0");
        } else {
            NSMutableArray *array  = [NSMutableArray array];
            for (MKRoute *route in response.routes) {
                [array addObject:route.polyline];
            }
            isMainRoute = temp;

            [self.mapView addOverlays:array level:MKOverlayLevelAboveRoads];
        }
    }];
}

- (void)removeRoutes {
    [self.mapView removeOverlays:self.mapView.overlays];
}

#pragma mark Action to pin button

- (void) actionDescription:(UIButton*) sender {
    MKAnnotationView* annotationView = [sender superAnnotationView];
    NSString *str = [NSString stringWithFormat:@"%ld",
                     (long)((HMMapAnnotation *)annotationView.annotation).idPlace];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id == %@", str];
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Place"];
    request.predicate = predicate;
    self.placeArray = [[self managedObjectContext] executeFetchRequest:request
                                                                 error:nil];
    [self performSegueWithIdentifier:@"Comments" sender:self];
}

- (void) actionDirection:(UIButton*) sender {
    [self removeRoutes];
    MKAnnotationView* annotationView = [sender superAnnotationView];
    if (!annotationView) {
        return;
    }
    CLLocationCoordinate2D coordinate = annotationView.annotation.coordinate;

    isMainRoute = YES;
    [self createRouteForAnotationCoordinate:self.mapView.userLocation.coordinate
                            startCoordinate:coordinate];
    isMainRoute = NO;
    [self createRouteForAnotationCoordinate:self.mapView.userLocation.coordinate
                            startCoordinate:coordinate];
}

- (void) actionRemoveRoute:(UIButton*) sender {
    MKAnnotationView* annotationView = [sender superAnnotationView];
    UIButton* directionButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
    [directionButton addTarget:self action:@selector(actionDirection:) forControlEvents:UIControlEventTouchUpInside];
    annotationView.leftCalloutAccessoryView = directionButton;

    [self removeRoutes];
}

- (void)printPointWithContinent {
    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Place"];

    NSInteger minForPoint = 0;
    NSInteger maxForPoint = 5;

    switch (self.ratingOfPoints) {
        case 0:
        {
            minForPoint = 0;
            maxForPoint = 5;
            break;
        }
        case 1:
        {
            minForPoint = 1;
            maxForPoint = 3;
            break;
        }
        case 2:
        {
            minForPoint = 4;
            maxForPoint = 5;
            break;
        }
        default:
            break;
    }

    NSPredicate* ratingPredicate = [NSPredicate predicateWithFormat:@"%@ => rating  AND rating >= %@",[NSString stringWithFormat:@" %ld",(long)maxForPoint],[NSString stringWithFormat:@" %ld",(long)minForPoint]];

    if(!self.pointHasComments) {
        [fetchRequest setPredicate:ratingPredicate];
    } else {
        NSPredicate* commentsCountPredicate = [NSPredicate predicateWithFormat:@"comments_count > %@",@0];
        NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:ratingPredicate, commentsCountPredicate, nil]];

        [fetchRequest setPredicate:compoundPredicate];
    }
    self.mapPointArray = [[managedObjectContext executeFetchRequest:fetchRequest
                                                              error:nil] mutableCopy];
    NSLog(@"MAP annotation array count %lu",(unsigned long)self.mapPointArray.count);

    for (Place* place in self.mapPointArray) {
        HMMapAnnotation *annotation = [[HMMapAnnotation alloc] init];
        CLLocationCoordinate2D coordinate;
        coordinate.latitude = [place.lat doubleValue];
        coordinate.longitude = [place.lon doubleValue];
        if ([place.rating intValue] == 0) {
            annotation.ratingForColor = senseLess;
        } else if (([place.rating intValue] >=4) && ([place.rating intValue] <= 5)) {
            annotation.ratingForColor = badRating;
        } else if (([place.rating intValue] >=1) && ([place.rating intValue] <= 3)) {
            annotation.ratingForColor = veryGoodRating;
        }
        annotation.coordinate = coordinate;
        annotation.title = [NSString stringWithFormat:@"Rating = %@", place.rating];
        annotation.subtitle = [NSString stringWithFormat:@"%.5g, %.5g",
                               annotation.coordinate.latitude,
                               annotation.coordinate.longitude];
        annotation.idPlace = [place.id integerValue];

        [self.mapView addAnnotation:annotation];
    }
}

#pragma mark - methods for Notification

- (void)showPlace:(NSNotification *)notification {
    [self.navigationController popViewControllerAnimated:YES];
    SVPlacemark *object =
    [notification.userInfo objectForKey:showPlaceNotificationCenterInfoKey];
    CLLocationCoordinate2D point = object.coordinate;
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(point, 800, 800);
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
}

#pragma mark - Map Type Saving

- (void)saveSettings {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    [userDefaults setInteger:self.mapView.mapType forKey:@"kMapType"];

    [userDefaults synchronize];
}

- (void)loadSettings {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    self.mapView.mapType = [userDefaults integerForKey:@"kMapType"];
}

#pragma mark - Heading Update

- (void)startHeadingEvents {

    if (!self.locationManager) {
        CLLocationManager *theManager = [[CLLocationManager alloc] init];
        self.locationManager = theManager;
        self.locationManager.delegate = self;
    }

    self.locationManager.distanceFilter = 1000;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
    [self.locationManager startUpdatingLocation];

    if ([CLLocationManager headingAvailable]) {
        self.locationManager.headingFilter = 5;
        [self.locationManager startUpdatingHeading];
    }

}

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {

    self.userLocationPin.transform = CGAffineTransformMakeRotation((manager.heading.trueHeading*M_PI)/180.f);

}

@end


text:
export * from './core.module';
export * from './core.component';


text:
require 'socket'
require 'concurrent'
require 'attention/publisher'

module Attention
  # A publishable representation of the current server
  #
  # When an instance is {#publish}ed, an event is sent in the format
  #   {
  #      'added' => {
  #        'id' => '123',
  #        'ip' => '127.0.0.1',
  #        'port' => 9000
  #      }
  #   }
  #
  # When an instance is {#unpublish}ed, an event is sent in the format
  #   {
  #      'removed' => {
  #        'id' => '123',
  #        'ip' => '127.0.0.1',
  #        'port' => 9000
  #      }
  #   }
  class Instance
    attr_reader :id

    # @!visibility private
    attr_reader :publisher

    # Creates an Instance
    # @param ip [String] Optionally override the IP of the server
    # @param port [Fixnum, Numeric] Optionally specify the port of the server
    def initialize(ip: nil, port: nil)
      @id = Attention.redis.call.incr('instances').to_s
      @ip = ip
      @port = port
      @publisher = Publisher.new
    end

    # Publishes this server and starts the {#heartbeat}
    def publish
      publisher.publish('instance', added: info) do |redis|
        redis.setex "instance_#{ @id }", Attention.options[:ttl], JSON.dump(info)
      end
      heartbeat
    end

    # Unpublishes this server and stops the {#heartbeat}
    def unpublish
      return unless @heartbeat
      @heartbeat.shutdown
      publisher.publish('instance', removed: info) do |redis|
        redis.del "instance_#{ @id }"
      end
      @heartbeat = nil
    end

    # Published information about this instance
    # @return [Hash<id: Fixnum, ip: String, port: Numeric>]
    # @option @return [Fixnum] :id The instance id
    def info
      { id: @id, ip: ip }.tap do |h|
        h[:port] = @port if @port
      end
    end

    private

    # Uses a {Concurrent::TimerTask} to periodically tell Redis that this
    # server is still online
    # @!visibility public
    # @api private
    def heartbeat
      return @heartbeat if @heartbeat
      @heartbeat = Concurrent::TimerTask.new(execution_interval: heartbeat_frequency) do
        Attention.redis.call.setex "instance_#{ @id }", Attention.options[:ttl], JSON.dump(info)
      end
      @heartbeat.execute
      @heartbeat
    end

    # The frequency of the {#heartbeat} is based on Attention.options[:ttl]
    # @!visibility public
    # @api private
    def heartbeat_frequency
      [1, Attention.options[:ttl] - 5].max
    end

    # Attempts to automatically discover the IP address of the server
    def ip
      return @ip if @ip
      address = Socket.ip_address_list.find &:ipv4_private?
      @ip = address && address.ip_address
    end
  end
end