text:
describe "Banana.delicious!" do
  test "nothing raised" do
    assert_nothing_raised do
      Banana.delicious!
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
class CreateAgencyContacts < ActiveRecord::Migration
  def change
    create_table :agency_contacts do |t|
      t.string :email
      t.string :agency_id

      t.timestamps
    end
    add_index :agency_contacts, :agency_id
  end
end


text: .. automodule:: compas.datastructures


text:
A shortcut python script to automate net-access login

## Requirements

selenium>=2.53.6

## Trial

First clone the repository,

```
$ git clone https://github.com/Aravind-Suresh/nfw-access-iitm.git
$ cd nfw-access-iitm
```

To install dependencies, run

```
$ pip install -r requirements.txt
```

For a sample run,

```
$ python main.py
```


text:
Быстрый старт
===========

## Добавление экшена в контроллер

Следующий шаг заключается в добавлении [[yii\authclient\AuthAction]] в веб контроллер и обеспечении реализации
`successCallback`, выполняющий ваши требования.

```php
class SiteController extends Controller
{
    public function actions()
    {
        return [
            'auth' => [
                'class' => 'yii\authclient\AuthAction',
                'successCallback' => [$this, 'onAuthSuccess'],
            ],
        ];
    }

    public function onAuthSuccess($client)
    {
        $attributes = $client->getUserAttributes();

        /* @var $auth Auth */
        $auth = Auth::find()->where([
            'source' => $client->getId(),
            'source_id' => $attributes['id'],
        ])->one();

        if (Yii::$app->user->isGuest) {
            if ($auth) { // авторизация
                $user = $auth->user;
                Yii::$app->user->login($user);
            } else { // регистрация
                if (isset($attributes['email']) && User::find()->where(['email' => $attributes['email']])->exists()) {
                    Yii::$app->getSession()->setFlash('error', [
                        Yii::t('app', "Пользователь с такой электронной почтой как в {client} уже существует, но с ним не связан. Для начала войдите на сайт использую электронную почту, для того, что бы связать её.", ['client' => $client->getTitle()]),
                    ]);
                } else {
                    $password = Yii::$app->security->generateRandomString(6);
                    $user = new User([
                        'username' => $attributes['login'],
                        'email' => $attributes['email'],
                        'password' => $password,
                    ]);
                    $user->generateAuthKey();
                    $user->generatePasswordResetToken();
                    $transaction = $user->getDb()->beginTransaction();
                    if ($user->save()) {
                        $auth = new Auth([
                            'user_id' => $user->id,
                            'source' => $client->getId(),
                            'source_id' => (string)$attributes['id'],
                        ]);
                        if ($auth->save()) {
                            $transaction->commit();
                            Yii::$app->user->login($user);
                        } else {
                            print_r($auth->getErrors());
                        }
                    } else {
                        print_r($user->getErrors());
                    }
                }
            }
        } else { // Пользователь уже зарегистрирован
            if (!$auth) { // добавляем внешний сервис аутентификации
                $auth = new Auth([
                    'user_id' => Yii::$app->user->id,
                    'source' => $client->getId(),
                    'source_id' => $attributes['id'],
                ]);
                $auth->save();
            }
        }
    }
}
```

Метод `successCallback` вызывается, когда пользователь был успешно аутентифицирован через внешний сервис. Через
экземпляр `$client` мы можем извлечь полученную информацию. В нашем случае мы хотели бы:

- Если пользователь гость и в таблице auth существует запись, то проводим аутентификацию этого пользователя.
- Если пользователь гость и в таблице auth записи не существует, то создаём нового пользователя и запись в таблице auth. После
проводим аутентификацию пользователя.
- Если пользователь прошёл аутентификацию и запись в таблице auth не найдена, то пытаемся подключить дополнительный
аккаунт (сохранить его данные в таблицу auth).

> Примечание: Могут потребоваться различные подходы обработки успешной аутентификации для различных клиентов
аутентификации.
  Например: Twitter не допускает возвращение электронной почты пользователя, но так или иначе Вы должны с этим как то
  работать.

### Базовая структура клиента аутентификации

Хоть все клиенты и разные, всё же они реализуют базовый интерфейс [[yii\authclient\ClientInterface]], который управляет
общим API.

У каждого клиента есть некоторые описательные данные, которые могут использоваться в различных целях:

- `id` - уникальный идентификатор клиента, который отделяет его от других клиентов, может использоваться
  в URL'ах, логах и т.д.
- `name` - внешнее подлиное имя сервиса аутентификации, которое так же соответствует имени клиента. Различные
  клиенты аутентификации могут иметь одно и то же имя, если они относятся к одному и тому же внешнему сервису
  аутентификации.
  Например: клиенты для Google OpenID и Google OAuth имеют одинаковое имя "google".
  Данный атрибут может быть использован внутри баз данных, CSS стилей и так далее.
- `title` - удобное для пользователя имя внешнего сервиса аутентификации, используется для предоставления клиента
  аутентификации на уровне представления.

Каждый клиент аутентификации имеет отличный от других процесс аутентификации, но каждый из них поддерживает метод
`getUserAttributes()`, который может быть вызван, в случае, если аутентификация прошла успешно.

Это метод позволяет получить информацию о внешней учетной записи пользователя, такую, как ID, адрес электронной почты,
полное имя, предпочитаемый язык и т.д. Обратите внимание, что для каждого внешнего сервиса в списке доступных полей
может изменяться как название поля, так и сам факт его существования.

Определение списка атрибутов, возвращаемых внешним сервисом аутентификации, зависит от типа самого клиента:

- [[yii\authclient\OpenId]]: сочетание `requiredAttributes` и `optionalAttributes`.
- [[yii\authclient\OAuth1]] и [[yii\authclient\OAuth2]]: поле `scope`, обратите внимание, что разные сервисы используют
разные форматы для scope.

> Совет: если Вы используете несколько различных клиентов, Вы можете объединить структуры атрибутов, которые они
возвращают, при помощи[[yii\authclient\BaseClient::normalizeUserAttributeMap]].

### Получение дополнительных данных с помощью дополнительных обращений к API

Оба клиента, [[yii\authclient\OAuth1]] и [[yii\authclient\OAuth2]], обеспечивают метод `api()`, который может быть
использован для доступа к REST API внешнего сервиса аутентификации. Однако это метод очень простой и этого может быть
недостаточно, что бы получить полный доступ к функционалу внешнего API. Данный метод используется, в основном, для
получения данных внешней учетной записи пользователя.

Что бы использовать дополнительные обращения к API, необходимо настроить [[yii\authclient\BaseOAuth::apiBaseUrl]] в
соответствии со спецификацией API. Тогда Вы сможете вызвать метод [[yii\authclient\BaseOAuth::api()]]:

```php
use yii\authclient\OAuth2;

$client = new OAuth2;

// ...

$client->apiBaseUrl = 'https://www.googleapis.com/oauth2/v1';
$userInfo = $client->api('userinfo', 'GET');
```

## Добавление виджета в представление аутентификации

В представлениях можно использовать готовый виджет [[yii\authclient\widgets\AuthChoice]]:

```php
<?= yii\authclient\widgets\AuthChoice::widget([
     'baseAuthUrl' => ['site/auth'],
     'popupMode' => false,
]) ?>
```


text:
from django.test.utils import override_settings
from django.conf import settings
from sis_provisioner.management.commands import SISProvisionerCommand
from sis_provisioner.models.external_tools import ExternalTool
from sis_provisioner.dao.canvas import update_external_tool
from uw_canvas.accounts import Accounts
from restclients_core.dao import LiveDAO
from restclients_core.exceptions import DataFailureException
import json

class Command(SISProvisionerCommand):
    help = "Fixes the discovery and LTI URLs for uw.test and uw.beta"

    BLTI_HOSTS = {
        'canvas': {
            'prod': 'https://apps.canvas.uw.edu',
            'test': 'https://test-apps.canvas.uw.edu'},
        'panopto': {
            'prod': 'https://panopto-app.uw.edu',
            'test': 'https://test.panopto-app.uw.edu'},
        'course-users': {
            'prod': 'https://course-users.canvas.uw.edu',
            'test': 'https://test-course-users.canvas.uw.edu'},
        'course-roster': {
            'prod': 'https://courseroster.canvas.uw.edu',
            'test': 'https://test-courseroster.canvas.uw.edu'},
        'grading-standards': {
            'prod': 'https://grading-standards.canvas.uw.edu',
            'test': 'https://test-grading-standards.canvas.uw.edu'},
        'libguides': {
            'prod': 'https://libguides.canvas.uw.edu',
            'test': 'https://test-libguides.canvas.uw.edu'},
        'infohub': {
            'prod': 'https://infohub.canvas.uw.edu',
            'test': 'https://test-infohub.canvas.uw.edu'},
    }
    LOGIN_TEST_HOST = 'https://test-login.canvas.uw.edu'

    def handle(self, *args, **options):
        self.update_canvas_test()
        self.update_canvas_beta()
        self.update_job()

    def update_discovery_url(self, discovery_url):
        account_id = settings.RESTCLIENTS_CANVAS_ACCOUNT_ID

        LiveDAO.pools = {}
        auth = Accounts().get_auth_settings(account_id)

        if auth.auth_discovery_url != discovery_url:
            auth.auth_discovery_url = discovery_url
            Accounts().update_auth_settings(account_id, auth)

    def update_blti_urls(self):
        for service in self.BLTI_HOSTS:
            prod_host = self.BLTI_HOSTS.get(service).get('prod')
            test_host = self.BLTI_HOSTS.get(service).get('test')

            for tool in ExternalTool.objects.get_by_hostname(prod_host):
                new_config = tool.config.replace(prod_host, test_host)
                try:
                    update_external_tool(
                        tool.account.canvas_id, tool.canvas_id,
                        json.loads(new_config))
                except DataFailureException as err:
                    # 404s OK
                    if err.status != 404:
                        raise

    @override_settings(
        RESTCLIENTS_CANVAS_HOST="https://uw.beta.instructure.com")
    def update_canvas_beta(self):
        self.update_discovery_url(
            "{host}/wayf-beta".format(host=self.LOGIN_TEST_HOST))
        self.update_blti_urls()

    @override_settings(
        RESTCLIENTS_CANVAS_HOST="https://uw.test.instructure.com")
    def update_canvas_test(self):
        self.update_discovery_url(
            "{host}/wayf-test".format(host=self.LOGIN_TEST_HOST))
        self.update_blti_urls()


text:
all:
	rm -r build/
	python2 setup.py build

build:
	python2 setup.py build

clean:
	rm -r build/

test:
	python2 bubbletest.py


text:
<fieldset class="{{ fieldset.classes }} well">
    {% if fieldset.name %}
{{ fieldset.name }}
{% endif %}
    {% if fieldset.description %}

{{ fieldset.description|safe }}

    {% endif %}
    {% for line in fieldset %}

            {% for field in line %}
                    {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %}

                        {{ field.label_tag }}
                        {% if field.is_readonly %}

{{ field.contents }}

                        {% else %}

                              {{ field.field }}
                              {{ line.errors }}

                        {% endif %}

                    {% if field.field.help_text %}

{{ field.field.help_text|safe }}

                    {% endif %}
            {% endfor %}

    {% endfor %}
</fieldset>


text:
import datetime
import io
import os
import time
import traceback
from lxml import etree
from urlparse import urlparse, ParseResult
try:
    import cPickle as pickle    # NOQA
except:
    import pickle # NOQA

LAST_USED = {}
USE_RATE = 60
PICKLEFILE = os.path.expanduser("~/.pommerss")
CHECK_INTERVAL = 5 * 60
try:
    FEEDCACHE = pickle.load(io.open(PICKLEFILE, 'r+b'))
except:
    FEEDCACHE = {}

class RSSException(Exception):
    pass

class RSSItem(object):
    def __init__(self, node):
        """ Expects an etree-node, so don't try anything else. """
        self.title = node.find("title").text
        self.pubdate = node.find("pubDate").text
        try:
            self.guid = node.find("guid").text
        except:
            # Some feeds don't supply a uid D:
            self.guid = self.pubdate
        try:
            self.link = node.find("link").text
        except:
            # Python.org's rdf doesn't do link tags, but uses guid for this.
            self.link = self.guid
        self.description = node.find("description").text

class RSSFeed(object):
    def __init__(self, feed):
        self.feed = feed
        self.items = []

    def update(self):
        self.items = []

        print "RSS: Pulling", self.feed
        doc = etree.parse(self.feed)
        items = doc.findall('//item')
        for item in items:
            self.items.append(RSSItem(item))

def pubmsg(connection, event):
    global LAST_USED
    global USE_RATE

    message = event._arguments[0].strip()
    if message[0] != '!':
        return
    (command, remainer) = message.split(" ", 1)

    if command in ('!feeds', '!rss-feeds'):
        uid = '/'.join([connection.server, event.target()])

        # Throttling.
        if uid in LAST_USED and not older_than_rate(LAST_USED[uid],
                                 datetime.datetime.now(),
                                 USE_RATE):
            return
        LAST_USED[uid] = datetime.datetime.now()

        feedlist = [feed for feed, data
                         in FEEDCACHE.iteritems()
                         if uid in data['channels']]
        if len(feedlist) > 0:
            connection.privmsg(event.target(), "Lijstje!")
            for feed in feedlist:
                connection.privmsg(event.target(), str(feed))
                time.sleep(1)
        else:
            connection.privmsg(event.target(),
                               'Nope. Go away.')

def privmsg(connection, event):
    message = event._arguments[0].strip()
    if message[0] != '!':
        return
    (command, remainder) = message.split(" ", 1)

    if command in ('!add-feed',):
        (feed, channels) = remainder.split(" ", 1)
        try:
            add_feed(connection,
                     nick_from_source(event.source()),
                     feed,
                     channels.split())
        except RSSException:
            return
        except Exception as e:
            print "Exception during adding RSS feed:", e
    elif command in ('!del-feed',):
        global FEEDCACHE
        if remainder in FEEDCACHE:
            del FEEDCACHE[remainder]
        store_feedcache()

def cycle(connections):
    global FEEDCACHE

    now = datetime.datetime.now()
    feeds = get_feeds_to_check(now)
    if feeds:
        print "Checking", feeds
    for feed in feeds:
        try:
            FEEDCACHE[feed]['lastchecked'] = now

            feed_ = RSSFeed(feed)
            feed_.update()

            if len(feed_.items) == 0:
                continue

            if feed_.items[0].guid > FEEDCACHE[feed]['lastguid']:
                FEEDCACHE[feed]['lastguid'] = feed_.items[0].guid
                spam(feed_.items[0], FEEDCACHE[feed], connections)
        except:
            print "Failed updating", feed
            traceback.print_exc()
    store_feedcache()

def store_feedcache():
    global FEEDCACHE
    global PICKLEFILE
    pickle.dump(FEEDCACHE, io.open(PICKLEFILE, 'w+b'))

def spam(feed, feeddata, connections):
    c_hash = dict([(c.server, c) for c in connections])
    message = '%s - %s' % (feed.title, strip_utm(feed.link))
    for channel in feeddata['channels']:
        server, channel_name = channel.split('/', 1)
        if server in c_hash:
            c = c_hash[server]
            c.privmsg(channel_name, message)

# Supporting functions
def older_than_rate(t1, t2, rate):
    diff = t2 - t1
    return diff.days > 0 or diff.seconds > rate

def get_feeds_to_check(now):
    global FEEDCACHE
    global CHECK_INTERVAL

    to_check = []

    check_time = datetime.timedelta(seconds=CHECK_INTERVAL)
    for feed, data in FEEDCACHE.iteritems():
        if data['lastchecked'] + check_time < now:
            to_check.append(feed)

    return to_check

def add_feed(connection, source, feed, channels):
    connection.privmsg(source, ">>" + str(channels))
    if not channels:
        connection.privmsg(source, "I want channels")
    if not feed in FEEDCACHE:
        if not check_feed(feed):
            raise RSSException("Not a RSS feed")
        add_feed_to_cache(feed)
    add_channels_to_feed([gen_uid(connection.server, channel)
                          for channel
                          in channels], feed)
    store_feedcache()
    connection.privmsg(source, u"added.")

def gen_uid(server, channel):
    return '/'.join([server, channel])

def check_feed(feed):
    try:
        doc = etree.parse(feed)
        return (unicode(doc.getroot().tag) == u'rss')
    except Exception as e:
        print "Exception:", e
        return False

def add_feed_to_cache(feed):
    global FEEDCACHE
    if feed in FEEDCACHE:
        return

    empty_dict = dict()
    empty_dict['lastchecked'] = datetime.datetime(2011, 1, 1)
    empty_dict['lastguid'] = ''
    empty_dict['channels'] = set()

    FEEDCACHE[feed] = empty_dict

def add_channels_to_feed(channels, feed):
    try:
        FEEDCACHE[feed]['channels'].update(channels)
    except Exception as e:
        print e

def nick_from_source(source):
    return source.split('!')[0]

def strip_utm(link):
    """ This method removes utm_* query parts from a link, to make sure our
        privacy is insured. *cough*
    """
    d = urlparse(link)
    query = '&'.join([x for x in d.query.split("&") if x[:4] != 'utm_'])
    return ParseResult(d.scheme,
                       d.netloc,
                       d.path,
                       d.params,
                       query,
                       d.fragment).geturl()


text:
'use strict';

$('.slide').mouseover(function(){
  $(this).next('*').slideToggle();
});

var timeDay = ['6am', '7am', '8am', '9am', '10am', '11 am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm'];
var mainTable = document.getElementById('main-table'); //Get main table
//Get element access

// var eRowItem = document.createElement('td');

// }else if{
// eRowItem.textContent = avgCookiesArray;
// this.CookieArray.push(avgCookiesArray);
// loopTr.appendChild(eRowItem);

function loopRenderTable(){
  for(var w = 0; w < stores.length; w++){
    stores[w].renderTable();
  }
}

//Cookie store repo
function CookieStore(name, minCust, maxCust, avgSale) {
  this.name = name;
  this.minCust = minCust; //maximum customers per hour
  this.maxCust = maxCust; //minimum customers per hour
  this.avgSale = avgSale; //avg sales per customery
  this.cookieArray = [];
  this.totalSales = 0;
}

//Our Stores
var onePike = new CookieStore('First and Pike', 23, 65, 6.3); //First and Pike Store
var seaTac = new CookieStore('Seatac Airport', 3, 24, 1.2); //Seatac Store
var seaCenter = new CookieStore('Seattle Center', 11, 38, 3.7); //Seattle Center Store
var capHill = new CookieStore('Capitol Hill', 20, 38, 2.3); //Capitol Hill Store
var alki = new CookieStore('Alki', 2, 16, 4.6); //Alki Store

var stores = [onePike, seaTac, seaCenter, capHill, alki];

//RNGEESUS
CookieStore.prototype.avgHourly = function(){
  return Math.floor(Math.floor((Math.random() * (this.maxCust - this.minCust + 1) + this.minCust)) * this.avgSale);
}; //Function for calculating random number based on each location's info.

//CREATE PROTOTYPE THAT CREATES A TH FOR STORE TITLE AND TDS
CookieStore.prototype.renderTable = function(){
  var loopTr = document.createElement('tr');
  var storeTh = document.createElement('th');
  mainTable.appendChild(loopTr);
  storeTh.textContent = this.name;
  loopTr.appendChild(storeTh);
  for(var h = 0; h < timeDay.length; h++){
    var eRowItem = document.createElement('td');
    var avgCookiesArray = this.avgHourly();
    eRowItem.textContent = avgCookiesArray;
    this.cookieArray.push(avgCookiesArray);
    loopTr.appendChild(eRowItem);
    this.totalSales = 0;
  }
  //measures all sales and saves them to their respective cookie store
  for(var d = 0; d < this.cookieArray.length; d++){
    this.totalSales += this.cookieArray[d];
  }
  //makes a final column for each store, which contains the totals of each row.
  var totalColumn = document.createElement('td');
  totalColumn.textContent = this.totalSales;
  loopTr.appendChild(totalColumn);
};

var tableHead = document.createElement('thead');//

mainTable.appendChild(tableHead); //

// spacer block for thead
var spacerTh = document.createElement('th');//

spacerTh.textContent = 'Stores';
tableHead.appendChild(spacerTh); // //

//creates header with time range
for(var h = 0; h < timeDay.length; h++){
  var eHeaderItem = document.createElement('th'); //
  eHeaderItem.textContent = timeDay[h];
  tableHead.appendChild(eHeaderItem); //

}

var titleHeader = document.createElement('th'); //
titleHeader .textContent = 'Total';
tableHead.appendChild(titleHeader); //

//Makes totals at the bottom of the table

function totalBottomRow(){
  //define the table footer that the totals will go into, and append to parent element
  var tableFoot = document.createElement('tfoot');//

  tableFoot.setAttribute('id', 'table-footer');
  mainTable.appendChild(tableFoot); //

  var storeTotalBlock = document.createElement('td'); //
  tableFoot.appendChild(storeTotalBlock); //

  storeTotalBlock.textContent = 'Total';
  var cookieTotal = 0;
  for(var h = 0; h < timeDay.length; h++) {
    if(h < timeDay.length){
      var totalRow = 0;
      for(var m = 0; m < stores.length; m++){
        var currentStore = stores[m];
        totalRow += currentStore.cookieArray[h];
        console.log(currentStore.cookieArray[h]);
      }
      var tableFootData = document.createElement('td');//

      tableFoot.appendChild(tableFootData); //

      tableFootData.textContent = totalRow;
      cookieTotal += totalRow;
    }else {
      var tableColumnTotal = document.createElement('td');//

      tableFoot.appendChild(tableColumnTotal); //

      tableFootData.text = cookieTotal;
    }
  }
  var totalTotal = document.createElement('td'); //
  tableFoot.appendChild(totalTotal); //

  totalTotal.textContent = cookieTotal;
}

loopRenderTable();
totalBottomRow();

//EVENT LISTENERS

// WILL NEED A PARSEINT TO TURN THE FIELD INPUT INTO NON-STRINGS

// use blur for non-numbers in the boxes
var storeFormEl = document.getElementById('new-store-form'); //creates form
//^^html element node

storeFormEl.addEventListener('submit', handleSubmit); //hitting false makes the older browsers bubble
//^^you can have an addEventListener for any html element node

function handleSubmit(event){
  event.preventDefault(); //stops page from reloading/sending data to server - the default setting for submission
  event.stopPropagation(); //stops bubbling, stop capturing

  var storeName = event.target.cookieStoreName.value; //this will log whatever the event's goal, or "target" action is
  var minCust = parseInt(event.target.minCust.value); //this will log whatever the event's goal, or "target" action is
  var maxCust = parseInt(event.target.maxCust.value); //this will log whatever the event's goal, or "target" action is
  var avgSale = parseFloat(event.target.avgSale.value); //this will log whatever the event's goal, or "target" action is

  console.log(storeName); //this will log whatever the event's goal, or "target" action is
  console.log(minCust); //this will log whatever the event's goal, or "target" action is
  console.log(maxCust); //this will log whatever the event's goal, or "target" action is
  console.log(avgSale); //this will log whatever the event's goal, or "target" action is
  console.log('user pressed submit button on form');

  var nuevoStore = new CookieStore(storeName, minCust, maxCust, avgSale);
  stores.push(nuevoStore);
  // storesConstructed.push(storeName);
  // console.log(store);
  nuevoStore.renderTable(); //add whatever nuevoStore is to the table
  var footer = document.getElementById('table-footer'); //allows us to access the #table-footer from html
  footer.remove();
  totalBottomRow();
}

// //Loop stores
// function loopStores(){
//   for(var o = 0; o < stores.length; o++){
//     console.log(stores[i]);
//   }
// }

// mainDiv.appendChild(loopTr);
// var eHeaderItem = document.createElement('tr');
// var loopedId = document.getElementById(stores[v]);
// storeTr.setAttribute('id', storesHtml[v]);
// timeDay[h] + ': ' +
// var eHeaderItem = document.createElement('th');
// eHeaderItem.textContent = timeDay[h];
// tableHead.appendChild(eHeaderItem);

// function avgHourly(){
//   return Math.floor(Math.random() * ((this.maxCust - this.minCust + 1) + this.minCust) * this.avgSale);
// };

    //--STORE OBJECTS BELOW--

    // var onePike = {
    //   minCust: 23,
    //   maxCust: 65,
    //   avgSale: 6.3,
    //   avgHourly: function(){
    //     return Math.floor(Math.random() * ((this.maxCust - this.minCust + 1) + this.minCust) * this.avgSale);
    //   },
    // };
    //
    // var seaTac = {
    //   minCust: 3,
    //   maxCust: 24,
    //
    // var seaCenter = {
    //   minCust: 11,
    //   maxCust: 38,
    //   avgSale: 3.7,
    //   avgHourly: function(){
    //     return Math.floor(Math.random() * ((this.maxCust - this.minCust + 1) + this.minCust) * this.avgSale);
    //   }
    // };
    //
    //   avgSale: 1.2,
    //   avgHourly: function(){
    //     return Math.floor(Math.random() * ((this.maxCust - this.minCust + 1) + this.minCust) * this.avgSale);
    //   }
    // };
    //
    // var capHill = {
    //   minCust: 20,
    //   maxCust: 38,
    //   avgSale: 2.3,
    //   avgHourly: function(){
    //     return Math.floor(Math.random() * ((this.maxCust - this.minCust + 1) + this.minCust) * this.avgSale);
    //   }
    // };
    //
    // var alki = {
    //   minCust: 2,
    //   maxCust: 16,
    //   avgSale: 4.6,
    //   avgHourly: function(){
    //     return Math.floor(Math.random() * ((this.maxCust - this.minCust + 1) + this.minCust) * this.avgSale);
    //   }
    // };
    //

// document. body.appendChild(mainDiv);

// var stores = [pikePlace, otherStore, anotherStore];
//
// var tableEl = document.createElement('table');
// for(b = 0; b < tableEl.length; b++){
//   var currentStore = stores[b];
//   var rowEl = document.createElement('tr');
//   var nameEl = document.createElement('th');
//   nameEl.textContent = currentStore.name;
//   rowEl.appendChild(nameEl);
//
//   var minCustEl = document.createElement('td');
//   minCustEl.textContent = currentStore.minCustomers;
//   rowEl.appendChild(minCustEl);
//
//   var maxCustEl = document.createElement('td');
//   maxCustEl.textContent = currentStore.maxCustomers;
//   rowEl.appendChild(maxCustEl);
//
//   var avgCookiesEl = document.createElement('td');
//   avgCookiesEl.textContent = currentStore.avgCookies;
//   rowEl.appendChild(avgCookiesEl);
//
//   rowEl.appendChild(rowEl);
// }
// document.body.appendChild(tableEl);

// break;
// function randomInt(min, max){
//   min = Math.ciel(this.minCust);
//   max = Math.floor(this.maxCust);
//   return Math.floor(Math.random() * (max - min + 1 )) + this.minCust;
// }

// //LOOP AVG COOKIES PER HR
// function loopAvgCookies(){
//   for(var j = 0; j < avgCookies.length; j++){
//     console.log(avgCookies[j]);
//   }
// };

// var avgCookies = [onePike.avgHourly(), seaTac.avgHourly(), seaCenter.avgHourly(), capHill.avgHourly(), alki.avgHourly()];

// function mainTable(){
//   document.getElementsByClassName('locations');
// }

//Loop Store Titles to td
// function loopStore(){
//   for(var t = 0; t < stores.length; t++){
//     return stores[t];
//   };
// }

//LOOP TIME OF DAY
// function loopTime(){
//   for(var i = 0; i < timeDay.length; i++){
//     console.log(timeDay[i]);
//     return timeDay[i];
//   };
// }

// var sectionEl = document.getElementById('main-content');

// var userElement = document.createElement('td'); //step one: create html element node

// userElement.setAttribute('id', 'made-an-element'); //step two: this is a method that changes an html element node
//the first input here is the type of element that we're making, the next is the id
//this would thus far do the following:

// sectionEl.appendChild(userElement);

// loopAvgCookies();

// for(var z = 0; 0 < stores.list; z++){
//   var eListTitle = document.createElement('td');
//   console.log(loopstore());
//   eListTitle.textContent = loopStore();
//   ('body').appendChild(eListTitle);
//
// }

// function loopTime(){
//   for(var i = 0; i < timeDay.length; i++){
//     console.log(avgCookies[i]);
//     console.log(timeDay[i]);
//     return timeDay[i];
//   }
// };

// function printEverything(){

// storesList();
// aDay(seaTac);
// aDay(seaTac);
// aDay(capHill);
// aDay(alki);

//DEMOING PRINTING TO PAGE


text:
This is the JSON prototype for version 0.1 of the Conceptual Graph.
Please always follow this format, anything else won't be parsed and will result in a runtime exception.

```json
{
    "version" : "1",
    "guid" : "00000000-0000-0000-0000-000000000000",
    "creator" : null,
    "relations" : [
     {
         "label" : "is",
         "postag" : "VBZ",
         "index" : "1",
         "id" : "2976782025758403374"
     }],
     "concepts" : [
     {
         "label" : "sky",
         "postag" : "NNZ",
         "index" : "0",
         "id" : "1577683746703680484"
     },
     {
         "label" : "blue",
         "postag" : "NNZ",
         "index" : "2",
         "id" : "15843861542616104093"
     }],
     "adjacencies": [
     {
         "nodeTo" : "1577683746703680484",
         "nodeFrom" : "2976782025758403374",
         "index" : "0",
         "order" : "cr"
     },
     {
         "nodeTo" : "15843861542616104093",
         "nodeFrom" : "2976782025758403374",
         "index" : "1",
         "order" : "rc"
     }]
}
```

* `version` defines the current protocol version.
* `guid` must be a valid UUID version 4, invalid ones will throw an exception.
* `creator` is optional.
* `relations` array must contain all graph relation nodes.
* `concepts` array must contain all graph concept nodes.
* `adjacencies` array must contain all edges.

A few important notes:

* `label` is the actual string value of a node, it is mandatory.
* `postag` is the part-of-speech tag of a node, it is optional.
* `index` is the position of the node in a text sentence and is mandatory. Conflicting `index` fields will throw an exception.
* `id` is a unique id for a specific node. If not unique the library *may* throw an exception. Its best to use Murmur or similar hash.

Adjacencies work by creating an *adjacency matrix* where each edge is described by members `nodeTo` and `nodeFrom`.
* `index` in an adjacency object defines the order of the edge list, and must be unique and is mandatory.
* `order` in an adjacency object defines the node class types, e.g., if [Concept→ Relation] use `cr` and `rc` for the opposite.


text:
package com.grayben.riskExtractor.helpers;

import com.grayben.riskExtractor.htmlScorer.HtmlScorer;
import com.grayben.riskExtractor.htmlScorer.ScoredText;
import com.grayben.riskExtractor.htmlScorer.ScoringAndFlatteningNodeVisitor;
import com.grayben.riskExtractor.htmlScorer.TreeHtmlScorer;
import com.grayben.riskExtractor.htmlScorer.partScorers.Scorer;
import com.grayben.tools.testOracle.SystemUnderTest;
import com.grayben.tools.testOracle.oracle.passive.PassiveOracle;
import com.grayben.tools.testOracle.testContainer.TestContainer;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * Created by Ben Gray on 19/02/2016.
 */
public class TreeHtmlScorerReverserTestContainerSupplier implements Supplier<TestContainer<ScoredText, ScoredText>> {

    private final Supplier<Set<Scorer<Element>>> elementScorersSupplier;

    public TreeHtmlScorerReverserTestContainerSupplier(Supplier<Set<Scorer<Element>>> elementScorersSupplier) {
        this.elementScorersSupplier = elementScorersSupplier;
    }

    @Override
    public TestContainer<ScoredText, ScoredText> get() {
        return new TestContainer.Builder<ScoredText, ScoredText>()
                .begin()
                .systemUnderTest(systemUnderTest())
                .oracle(passiveOracle())
                .build();
    }

    private PassiveOracle<ScoredText, ScoredText> passiveOracle(){
        return (input, actualOutput) -> input.equals(actualOutput);
    }

    /**
     *
     * @return an InputStream for which a correct implementation of TreeHtmlScorer will produce the specified ScoredText
     */
    private Function<ScoredText, InputStream> reverse(){
        return scoredText -> ScoredTextReverseEngineerer.inputStreamFromElementScorers(scoredText, elementScorersSupplier.get());
    }

    private Function<InputStream, ScoredText> forward(){
        return inputStream -> {
            ScoringAndFlatteningNodeVisitor nv = new ScoringAndFlatteningNodeVisitor(elementScorersSupplier.get());
            HtmlScorer htmlScorer = new TreeHtmlScorer(nv);
            ScoredText scoredText = null;
            try {
                scoredText = htmlScorer.scoreHtml(inputStream, "unicode", "");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return scoredText;
        };

    }

    private SystemUnderTest<ScoredText, ScoredText> systemUnderTest() {
        return scoredText -> reverse().andThen(forward()).apply(scoredText);
    }

}


text:
layout:     post
title:      cloudy all the way
date:       2015-07-12 20:17:26
summary:
categories: drawing
---
![cloudy all the way](/images/diary/cloudy-all-the-way.png "both the mood and the weather")


text:
package bftsmart.tom.core;

import java.util.concurrent.LinkedBlockingQueue;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import bftsmart.paxosatwar.Consensus;
import bftsmart.reconfiguration.ServerViewManager;
import bftsmart.statemanagment.ApplicationState;
import bftsmart.tom.MessageContext;
import bftsmart.tom.TOMReceiver;
import bftsmart.tom.core.messages.TOMMessage;
import bftsmart.tom.core.messages.TOMMessageType;
import bftsmart.tom.server.Recoverable;
import bftsmart.tom.util.BatchReader;
import bftsmart.tom.util.Logger;

/**
 * This class implements a thread which will deliver totally ordered requests to the application
 *
 */
public final class DeliveryThread extends Thread {

    private LinkedBlockingQueue<Consensus> decided = new LinkedBlockingQueue<Consensus>(); // decided consensus
    private TOMLayer tomLayer; // TOM layer
    private TOMReceiver receiver; // Object that receives requests from clients
    private Recoverable recoverer; // Object that uses state transfer
    private ServerViewManager manager;

    /**
     * Creates a new instance of DeliveryThread
     * @param tomLayer TOM layer
     * @param receiver Object that receives requests from clients
     * @param conf TOM configuration
     */
    public DeliveryThread(TOMLayer tomLayer, TOMReceiver receiver, Recoverable recoverer, ServerViewManager manager) {
        super("Delivery Thread");

        this.tomLayer = tomLayer;
        this.receiver = receiver;
        this.recoverer = recoverer;
        //******* EDUARDO BEGIN **************//
        this.manager = manager;
        //******* EDUARDO END **************//
    }

    public TOMReceiver getReceiver() {
        return receiver;
    }

   public Recoverable getRecoverer() {
        return recoverer;
    }

    /**
     * Invoked by the TOM layer, to deliver a decide consensus
     * @param cons Consensus established as being decided
     */
    public void delivery(Consensus cons) {
        if (!containsGoodReconfig(cons)) {

            Logger.println("(DeliveryThread.delivery) Consensus ID " + cons.getId() + " does not contain good reconfiguration");
            //set this consensus as the last executed
            tomLayer.setLastExec(cons.getId());
            //define that end of this execution
            tomLayer.setInExec(-1);
        }
        try {
            decided.put(cons);
            Logger.println("(DeliveryThread.delivery) Consensus " + cons.getId() + " finished. Decided size=" + decided.size());
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }

    private boolean containsGoodReconfig(Consensus cons) {
        TOMMessage[] decidedMessages = cons.getDeserializedDecision();

        for (TOMMessage decidedMessage : decidedMessages) {
            if (decidedMessage.getReqType() == TOMMessageType.RECONFIG
                    && decidedMessage.getViewID() == manager.getCurrentViewId()) {
                return true;
            }
        }

        return false;
    }

    /** THIS IS JOAO'S CODE, TO HANDLE STATE TRANSFER */
    private ReentrantLock deliverLock = new ReentrantLock();
    private Condition canDeliver = deliverLock.newCondition();

    public void deliverLock() {
        deliverLock.lock();
        //Logger.println("(DeliveryThread.deliverLock) Deliver lock obtained");
    }

    public void deliverUnlock() {
        deliverLock.unlock();
        //Logger.println("(DeliveryThread.deliverUnlock) Deliver Released");
    }

    public void canDeliver() {
        canDeliver.signalAll();
    }

    public void update(ApplicationState state) {

        int lastEid =  recoverer.setState(state);

        //set this consensus as the last executed
        System.out.println("Setting last EID to " + lastEid);
        tomLayer.setLastExec(lastEid);

        //define the last stable consensus... the stable consensus can
        //be removed from the leaderManager and the executionManager
        if (lastEid > 2) {
            int stableConsensus = lastEid - 3;

            //tomLayer.lm.removeStableMultipleConsenusInfos(lastCheckpointEid, stableConsensus);
            tomLayer.execManager.removeOutOfContexts(stableConsensus);
        }

        //define that end of this execution
        //stateManager.setWaiting(-1);
        tomLayer.setNoExec();

        decided.clear();

        Logger.println("(DeliveryThread.update) All finished from up to " + lastEid);
    }

    /**
     * This is the code for the thread. It delivers decided consensus to the TOM
     * request receiver object (which is the application)
     */
    @Override
    public void run() {
        while (true) {
            /** THIS IS JOAO'S CODE, TO HANDLE STATE TRANSFER */
            deliverLock();
            while (tomLayer.isRetrievingState()) {
                Logger.println("(DeliveryThread.run) Retrieving State.");
                canDeliver.awaitUninterruptibly();
            }
            /******************************************************************/
            try { //no exception should stop the batch delivery thread
                // take a decided consensus
                Consensus cons = decided.poll(1500, TimeUnit.MILLISECONDS);
                if (cons == null) {
                    deliverUnlock();
                    continue; //go back to the start of the loop
                }
                Logger.println("(DeliveryThread.run) Consensus " + cons.getId() + " was delivered.");

                TOMMessage[] requests = extractMessagesFromDecision(cons);

                if (requests != null && requests.length > 0) {
                    //cons.firstMessageProposed contains the performance counters
                    if (requests[0].equals(cons.firstMessageProposed)) {
                    	long time = requests[0].timestamp;
                        requests[0] = cons.firstMessageProposed;
                        requests[0].timestamp = time;
                    }

                    //clean the ordered messages from the pending buffer
                    tomLayer.clientsManager.requestsOrdered(requests);

                    deliverMessages(cons.getId(), tomLayer.getLCManager().getLastReg(), true, requests, cons.getDecision());

                    //******* EDUARDO BEGIN **************//
                    if (manager.hasUpdates()) {
                        processReconfigMessages(cons.getId(), cons.getDecisionRound().getNumber());
                        //set this consensus as the last executed
                        tomLayer.setLastExec(cons.getId());
                        //define that end of this execution
                        tomLayer.setInExec(-1);
                    }
                    //******* EDUARDO END **************//
                }

                /** THIS IS JOAO'S CODE, TO HANDLE CHECKPOINTS */
                //logDecision(cons);
                /********************************************************/
                //define the last stable consensus... the stable consensus can
                //be removed from the leaderManager and the executionManager
                //TODO: Is this part necessary? If it is, can we put it inside setLastExec
                if (cons.getId() > 2) {
                    int stableConsensus = cons.getId() - 3;

                    tomLayer.lm.removeStableConsenusInfos(stableConsensus);
                    tomLayer.execManager.removeExecution(stableConsensus);
                }

            } catch (Exception e) {
                e.printStackTrace(System.err);
            }

            /** THIS IS JOAO'S CODE, TO HANDLE STATE TRANSFER */
            deliverUnlock();
            /******************************************************************/
        }
    }

    private TOMMessage[] extractMessagesFromDecision(Consensus cons) {
        TOMMessage[] requests = (TOMMessage[]) cons.getDeserializedDecision();

        if (requests == null) {
            //there are no cached deserialized requests
            //this may happen if this batch proposal was not verified
            //TODO: this condition is possible?

            Logger.println("(DeliveryThread.run) interpreting and verifying batched requests.");

            // obtain an array of requests from the taken consensus
            BatchReader batchReader = new BatchReader(cons.getDecision(),
                    manager.getStaticConf().getUseSignatures() == 1);
            requests = batchReader.deserialiseRequests(manager);
        } else {
            Logger.println("(DeliveryThread.run) using cached requests from the propose.");
        }

        return requests;
    }

    public void deliverUnordered(TOMMessage request, int regency) {
        MessageContext msgCtx = new MessageContext(System.currentTimeMillis(),
                new byte[0], regency, -1, request.getSender(), null);
        receiver.receiveReadonlyMessage(request, msgCtx);
    }

    private void deliverMessages(int consId, int regency, boolean fromConsensus, TOMMessage[] requests, byte[] decision) {
        receiver.receiveMessages(consId, regency, fromConsensus, requests, decision);
    }

    private void processReconfigMessages(int consId, int decisionRoundNumber) {
        byte[] response = manager.executeUpdates(consId, decisionRoundNumber);
        TOMMessage[] dests = manager.clearUpdates();

        for (int i = 0; i < dests.length; i++) {
            tomLayer.getCommunication().send(new int[]{dests[i].getSender()},
                    new TOMMessage(manager.getStaticConf().getProcessId(),
                    dests[i].getSession(), dests[i].getSequence(), response,
                    manager.getCurrentViewId(),TOMMessageType.RECONFIG));
        }

        tomLayer.getCommunication().updateServersConnections();
    }

    private void logDecision(Consensus cons) {
        if (manager.getStaticConf().getCheckpointPeriod() > 0) {
            if ((cons.getId() > 0) && ((cons.getId() % manager.getStaticConf().getCheckpointPeriod()) == 0)) {
                Logger.println("(DeliveryThread.run) Performing checkpoint for consensus " + cons.getId());
                //byte[] state = receiver.getState();
                //tomLayer.getStateManager().saveState(state, cons.getId(), cons.getDecisionRound().getNumber(), tomLayer.lm.getCurrentLeader()/*tomLayer.lm.getLeader(cons.getId(), cons.getDecisionRound().getNumber())*/);
            } else {
                Logger.println("(DeliveryThread.run) Storing message batch in the state log for consensus " + cons.getId());
                //tomLayer.getStateManager().saveBatch(cons.getDecision(), cons.getId(), cons.getDecisionRound().getNumber(), tomLayer.lm.getCurrentLeader()/*tomLayer.lm.getLeader(cons.getId(), cons.getDecisionRound().getNumber())*/);
            }
        }
    }
}


text:
from copy import copy

# Call the data you have at this point "a".
# Make a copy of "a"; call this copy "b".
# Reverse the order of the characters in "b".
# In "b", replace all instances of 0 with 1 and all 1s with 0.
# The resulting data is "a", then a single 0, then "b".

def dragon_one(data):
    new_data = copy(data)
    new_data.reverse()

    new_data = [(digit + 1) % 2 for digit in new_data]
    return data + [0] + new_data

# Consider each pair: 11, 00, 10, 11, 01, 00.
# These are same, same, different, same, different, same, producing 110101.
# The resulting string has length 6, which is even, so we repeat the process.
# The pairs are 11 (same), 01 (different), 01 (different).
# This produces the checksum 100, which has an odd length, so we stop.

def calculate_checksum(data):
    if len(data) % 2 == 1:
        return data

    checksum = []

    for i in range(len(data) // 2):
        pair = data[2*i:2*i+2]
        if pair[0] == pair[1]:
            checksum.append(1)
        else:
            checksum.append(0)

    return calculate_checksum(checksum)

def to_list(s):
    return [int(c) for c in s]

print calculate_checksum(to_list("110010110100"))

data = to_list("00101000101111010")

while len(data) < 35651584:
    data = dragon_one(data)

# print data
print "".join([str(digit) for digit in calculate_checksum(data[:35651584])])


text:
const STEP_COMPLETE = 'step/complete';
const STEP_PARTIAL = 'step/partial';
const STEP_INITIAL = 'step/initial';
const STEP_CLEAR = 'step/clear';

export const STATUS = {
  complete: 'complete',
  partial: 'partial'
};

export default function reducer(state = {}, action = {}) {
  const { type, step, data } = action;
  switch (type) {
    case STEP_COMPLETE:
      return Object.assign({}, state, {
        [step]: STATUS.complete
      });
    case STEP_PARTIAL:
      return Object.assign({}, state, {
        [step]: STATUS.partial
      });
    case STEP_CLEAR:
      return Object.assign({}, state, {
        [step]: void 0
      });
    case STEP_INITIAL:
      return data;
    default:
      return state;
  }
};

export const constants = {
    STEP_COMPLETE,
    STEP_PARTIAL,
    STEP_CLEAR,
    STEP_INITIAL
};

export const stepComplete = (step) => ({ type: STEP_COMPLETE, step });
export const stepPartial = (step) => ({ type: STEP_PARTIAL, step });
export const stepClear = (step) => ({ type: STEP_CLEAR, step });
export const setSteps = (data) => ({ type: STEP_INITIAL, data });

export const actions = {
  stepComplete,
  stepPartial,
  stepClear,
  setSteps
};


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Social on Hugo tranquilpeak theme</title>
    <link>/tags/social/</link>
    <description>Recent content in Social on Hugo tranquilpeak theme</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Sun, 17 Aug 2014 00:00:00 +0000</lastBuildDate>

	<atom:link href="/tags/social/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Hidden social section showcase</title>
      <link>/2014/08/hidden-social-section-showcase/</link>
      <pubDate>Sun, 17 Aug 2014 00:00:00 +0000</pubDate>

      <guid>/2014/08/hidden-social-section-showcase/</guid>
      <description><p>This post is used to show how a site looks if the social section is hidden.
</p></description>
    </item>

  </channel>
</rss>


text:
+++ setup.py
@@ -54,7 +54,7 @@ data_files=[
         (os.path.join(sys.prefix, 'share/onionshare/locale'), file_list('share/locale')),
         (os.path.join(sys.prefix, 'share/onionshare/html'), file_list('share/html')),
     ]
-if platform.system() != 'OpenBSD':
+if not platform.system().endswith('BSD'):
     data_files.append(('/usr/share/nautilus-python/extensions/', ['install/scripts/onionshare-nautilus.py']))

 setup(


text:
package org.pentaho.big.data.impl.shim.mapreduce;

import org.pentaho.bigdata.api.mapreduce.MapReduceExecutionException;
import org.pentaho.di.job.entries.hadoopjobexecutor.NoExitSecurityManager;
import org.pentaho.di.job.entries.hadoopjobexecutor.SecurityManagerStack;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Created by bryan on 12/7/15.
 */
public class FutureMapReduceJobSimpleRunnable implements Runnable {
  private static final SecurityManagerStack securityManagerStack = SecurityManagerStack.getInstance();
  private final Class<?> mainClass;
  private final String commandLineArgs;
  private final AtomicBoolean complete;
  private final AtomicInteger status;
  private final AtomicReference<MapReduceExecutionException> exceptionAtomicReference;

  public FutureMapReduceJobSimpleRunnable( Class<?> mainClass, String commandLineArgs, AtomicBoolean complete,
                                           AtomicInteger status,
                                           AtomicReference<MapReduceExecutionException> exceptionAtomicReference ) {
    this.mainClass = mainClass;
    this.commandLineArgs = commandLineArgs;
    this.complete = complete;
    this.status = status;
    this.exceptionAtomicReference = exceptionAtomicReference;
  }

  @Override public void run() {
    final NoExitSecurityManager nesm = new NoExitSecurityManager( System.getSecurityManager() );
    securityManagerStack.setSecurityManager( nesm );
    try {
      nesm.addBlockedThread( Thread.currentThread() );
      try {
        executeMainMethod( mainClass, commandLineArgs );
        updateWithStatus( 0, null );
      } finally {
        nesm.removeBlockedThread( Thread.currentThread() );
        securityManagerStack.removeSecurityManager( nesm );
      }
    } catch ( Throwable ex ) {
      if ( ex instanceof InvocationTargetException ) {
        ex = ( (InvocationTargetException) ex ).getTargetException();
      }
      if ( ex instanceof NoExitSecurityManager.NoExitSecurityException ) {
        updateWithStatus( ( (NoExitSecurityManager.NoExitSecurityException) ex ).getStatus(), null );
      } else {
        updateWithStatus( -1, new MapReduceExecutionException( ex ) );
      }
    }
  }

  /**
   * Execute the main method of the provided class with the current command line arguments.
   *
   * @param clazz Class with main method to execute
   * @throws NoSuchMethodException
   * @throws IllegalAccessException
   * @throws InvocationTargetException
   */
  protected void executeMainMethod( Class<?> clazz, String commandLineArgs )
    throws NoSuchMethodException, IllegalAccessException,
    InvocationTargetException {
    final ClassLoader cl = Thread.currentThread().getContextClassLoader();
    try {
      Thread.currentThread().setContextClassLoader( clazz.getClassLoader() );
      Method mainMethod = clazz.getMethod( "main", new Class[] { String[].class } );
      Object[] args =
        ( commandLineArgs != null ) ? new Object[] { commandLineArgs.split( " " ) } : new Object[] { new String[ 0 ] };
      mainMethod.invoke( null, args );
    } finally {
      Thread.currentThread().setContextClassLoader( cl );
    }
  }

  private void updateWithStatus( int status, MapReduceExecutionException exception ) {
    complete.set( true );
    this.status.set( status );
    exceptionAtomicReference.set( exception );
  }

  public AtomicBoolean getComplete() {
    return complete;
  }

  public AtomicInteger getStatus() {
    return status;
  }

  public AtomicReference<MapReduceExecutionException> getExceptionAtomicReference() {
    return exceptionAtomicReference;
  }
}


text:
// Sh: A GPU metaprogramming language.
//
// Copyright (c) 2003 University of Waterloo Computer Graphics Laboratory
// Project administrator: Michael D. McCool
// Authors: Zheng Qin, Stefanus Du Toit, Kevin Moule, Tiberiu S. Popa,
//          Michael D. McCool
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must
// not claim that you wrote the original software. If you use this
// software in a product, an acknowledgment in the product documentation
// would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//////////////////////////////////////////////////////////////////////////////
#ifndef SHSTORAGETYPE_HPP
#define SHSTORAGETYPE_HPP

#include "ShUtility.hpp"
#include "ShVariableType.hpp"
#include "ShInterval.hpp"
#include "ShHalf.hpp"
#include "ShFraction.hpp"

/** @file ShDataType.hpp
 * Defines the host computation and memory storage c++ types associated with
 * each Sh value type.
 *
 * Also defines
 */
namespace SH {

/** A special C++ type used to represent an invalid storage type */
struct ShInvalidStorageType {};

/**  The various value type integers correspond to storage types.
 *
 * Sh internally uses unsigned integers < 2^16.  User-defined types must use
 * values >= 2^16.
 *
 * This is idea behind the current set of value types:
 * i) bits 0-2 = B, where 1 << B = sizeof type in bytes
 * ii) bit 3 = 0 for signed type, 1 for unsigned
 * iii) bits 4-7 = 0 for floating point, 1 for integer, 2 for fraction
 * iv) bits 8-14 = 0 for regular, 1 for interval, 2 for affine
 * v) bit 15 = 0 for valid type, 1 for invalid type
 * @{ */
typedef unsigned int ShValueType;
enum __ShValueTypeEnum {
  SH_HALF       = 0x0001,
  SH_FLOAT      = 0x0002,
  SH_DOUBLE     = 0x0003,

  SH_BYTE       = 0x0010,
  SH_SHORT      = 0x0011,
  SH_INT        = 0x0012,

  SH_UBYTE      = 0x0018,
  SH_USHORT     = 0x0019,
  SH_UINT       = 0x001A,

  SH_FBYTE      = 0x0020,
  SH_FSHORT     = 0x0021,
  SH_FINT       = 0x0022,

  SH_FUBYTE     = 0x0028,
  SH_FUSHORT    = 0x0029,
  SH_FUINT      = 0x002A,

  SH_I_HALF    = 0x0101,
  SH_I_FLOAT   = 0x0102,
  SH_I_DOUBLE  = 0x0103,

  SH_A_HALF    = 0x0201,
  SH_A_FLOAT   = 0x0202,
  SH_A_DOUBLE  = 0x0203,

  SH_VALUETYPE_SIZE_MASK = 0x0007,

  SH_VALUETYPE_SIGNED_MASK = 0x0008,
  SH_VALUETYPE_SIGNED = 0x0000,

  SH_VALUETYPE_TYPE_MASK = 0x00F0,
  SH_VALUETYPE_TYPE_FLOAT = 0x0000,
  SH_VALUETYPE_TYPE_INT   = 0x0010,
  SH_VALUETYPE_TYPE_FRAC  = 0x0020,

  SH_VALUETYPE_SPECIAL_MASK = 0x7F00,
  SH_VALUETYPE_SPECIAL_NONE = 0x0100,
  SH_VALUETYPE_SPECIAL_I    = 0x0100,
  SH_VALUETYPE_SPECIAL_A    = 0x0200,

  SH_VALUETYPE_END = 0xFFFF
};
// @}

/** Functions to retrieve traits about storage types from their ShValueType
 *
 * @todo range - these should check for user defined value types later
 * and return false.
 * @{ */
bool shIsFloat(ShValueType value_type);
bool shIsInteger(ShValueType value_type);
bool shIsFraction(ShValueType value_type);

bool shIsSigned(ShValueType value_type);

bool shIsRegularValueType(ShValueType value_type);
bool shIsInterval(ShValueType value_type);

bool shIsInvalidValueType(ShValueType value_type);
// @}

/** Mappings from value type to storage type and back.
 * @{ */
template<ShValueType V> struct __ShValueToStorageType { typedef ShInvalidStorageType type; };
template<typename T> struct __ShStorageToValueType { static const ShValueType type = SH_VALUETYPE_END; };

#define SH_VALUE_STORAGE_TYPE_MAPPING(V, T)\
  template<> struct __ShValueToStorageType<V >    { typedef T type; }; \
  template<> struct __ShStorageToValueType<T >    { static const ShValueType type = V; };

SH_VALUE_STORAGE_TYPE_MAPPING(SH_HALF,    ShHalf);
SH_VALUE_STORAGE_TYPE_MAPPING(SH_FLOAT,   float);
SH_VALUE_STORAGE_TYPE_MAPPING(SH_DOUBLE,  double);

SH_VALUE_STORAGE_TYPE_MAPPING(SH_BYTE,    char);
SH_VALUE_STORAGE_TYPE_MAPPING(SH_SHORT,   short);
SH_VALUE_STORAGE_TYPE_MAPPING(SH_INT,     int);
SH_VALUE_STORAGE_TYPE_MAPPING(SH_UBYTE,   unsigned char);
SH_VALUE_STORAGE_TYPE_MAPPING(SH_USHORT,  unsigned short);
SH_VALUE_STORAGE_TYPE_MAPPING(SH_UINT,    unsigned int);

SH_VALUE_STORAGE_TYPE_MAPPING(SH_FBYTE,   ShFracByte);
SH_VALUE_STORAGE_TYPE_MAPPING(SH_FSHORT,  ShFracShort);
SH_VALUE_STORAGE_TYPE_MAPPING(SH_FINT,    ShFracInt);
SH_VALUE_STORAGE_TYPE_MAPPING(SH_FUBYTE,  ShFracUByte);
SH_VALUE_STORAGE_TYPE_MAPPING(SH_FUSHORT, ShFracUShort);
SH_VALUE_STORAGE_TYPE_MAPPING(SH_FUINT,   ShFracUInt);

SH_VALUE_STORAGE_TYPE_MAPPING(SH_I_HALF,  ShInterval<ShHalf>);
SH_VALUE_STORAGE_TYPE_MAPPING(SH_I_FLOAT, ShInterval<float>);
SH_VALUE_STORAGE_TYPE_MAPPING(SH_I_DOUBLE,ShInterval<double>);

// @}

/** Mapping from Storage Type to a name
 * @{*/
template<typename T> struct __ShStorageTypeName { static const char* name; };
template<typename T> const char* __ShStorageTypeName<T>::name = "unknown";

#define SH_STORAGETYPE_NAME_SPEC(T)\
  template<> struct SH_DLLEXPORT __ShStorageTypeName<T > { static const char* name; };

SH_STORAGETYPE_NAME_SPEC(ShHalf);
SH_STORAGETYPE_NAME_SPEC(float);
SH_STORAGETYPE_NAME_SPEC(double);

SH_STORAGETYPE_NAME_SPEC(char);
SH_STORAGETYPE_NAME_SPEC(short);
SH_STORAGETYPE_NAME_SPEC(int);
SH_STORAGETYPE_NAME_SPEC(unsigned char);
SH_STORAGETYPE_NAME_SPEC(unsigned short);
SH_STORAGETYPE_NAME_SPEC(unsigned int);

SH_STORAGETYPE_NAME_SPEC(ShFracByte);
SH_STORAGETYPE_NAME_SPEC(ShFracShort);
SH_STORAGETYPE_NAME_SPEC(ShFracInt);
SH_STORAGETYPE_NAME_SPEC(ShFracUByte);
SH_STORAGETYPE_NAME_SPEC(ShFracUShort);
SH_STORAGETYPE_NAME_SPEC(ShFracUInt);

SH_STORAGETYPE_NAME_SPEC(ShInterval<ShHalf>);
SH_STORAGETYPE_NAME_SPEC(ShInterval<float>);
SH_STORAGETYPE_NAME_SPEC(ShInterval<double>);

#undef SH_STORAGETYPE_NAME_SPEC
//@}

/** Returns whether a type is an interval type
 * @{ */
template<typename T>
struct ShIsInterval: public MatchTemplateType<T, ShInterval> {};
//@}

/** Returns whether a type is an interval type
 * @{ */
template<typename T>
struct ShIsFraction: public MatchTemplateType<T, ShFraction> {};
//@}

/** Returns an interval value type corresponding to a type,
 * or SH_VALUETYPE_NONE if no such type is defined;
 * @{ */

template<typename T>
struct __ShIntervalStorageType
{
  static const bool invalid = MatchType<T, ShInvalidStorageType>::matches;
  static const bool is_interval = ShIsInterval<T>::matches;
  // @todo range - this doesn't quite work once we have other special types,
  // perhaps...
  typedef typename SelectType<invalid, ShInvalidStorageType,
           typename SelectType<is_interval, T, ShInterval<T> >::type>::type type;
};

inline
ShValueType shIntervalValueType(ShValueType value_type);
// @}

/** Returns the regular value type corresponding to a special templated value type
 * (interval or affine) so far
 * @{ */
template<ShValueType V>
struct __ShRegularValueType
{
  static const ShValueType type = (V & ~SH_VALUETYPE_SPECIAL_MASK);
};

template<typename T>
struct __ShRegularStorageType
{
  static const ShValueType range_value_type = __ShStorageToValueType<T>::type;
  static const ShValueType value_type = __ShRegularValueType<range_value_type>::type;
  typedef typename __ShValueToStorageType<value_type>::type type;
};

inline
ShValueType shRegularValueType(ShValueType value_type);
// @}

/** Provides a least common ancestor in the automatic promotion tree
 * for use in immediate mode
 * @{ */
template<typename T1, typename T2>
struct ShCommonType;

template<typename T1, typename T2, typename T3>
struct ShCommonType3 {
  typedef typename ShCommonType<typename ShCommonType<T1, T2>::type, T3>::type type;
};

template<typename T1, typename T2, typename T3, typename T4>
struct ShCommonType4 {
  typedef typename ShCommonType<typename ShCommonType<T1, T2>::type,
                                typename ShCommonType<T3, T4>::type>::type type;
};
// @}

/** Holds much of the above information in one place.
 * This is the class to specialize for user-defined types
 * @{ */
template<typename T>
struct ShStorageTypeInfo {
  typedef T storage_type;
  static const ShValueType value_type = __ShStorageToValueType<T>::type;

  /** Non-special storage type corresponding to T */
  typedef typename __ShRegularStorageType<T>::type RegularType;
  static const ShValueType RegularValueType = __ShStorageToValueType<RegularType>::type;

  // @todo not sure we want all of these here, since there could be user-defined
  // special types too.  This might be too restrictive if we depend on these.

  /** Interval storage type corresponding to T (either T itself or uses T as its
   * bounds).  May be ShInvalidStorageType if no proper interval type exists */
  typedef typename __ShIntervalStorageType<T>::type IntervalType;
  static const ShValueType IntervalValueType = __ShStorageToValueType<IntervalType>::type;

  static const char* name;

  // @todo type include here the ability to set available operations

  // @todo type include here ShPrograms for transforming from this
  // storage type to a set of different ones, allowing the transformers
  // to choose the best conversions.

  // once the above two things are complete, than user-defined types should
  // work just fine.
};

template<typename T>
const char* ShStorageTypeInfo<T>::name = __ShStorageTypeName<T>::name;

//@}

/** Subclass of ShStorageTypeInfo so we can lookup the same things with a
 * ShValueType.  This is probably not necessary though since most of the time
 * ShValueType is used only internally in the bowels of Sh. */
template<ShValueType V>
struct ShValueTypeInfo: public ShStorageTypeInfo<typename __ShValueToStorageType<V>::type> {
};

}

#include "ShStorageTypeImpl.hpp"

#endif


text:
from SimpleCV import Color, Display, Image, Line
from util import dist, show_img, timer, cart_to_polar

import PIL

import numpy as np
from math import sqrt, ceil, pi, atan2

class ParsedFrame:
    def __init__(self, img, bimg, arr, rot_arr, rot_img, cursor_r, cursor_angle):
        w,h = img.size()

        self.img = img
        self.center_point = (w/2, h/2)
        self.bimg = bimg
        self.arr = arr
        self.rot_arr = rot_arr
        self.rot_img = rot_img
        self.cursor_r = cursor_r
        self.cursor_angle = cursor_angle

        rw, rh = self.rot_img.size()

        max_r = ceil(dist(0, 0, w/2, h/2))

        cursor_y = rh - int(rh * cursor_r/max_r)
        cursor_x = int(float(rw) * self.cursor_angle / 360)

        self.rot_img.dl().circle((cursor_x, cursor_y), 3, color=Color.RED, filled=True)

def parse_frame(img):
    """
    Parses a SimpleCV image object of a frame from Super Hexagon.
    Returns a ParsedFrame object containing selected features.
    """

    img

    # helper image size variables
    w,h = img.size()
    midx,midy = w/2,h/2

    # Create normalized images for targeting objects in the foreground or background.
    # (This normalization is handy since Super Hexagon's colors are inverted for some parts of the game)
    # fg_img = foreground image (bright walls, black when binarized)
    # bg_img = background image (bright space, black when binarized)
    fg_img = img
    if sum(img.binarize().getPixel(midx,midy)) == 0:
        fg_img = img.invert()
    bg_img = fg_img.invert()

    # We need to close any gaps around the center wall so we can detect its containing blob.
    # The gaps are resulting artifacts from video encoding.
    # The 'erode' function does this by expanding the dark parts of the image.
    bimg = bg_img.binarize()
    bimg = black_out_GUI(bimg)

    blobs = bimg.findBlobs()
    cursor_blob = get_cursor_blob(blobs, h, midx, midy)

    if cursor_blob:
        cursor_point = map(int, cursor_blob.centroid())
        cursor_r, cursor_angle = cart_to_polar(cursor_point[0] - midx, midy - cursor_point[1])

        cursor_angle = int(cursor_angle * 360/ (2 * pi))
        cursor_angle = 180 - cursor_angle
        if cursor_angle < 0:
            a += 360

        bimg = black_out_center(bimg, cursor_r).applyLayers()
        arr = bimg.resize(100).getGrayNumpy() > 100
        rot_arr = arr_to_polar(arr)
        rot_img = Image(PIL.Image.fromarray(np.uint8(np.transpose(rot_arr)*255))).dilate(iterations=3)
        rot_arr = rot_img.getGrayNumpy() > 100
        rot_img = rot_img.resize(400).flipVertical()
        return ParsedFrame(img, bimg, arr, rot_arr, rot_img, cursor_r, cursor_angle)
    else:
        return None

def get_cursor_blob(blobs, h, midx, midy):
    def is_cursor(b):
        max_size = h * 0.05 # cursor is teensy tiny
        cx, cy = b.centroid()
        max_dist_from_center = h * 0.2 # and close to the middle
        return (b.width() < max_size
                and b.height() < max_size
                and dist(cx, cy, midx, midy) < max_dist_from_center)

    # Locate the blob within a given size containing the midpoint of the screen.
    # Select the one with the largest area.
    cursor_blob = None

    if blobs:
        for b in blobs:
            if is_cursor(b):
                cursor_blob = b
                break

    return cursor_blob

def arr_to_polar(arr):
    w, h = arr.shape
    cx, cy = w/2, h/2
    max_r = ceil(dist(0, 0, cx, cy))

    new_w = 100
    new_h = 62

    x_bound = new_w - 1
    y_bound = new_h - 1

    new_arr = np.zeros((new_w, new_h), dtype=np.bool_)

    it =  np.nditer(arr, flags=['multi_index'])
    while not it.finished:
        x, y = it.multi_index
        r, t = cart_to_polar(x-cx,cy-y) # flip y

        new_x = x_bound - int(x_bound * (t + pi) / ( 2 * pi))
        new_y = int(y_bound * r/max_r)

        new_arr[new_x, new_y] = it[0]
        it.iternext()

    return new_arr

def black_out_GUI(img):
    dl = img.dl()
    dl.rectangle((0,0), (209, 31), filled=True)

    total_w = img.size()[0]
    w2, h2 = (229, 31)
    w3, h3 = (111, 51)

    dl.rectangle((total_w-w2,0), (w2, h2), filled=True)
    dl.rectangle((total_w-w3,0), (w3, h3), filled=True)

    return img

def black_out_center(img, radius):
    dl = img.dl()
    w,h = img.size()
    center = (w/2, h/2)
    dl.circle(center, radius+10, filled=True)

    return img

def test():
    with timer('image'):
        img = Image('train/372.png')

    print "image size (%d, %d)" % img.size()

    with timer('parse'):
        p = parse_frame(img)
        print '--------------'

    return p

if __name__ == "__main__":
    p = test()
    if p:
        print 'cursor angle: %d' % p.cursor_angle
        show_img(p.rot_img)
    else:
        print 'PARSE FAILED'


text:
package com.vaadin.tests.widgetset.client;

/**
 * @author Vaadin Ltd
 *
 */
public enum EmptyEnum {

}


text:
namespace google {
namespace cloud {
namespace beyondcorp_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

ClientGatewaysServiceConnectionImpl::ClientGatewaysServiceConnectionImpl(
    std::unique_ptr<google::cloud::BackgroundThreads> background,
    std::shared_ptr<beyondcorp_internal::ClientGatewaysServiceStub> stub,
    Options options)
    : background_(std::move(background)),
      stub_(std::move(stub)),
      options_(internal::MergeOptions(
          std::move(options), ClientGatewaysServiceConnection::options())) {}

StreamRange<google::cloud::beyondcorp::clientgateways::v1::ClientGateway>
ClientGatewaysServiceConnectionImpl::ListClientGateways(
    google::cloud::beyondcorp::clientgateways::v1::ListClientGatewaysRequest
        request) {
  request.clear_page_token();
  auto& stub = stub_;
  auto retry =
      std::shared_ptr<beyondcorp::ClientGatewaysServiceRetryPolicy const>(
          retry_policy());
  auto backoff = std::shared_ptr<BackoffPolicy const>(backoff_policy());
  auto idempotency = idempotency_policy()->ListClientGateways(request);
  char const* function_name = __func__;
  return google::cloud::internal::MakePaginationRange<StreamRange<
      google::cloud::beyondcorp::clientgateways::v1::ClientGateway>>(
      std::move(request),
      [stub, retry, backoff, idempotency,
       function_name](google::cloud::beyondcorp::clientgateways::v1::
                          ListClientGatewaysRequest const& r) {
        return google::cloud::internal::RetryLoop(
            retry->clone(), backoff->clone(), idempotency,
            [stub](grpc::ClientContext& context,
                   google::cloud::beyondcorp::clientgateways::v1::
                       ListClientGatewaysRequest const& request) {
              return stub->ListClientGateways(context, request);
            },
            r, function_name);
      },
      [](google::cloud::beyondcorp::clientgateways::v1::
             ListClientGatewaysResponse r) {
        std::vector<
            google::cloud::beyondcorp::clientgateways::v1::ClientGateway>
            result(r.client_gateways().size());
        auto& messages = *r.mutable_client_gateways();
        std::move(messages.begin(), messages.end(), result.begin());
        return result;
      });
}

StatusOr<google::cloud::beyondcorp::clientgateways::v1::ClientGateway>
ClientGatewaysServiceConnectionImpl::GetClientGateway(
    google::cloud::beyondcorp::clientgateways::v1::
        GetClientGatewayRequest const& request) {
  return google::cloud::internal::RetryLoop(
      retry_policy(), backoff_policy(),
      idempotency_policy()->GetClientGateway(request),
      [this](grpc::ClientContext& context,
             google::cloud::beyondcorp::clientgateways::v1::
                 GetClientGatewayRequest const& request) {
        return stub_->GetClientGateway(context, request);
      },
      request, __func__);
}

future<StatusOr<google::cloud::beyondcorp::clientgateways::v1::ClientGateway>>
ClientGatewaysServiceConnectionImpl::CreateClientGateway(
    google::cloud::beyondcorp::clientgateways::v1::
        CreateClientGatewayRequest const& request) {
  auto& stub = stub_;
  return google::cloud::internal::AsyncLongRunningOperation<
      google::cloud::beyondcorp::clientgateways::v1::ClientGateway>(
      background_->cq(), request,
      [stub](google::cloud::CompletionQueue& cq,
             std::unique_ptr<grpc::ClientContext> context,
             google::cloud::beyondcorp::clientgateways::v1::
                 CreateClientGatewayRequest const& request) {
        return stub->AsyncCreateClientGateway(cq, std::move(context), request);
      },
      [stub](google::cloud::CompletionQueue& cq,
             std::unique_ptr<grpc::ClientContext> context,
             google::longrunning::GetOperationRequest const& request) {
        return stub->AsyncGetOperation(cq, std::move(context), request);
      },
      [stub](google::cloud::CompletionQueue& cq,
             std::unique_ptr<grpc::ClientContext> context,
             google::longrunning::CancelOperationRequest const& request) {
        return stub->AsyncCancelOperation(cq, std::move(context), request);
      },
      &google::cloud::internal::ExtractLongRunningResultResponse<
          google::cloud::beyondcorp::clientgateways::v1::ClientGateway>,
      retry_policy(), backoff_policy(),
      idempotency_policy()->CreateClientGateway(request), polling_policy(),
      __func__);
}

future<StatusOr<google::cloud::beyondcorp::clientgateways::v1::
                    ClientGatewayOperationMetadata>>
ClientGatewaysServiceConnectionImpl::DeleteClientGateway(
    google::cloud::beyondcorp::clientgateways::v1::
        DeleteClientGatewayRequest const& request) {
  auto& stub = stub_;
  return google::cloud::internal::AsyncLongRunningOperation<
      google::cloud::beyondcorp::clientgateways::v1::
          ClientGatewayOperationMetadata>(
      background_->cq(), request,
      [stub](google::cloud::CompletionQueue& cq,
             std::unique_ptr<grpc::ClientContext> context,
             google::cloud::beyondcorp::clientgateways::v1::
                 DeleteClientGatewayRequest const& request) {
        return stub->AsyncDeleteClientGateway(cq, std::move(context), request);
      },
      [stub](google::cloud::CompletionQueue& cq,
             std::unique_ptr<grpc::ClientContext> context,
             google::longrunning::GetOperationRequest const& request) {
        return stub->AsyncGetOperation(cq, std::move(context), request);
      },
      [stub](google::cloud::CompletionQueue& cq,
             std::unique_ptr<grpc::ClientContext> context,
             google::longrunning::CancelOperationRequest const& request) {
        return stub->AsyncCancelOperation(cq, std::move(context), request);
      },
      &google::cloud::internal::ExtractLongRunningResultMetadata<
          google::cloud::beyondcorp::clientgateways::v1::
              ClientGatewayOperationMetadata>,
      retry_policy(), backoff_policy(),
      idempotency_policy()->DeleteClientGateway(request), polling_policy(),
      __func__);
}

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace beyondcorp_internal
}  // namespace cloud
}  // namespace google


text:
#ifndef __AP_HAL_SPI_DRIVER_H__
#define __AP_HAL_SPI_DRIVER_H__

#include "AP_HAL_Namespace.h"

class AP_HAL::SPIDeviceManager {
public:
    virtual void init(void *) = 0;
    virtual AP_HAL::SPIDeviceDriver* device(enum AP_HAL::SPIDevice) = 0;
};

/**
 * We still need an abstraction for performing bulk
 * transfers to be portable to other platforms.
 */

class AP_HAL::SPIDeviceDriver {
public:
    virtual void init() = 0;
    virtual AP_HAL::Semaphore* get_semaphore() = 0;
    virtual void transaction(const uint8_t *tx, uint8_t *rx, uint16_t len) = 0;

    virtual void cs_assert() = 0;
    virtual void cs_release() = 0;
    virtual uint8_t transfer (uint8_t data) = 0;
    virtual void transfer (const uint8_t *data, uint16_t len) = 0;

    /**
       optional set_bus_speed() interface. This can be used by drivers
       to request higher speed for sensor registers once the sensor is
       initialised. This is used by the MPU6000 driver which can
       handle 20MHz for sensor register reads, but only 1MHz for other
       registers.
     */
    enum bus_speed {
        SPI_SPEED_LOW, SPI_SPEED_HIGH
    };

    virtual void set_bus_speed(enum bus_speed speed) {}

};

#endif // __AP_HAL_SPI_DRIVER_H__


text:
ACCEPTED

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

#### Published in
null

#### Original name
Syntherisma argillaceum Hitchcock & Chase

### Remarks
null


text:
import activity from './activity.svg';
import addItem from './add-item.svg';
import alarm from './alarm.svg';
import apps from './apps.svg';
import archive from './archive.svg';
import arrowDoubleLeft from './arrow-double-left.svg';
import arrowDoubleRight from './arrow-double-right.svg';
import arrowBack from './arrow-back.svg';
import arrowDown from './arrow-down.svg';
import arrowDownThick from './arrow-down-thick.svg';
import arrowForward from './arrow-forward.svg';
import arrowLeft from './arrow-left.svg';
import arrowLeftThick from './arrow-left-thick.svg';
import arrowRight from './arrow-right.svg';
import arrowRightThick from './arrow-right-thick.svg';
import arrowUp from './arrow-up.svg';
import arrowUpThick from './arrow-up-thick.svg';
import audio from './audio.svg';
import back from './back.svg';
import backspace from './backspace.svg';
import bold from './bold.svg';
import boltOutline from './bolt-outline.svg';
import boltSolid from './bolt-solid.svg';
import bookOpen from './book-open.svg';
import bookmark from './bookmark.svg';
import bookmarkOutline from './bookmark-outline.svg';
import box from './box.svg';
import calendar from './calendar.svg';
import camera from './camera.svg';
import caretDown from './caret-down.svg';
import caretUp from './caret-up.svg';
import checkLine from './check-line.svg';
import checkLineThick from './check-line-thick.svg';
import checkOutline from './check-outline.svg';
import checkOutlineSquare from './check-outline-square.svg';
import checkSolid from './check-solid.svg';
import checkSolidSquare from './check-solid-square.svg';
import circle from './circle.svg';
import circleOutline from './circle-outline.svg';
import clipboard from './clipboard.svg';
import clockOutline from './clock-outline.svg';
import clockSolid from './clock-solid.svg';
import close from './close.svg';
import closeSm from './close-sm.svg';
import cloudDownload from './cloud-download.svg';
import cloudUpload from './cloud-upload.svg';
import code from './code.svg';
import cog from './cog.svg';
import cogOutline from './cog-outline.svg';
import collection from './collection.svg';
import comment from './comment.svg';
import commentOval from './comment-oval.svg';
import compress from './compress.svg';
import dataDownload from './data-download.svg';
import dataUpload from './data-upload.svg';
import deleteIcon from './delete.svg';
import deleteKey from './delete-key.svg';
import deleteLine from './delete-line.svg';
import deleteLineThick from './delete-line-thick.svg';
import deleteOutline from './delete-outline.svg';
import deleteSolid from './delete-solid.svg';
import desktop from './desktop.svg';
import directory from './directory.svg';
import document from './document.svg';
import documents from './documents.svg';
import download from './download.svg';
import edit from './edit.svg';
import eye from './eye.svg';
import expand from './expand.svg';
import external from './external.svg';
import dataTransferDownload from './data-transfer-download.svg';
import dataTransferUpload from './data-transfer-upload.svg';
import facebook from './facebook.svg';
import folder from './folder.svg';
import fullScreen from './full-screen.svg';
import gallery from './gallery.svg';
import google from './google.svg';
import googleMaps from './google-maps.svg';
import gridFourUp from './grid-four-up.svg';
import gridThreeUp from './grid-three-up.svg';
import gridTwoUp from './grid-two-up.svg';
import header from './header.svg';
import headphones from './headphones.svg';
import heart from './heart.svg';
import highlight from './highlight.svg';
import homeOutline from './home-outline.svg';
import homeSolid from './home-solid.svg';
import iframe from './iframe.svg';
import iframeText from './iframe-text.svg';
import imgur from './imgur.svg';
import instagram from './instagram.svg';
import infoOutline from './info-outline.svg';
import infoSolid from './info-solid.svg';
import insert from './insert.svg';
import italic from './italic.svg';
import link from './link.svg';
import linkedin from './linkedin.svg';
import list from './list.svg';
import listCards from './list-cards.svg';
import locationOutline from './location-outline.svg';
import locationSolid from './location-solid.svg';
import locked from './locked.svg';
import lockedSolid from './locked-solid.svg';
import login from './login.svg';
import logout from './logout.svg';
import mail from './mail.svg';
import menu from './menu.svg';
import microphone from './microphone.svg';
import minus from './minus.svg';
import minusLine from './minus-line.svg';
import minusLineThick from './minus-line-thick.svg';
import minusOutline from './minus-outline.svg';
import minusOutlineSquare from './minus-outline-square.svg';
import minusSolid from './minus-solid.svg';
import moreHorizontal from './more-horizontal.svg';
import moreVertical from './more-vertical.svg';
import move from './move.svg';
import notification from './notification.svg';
import notificationOutline from './notification-outline.svg';
import orderedList from './ordered-list.svg';
import pageBreak from './page-break.svg';
import paperclip from './paperclip.svg';
import pause from './pause.svg';
import pauseOutline from './pause-outline.svg';
import pencil from './pencil.svg';
import phoneMobile from './phone-mobile.svg';
import phoneOutline from './phone-outline.svg';
import phoneSolid from './phone-solid.svg';
import photo from './photo.svg';
import pin from './pin.svg';
import pinOutlineSlanted from './pin-outline-slanted.svg';
import pinSlanted from './pin-slanted.svg';
import pinterest from './pinterest.svg';
import play from './play.svg';
import playStroke from './play-stroke.svg';
import playOutline from './play-outline.svg';
import playlist from './playlist.svg';
import plus from './plus.svg';
import plusLine from './plus-line.svg';
import plusLineThick from './plus-line-thick.svg';
import plusOutline from './plus-outline.svg';
import plusOutlineSquare from './plus-outline-square.svg';
import plusSolid from './plus-solid.svg';
import poll from './poll.svg';
import pollGrid from './poll-grid.svg';
import print from './print.svg';
import question from './question.svg';
import questionOutline from './question-outline.svg';
import questionSolid from './question-solid.svg';
import quote from './quote.svg';
import refresh from './refresh.svg';
import revert from './revert.svg';
import save from './save.svg';
import saveDisk from './save-disk.svg';
import saveDiskette from './save-diskette.svg';
import search from './search.svg';
import services from './services.svg';
import settings from './settings.svg';
import social from './social.svg';
import sort from './sort.svg';
import sortHorizontal from './sort-horizontal.svg';
import sortVertical from './sort-vertical.svg';
import soundHistogram from './sound-histogram.svg';
import soundcloud from './soundcloud.svg';
import soundWave from './sound-wave.svg';
import star from './star.svg';
import starOutline from './star-outline.svg';
import status from './status.svg';
import strikethrough from './strikethrough.svg';
import tablet from './tablet.svg';
import tagOutline from './tag-outline.svg';
import tagOutlineSlanted from './tag-outline-slanted.svg';
import tagSlanted from './tag-slanted.svg';
import tagSolid from './tag-solid.svg';
import tiktok from './tiktok.svg';
import timeline from './timeline.svg';
import trash from './trash.svg';
import triniti from './triniti.svg';
import tweet from './tweet.svg';
import twitter from './twitter.svg';
import underline from './underline.svg';
import unknown from './unknown.svg';
import unlink from './unlink.svg';
import unlocked from './unlocked.svg';
import unlockedSolid from './unlocked-solid.svg';
import upload from './upload.svg';
import user from './user.svg';
import users from './users.svg';
import userSolid from './user-solid.svg';
import vevo from './vevo.svg';
import video from './video.svg';
import videoCamera from './video-camera.svg';
import vimeo from './vimeo.svg';
import warning from './warning.svg';
import warningOutline from './warning-outline.svg';
import warningOutlineAlt from './warning-outline-alt.svg';
import warningOutlineTriangle from './warning-outline-triangle.svg';
import warningSolid from './warning-solid.svg';
import warningSolidAlt from './warning-solid-alt.svg';
import warningSolidTriangle from './warning-solid-triangle.svg';
import youtube from './youtube.svg';
import zip from './zip.svg';
import zoomIn from './zoom-in.svg';
import zoomOut from './zoom-out.svg';

const icons = {
  activity,
  'add-item': addItem,
  alarm,
  apps,
  archive,
  'arrow-back': arrowBack,
  'arrow-double-left': arrowDoubleLeft,
  'arrow-double-right': arrowDoubleRight,
  'arrow-down': arrowDown,
  'arrow-down-thick': arrowDownThick,
  'arrow-forward': arrowForward,
  'arrow-left': arrowLeft,
  'arrow-left-thick': arrowLeftThick,
  'arrow-right': arrowRight,
  'arrow-right-thick': arrowRightThick,
  'arrow-up': arrowUp,
  'arrow-up-thick': arrowUpThick,
  audio,
  back,
  backspace,
  bold,
  'bolt-outline': boltOutline,
  'bolt-solid': boltSolid,
  'book-open': bookOpen,
  bookmark,
  'bookmark-outline': bookmarkOutline,
  box,
  calendar,
  camera,
  'caret-down': caretDown,
  'caret-up': caretUp,
  'check-line': checkLine,
  'check-line-thick': checkLineThick,
  'check-outline': checkOutline,
  'check-outline-square': checkOutlineSquare,
  'check-solid': checkSolid,
  'check-solid-square': checkSolidSquare,
  circle,
  'circle-outline': circleOutline,
  clipboard,
  'clock-outline': clockOutline,
  'clock-solid': clockSolid,
  close,
  'close-sm': closeSm,
  'cloud-download': cloudDownload,
  'cloud-upload': cloudUpload,
  code,
  cog,
  'cog-outline': cogOutline,
  collection,
  comment,
  'comment-oval': commentOval,
  compress,
  'data-download': dataDownload,
  'data-upload': dataUpload,
  'data-transfer-download': dataTransferDownload,
  'data-transfer-upload': dataTransferUpload,
  delete: deleteIcon,
  'delete-key': deleteKey,
  'delete-line': deleteLine,
  'delete-line-thick': deleteLineThick,
  'delete-outline': deleteOutline,
  'delete-solid': deleteSolid,
  desktop,
  directory,
  document,
  documents,
  download,
  edit,
  eye,
  expand,
  external,
  facebook,
  folder,
  'full-screen': fullScreen,
  gallery,
  google,
  'google-maps': googleMaps,
  'grid-four-up': gridFourUp,
  'grid-three-up': gridThreeUp,
  'grid-two-up': gridTwoUp,
  header,
  headphones,
  heart,
  highlight,
  'home-outline': homeOutline,
  'home-solid': homeSolid,
  iframe,
  'iframe-text': iframeText,
  imgur,
  'info-outline': infoOutline,
  'info-solid': infoSolid,
  insert,
  instagram,
  italic,
  link,
  linkedin,
  list,
  'list-cards': listCards,
  'location-outline': locationOutline,
  'location-solid': locationSolid,
  locked,
  'locked-solid': lockedSolid,
  login,
  logout,
  mail,
  menu,
  microphone,
  minus,
  'minus-line': minusLine,
  'minus-line-thick': minusLineThick,
  'minus-outline': minusOutline,
  'minus-outline-square': minusOutlineSquare,
  'minus-solid': minusSolid,
  'more-horizontal': moreHorizontal,
  'more-vertical': moreVertical,
  move,
  notification,
  'notification-outline': notificationOutline,
  'ordered-list': orderedList,
  paperclip,
  'page-break': pageBreak,
  pause,
  'pause-outline': pauseOutline,
  pencil,
  'phone-mobile': phoneMobile,
  'phone-outline': phoneOutline,
  'phone-solid': phoneSolid,
  photo,
  pin,
  'pin-outline-slanted': pinOutlineSlanted,
  'pin-slanted': pinSlanted,
  pinterest,
  play,
  'play-stroke': playStroke,
  'play-outline': playOutline,
  playlist,
  plus,
  'plus-line': plusLine,
  'plus-line-thick': plusLineThick,
  'plus-outline': plusOutline,
  'plus-outline-square': plusOutlineSquare,
  'plus-solid': plusSolid,
  poll,
  'poll-grid': pollGrid,
  print,
  question,
  'question-outline': questionOutline,
  'question-solid': questionSolid,
  quote,
  refresh,
  revert,
  save,
  'save-disk': saveDisk,
  'save-diskette': saveDiskette,
  search,
  services,
  settings,
  social,
  sort,
  'sort-horizontal': sortHorizontal,
  'sort-vertical': sortVertical,
  'sound-histogram': soundHistogram,
  'sound-wave': soundWave,
  soundcloud,
  star,
  'star-outline': starOutline,
  status,
  strikethrough,
  tablet,
  'tag-outline': tagOutline,
  'tag-outline-slanted': tagOutlineSlanted,
  'tag-slanted': tagSlanted,
  'tag-solid': tagSolid,
  tiktok,
  timeline,
  trash,
  triniti,
  tweet,
  twitter,
  underline,
  unknown,
  unlink,
  unlocked,
  'unlocked-solid': unlockedSolid,
  upload,
  user,
  users,
  'user-solid': userSolid,
  vevo,
  video,
  'video-camera': videoCamera,
  vimeo,
  warning,
  'warning-outline': warningOutline,
  'warning-outline-alt': warningOutlineAlt,
  'warning-outline-triangle': warningOutlineTriangle,
  'warning-solid': warningSolid,
  'warning-solid-alt': warningSolidAlt,
  'warning-solid-triangle': warningSolidTriangle,
  youtube,
  zip,
  'zoom-in': zoomIn,
  'zoom-out': zoomOut,
};

export default (name) => icons[name];


text:
#include <folly/SingletonThreadLocal.h>

using namespace folly;

namespace folly {
using Make = detail::DefaultMake<int>;
} // namespace folly

struct Make1 : Make {};
struct Make2 : Make {};
struct DeathTag {};

int stl_get_sum() {
  auto& i1 = SingletonThreadLocal<int, DeathTag, Make1>::get();
  auto& i2 = SingletonThreadLocal<int, DeathTag, Make2>::get();
  return i1 + i2;
}


text:
.. _`AXUI AppMap`:

=========================
AXUI AppMap
=========================

:Page Status: Development
:Last Reviewed:

AppMap overview
=========================

AppMap is a key feature of AXUI, use AppMap smart can make your automation task much easier.
Basically, AppMap is to store all changeable UI element features, and provide a consistent AppMap element for use.
Thus, AppMap could reduce the scripts mutability, and make script easier for maintenance.
This feature also provide a direct solution for internationalization.

We will provide a detail introduce for each part of AppMap below, before that, here provide a sample AppMap containing all parts of AppMap::

    <AXUI:app_map xmlns:AXUI="AXUI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="AXUI AXUI_app_map.xsd">

    <AXUI:variables>
        <AXUI:variable name="" value="" />
    </AXUI:variables>

    <AXUI:includes>
        <AXUI:include name="" path="" />
    </AXUI:includes>

    <AXUI:funcs>
        <AXUI:func name="" description="">
            <AXUI:step type="" cmd=''/>
        </AXUI:func>
    </AXUI:funcs>

    <AXUI:UI_elements>
        <AXUI:Root_element name=""/>

        <AXUI:UI_element name="" parent="" identifier="" start_func="" stop_func="">
            <AXUI:UI_element name="" identifier="" start_func="">
                <AXUI:UI_element name="" identifier="" />
            </AXUI:UI_element>
        </AXUI:UI_element>
    </AXUI:UI_elements>

</AXUI:app_map>

AppMap elements
=====================

Here we have an introduce for each element in AppMap, AppMap will be checked with a pre-defined schema ``AXUI/XML/schemas/AXUI_app_map.xsd``

root element -- AXUI:app_map
----------------------------

``AXUI:app_map`` is the root element of AppMap, it should always be::

    <AXUI:app_map xmlns:AXUI="AXUI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="AXUI AXUI_app_map.xsd">
        ......
    </AXUI:app_map>

AXUI:variables
------------------

``AXUI:variables`` can include multiple ``AXUI:variable`` elements, ``AXUI:variables`` has no attributes.

AXUI:variable
##################

``AXUI:variable`` element provide a dynamic way to change AppMap contents, currently only support change command line in ``AXUI:func`` element

typical usage::

    <AXUI:variables>
        <AXUI:variable name="AppPath" value='"some_app_path"'/>
    </AXUI:variables>

    <AXUI:funcs>
        <AXUI:func name="start_some_element" description="">
            <AXUI:step type="CLI" cmd='{AppPath}'/>
        </AXUI:func>
    </AXUI:funcs>

OR::

    <AXUI:funcs>
        <AXUI:func name="start_some_element" description="">
            <AXUI:step type="CLI" cmd='{AppPath}'/>
        </AXUI:func>
    </AXUI:funcs>

    #in script
    appmap.variables["AppPath"] = "some_app_path"

AXUI:includes
-----------------

``AXUI:includes`` can include multiple ``AXUI:include`` elements, ``AXUI:includes`` has no attributes.

AXUI:include
##################

AXUI support include other AppMap to use other AppMap definitions by using ``AXUI:include``, this is used when some app is used by other apps, or you want to extend original app UI elements.

typical usage::

    <AXUI:includes>
        <AXUI:include name="namespace_name" path="included_appmap_name" />
        ...
    </AXUI:includes>

    #in script
    appmap.namespace_name.element_name...

OR using it as element parent::

    <AXUI:includes>
        <AXUI:include name="namespace_name" path="included_appmap_name" />
        ...
    </AXUI:includes>

    <AXUI:UI_elements>
        <AXUI:UI_element name="" parent="namespace_name.element_name" />
    </AXUI:UI_elements>

AXUI:funcs
-----------------

``AXUI:funcs`` can include multiple ``AXUI:func`` element, ``AXUI:funcs`` has no attributes.

AXUI:func
##################

``AXUI:func`` can include multiple ``AXUI:step`` element, ``AXUI:func`` has two attributes "name" and "description".
"name" attribute is to provide an identifier to use this function, this attribute is must have,
"description" provide a description for this function, it's optional.

.. note::

 it's recommend to use ``AXUI:func`` element for UI element start/stop function

 not recommend to use ``AXUI:func`` to replace python functions

AXUI:step
""""""""""""""""""

``AXUI:step`` has three attributes: "type", "cmd", "app_map".
"type" specifies step type, could be "CLI" for command or "GUI" for UI operation
"cmd" specifies the detail executing step, for "CLI" type, it's a string of command line; for "GUI" type, it's a string of GUI command just like AXUI command in appmap
"app_map" is optional, indicate which AppMap to execute the step

typical usage::

    <AXUI:funcs>
        <AXUI:func name="wmplayer_start_open_dialog" description="">
            <AXUI:step type="CLI" cmd='"C:\Program Files\Windows Media Player\wmplayer.exe"'/>
            <AXUI:step type="GUI" cmd="wmplayer_Window.keyboard.Input '^o'"/>
            ...
        </AXUI:func>
        ...
    </AXUI:funcs>

    <AXUI:UI_elements>
        <AXUI:UI_element name="OpenDialog" parent="" start_func="wmplayer_start_open_dialog"/>
    </AXUI:UI_elements>

AXUI:UI_elements
-----------------

``AXUI:UI_elements`` can include multiple ``AXUI:UI_element`` \\ ``AXUI:Root_element`` \\ ``AXUI:UI_element_group`` elements, ``AXUI:UI_elements`` has no attributes.

AXUI:Root_element
##################

``AXUI:Root_element`` element represents the enter point of UI automation API, like desktop of windows UIA, web browser of ``WebDriver``.

``AXUI:Root_element`` element can include multiple ``AXUI:UI_element`` \\ ``AXUI:UI_element_group`` elements, element included are treated as children of ``AXUI:Root_element`` element.

``AXUI:Root_element`` element has a ``name`` attribute as identifier.

AXUI:UI_element
##################

``AXUI:UI_element`` element represents the normal UI elements,

``AXUI:UI_element`` element can contain multiple ``AXUI:UI_element`` \\ ``AXUI:UI_element_group`` elements, element included are treated as children of ``AXUI:UI_element`` element.

``AXUI:UI_element`` element has six attributes::

- ``name`` attribute, must have, identifier of this element
- ``parent`` attribute, must have for elements of the direct children of ``AXUI:UI_elements``
- ``identifier`` attribute, optional, a string for UI API to find the element, check :ref:`AXUI built-in drivers` for detail identifier format
- ``start_func`` attribute, optional, how to start the element
- ``stop_func`` attribute, optional, how to stop the element
- ``timeout`` attribute, optional, element unique timeout time, will replace global timeout in config file

AXUI:UI_element_group
########################

``AXUI:UI_element_group`` element represents the UI element list,

``AXUI:UI_element_group`` element cannot contain any element,

``AXUI:UI_element_group`` element also has six attributes::

- ``name`` attribute, must have, identifier of this element
- ``parent`` attribute, must have for elements of the direct children of ``AXUI:UI_elements``
- ``identifier`` attribute, optional, a string for UI API to find the element, check :ref:`AXUI built-in drivers` for detail identifier format
- ``start_func`` attribute, optional, how to start the element
- ``stop_func`` attribute, optional, how to stop the element
- ``timedelay`` attribute, optional, will find the element group after time specified


text:
<?php

namespace Minph\Utility;

/**
 * @class Minph\Utility\Number
 */
class Number
{

    private function __construct()
    {
    }

    /**
     * @method (static) toInt
     * @param `$value`
     * @param int `$default` (default = 0)
     * @return int value
     */
    public static function toInt($value, $default = 0)
    {
        if (is_numeric($value)) {
            return (int)$value;
        }
        return $default;
    }

    /**
     * @method (static) toFloat
     * @param `$value`
     * @param float `$default` (default = 0)
     * @return float value
     */
    public static function toFloat($value, $default = 0.0)
    {
        if (is_numeric($value)) {
            return (float)$value;
        }
        return $default;
    }
}


text:
Tinytest.add('Client - Group - validate path definition', function (test, next) {
  // path & prefix must start with '/'
  test.throws(function() {
    new Group(null, {prefix: Random.id()});
  });

  var group = FlowRouter.group({prefix: '/' + Random.id()});

  test.throws(function() {
    group.route(Random.id());
  });
});

Tinytest.addAsync('Client - Group - define and go to route with prefix', function (test, next) {
  var prefix = Random.id();
  var rand = Random.id();
  var rendered = 0;

  var group = FlowRouter.group({prefix: '/' + prefix});

  group.route('/' + rand, {
    action: function(_params) {
      rendered++;
    }
  });

  FlowRouter.go('/' + prefix + '/' + rand);

  setTimeout(function() {
    test.equal(rendered, 1);
    setTimeout(next, 100);
  }, 100);
});

Tinytest.addAsync('Client - Group - define and go to route without prefix', function (test, next) {
  var rand = Random.id();
  var rendered = 0;

  var group = FlowRouter.group();

  group.route('/' + rand, {
    action: function(_params) {
      rendered++;
    }
  });

  FlowRouter.go('/' + rand);

  setTimeout(function() {
    test.equal(rendered, 1);
    setTimeout(next, 100);
  }, 100);
});

Tinytest.addAsync('Client - Group - subscribe', function (test, next) {
  var rand = Random.id();

  var group = FlowRouter.group({
    subscriptions: function (params) {
      this.register('baz', Meteor.subscribe('baz'));
    }
  });

  group.route('/' + rand);

  FlowRouter.go('/' + rand);
  setTimeout(function() {
    test.isTrue(!!GetSub('baz'));
    next();
  }, 100);
});


text:
#import <Foundation/Foundation.h>
#import "PLClangSourceLocation.h"

@interface PLClangSourceRange : NSObject

- (instancetype) initWithStartLocation: (PLClangSourceLocation *) startLocation
                           endLocation: (PLClangSourceLocation *) endLocation;

/**
 * The start location of this source range.
 */
@property(nonatomic, readonly) PLClangSourceLocation *startLocation;

/**
 * The end location of the this range.
 */
@property(nonatomic, readonly) PLClangSourceLocation *endLocation;

@end